Standard units Reference Guide .fr

Page 7 ...... Description: DosExitCode contains (in the low byte) the exit-code of a ...... The %fs selector is preloaded with the DOSMEMSELECTOR variable at startup ..... real mode register data structure; typically, this is accomplished by extracting the ...... Errors: On error, the first form of the function returns -1; the second one ...
4MB taille 15 téléchargements 578 vues
Free Pascal supplied units : Reference guide. Reference guide for standard Free Pascal units. Document version 1.10 August 2004

Michaël Van Canneyt Florian Klämpfl

Contents 1

The CRT unit.

28

1.1

Types, Variables, Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

28

1.2

Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

AssignCrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

CursorBig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

ClrEol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

ClrScr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31

CursorOff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31

CursorOn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

DelLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

GotoXY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

33

HighVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

33

InsLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

34

KeyPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

34

LowVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35

NormVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35

NoSound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35

ReadKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

36

Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

37

TextBackground . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

37

TextColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

37

TextMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

38

WhereX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

38

WhereY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

38

Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

39

2 The DOS unit. 2.1

40

Types, Variables, Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

40

Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

40

File attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

40

1

CONTENTS

2.2

2.3

fmXXXX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

40

Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43

Function list by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43

File handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43

Directory and disk handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

44

Process handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

44

System information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

44

Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45

AddDisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45

DiskFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45

DiskSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

46

DosExitCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47

DosVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47

EnvCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

EnvStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

Exec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

49

FExpand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

49

FindClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

49

FindFirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

50

FindNext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

50

FSearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51

FSplit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51

GetCBreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

52

GetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

52

GetEnv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

53

GetFAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

53

GetFTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

54

GetIntVec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55

GetLongName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55

GetShortName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55

GetTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55

GetVerify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

56

Intr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

56

Keep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

57

MSDos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

57

PackTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

57

SetCBreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

58

SetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

58

2

CONTENTS

SetFAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

58

SetFTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59

SetIntVec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59

SetTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59

SetVerify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59

SwapVectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

60

UnPackTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

60

3 The DXELOAD unit

61

3.1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

3.2

Constants, types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

dxe_load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

3.3

4 The EMU387 unit 4.1

63

Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

63

npxsetup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

63

5 The GETOPTS unit. 5.1

5.2

64

Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . . . . . . . . .

64

Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

64

Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

64

Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

65

Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

65

GetLongOpts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

65

Getopt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

65

6 The GPM unit

68

6.1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

68

6.2

Constants, types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

68

constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

68

Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

69

Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

70

Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

70

Gpm_AnyDouble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

70

Gpm_AnySingle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

71

Gpm_AnyTriple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

71

Gpm_Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

71

Gpm_FitValues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

71

6.3

3

CONTENTS

Gpm_FitValuesM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

71

Gpm_GetEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

72

Gpm_GetLibVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

73

Gpm_GetServerVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

73

Gpm_GetSnapshot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

73

Gpm_LowerRoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

74

Gpm_Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

74

Gpm_PopRoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

74

Gpm_PushRoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

74

Gpm_RaiseRoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

Gpm_Repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

Gpm_StrictDouble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

Gpm_StrictSingle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

Gpm_StrictTriple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

76

7 The GO32 unit

77

7.1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

7.2

Protected mode memory organization . . . . . . . . . . . . . . . . . . . . . . . . .

77

What is DPMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

Selectors and descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

FPC specialities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

memory access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

I/O port access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

Processor access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

Interrupt redirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

Handling interrupts with DPMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

79

Protected mode interrupts vs. Real mode interrupts . . . . . . . . . . . . . . . . . .

79

Creating own interrupt handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . .

79

Disabling interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

79

Hardware interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

79

Software interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

81

Real mode callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

83

Types, Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

Constants returned by get_run_mode . . . . . . . . . . . . . . . . . . . . .

84

Processor flags constants . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

Predefined types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

86

Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

86

allocate_ldt_descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

86

DOS

7.3

7.4

4

CONTENTS

allocate_memory_block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

88

copyfromdos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

88

copytodos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

88

create_code_segment_alias_descriptor . . . . . . . . . . . . . . . . . . . . . . . . .

89

disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

89

dosmemfillchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

89

dosmemfillword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

90

dosmemget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

91

dosmemmove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

91

dosmemput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

91

enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

92

free_ldt_descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

92

free_memory_block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

92

free_rm_callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

92

get_cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

93

get_descriptor_access_rights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

93

get_ds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

93

get_linear_addr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

93

get_meminfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

94

get_next_selector_increment_value . . . . . . . . . . . . . . . . . . . . . . . . . . .

95

get_page_size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

95

get_pm_interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

95

get_rm_callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

96

get_rm_interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

98

get_run_mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

99

get_segment_base_address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

99

get_segment_limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 get_ss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 global_dos_alloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 global_dos_free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 inportb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 inportl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 inportw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 lock_code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 lock_data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 lock_linear_region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 outportb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 outportl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 outportw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 realintr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

5

CONTENTS

seg_fillchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 seg_fillword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 segment_to_descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 seg_move . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 set_descriptor_access_rights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 set_pm_interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 set_rm_interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 set_segment_base_address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 set_segment_limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 tb_size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 transfer_buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 unlock_code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 unlock_data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 unlock_linear_region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 8 The GRAPH unit. 8.1

112

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 A word about mode selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

8.2

Constants, Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

8.3

Function list by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 screen management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Color management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Drawing primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Filled drawings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Text and font handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

8.4

Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Arc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Bar3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 ClearDevice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 ClearViewPort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 CloseGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 DetectGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 DrawPoly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Ellipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 FillEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

6

CONTENTS

FillPoly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 FloodFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 GetArcCoords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 GetAspectRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 GetBkColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 GetColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 GetDefaultPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 GetDriverName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetFillPattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetFillSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetGraphMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetLineSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetMaxColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 GetMaxMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 GetMaxX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 GetMaxY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 GetModeName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 GetModeRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 GetPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 GetPaletteSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 GetPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 GetTextSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 GetViewSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 GetX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 GetY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 GraphDefaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 GraphErrorMsg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 GraphResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 ImageSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 InitGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 InstallUserDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 InstallUserFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 LineRel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 LineTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 MoveRel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 MoveTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 OutText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 OutTextXY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

7

CONTENTS

PieSlice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 PutImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 PutPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 RegisterBGIDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 RegisterBGIFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 RestoreCRTMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 SetActivePage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 SetAllPallette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 SetAspectRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 SetBkColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 SetColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 SetFillPattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 SetFillStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 SetGraphBufSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 SetGraphMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 SetLineStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 SetPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 SetRGBPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 SetTextJustify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 SetTextStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 SetUserCharSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 SetViewPort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 SetVisualPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 SetWriteMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 TextHeight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 TextWidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 8.5

Target specific issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 DOS

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

W INDOWS LINUX

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

9 The HEAPTRC unit.

139

9.1

Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

9.2

Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

9.3

Constants, Types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

9.4

Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 DumpHeap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 MarkHeap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

8

CONTENTS

SetExtraInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 SetHeapTraceOutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 10 The IPC unit.

144

10.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 10.2 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 ftok . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 msgget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 msgsnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 msgrcv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 msgctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 semget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 semop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 semctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 shmget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 shmat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 shmdt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 shmctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 11 The KEYBOARD unit 11.1 Constants, Type and variables

162 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 11.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 DoneKeyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 FunctionKeyName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 GetKeyboardDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 GetKeyEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 GetKeyEventChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 GetKeyEventCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 GetKeyEventFlags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 GetKeyEventShiftState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 GetKeyEventUniCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 InitKeyBoard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 IsFunctionKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 KeyEventToString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 PollKeyEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 PollShiftStateEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 9

CONTENTS

PutKeyEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 SetKeyboardDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 ShiftStateToString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 TranslateKeyEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 TranslateKeyEventUniCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 11.3 Keyboard scan codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 11.4 Writing a keyboard driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 12 The LINUX unit.

180

12.1 Type, Variable and Constant declarations . . . . . . . . . . . . . . . . . . . . . . . . 180 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 12.2 Function list by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 File Input/Output routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 General File handling routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Pipes, FIFOs and streams

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Directory handling routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Process handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 System information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Terminal functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Port input/output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Utility routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 12.3 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 Alarm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 AssignPipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 AssignStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 BaseName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 CFMakeRaw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 CFSetISpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 CFSetOSpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Chown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Chmod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Clone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 CloseDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 CreateShellArgV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 DirName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Dup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

10

CONTENTS

Dup2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 EpochToLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 Execl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Execle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Execlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Execv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Execve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Execvp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 FD_ZERO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 FD_Clr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 FD_IsSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 FD_Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 fdClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 fdFlush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 fdOpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 fdRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 fdSeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 fdTruncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 fdWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 FExpand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 FLock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 FNMatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 FSearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 FSplit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 FSStat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 FStat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Fcntl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Fcntl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Fork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 FRename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 GetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 GetDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 GetDomainName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 GetEGid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 GetEUid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 GetEnv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 GetEpochTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 GetFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 GetGid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 GetHostName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

11

CONTENTS

GetLocalTimezone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 GetPid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 GetPPid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 GetPriority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 GetTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 GetTimeOfDay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 GetTimeOfDay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 GetTimezoneFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 GetUid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 Glob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 GlobFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 IOCtl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 IOperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 IsATTY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 S_ISBLK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 S_ISCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 S_ISDIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 S_ISFIFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 S_ISLNK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 S_ISREG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 S_ISSOCK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 Kill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 LStat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 Link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 LocalToEpoch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 MkFifo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 MMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 MUnMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 NanoSleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Nice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Octal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 OpenDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 pause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 PClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 POpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 ReadDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 ReadLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 ReadPort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 ReadPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 ReadPortL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

12

CONTENTS

ReadPortW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 ReadTimezoneFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 SeekDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 SelectText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 SetPriority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 SigAction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 SigPending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 SigProcMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 SigRaise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 SigSuspend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 StringToPPchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 SymLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 SysInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 TCDrain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 TCFlow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 TCFlush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 TCGetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 TCGetPGrp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 TCSendBreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 TCSetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 TCSetPGrp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 TTYName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 TellDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 Umask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 Uname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 UnLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Utime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 WaitPid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 WritePort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 WritePortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 WritePortL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 WritePortW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 13 The MATH unit

261

13.1 Constants and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 13.2 Function list by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Min/max determination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

13

CONTENTS

Angle conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Trigoniometric functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Hyperbolic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Exponential and logarithmic functions . . . . . . . . . . . . . . . . . . . . . . . . . 263 Number converting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Statistical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Geometrical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 13.3 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 arccos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 arcosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 arcsin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 arctan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 arsinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 artanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 cosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 cotan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 cycletorad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 degtograd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 degtorad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 floor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 frexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 gradtodeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 gradtorad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 hypot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 intpower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 ldexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 lnxp1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 log10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 log2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 logn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 max . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 maxIntValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 maxvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 meanandstddev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 min . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 minIntValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 minvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 momentskewkurtosis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

14

CONTENTS

norm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 popnstddev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 popnvariance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 radtocycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 radtodeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 radtograd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 randg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 sincos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 sinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 stddev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 sumofsquares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 sumsandsquares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 totalvariance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 14 The MMX unit

293

14.1 Variables, Types and constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 14.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 Emms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 15 The MOUSE unit

295

15.1 Constants, Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 15.2 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 DetectMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 DoneMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 GetMouseButtons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 GetMouseDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 GetMouseEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 GetMouseX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 GetMouseY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 HideMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 InitMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 PollMouseEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 PutMouseEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 15

CONTENTS

SetMouseDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 SetMouseXY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 ShowMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 15.3 Writing a custom mouse driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 16 The MsMouse unit

305

16.1 Constants, types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 16.2 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 GetLastButtonPress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 GetLastButtonRelease . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 GetMouseState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 HideMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 InitMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 LPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 MPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 RPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 SetMouseAscii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 SetMouseHideWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 SetMousePos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 SetMouseShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 SetMouseSpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 SetMouseWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 SetMouseXRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 SetMouseYRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 ShowMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 17 The Objects unit.

317

17.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 17.2 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 17.3 Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 NewStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 DisposeStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 Abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 RegisterObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 RegisterType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 LongMul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 LongDiv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 17.4 TRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 TRect.Empty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 TRect.Equals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 TRect.Contains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 16

CONTENTS

TRect.Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 TRect.Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 TRect.Intersect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 TRect.Move . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 TRect.Grow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 TRect.Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 17.5 TObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 TObject.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 TObject.Free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 TObject.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 17.6 TStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 TStream.Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 TStream.StrRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 TStream.GetPos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 TStream.GetSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 TStream.ReadStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 TStream.Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 TStream.Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 TStream.Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 TStream.Flush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 TStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 TStream.Put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 TStream.StrWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 TStream.WriteStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 TStream.Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 TStream.Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 TStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 TStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 TStream.CopyFrom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 17.7 TDosStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 TDosStream.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 TDosStream.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 TDosStream.Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 TDosStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 TDosStream.Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 TDosStream.Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 TDosStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 TDosStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 17.8 TBufStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 TBufStream.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341

17

CONTENTS

TBufStream.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 TBufStream.Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 TBufStream.Flush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 TBufStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 TBufStream.Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 TBufStream.Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 TBufStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 TBufStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 17.9 TMemoryStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 TMemoryStream.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 TMemoryStream.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 TMemoryStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 TMemoryStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 TMemoryStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 17.10TCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 TCollection.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 TCollection.Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 TCollection.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 TCollection.At . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 TCollection.IndexOf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 TCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 TCollection.LastThat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 TCollection.FirstThat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 TCollection.Pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 TCollection.FreeAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 TCollection.DeleteAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 TCollection.Free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 TCollection.Insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 TCollection.Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 TCollection.AtFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 TCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 TCollection.AtDelete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 TCollection.ForEach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 TCollection.SetLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 TCollection.Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 TCollection.AtPut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 TCollection.AtInsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 TCollection.Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 TCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 17.11TSortedCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361

18

CONTENTS

TSortedCollection.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 TSortedCollection.Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 TSortedCollection.KeyOf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 TSortedCollection.IndexOf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 TSortedCollection.Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 TSortedCollection.Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364 TSortedCollection.Insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 TSortedCollection.Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 17.12TStringCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 TStringCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 TStringCollection.Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 TStringCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 TStringCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 17.13TStrCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 TStrCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 TStrCollection.Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 TStrCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 TStrCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 17.14TUnSortedStrCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 TUnSortedStrCollection.Insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 17.15TResourceCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 TResourceCollection.KeyOf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 TResourceCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 TResourceCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 TResourceCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 17.16TResourceFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 TResourceFile Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 TResourceFile.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 TResourceFile.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 TResourceFile.Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 TResourceFile.KeyAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 TResourceFile.Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 TResourceFile.SwitchTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 TResourceFile.Flush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 TResourceFile.Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 TResourceFile.Put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 17.17TStringList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 TStringList.Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 TStringList.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 TStringList.Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

19

CONTENTS

17.18TStrListMaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 TStrListMaker.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 TStrListMaker.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 TStrListMaker.Put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 TStrListMaker.Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 18 The PORTS unit

377

18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 18.2 Types,constants and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 19 The PRINTER unit.

379

19.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 19.2 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 AssignLst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 20 The SOCKETS unit.

381

20.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 20.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 Bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 Bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 GetPeerName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 GetSocketName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 GetSocketOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 Listen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 Recv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 SetSocketOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 Shutdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 Sock2File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 Sock2Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391

20

CONTENTS

SocketPair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 Str2UnixSockAddr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 21 The STRINGS unit.

392

21.1 Functions and procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 StrAlloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 StrCat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 StrComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 StrCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 StrDispose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 StrECopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 StrEnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 StrIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 StrLCat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 StrLComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 StrLCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 StrLen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 StrLIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 StrLower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 StrMove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 StrNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 StrPas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 StrPCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 StrPos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 StrRScan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 StrScan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 StrUpper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 22 The SYSUTILS unit.

403

22.1 Constants and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 22.2 Function list by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 String functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Formatting strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 File input/output routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 File handling routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 Date/time routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 22.3 Miscellaneous conversion routines . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 22.4 Date and time functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Date and time formatting characters . . . . . . . . . . . . . . . . . . . . . . . . . . 410 TDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 21

CONTENTS

DateTimeToFileDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 DateTimeToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 DateTimeToString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 DateTimeToSystemTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 DateTimeToTimeStamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 DateToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 DayOfWeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 DecodeDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 DecodeTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 EncodeDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 EncodeTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 FileDateToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 FormatDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 IncMonth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 IsLeapYear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 MSecsToTimeStamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Now . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 StrToDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 StrToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422 StrToTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422 SystemTimeToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 TimeStampToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 TimeStampToMSecs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 TimeToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 22.5 Disk functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 AddDisk (Linux only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 CreateDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 DiskFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 DiskSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 GetCurrentDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 RemoveDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 SetCurrentDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 22.6 File handling functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 ChangeFileExt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 DeleteFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 DoDirSeparators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 ExpandFileName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430 ExpandUNCFileName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430 ExtractFileDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431

22

CONTENTS

ExtractFileDrive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431 ExtractFileExt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432 ExtractFileName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432 ExtractFilePath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432 ExtractRelativePath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432 FileAge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 FileClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 FileCreate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 FileExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 FileGetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 FileGetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 FileOpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 FileRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 FileSearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438 FileSeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438 FileSetAttr (Not on Linux) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 FileSetDate (Not on Linux) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 FileTruncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 FileWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 FindClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 FindFirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 FindNext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 GetDirs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 RenameFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442 SetDirSeparators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442 22.7 PChar functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 StrAlloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 StrBufSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 StrDispose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 StrPCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 StrPLCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 StrPas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 22.8 String handling functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 AdjustLineBreaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 AnsiCompareStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 AnsiCompareText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 AnsiExtractQuotedStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 AnsiLastChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 AnsiLowerCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449

23

CONTENTS

AnsiQuotedStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 AnsiStrComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 AnsiStrIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450 AnsiStrLastChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451 AnsiStrLComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 AnsiStrLIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 AnsiStrLower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453 AnsiStrUpper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 AnsiUpperCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 AppendStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 AssignStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 BCDToInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 CompareMem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 CompareStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 CompareText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 DisposeStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 FloatToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 FloatToStrF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 FloatToText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 FmtStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 FormatBuf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468 FormatFloat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468 IntToHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 IntToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470 IsValidIdent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 LastDelimiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 LeftStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 LoadStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 LowerCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 NewStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 QuotedStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 RightStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 StrFmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474 StrLFmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474 StrToFloat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475 StrToInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 StrToIntDef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 TextToFloat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 Trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

24

CONTENTS

TrimLeft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 TrimRight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 UpperCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 23 The TYPINFO unit

481

23.1 Constants, Types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 23.2 Function list by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484 Examining published property information . . . . . . . . . . . . . . . . . . . . . . . 484 Getting or setting property values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 Auxiliary functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 23.3 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 FindPropInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 GetEnumName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 GetEnumProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 GetEnumValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 GetFloatProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 GetInt64Prop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 GetMethodProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 GetObjectProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492 GetObjectPropClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 GetOrdProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 GetPropInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 GetPropInfos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 GetPropList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 GetPropValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 GetSetProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 GetStrProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498 GetTypeData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 GetVariantProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 IsPublishedProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 IsStoredProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 PropIsType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 PropType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 SetEnumProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 SetFloatProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 SetInt64Prop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 SetMethodProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504 SetObjectProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504

25

CONTENTS

SetOrdProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 SetPropValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 SetSetProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 SetStrProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 SetToString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 SetVariantProp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507 StringToSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507 24 The VIDEO unit 24.1 Constants, Type and variables

508 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511 24.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512 ClearScreen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512 DefaultErrorHandler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 DoneVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 GetCapabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514 GetCursorType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515 GetLockScreenCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515 GetVideoDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516 GetVideoMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516 GetVideoModeCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517 GetVideoModeData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518 InitVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518 LockScreenUpdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 SetCursorPos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 SetCursorType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520 SetVideoDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520 SetVideoMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 UnlockScreenUpdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 UpdateScreen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522 24.3 Writing a custom video driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522

26

CONTENTS

About this guide This document describes all constants, types, variables, functions and procedures as they are declared in the units that come standard with Free Pascal. Throughout this document, we will refer to functions, types and variables with typewriter font. Functions and procedures gave their own subsections, and for each function or procedure we have the following topics: Declaration The exact declaration of the function. Description What does the procedure exactly do ? Errors What errors can occur. See Also Cross references to other related functions/commands. The cross-references come in two flavors: • References to other functions in this manual. In the printed copy, a number will appear after this reference. It refers to the page where this function is explained. In the on-line help pages, this is a hyperlink, on which you can click to jump to the declaration. • References to Unix manual pages. (For Linux related things only) they are printed in typewriter font, and the number after it is the Unix manual section. The chapters are ordered alphabetically. The functions and procedures in most cases also, but don’t count on it. Use the table of contents for quick lookup.

27

Chapter 1

The CRT unit. This chapter describes the CRT unit for Free Pascal, both under DOS LINUX and W INDOWS. The unit was first written for DOS by Florian klämpfl. The unit was ported to LINUX by Mark May1 , and enhanced by Michaël Van Canneyt and Peter Vreman. It works on the LINUX console, and in xterm and rxvt windows under X-Windows. The functionality for both is the same, except that under LINUX the use of an early implementation (versions 0.9.1 and earlier of the compiler) the crt unit automatically cleared the screen at program startup. There are some caveats when using the CRT unit: • Programs using the CRT unit will not be usable when input/output is being redirected on the command-line. • For similar reasons they are not usable as CGI-scripts for use with a webserver. • The use of the CRT unit and the graph unit may not always be supported. • On LINUX or other unix OSes , executing other programs that expect special terminal behaviour (using one of the special functions in the linux unit) will not work. The terminal is set in RAW mode, which will destroy most terminal emulation settings. This chapter is divided in two sections. • The first section lists the pre-defined constants, types and variables. • The second section describes the functions which appear in the interface part of the CRT unit.

1.1

Types, Variables, Constants

Color definitions : Black = 0; Blue = 1; Green = 2; Cyan = 3; Red = 4; Magenta = 5; Brown = 6; 1 Current

e-mail address [email protected]

28

CHAPTER 1. THE CRT UNIT.

LightGray = 7; DarkGray = 8; LightBlue = 9; LightGreen = 10; LightCyan = 11; LightRed = 12; LightMagenta = 13; Yellow = 14; White = 15; Blink = 128; Miscellaneous constants TextAttr: Byte = $07; TextChar: Char = ’ ’; CheckBreak: Boolean = True; CheckEOF: Boolean = False; CheckSnow: Boolean = False; DirectVideo: Boolean = False; LastMode: Word = 3; WindMin: Word = $0; WindMax: Word = $184f; ScreenWidth = 80; ScreenHeight = 25; Some variables for compatibility with Turbo Pascal. However, they’re not used by Free Pascal. var checkbreak : boolean; checkeof : boolean; checksnow : boolean; The following constants define screen modes on a DOS system: Const bw40 co40 bw80 co80 mono

= = = = =

0; 1; 2; 3; 7;

The TextAttr variable controls the attributes with which characters are written to screen. var TextAttr : byte; The DirectVideo variable controls the writing to the screen. If it is True, the the cursor is set via direct port access. If False, then the BIOS is used. This is defined under DOS only. var DirectVideo : Boolean; The Lastmode variable tells you which mode was last selected for the screen. It is defined on DOS only. var lastmode : Word; 29

CHAPTER 1. THE CRT UNIT.

1.2

Procedures and Functions

AssignCrt Declaration: Procedure AssignCrt (Var F: Text); Description: AssignCrt Assigns a file F to the console. Everything written to the file F goes to the console instead. If the console contains a window, everything is written to the window instead. Errors: None. See also: Window (39) Listing: crtex/ex1.pp Program Example1 ; uses C r t ; { Program t o demonstrate t h e A s s i g n C r t f u n c t i o n . } var F : Text ; begin AssignCrt ( F ) ; Rewrite ( F ) ; { Don ’ t f o r g e t t o open f o r o u t p u t ! } WriteLn ( F , ’ T h i s i s w r i t t e n t o t h e Assigned F i l e ’ ) ; Close ( F ) ; end .

CursorBig Declaration: Procedure CursorBig ; Description: Makes the cursor a big rectangle. Not implemented on LINUX. Errors: None. See also: CursorOn (32), CursorOff (31)

ClrEol Declaration: Procedure ClrEol ; Description: ClrEol clears the current line, starting from the cursor position, to the end of the window. The cursor doesn’t move Errors: None. See also: DelLine (32), InsLine (34), ClrScr (31) Listing: crtex/ex9.pp Program Example9 ; uses C r t ; { Program t o demonstrate t h e C l r E o l f u n c t i o n . } var

30

CHAPTER 1. THE CRT UNIT.

I , J : integer ; begin For I : = 1 to 1 5 do For J : = 1 to 8 0 do begin gotoxy ( j , i ) ; Write ( j mod 1 0 ) ; end ; Window ( 5 , 5 , 7 5 , 1 2 ) ; Write ( ’ T h i s l i n e w i l l be c l e a r e d from ’ , ’ here t i l l t h e r i g h t o f t h e window ’ ) ; GotoXY ( 2 7 ,WhereY ) ; ReadKey ; ClrEol ; WriteLn ; end .

ClrScr Declaration: Procedure ClrScr ; Description: ClrScr clears the current window (using the current colors), and sets the cursor in the top left corner of the current window. Errors: None. See also: Window (39) Listing: crtex/ex8.pp Program Example8 ; uses C r t ; { Program t o demonstrate t h e C l r S c r f u n c t i o n . } begin W r i t e l n ( ’ Press any key t o c l e a r t h e screen ’ ) ; ReadKey ; ClrScr ; W r i t e l n ( ’ Have f u n w i t h t h e c l e a r e d screen ’ ) ; end .

CursorOff Declaration: Procedure CursorOff ; Description: Switches the cursor off (i.e. the cursor is no longer visible). Not implemented on LINUX. Errors: None. See also: CursorOn (32), CursorBig (30)

31

CHAPTER 1. THE CRT UNIT.

CursorOn Declaration: Procedure CursorOn ; Description: Switches the cursor on. Not implemented on LINUX. Errors: None. See also: CursorBig (30), CursorOff (31)

Delay Declaration: Procedure Delay (DTime:

Word);

Description: Delay waits a specified number of milliseconds. The number of specified seconds is an approximation, and may be off a lot, if system load is high. Errors: None See also: Sound (37), NoSound (35) Listing: crtex/ex15.pp Program Example15 ; uses C r t ; { Program t o demonstrate t h e Delay f u n c t i o n . } var i : longint ; begin WriteLn ( ’ Counting Down ’ ) ; f o r i : = 1 0 downto 1 do begin WriteLn ( i ) ; Delay ( 1 0 0 0 ) ; { Wait one second } end ; WriteLn ( ’BOOM ! ! ! ’ ) ; end .

DelLine Declaration: Procedure DelLine ; Description: DelLine removes the current line. Lines following the current line are scrolled 1 line up, and an empty line is inserted at the bottom of the current window. The cursor doesn’t move. Errors: None. See also: ClrEol (30), InsLine (34), ClrScr (31) Listing: crtex/ex11.pp Program Example10 ; uses C r t ; { Program t o demonstrate t h e I n s L i n e f u n c t i o n . } begin

32

CHAPTER 1. THE CRT UNIT.

ClrScr ; WriteLn ; WriteLn ( WriteLn ( WriteLn ( WriteLn ( WriteLn ; WriteLn (

’ Line ’ Line ’ Line ’ Line

1 2 2 3

’ ’ ’ ’

); ); ); );

’ Oops , L i n e 2 i s l i s t e d t w i c e , ’ , ’ l e t ’ ’ s delete the l i n e at the cursor postion ’ ) ; GotoXY ( 1 , 3 ) ; ReadKey ; DelLine ; GotoXY ( 1 , 1 0 ) ; end .

GotoXY Declaration: Procedure GotoXY (X: Byte; Y: Byte); Description: Positions the cursor at (X,Y), X in horizontal, Y in vertical direction relative to the origin of the current window. The origin is located at (1,1), the upper-left corner of the window. Errors: None. See also: WhereX (38), WhereY (38), Window (39) Listing: crtex/ex6.pp Program Example6 ; uses C r t ; { Program t o demonstrate t h e GotoXY f u n c t i o n . } begin ClrScr ; GotoXY ( 1 0 , 1 0 ) ; Write ( ’ 10 ,10 ’ ) ; GotoXY ( 7 0 , 2 0 ) ; Write ( ’ 70 ,20 ’ ) ; GotoXY ( 1 , 2 2 ) ; end .

HighVideo Declaration: Procedure HighVideo ; Description: HighVideo switches the output to highlighted text. (It sets the high intensity bit of the video attribute) Errors: None. See also: TextColor (37), TextBackground (37), LowVideo (35), NormVideo (35) Listing: crtex/ex14.pp

33

CHAPTER 1. THE CRT UNIT.

Program Example14 ; uses C r t ; { Program t o demonstrate t h e LowVideo , HighVideo , NormVideo f u n c t i o n s . } begin LowVideo ; WriteLn ( ’ T h i s i s w r i t t e n w i t h LowVideo ’ ) ; HighVideo ; WriteLn ( ’ T h i s i s w r i t t e n w i t h HighVideo ’ ) ; NormVideo ; WriteLn ( ’ T h i s i s w r i t t e n w i t h NormVideo ’ ) ; end .

InsLine Declaration: Procedure InsLine ; Description: InsLine inserts an empty line at the current cursor position. Lines following the current line are scrolled 1 line down, causing the last line to disappear from the window. The cursor doesn’t move. Errors: None. See also: ClrEol (30), DelLine (32), ClrScr (31) Listing: crtex/ex10.pp Program Example10 ; uses C r t ; { Program t o demonstrate t h e I n s L i n e f u n c t i o n . } begin ClrScr ; WriteLn ; WriteLn ( ’ L i n e 1 ’ ) ; WriteLn ( ’ L i n e 3 ’ ) ; WriteLn ; WriteLn ( ’ Oops , f o r g o t L i n e 2 , l e t ’ ’ s i n s e r t a t t h e c u r s o r p o s t i o n ’ ) ; GotoXY ( 1 , 3 ) ; ReadKey ; InsLine ; Write ( ’ L i n e 2 ’ ) ; GotoXY ( 1 , 1 0 ) ; end .

KeyPressed Declaration: Function KeyPressed :

Boolean;

Description: The Keypressed function scans the keyboard buffer and sees if a key has been pressed. If this is the case, True is returned. If not, False is returned. The Shift, Alt, Ctrl keys are not reported. The key is not removed from the buffer, and can hence still be read after the KeyPressed function has been called.

34

CHAPTER 1. THE CRT UNIT.

Errors: None. See also: ReadKey (36) Listing: crtex/ex2.pp Program Example2 ; uses C r t ; { Program t o demonstrate t h e KeyPressed f u n c t i o n . } begin WriteLn ( ’ W a i t i n g u n t i l a key i s pressed ’ ) ; repeat u n t i l KeyPressed ; { The key i s n o t Read , so i t should a l s o be o u t p u t t e d a t t h e commandline } end .

LowVideo Declaration: Procedure LowVideo ; Description: LowVideo switches the output to non-highlighted text. (It clears the high intensity bit of the video attribute) Errors: None. See also: TextColor (37), TextBackground (37), HighVideo (33), NormVideo (35) For an example, see HighVideo (33)

NormVideo Declaration: Procedure NormVideo ; Description: NormVideo switches the output to the defaults, read at startup. (The defaults are read from the cursor position at startup) Errors: None. See also: TextColor (37), TextBackground (37), LowVideo (35), HighVideo (33) For an example, see HighVideo (33)

NoSound Declaration: Procedure NoSound ; Description: Stops the speaker sound. This call is not supported on all operating systems. Errors: None. See also: Sound (37) Listing: crtex/ex16.pp 35

CHAPTER 1. THE CRT UNIT.

Program Example16 ; uses C r t ; { Program t o demonstrate t h e Sound and NoSound f u n c t i o n . } var i : longint ; begin WriteLn ( ’ You w i l l hear some tones from your speaker ’ ) ; while ( i 0 then WriteLn ( ’ − A r c h i v e ’ ) ; i f ( A t t r and d i r e c t o r y ) < >0 then WriteLn ( ’ − D i r e c t o r y ’ ) ; i f ( A t t r and r e a d o n l y ) < >0 then WriteLn ( ’ − Read−Only ’ ) ; i f ( A t t r and s y s f i l e ) < >0 then WriteLn ( ’ − System ’ ) ; i f ( A t t r and hidden ) < >0 then WriteLn ( ’ − Hidden ’ ) ; end .

GetFTime Declaration: Procedure GetFTime (var F; var Time:

longint);

Description: GetFTime returns the modification time of a file. This time is encoded and must be decoded with UnPackTime. F must be a file type, which has been assigned, and opened. Errors: Errors are reported in DosError See also: SetFTime (59), PackTime (57),UnPackTime (60) Listing: dosex/ex9.pp Program Example9 ; uses Dos ; { Program t o demonstrate t h e GetFTime f u n c t i o n . } Function L0 (w : word ) : s t r i n g ; var s : string ; begin S t r (w, s ) ; i f w0 then Assign ( f , ParamStr ( 1 ) ) else Assign ( f , ’ ex9 . pp ’ ) ; Reset ( f ) ; GetFTime ( f , Time ) ; Close ( f ) ; UnPackTime ( Time , DT ) ; Write ( ’ F i l e ’ , ParamStr ( 1 ) , ’ i s l a s t m o d i f i e d on ’ ) ;

54

CHAPTER 2. THE DOS UNIT.

W r i t e l n ( L0 (DT . Month ) , ’− ’ , L0 (DT . Day ) , ’− ’ ,DT . Year , ’ a t ’ , L0 (DT . Hour ) , ’ : ’ , L0 (DT . Min ) ) ; end .

GetIntVec Declaration: Procedure GetIntVec (IntNo:

byte; var Vector:

pointer);

Description: GetIntVec returns the address of interrupt vector IntNo. Portability: This call does nothing, it is present for compatibility only. Errors: None. See also: SetIntVec (59)

GetLongName Declaration: function GetLongName(var p :

String) :

boolean;

Description: This function is only implemented in the GO32V2 version of Free Pascal. GetLongName changes the filename p to a long filename if the DOS call to do this is successful. The resulting string is the long file name corresponding to the short filename p. The function returns True if the DOS call was successful, False otherwise. This function should only be necessary when using the DOS extender under Windows 95 and higher. Errors: If the DOS call was not succesfull, False is returned. See also: GetShortName (55)

GetShortName Declaration: function GetShortName(var p :

String) :

boolean;

Description: This function is only implemented in the GO32V2 version of Free Pascal. GetShortName changes the filename p to a short filename if the DOS call to do this is successful. The resulting string is the short file name corresponding to the long filename p. The function returns True if the DOS call was successful, False otherwise. This function should only be necessary when using the DOS extender under Windows 95 and higher. Errors: If the DOS call was not successful, False is returned. See also: GetLongName (55)

GetTime Declaration: Procedure GetTime (var hour, minute, second, sec100:

word);

Description: GetTime returns the system’s time. Hour is a on a 24-hour time scale. sec100 is in hundredth of a second. Portability: Certain operating systems (such as A MIGA), always set the sec100 field to zero. Errors: None. 55

CHAPTER 2. THE DOS UNIT.

See also: GetDate (52), SetTime (59) Listing: dosex/ex3.pp Program Example3 ; uses Dos ; { Program t o demonstrate t h e GetTime f u n c t i o n . } Function L0 (w : word ) : s t r i n g ; var s : string ; begin S t r (w, s ) ; i f w0 then w r i t e l n ( ’ With v a l u e : ’ , optarg ) else writeln end ; ’ a ’ : w r i t e l n ( ’ Option a . ’ ) ; ’ b ’ : w r i t e l n ( ’ Option b . ’ ) ; ’ c ’ : w r i t e l n ( ’ Option c : ’ , o p t a r g ) ; ’ d ’ : w r i t e l n ( ’ Option d : ’ , o p t a r g ) ; ’ ? ’ , ’ : ’ : writeln ( ’ Error with opt : ’ , optopt ) ; end ; { case } u n t i l c= e n d o f o p t i o n s ; i f o p t i n d 0 then write ( ’ r i g h t ’ ) ; i f ( b u t t o n s and Gpm_b_middle ) < >0 then Write ( ’ middle ’ ) ; Write ( ’ ) Event : ’ ) ; Case EventType and $F of GPM_MOVE : w r i t e ( ’ Move ’ ) ; GPM_DRAG : w r i t e ( ’ Drag ’ ) ; GPM_DOWN: w r i t e ( ’Down ’ ) ; GPM_UP : w r i t e ( ’ Up ’ ) ; end ; Writeln ; end ; U n t i l ( Event . B u t t o n s and gpm_b_right ) < >0; gpm_close ;

72

CHAPTER 6. THE GPM UNIT

end .

Gpm_GetLibVersion Declaration: function Gpm_GetLibVersion(var where:longint):pchar;cdecl;external; Description: Gpm_GetLibVersion returns a pointer to a version string, and returns in where an integer representing the version. The version string represents the version of the gpm library. The return value is a pchar, which should not be dealloacted, i.e. it is not on the heap. Errors: None. See also: Gpm_GetServerVersion (73)

Gpm_GetServerVersion Declaration: function Gpm_GetServerVersion(var where:longint):pchar;cdecl;external; Description: Gpm_GetServerVersion returns a pointer to a version string, and returns in where an integer representing the version. The version string represents the version of the gpm server program. The return value is a pchar, which should not be dealloacted, i.e. it is not on the heap. Errors: If the gpm program is not present, then the function returns Nil See also: Gpm_GetLibVersion (73)

Gpm_GetSnapshot Declaration: function Gpm_GetSnapshot(var Event:TGpmEvent):longint;cdecl;external; Description: Gpm_GetSnapshot returns the picture that the server has of the current situation in Event. This call will not read the current situation from the mouse file descriptor, but returns a buffered version. The meaning of the fields is as follows: x,ycurrent position of the cursor. dx,dysize of the window. vcnumber of te virtual console. modifierskeyboard shift state. buttonsbuttons which are currently pressed. clicksnumber of clicks (0,1 or 2). The function returns the number of mouse buttons, or -1 if this information is not available. Errors: None. See also: Gpm_GetEvent (72)

73

CHAPTER 6. THE GPM UNIT

Gpm_LowerRoi Declaration: function Gpm_LowerRoi(which:PGpmRoi; after:PGpmRoi):PGpmRoi;cdecl;external; Description: Gpm_LowerRoi lowers the region of interest which after after. If after is Nil, the region of interest is moved to the bottom of the stack. The return value is the new top of the region-of-interest stack. Errors: None. See also: Gpm_RaiseRoi (75), Gpm_PopRoi (74), Gpm_PushRoi (74)

Gpm_Open Declaration: function Gpm_Open(var Conn:TGpmConnect; Flag:longint):longint;cdecl;external; Description: Gpm_Open opens a new connection to the mouse server. The connection is described by the fields of the conn record: EventMaskA bitmask of the events the program wants to receive. DefaultMaskA bitmask to tell the library which events get their default treatment (text selection). minModthe minimum amount of modifiers needed by the program. maxModthe maximum amount of modifiers needed by the program. if Flag is 0, then the application only receives events that come from its own terminal device. If it is negative it will receive all events. If the value is positive then it is considered a console number to which to connect. The return value is -1 on error, or the file descriptor used to communicate with the client. Under an X-Term the return value is -2. Errors: On Error, the return value is -1. See also: Gpm_Open (74) for an example, see Gpm_GetEvent (72).

Gpm_PopRoi Declaration: function Gpm_PopRoi(which:PGpmRoi):PGpmRoi;cdecl;external; Description: Gpm_PopRoi pops the topmost region of interest from the stack. It returns the next element on the stack, or Nil if the current element was the last one. Errors: None. See also: Gpm_RaiseRoi (75), Gpm_LowerRoi (74), Gpm_PushRoi (74)

Gpm_PushRoi Declaration: function Gpm_PushRoi(x1:longint; y1:longint; X2:longint; Y2:longint; mask:longint; fun:TGpmHandler; xtradata:pointer):PGpmRoi;cdecl;external; Description: Gpm_PushRoi puts a new region of interest on the stack. The region of interest is defined by a rectangle described by the corners (X1,Y1) and (X2,Y2). The mask describes which events the handler fun will handle; ExtraData will be put in the xtradata field of the TGPM_Roi record passed to the fun handler. 74

CHAPTER 6. THE GPM UNIT

Errors: None. See also: Gpm_RaiseRoi (75), Gpm_PopRoi (74), Gpm_LowerRoi (74)

Gpm_RaiseRoi Declaration: function Gpm_RaiseRoi(which:PGpmRoi; before:PGpmRoi):PGpmRoi;cdecl;external; Description: Gpm_RaiseRoi raises the region of interest which till it is on top of region before. If before is nil then the region is put on top of the stack. The returned value is the top of the stack. Errors: None. See also: Gpm_PushRoi (74), Gpm_PopRoi (74), Gpm_LowerRoi (74)

Gpm_Repeat Declaration: function Gpm_Repeat(millisec:longint):longint;cdecl;external; Description: Gpm_Repeat returns 1 of no mouse event arrives in the next millisec miiliseconds, it returns 0 otherwise. Errors: None. See also: Gpm_GetEvent (72)

Gpm_StrictDouble Declaration: function Gpm_StrictDouble(EventType :

longint) :

boolean;

Description: Gpm_StrictDouble returns true if EventType contains only a doubleclick event, False otherwise. Errors: None. See also: Gpm_StrictSingle (75), Gpm_AnyTriple (71), Gpm_AnyDouble (70), Gpm_StrictTriple (76), Gpm_AnySingle (71)

Gpm_StrictSingle Declaration: function Gpm_StrictSingle(EventType :

longint) :

boolean;

Description: Gpm_StrictDouble returns True if EventType contains only a singleclick event, False otherwise. Errors: None. See also: Gpm_AnyTriple (71), Gpm_StrictDouble (75), Gpm_AnyDouble (70), Gpm_StrictTriple (76), Gpm_AnySingle (71)

75

CHAPTER 6. THE GPM UNIT

Gpm_StrictTriple Declaration: function Gpm_StrictTriple(EventType :

longint) :

boolean;

Description: Gpm_StrictTriple returns true if EventType contains only a triple click event, False otherwise. Errors: None. See also: Gpm_AnyTriple (71), Gpm_StrictDouble (75), Gpm_AnyDouble (70), Gpm_StrictSingle (75), Gpm_AnySingle (71)

76

Chapter 7

The GO32 unit This chapter of the documentation describe the GO32 unit for the Free Pascal compiler under DOS. It was donated by Thomas Schatzl ([email protected]), for which my thanks. This unit was first written for DOS by Florian Kl"ampfl. This chapter is divided in four sections. The first two sections are an introduction to the GO32 unit. The third section lists the pre-defined constants, types and variables. The last section describes the functions which appear in the interface part of the GO32 unit.

7.1

Introduction

These docs contain information about the GO32 unit. Only the GO32V2 DPMI mode is discussed by me here due to the fact that new applications shouldn’t be created with the older GO32V1 model. The go32v2 version is much more advanced and better. Additionally a lot of functions only work in DPMI mode anyway. I hope the following explanations and introductions aren’t too confusing at all. If you notice an error or bug send it to the FPC mailing list or directly to me. So let’s get started and happy and error free coding I wish you.... Thomas Schatzl, 25. August 1998

7.2

Protected mode memory organization

What is DPMI The DOS Protected Mode Interface helps you with various aspects of protected mode programming. These are roughly divided into descriptor handling, access to DOS memory, management of interrupts and exceptions, calls to real mode functions and other stuff. Additionally it automatically provides swapping to disk for memory intensive applications. A DPMI host (either a Windows DOS box or CWSDPMI.EXE) provides these functions for your programs.

Selectors and descriptors Descriptors are a bit like real mode segments; they describe (as the name implies) a memory area in protected mode. A descriptor contains information about segment length, its base address and the attributes of it (i.e. type, access rights, ...). These descriptors are stored internally in a so-called descriptor table, which is basically an array of such descriptors. Selectors are roughly an index into this table. Because these ’segments’ can be up to 4 GB in size, 32 bits aren’t sufficient anymore to describe a single memory location like in real mode. 48 bits are now needed to do this, a 32 bit address and a 16 bit sized selector. The GO32 unit provides the tseginfo record to store such a 77

CHAPTER 7. THE GO32 UNIT

pointer. But due to the fact that most of the time data is stored and accessed in the %ds selector, FPC assumes that all pointers point to a memory location of this selector. So a single pointer is still only 32 bits in size. This value represents the offset from the data segment base address to this memory location.

FPC specialities The %ds and %es selector MUST always contain the same value or some system routines may crash when called. The %fs selector is preloaded with the DOSMEMSELECTOR variable at startup, and it MUST be restored after use, because again FPC relys on this for some functions. Luckily we asm programmers can still use the %gs selector for our own purposes, but for how long ? See also: get_cs (93), get_ds (93), gett_ss (100), allocate_ldt_descriptors (86), free_ldt_descriptor (92), segment_to_descriptor (106), get_next_selector_increment_value (95), get_segment_base_address (99), set_segment_base_address (109), set_segment_limit (109), create_code_segment_alias_descriptor (89)

DOS

memory access

DOS memory is accessed by the predefined dosmemselector selector; the GO32 unit additionally provides some functions to help you with standard tasks, like copying memory from heap to DOS memory and the likes. Because of this it is strongly recommened to use them, but you are still free to use the provided standard memory accessing functions which use 48 bit pointers. The third, but only thought for compatibility purposes, is using the mem[]-arrays. These arrays map the whole 1 Mb DOS space. They shouldn’t be used within new programs. To convert a segment:offset real mode address to a protected mode linear address you have to multiply the segment by 16 and add its offset. This linear address can be used in combination with the DOSMEMSELECTOR variable. See also: dosmemget (91), dosmemput (91), dosmemmove (91), dosmemfillchar (89), dosmemfillword (90), mem[]-arrays, seg_move (107), seg_fillchar (105), seg_fillword (106).

I/O port access The I/O port access is done via the various inportb (102), outportb (104) functions which are available. Additionally Free Pascal supports the Turbo Pascal PORT[]-arrays but it is by no means recommened to use them, because they’re only for compatibility purposes. See also: outportb (104), inportb (102), PORT[]-arrays

Processor access These are some functions to access various segment registers (%cs, %ds, %ss) which makes your work a bit easier. See also: get_cs (93), get_ds (93), get_ss (100)

Interrupt redirection Interrupts are program interruption requests, which in one or another way get to the processor; there’s a distinction between software and hardware interrupts. The former are explicitely called by an ’int’ instruction and are a bit comparable to normal functions. Hardware interrupts come from external devices like the keyboard or mouse. Functions that handle hardware interrupts are called handlers.

78

CHAPTER 7. THE GO32 UNIT

Handling interrupts with DPMI The interrupt functions are real-mode procedures; they normally can’t be called in protected mode without the risk of an protection fault. So the DPMI host creates an interrupt descriptor table for the application. Initially all software interrupts (except for int 31h, 2Fh and 21h function 4Ch) or external hardware interrupts are simply directed to a handler that reflects the interrupt in real-mode, i.e. the DPMI host’s default handlers switch the CPU to real-mode, issue the interrupt and switch back to protected mode. The contents of general registers and flags are passed to the real mode handler and the modified registers and flags are returned to the protected mode handler. Segment registers and stack pointer are not passed between modes.

Protected mode interrupts vs. Real mode interrupts As mentioned before, there’s a distinction between real mode interrupts and protected mode interrupts; the latter are protected mode programs, while the former must be real mode programs. To call a protected mode interrupt handler, an assembly ’int’ call must be issued, while the other is called via the realintr() or intr() function. Consequently, a real mode interrupt then must either reside in DOS memory ( # 1 3 ) do begin ch : = readkey ; w r i t e ( ch ) ; end ; remove_click ; end .

Software interrupts Ordinarily, a handler installed with set_pm_interrupt (107) only services software interrupts that are executed in protected mode; real mode software interrupts can be redirected by set_rm_interrupt (108). See also set_rm_interrupt (108), get_rm_interrupt (98), set_pm_interrupt (107), get_pm_interrupt (95), lock_data (103), lock_code (103), enable (92), disable (89), outportb (104) Executing software interrupts Simply execute a realintr() call with the desired interrupt number and the supplied register data structure. But some of these interrupts require you to supply them a pointer to a buffer where they can store data to or obtain data from in memory. These interrupts are real mode functions and so they only can access the first Mb of linear address space, not FPC’s data segment. For this reason FPC supplies a pre-initialized DOS memory location within the GO32 unit. This buffer is internally used for DOS functions too and so it’s contents may change when calling other procedures. It’s size can be obtained with tb_size (109) and it’s linear address via transfer_buffer (110). Another way is to allocate a completely new DOS memory area via the global_dos_alloc (100) function for your use and supply its real mode address. See also: tb_size (109), transfer_buffer (110). global_dos_alloc (100), global_dos_free (102), realintr (105) The following examples illustrate the use of software interrupts. Listing: go32ex/softint.pp uses go32 ; var r : trealregs ; begin r . ah : = $30 ; r . a l : = $01 ; r e a l i n t r ( $21 , r ) ; W r i t e l n ( ’DOS v ’ , r . a l , ’ . ’ , r . ah , ’ d e t e c t e d ’ ) ; end .

81

CHAPTER 7. THE GO32 UNIT

Listing: go32ex/rmpmint.pp uses crt , go32 ; var r : trealregs ; axreg : Word ; oldint21h : tseginfo ; newint21h : t s e g i n f o ; procedure i n t 2 1 h _ h a n d l e r ; assembler ; asm cmpw $0x3001 , % ax jne . LCallOld movw $0x3112 , % ax iret . LCallOld : l j m p %cs : o l d i n t 2 1 h end ; procedure resume ; begin Writeln ; Write ( ’−− press any key t o resume −− ’ ) ; readkey ; gotoxy ( 1 , wherey ) ; c l r e o l ; end ; begin clrscr ; W r i t e l n ( ’ E x e c u t i n g r e a l mode i n t e r r u p t ’ ) ; resume ; r . ah : = $30 ; r . a l : = $01 ; r e a l i n t r ( $21 , r ) ; W r i t e l n ( ’DOS v ’ , r . a l , ’ . ’ , r . ah , ’ d e t e c t e d ’ ) ; resume ; W r i t e l n ( ’ E x e c u t i n g p r o t e c t e d mode i n t e r r u p t w i t h o u t our own ’ , ’ handler ’ ) ; Writeln ; asm movb $0x30 , % ah movb $0x01 , % a l i n t $0x21 movw %ax , axreg end ; W r i t e l n ( ’DOS v ’ , r . a l , ’ . ’ , r . ah , ’ d e t e c t e d ’ ) ; resume ; W r i t e l n ( ’ As you can see t h e DPMI h o s t s d e f a u l t p r o t e c t e d mode ’ , ’ handler ’ ) ; W r i t e l n ( ’ s i m p l y r e d i r e c t s i t t o t h e r e a l mode h a n d l e r ’ ) ; resume ; W r i t e l n ( ’Now exchanging t h e p r o t e c t e d mode i n t e r r u p t w i t h our ’ , ’ own h a n d l e r ’ ) ; resume ; newint21h . o f f s e t : = @int21h_handler ; newint21h . segment : = get_cs ; g e t _ p m _ i n t e r r u p t ( $21 , o l d i n t 2 1 h ) ;

82

CHAPTER 7. THE GO32 UNIT

s e t _ p m _ i n t e r r u p t ( $21 , newint21h ) ; W r i t e l n ( ’ E x e c u t i n g r e a l mode i n t e r r u p t again ’ ) ; resume ; r . ah : = $30 ; r . a l : = $01 ; r e a l i n t r ( $21 , r ) ; W r i t e l n ( ’DOS v ’ , r . a l , ’ . ’ , r . ah , ’ d e t e c t e d ’ ) ; Writeln ; W r i t e l n ( ’ See , i t d i d n ’ ’ t change i n any way . ’ ) ; resume ; W r i t e l n ( ’Now c a l l i n g p r o t e c t e d mode i n t e r r u p t ’ ) ; resume ; asm movb $0x30 , % ah movb $0x01 , % a l i n t $0x21 movw %ax , axreg end ; W r i t e l n ( ’DOS v ’ , l o ( axreg ) , ’ . ’ , h i ( axreg ) , ’ d e t e c t e d ’ ) ; Writeln ; W r i t e l n ( ’Now you can see t h a t t h e r e ’ ’ s a d i s t i n c t i o n between ’ , ’ t h e two ways o f c a l l i n g i n t e r r u p t s . . . ’ ) ; s e t _ p m _ i n t e r r u p t ( $21 , o l d i n t 2 1 h ) ; end .

Real mode callbacks The callback mechanism can be thought of as the converse of calling a real mode procedure (i.e. interrupt), which allows your program to pass information to a real mode program, or obtain services from it in a manner that’s transparent to the real mode program. In order to make a real mode callback available, you must first get the real mode callback address of your procedure and the selector and offset of a register data structure. This real mode callback address (this is a segment:offset address) can be passed to a real mode program via a software interrupt, a DOS memory block or any other convenient mechanism. When the real mode program calls the callback (via a far call), the DPMI host saves the registers contents in the supplied register data structure, switches into protected mode, and enters the callback routine with the following settings: • interrupts disabled • %CS:%EIP = 48 bit pointer specified in the original call to get_rm_callback (96) • %DS:%ESI = 48 bit pointer to to real mode SS:SP • %ES:%EDI = 48 bit pointer of real mode register data structure. • %SS:%ESP = locked protected mode stack • All other registers undefined The callback procedure can then extract its parameters from the real mode register data structure and/or copy parameters from the real mode stack to the protected mode stack. Recall that the segment register fields of the real mode register data structure contain segment or paragraph addresses that are not valid in protected mode. Far pointers passed in the real mode register data structure must be translated to virtual addresses before they can be used with a protected mode program. The callback procedure exits by executing an IRET with the address of the real mode register data structure in %ES:%EDI, passing information back to the real mode caller by modifying the contents of the real mode register data structure and/or manipulating the contents of the real mode stack. The callback 83

CHAPTER 7. THE GO32 UNIT

procedure is responsible for setting the proper address for resumption of real mode execution into the real mode register data structure; typically, this is accomplished by extracting the return address from the real mode stack and placing it into the %CS:%EIP fields of the real mode register data structure. After the IRET, the DPMI host switches the CPU back into real mode, loads ALL registers with the contents of the real mode register data structure, and finally returns control to the real mode program. All variables and code touched by the callback procedure MUST be locked to prevent page faults. See also: get_rm_callback (96), free_rm_callback (92), lock_code (103), lock_data (103)

7.3

Types, Variables and Constants

Constants Constants returned by get_run_mode Tells you under what memory environment (e.g. memory manager) the program currently runs. rm_unknown rm_raw rm_xms rm_vcpi rm_dpmi

= = = = =

0; 1; 2; 3; 4;

{ { { { {

unknown } raw (without HIMEM) } XMS (for example with HIMEM, without EMM386) } VCPI (for example HIMEM and EMM386) } DPMI (for example \dos box or 386Max) }

Note: GO32V2 always creates DPMI programs, so you need a suitable DPMI host like CWSDPMI.EXE or a Windows DOS box. So you don’t need to check it, these constants are only useful in GO32V1 mode. Processor flags constants They are provided for a simple check with the flags identifier in the trealregs type. To check a single flag, simply do an AND operation with the flag you want to check. It’s set if the result is the same as the flag value. const carryflag parityflag auxcarryflag zeroflag signflag trapflag interruptflag directionflag overflowflag

= = = = = = = = =

$001; $004; $010; $040; $080; $100; $200; $400; $800;

Predefined types type tmeminfo = record available_memory : Longint; available_pages : Longint; available_lockable_pages : Longint; linear_space : Longint; unlocked_pages : Longint; available_physical_pages : Longint; total_physical_pages : Longint; 84

CHAPTER 7. THE GO32 UNIT

free_linear_space : Longint; max_pages_in_paging_file : Longint; reserved : array[0..2] of Longint; end; Holds information about the memory allocation, etc. NOTE: The value of a field is -1 (0ffffffffh) if Table 7.1: Record description Record entry available_memory available_pages available_lockable_pages linear_space unlocked_pages available_physical_pages total_physical_pages free_linear_space max_pages_in_paging_file

Description Largest available free block in bytes. Maximum unlocked page allocation in pages Maximum locked page allocation in pages. Linear address space size in pages. Total number of unlocked pages. Total number of free pages. Total number of physical pages. Free linear address space in pages. Size of paging file/partition in pages.

the value is unknown, it’s only guaranteed, that available_memory contains a valid value. The size of the pages can be determined by the get_page_size() function. type trealregs = record case Integer of 1: { 32-bit } (EDI, ESI, EBP, Res, EBX, EDX, ECX, EAX: Longint; Flags, ES, DS, FS, GS, IP, CS, SP, SS: Word); 2: { 16-bit } (DI, DI2, SI, SI2, BP, BP2, R1, R2: Word; BX, BX2, DX, DX2, CX, CX2, AX, AX2: Word); 3: { 8-bit } (stuff: array[1..4] of Longint; BL, BH, BL2, BH2, DL, DH, DL2, DH2, CL, CH, CL2, CH2, AL, AH, AL2, AH2: Byte); 4: { Compat } (RealEDI, RealESI, RealEBP, RealRES, RealEBX, RealEDX, RealECX, RealEAX: Longint; RealFlags, RealES, RealDS, RealFS, RealGS, RealIP, RealCS, RealSP, RealSS: Word); end; registers = trealregs; These two types contain the data structure to pass register values to a interrupt handler or real mode callback. type tseginfo = record offset : Pointer; segment : Word; end; This record is used to store a full 48-bit pointer. This may be either a protected mode selector:offset address or in real mode a segment:offset address, depending on application. See also: Selectors and descriptors, DOS memory access, Interrupt redirection 85

CHAPTER 7. THE GO32 UNIT

Variables. var dosmemselector : Word; Selector to the DOS memory. The whole DOS memory is automatically mapped to this single descriptor at startup. This selector is the recommened way to access DOS memory. var int31error : Word; This variable holds the result of a DPMI interrupt call. Any nonzero value must be treated as a critical failure.

7.4

Functions and Procedures

allocate_ldt_descriptors Declaration: Function allocate_ldt_descriptors (count :

Word) :

Word;

Description: Allocates a number of new descriptors. Parameters: count: specifies the number of requested unique descriptors. Return value: The base selector. Notes: The descriptors allocated must be initialized by the application with other function calls. This function returns descriptors with a limit and size value set to zero. If more than one descriptor was requested, the function returns a base selector referencing the first of a contiguous array of descriptors. The selector values for subsequent descriptors in the array can be calculated by adding the value returned by the get_next_selector_increment_value (95) function. Errors: Check the int31error variable. See also: free_ldt_descriptor (92), get_next_selector_increment_value (95), segment_to_descriptor (106), create_code_segment_alias_descriptor (89), set_segment_limit (109), set_segment_base_address (109) Listing: go32ex/seldes.pp { $mode d e l p h i } uses crt , go32 ; const maxx = 8 0 ; maxy = 2 5 ; bytespercell = 2; s c r e e n s i z e = maxx ∗ maxy ∗ b y t e s p e r c e l l ; l i n B 8 0 0 0 = $B800 ∗ 1 6 ; type string80 = string [ 8 0 ] ; var t e x t _ s a v e : array [ 0 . . s c r e e n s i z e −1] of b y t e ; t e x t _ o l d x , t e x t _ o l d y : Word ; t e x t _ s e l : Word ;

86

CHAPTER 7. THE GO32 UNIT

procedure s t a t u s ( s : s t r i n g 8 0 ) ; begin gotoxy ( 1 , 1 ) ; c l r e o l ; w r i t e ( s ) ; readkey ; end ; procedure s e l i n f o ( s e l : Word ) ; begin gotoxy ( 1 , 2 4 ) ; c l r e o l ; w r i t e l n ( ’ D e s c r i p t o r base address : $ ’ , h e x s t r ( get_segment_base_address ( s e l ) , 8 ) ) ; clreol ; write ( ’ Descriptor l i m i t : ’ , get_segment_limit ( sel ) ) ; end ; function makechar ( ch : char ; c o l o r : b y t e ) : Word ; begin r e s u l t : = b y t e ( ch ) or ( c o l o r shl 8 ) ; end ; begin seg_move ( dosmemselector , linB8000 , get_ds , l o n g i n t ( @text_save ) , screensize ) ; t e x t _ o l d x : = wherex ; t e x t _ o l d y : = wherey ; s e g _ f i l l w o r d ( dosmemselector , linB8000 , s c r e e n s i z e div 2 , makechar ( ’ ’ , Black or ( Black shl 4 ) ) ) ; status ( ’ Creating selector ’ ’ t e x t _ s e l ’ ’ to a part of ’ + ’ t e x t screen memory ’ ) ; text_sel : = allocate_ldt_descriptors (1); set_segment_base_address ( t e x t _ s e l , l i n B 8 0 0 0 + b y t e s p e r c e l l ∗ maxx ∗ 1 ) ; set_segment_limit ( text_sel , screensize − 1 − bytespercell ∗ maxx ∗ 3 ) ; selinfo ( text_sel ) ; s t a t u s ( ’ and c l e a r i n g e n t i r e memory s e l e c t e d by ’ ’ t e x t _ s e l ’ ’ ’ + ’ descriptor ’ ) ; s e g _ f i l l w o r d ( t e x t _ s e l , 0 , ( g e t _ s e g m e n t _ l i m i t ( t e x t _ s e l ) + 1 ) div 2 , makechar ( ’ ’ , L i g h t B l u e shl 4 ) ) ; s t a t u s ( ’ N o t i c e t h a t o n l y t h e memory d e s c r i b e d by t h e ’ + ’ d e s c r i p t o r changed , n o t h i n g e l s e ’ ) ; s t a t u s ( ’Now r e d u c i n g i t ’ ’ s l i m i t and base and s e t t i n g i t ’ ’ s ’ + ’ d e s c r i b e d memory ’ ) ; set_segment_base_address ( t e x t _ s e l , get_segment_base_address ( t e x t _ s e l ) + b y t e s p e r c e l l ∗ maxx ) ; set_segment_limit ( text_sel , g e t _ s e g m e n t _ l i m i t ( t e x t _ s e l ) − b y t e s p e r c e l l ∗ maxx ∗ 2 ) ; selinfo ( text_sel ) ; s t a t u s ( ’ N o t i c e t h a t t h e base addr i n c r e a s e d by one l i n e b u t ’ + ’ t h e l i m i t decreased by 2 l i n e s ’ ) ; s t a t u s ( ’ T h i s should g i v e you t h e h i n t t h a t t h e l i m i t i s ’ + ’ r e l a t i v e t o t h e base ’ ) ; s e g _ f i l l w o r d ( t e x t _ s e l , 0 , ( g e t _ s e g m e n t _ l i m i t ( t e x t _ s e l ) + 1 ) div 2 , makechar ( # 1 7 6 , LightMagenta or Brown shl 4 ) ) ; s t a t u s ( ’Now l e t ’ ’ s g e t c r a z y and copy 1 0 l i n e s o f data from ’ + ’ t h e p r e v i o u s l y saved screen ’ ) ;

87

CHAPTER 7. THE GO32 UNIT

seg_move ( get_ds , l o n g i n t ( @text_save ) , t e x t _ s e l , maxx ∗ b y t e s p e r c e l l ∗ 2 , maxx ∗ b y t e s p e r c e l l ∗ 1 0 ) ; s t a t u s ( ’ At l a s t f r e e i n g t h e d e s c r i p t o r and r e s t o r i n g t h e o l d ’ + ’ screen c o n t e n t s . . ’ ) ; s t a t u s ( ’ I hope t h i s l i t t l e program may g i v e you some h i n t s on ’ + ’ working w i t h d e s c r i p t o r s ’ ) ; free_ldt_descriptor ( text_sel ) ; seg_move ( get_ds , l o n g i n t ( @text_save ) , dosmemselector , linB8000 , s c r e e n s i z e ) ; gotoxy ( t e x t _ o l d x , t e x t _ o l d y ) ; end .

allocate_memory_block Declaration: Function allocate_memory_block (size:Longint) :

Longint;

Description: Allocates a block of linear memory. Parameters: size: Size of requested linear memory block in bytes. Returned values: blockhandle - the memory handle to this memory block. Linear address of the requested memory. Notes: WARNING: According to my DPMI docs this function is not implemented correctly. Normally you should also get a blockhandle to this block after successful operation. This handle can then be used to free the memory block afterwards or use this handle for other purposes. Since the function isn’t implemented correctly, and doesn’t return a blockhandle, the block can’t be deallocated and is hence unusuable ! This function doesn’t allocate any descriptors for this block, it’s the applications resposibility to allocate and initialize for accessing this memory. Errors: Check the int31error variable. See also: free_memory_block (92)

copyfromdos Declaration: Procedure copyfromdos (var addr; len :

Longint);

Description: Copies data from the pre-allocated DOS memory transfer buffer to the heap. Parameters: addr: data to copy to. len: number of bytes to copy to heap. Notes: Can only be used in conjunction with the DOS memory transfer buffer. Errors: Check the int31error variable. See also: tb_size (109), transfer_buffer (110), copytodos (88)

copytodos Declaration: Procedure copytodos (var addr; len :

Longint);

Description: Copies data from heap to the pre-allocated DOS memory buffer. Parameters: addr: data to copy from. len: number of bytes to copy to DOS memory buffer. 88

CHAPTER 7. THE GO32 UNIT

Notes: This function fails if you try to copy more bytes than the transfer buffer is in size. It can only be used in conjunction with the transfer buffer. Errors: Check the int31error variable. See also: tb_size (109), transfer_buffer (110), copyfromdos (88)

create_code_segment_alias_descriptor Declaration: Function create_code_segment_alias_descriptor (seg :

Word) :

Word;

Description: Creates a new descriptor that has the same base and limit as the specified descriptor. Parameters: seg: Descriptor. Return values: The data selector (alias). Notes: In effect, the function returns a copy of the descriptor. The descriptor alias returned by this function will not track changes to the original descriptor. In other words, if an alias is created with this function, and the base or limit of the original segment is then changed, the two descriptors will no longer map the same memory. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), set_segment_limit (109), set_segment_base_address (109)

disable Declaration: Procedure disable ; Description: Disables all hardware interrupts by execution a CLI instruction. Parameters: None. Errors: None. See also: enable (92)

dosmemfillchar Declaration: Procedure dosmemfillchar (seg, ofs :

Word; count :

Longint; c :

Description: Sets a region of DOS memory to a specific byte value. Parameters: seg: real mode segment. ofs: real mode offset. count: number of bytes to set. c: value to set memory to. Notes: No range check is performed. Errors: None. See also: dosmemput (91), dosmemget (91), dosmemmove (91)dosmemmove, dosmemfillword (90), seg_move (107), seg_fillchar (105), seg_fillword (106) Listing: go32ex/textmess.pp

89

char);

CHAPTER 7. THE GO32 UNIT

uses crt , go32 ; const columns = 8 0 ; rows = 2 5 ; s c r e e n s i z e = rows ∗ columns ∗ 2 ; t e x t = ’ ! Hello world ! ’ ; var t e x t o f s : Longint ; save_screen : array [ 0 . . s c r e e n s i z e −1] of b y t e ; curx , c u r y : I n t e g e r ; begin randomize ; dosmemget ( $B800 , 0 , save_screen , s c r e e n s i z e ) ; c u r x : = wherex ; c u r y : = wherey ; gotoxy ( 1 , 1 ) ; Write ( t e x t ) ; t e x t o f s : = s c r e e n s i z e + length ( t e x t ) ∗ 2 ; dosmemmove ( $B800 , 0 , $B800 , t e x t o f s , length ( t e x t ) ∗ 2 ) ; d o s m e m f i l l c h a r ( $B800 , 0 , s c r e e n s i z e , # 0 ) ; while ( not keypressed ) do begin d o s m e m f i l l c h a r ( $B800 , t e x t o f s + random ( length ( t e x t ) ) ∗ 2 + 1 , 1 , char ( random ( 2 5 5 ) ) ) ; dosmemmove ( $B800 , t e x t o f s , $B800 , random ( columns )∗2+random ( rows ) ∗ columns ∗2 , length ( t e x t ) ∗ 2 ) ; delay ( 1 ) ; end ; readkey ; readkey ; dosmemput ( $B800 , 0 , save_screen , s c r e e n s i z e ) ; gotoxy ( curx , c u r y ) ; end .

dosmemfillword Declaration: Procedure dosmemfillword (seg,ofs :

Word; count :

Longint; w :

Word);

Description: Sets a region of DOS memory to a specific word value. Parameters: seg: real mode segment. ofs: real mode offset. count: number of words to set. w: value to set memory to. Notes: No range check is performed. Errors: None. See also: dosmemput (91), dosmemget (91), dosmemmove (91), dosmemfillchar (89), seg_move (107), seg_fillchar (105), seg_fillword (106)

90

CHAPTER 7. THE GO32 UNIT

dosmemget Declaration: Procedure dosmemget (seg :

Word; ofs :

Word; var data; count :

Longint);

Description: Copies data from the DOS memory onto the heap. Parameters: seg: source real mode segment. ofs: source real mode offset. data: destination. count: number of bytes to copy. Notes: No range checking is performed. Errors: None. See also: dosmemput (91), dosmemmove (91), dosmemfillchar (89), dosmemfillword (90), seg_move (107), seg_fillchar (105), seg_fillword (106) For an example, see global_dos_alloc (100).

dosmemmove Declaration: Procedure dosmemmove (sseg, sofs, dseg, dofs :

Word; count :

Longint);

Description: Copies count bytes of data between two DOS real mode memory locations. Parameters: sseg: source real mode segment. sofs: source real mode offset. dseg: destination real mode segment. dofs: destination real mode offset. count: number of bytes to copy. Notes: No range check is performed in any way. Errors: None. See also: dosmemput (91), dosmemget (91), dosmemfillchar (89), dosmemfillword (90) seg_move (107), seg_fillchar (105), seg_fillword (106) For an example, see seg_fillchar (105).

dosmemput Declaration: Procedure dosmemput (seg :

Word; ofs :

Word; var data; count :

Longint);

Description: Copies heap data to DOS real mode memory. Parameters: seg: destination real mode segment. ofs: destination real mode offset. data: source. count: number of bytes to copy. Notes: No range checking is performed. Errors: None. See also: dosmemget (91), dosmemmove (91), dosmemfillchar (89), dosmemfillword (90), seg_move (107), seg_fillchar (105), seg_fillword (106) For an example, see global_dos_alloc (100). 91

CHAPTER 7. THE GO32 UNIT

enable Declaration: Procedure enable ; Description: Enables all hardware interrupts by executing a STI instruction. Parameters: None. Errors: None. See also: disable (89)

free_ldt_descriptor Declaration: Function free_ldt_descriptor (des :

Word) :

boolean;

Description: Frees a previously allocated descriptor. Parameters: des: The descriptor to be freed. Return value: True if successful, False otherwise. Notes: After this call this selector is invalid and must not be used for any memory operations anymore. Each descriptor allocated with allocate_ldt_descriptors (86) must be freed individually with this function, even if it was previously allocated as a part of a contiguous array of descriptors. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), get_next_selector_increment_value (95) For an example, see allocate_ldt_descriptors (86).

free_memory_block Declaration: Function free_memory_block (blockhandle :

Longint) :

boolean;

Description: Frees a previously allocated memory block. Parameters: blockhandle: the handle to the memory area to free. Return value: True if successful, false otherwise. Notes: Frees memory that was previously allocated with allocate_memory_block (88) . This function doesn’t free any descriptors mapped to this block, it’s the application’s responsibility. Errors: Check int31error variable. See also: allocate_memory_block (88)

free_rm_callback Declaration: Function free_rm_callback (var intaddr :

tseginfo) :

boolean;

Description: Releases a real mode callback address that was previously allocated with the get_rm_callback (96) function. Parameters: intaddr: real mode address buffer returned by get_rm_callback (96) . Return values: True if successful, False if not Errors: Check the int31error variable. See also: set_rm_interrupt (108), get_rm_callback (96) For an example, see get_rm_callback (96). 92

CHAPTER 7. THE GO32 UNIT

get_cs Declaration: Function get_cs :

Word;

Description: Returns the cs selector. Parameters: None. Return values: The content of the cs segment register. Errors: None. See also: get_ds (93), get_ss (100) For an example, see set_pm_interrupt (107).

get_descriptor_access_rights Declaration: Function get_descriptor_access_rights (d :

Word) :

Longint;

Description: Gets the access rights of a descriptor. Parameters: d selector to descriptor. Return value: Access rights bit field. Errors: Check the int31error variable. See also: set_descriptor_access_rights (107)

get_ds Declaration: Function get_ds :

Word;

Description: Returns the ds selector. Parameters: None. Return values: The content of the ds segment register. Errors: None. See also: get_cs (93), get_ss (100)

get_linear_addr Declaration: Function get_linear_addr (phys_addr :

Longint; size :

Longint) :

Description: Converts a physical address into a linear address. Parameters: phys_addr: physical address of device. size: Size of region to map in bytes. Return value: Linear address that can be used to access the physical memory. Notes: It’s the applications resposibility to allocate and set up a descriptor for access to the memory. This function shouldn’t be used to map real mode addresses. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), set_segment_limit (109), set_segment_base_address (109)

93

Longint;

CHAPTER 7. THE GO32 UNIT

get_meminfo Declaration: Function get_meminfo (var meminfo :

tmeminfo) :

boolean;

Description: Returns information about the amount of available physical memory, linear address space, and disk space for page swapping. Parameters: meminfo: buffer to fill memory information into. Return values: Due to an implementation bug this function always returns False, but it always succeeds. Notes: Only the first field of the returned structure is guaranteed to contain a valid value. Any fields that are not supported by the DPMI host will be set by the host to -1 (0FFFFFFFFH) to indicate that the information is not available. The size of the pages used by the DPMI host can be obtained with the get_page_size (95) function. Errors: Check the int31error variable. See also: get_page_size (95) Listing: go32ex/meminfo.pp uses go32 ; var meminfo : tmeminfo ; begin get_meminfo ( meminfo ) ; i f ( i n t 3 1 e r r o r < > 0 ) then begin W r i t e l n ( ’ E r r o r g e t t i n g DPMI memory i n f o r m a t i o n . . . H a l t i n g ’ ) ; W r i t e l n ( ’ DPMI e r r o r number : ’ , i n t 3 1 e r r o r ) ; end else begin with meminfo do begin Writeln ( ’ Largest a v a i l a b l e f r e e block : ’ , available_memory div 1 0 2 4 , ’ k b y t e s ’ ) ; i f ( a v a i l a b l e _ p a g e s < > −1) then W r i t e l n ( ’ Maximum a v a i l a b l e unlocked pages : ’ , available_pages ) ; i f ( a v a i l a b l e _ l o c k a b l e _ p a g e s < > −1) then W r i t e l n ( ’ Maximum l o c k a b l e a v a i l a b l e pages : ’ , available_lockable_pages ) ; i f ( l i n e a r _ s p a c e < > −1) then W r i t e l n ( ’ L i n e a r address space s i z e : ’ , l i n e a r _ s p a c e ∗ get_page_size div 1 0 2 4 , ’ k b y t e s ’ ) ; i f ( unlocked_pages < > −1) then W r i t e l n ( ’ T o t a l number o f unlocked pages : ’ , unlocked_pages ) ; i f ( a v a i l a b l e _ p h y s i c a l _ p a g e s < > −1) then W r i t e l n ( ’ T o t a l number o f f r e e pages : ’ , available_physical_pages ) ; i f ( t o t a l _ p h y s i c a l _ p a g e s < > −1) then W r i t e l n ( ’ T o t a l number o f p h y s i c a l pages : ’ , total_physical_pages ) ; i f ( f r e e _ l i n e a r _ s p a c e < > −1) then W r i t e l n ( ’ Free l i n e a r address space : ’ , f r e e _ l i n e a r _ s p a c e ∗ get_page_size div 1 0 2 4 , ’ kbytes ’ ) ; i f ( m ax_p ages _in_ pagin g_fi le < > −1) then W r i t e l n ( ’ Maximum s i z e o f paging f i l e : ’ ,

94

CHAPTER 7. THE GO32 UNIT

max _pag es_i n_pag ing_ file ∗ get_page_size div 1 0 2 4 , ’ kbytes ’ ) ; end ; end ; end .

get_next_selector_increment_value Declaration: Function get_next_selector_increment_value :

Word;

Description: Returns the selector increment value when allocating multiple subsequent descriptors via allocate_ldt_descriptors (86). Parameters: None. Return value: Selector increment value. Notes: Because allocate_ldt_descriptors (86) only returns the selector for the first descriptor and so the value returned by this function can be used to calculate the selectors for subsequent descriptors in the array. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), free_ldt_descriptor (92)

get_page_size Declaration: Function get_page_size :

Longint;

Description: Returns the size of a single memory page. Return value: Size of a single page in bytes. Notes: The returned size is typically 4096 bytes. Errors: Check the int31error variable. See also: get_meminfo (94) For an example, see get_meminfo (94).

get_pm_interrupt Declaration: Function get_pm_interrupt (vector : : boolean;

byte; var intaddr :

tseginfo)

Description: Returns the address of a current protected mode interrupt handler. Parameters: vector: interrupt handler number you want the address to. intaddr: buffer to store address. Return values: True if successful, False if not. Notes: The returned address is a protected mode selector:offset address. Errors: Check the int31error variable. See also: set_pm_interrupt (107), set_rm_interrupt (108), get_rm_interrupt (98) For an example, see set_pm_interrupt (107).

95

CHAPTER 7. THE GO32 UNIT

get_rm_callback Declaration: Function get_rm_callback (pm_func : var rmcb: tseginfo) : boolean;

pointer; const reg :

trealregs;

Description: Returns a unique real mode segment:offset address, known as a "real mode callback," that will transfer control from real mode to a protected mode procedure. Parameters: pm_func: pointer to the protected mode callback function. reg: supplied registers structure. rmcb: buffer to real mode address of callback function. Return values: True if successful, otherwise False. Notes: Callback addresses obtained with this function can be passed by a protected mode program for example to an interrupt handler, device driver, or TSR, so that the real mode program can call procedures within the protected mode program or notify the protected mode program of an event. The contents of the supplied regs structure is not valid after function call, but only at the time of the actual callback. Errors: Check the int31error variable. See also: free_rm_callback (92) Listing: go32ex/callback.pp {$ASMMODE ATT } {$MODE FPC} uses crt , go32 ; const mouseint = $33 ; var mouse_regs : t r e a l r e g s ; e x t e r n a l name ’ ___v2prt0_rmcb_regs ’ ; mouse_seginfo : t s e g i n f o ; var mouse_numbuttons : l o n g i n t ; mouse_action : word ; mouse_x , mouse_y : Word ; mouse_b : Word ; u s e r p r o c _ i n s t a l l e d : Longbool ; userproc_length : Longint ; userproc_proc : p o i n t e r ; procedure c a l l b a c k _ h a n d l e r ; assembler ; asm pushw %ds p u s h l %eax movw %es , % ax movw %ax , % ds cmpl $1 , USERPROC_INSTALLED j n e . LNoCallback pushal

96

CHAPTER 7. THE GO32 UNIT

movw DOSmemSELECTOR, % ax movw %ax , % f s c a l l ∗USERPROC_PROC popal . LNoCallback : p o p l %eax popw %ds p u s h l %eax movl (% e s i ) , % eax movl %eax , % es : 4 2 ( % e d i ) addw $4 , % es :46(% e d i ) p o p l %eax iret end ; procedure mouse_dummy ; begin end ; procedure t e x t u s e r p r o c ; begin mouse_b : = mouse_regs . bx ; mouse_x : = ( mouse_regs . cx shr 3 ) + 1 ; mouse_y : = ( mouse_regs . dx shr 3 ) + 1 ; end ; procedure i n s t a l l _ m o u s e ( u s e r p r o c : p o i n t e r ; u s e r p r o c l e n : l o n g i n t ) ; var r : t r e a l r e g s ; begin r . eax : = $0 ; r e a l i n t r ( mouseint , r ) ; i f ( r . eax < > $FFFF ) then begin W r i t e l n ( ’ No M i c r o s o f t c o m p a t i b l e mouse found ’ ) ; W r i t e l n ( ’A M i c r o s o f t c o m p a t i b l e mouse d r i v e r i s necessary ’ , ’ t o run t h i s example ’ ) ; halt ; end ; i f ( r . bx = $ f f f f ) then mouse_numbuttons : = 2 else mouse_numbuttons : = r . bx ; W r i t e l n ( mouse_numbuttons , ’ b u t t o n M i c r o s o f t c o m p a t i b l e mouse ’ , ’ found . ’ ) ; i f ( u s e r p r o c < > n i l ) then begin userproc_proc : = userproc ; userproc_installed : = true ; userproc_length : = userproclen ; lock_code ( userproc_proc , u s e r p r o c _ l e n g t h ) ; end else begin userproc_proc : = n i l ; userproc_length : = 0 ; userproc_installed : = false ; end ; l o c k _ d a t a ( mouse_x , s i z e o f ( mouse_x ) ) ; l o c k _ d a t a ( mouse_y , s i z e o f ( mouse_y ) ) ; l o c k _ d a t a ( mouse_b , s i z e o f ( mouse_b ) ) ; l o c k _ d a t a ( mouse_action , s i z e o f ( mouse_action ) ) ; lock_data ( userproc_installed , sizeof ( us er pro c_ ins ta lle d ) ) ; l o c k _ d a t a ( userproc_proc , s i z e o f ( u s er p ro c _p r oc ) ) ; l o c k _ d a t a ( mouse_regs , s i z e o f ( mouse_regs ) ) ;

97

CHAPTER 7. THE GO32 UNIT

l o c k _ d a t a ( mouse_seginfo , s i z e o f ( mouse_seginfo ) ) ; lock_code ( @callback_handler , l o n g i n t (@mouse_dummy)− l o n g i n t ( @callback_handler ) ) ; g e t _ r m _ c a l l b a c k ( @callback_handler , mouse_regs , mouse_seginfo ) ; r . eax : = $0c ; r . ecx : = $ 7 f ; r . edx : = l o n g i n t ( mouse_seginfo . o f f s e t ) ; r . es : = mouse_seginfo . segment ; r e a l i n t r ( mouseint , r ) ; r . eax : = $01 ; r e a l i n t r ( mouseint , r ) ; end ; procedure remove_mouse ; var r : trealregs ; begin r . eax : = $02 ; r e a l i n t r ( mouseint , r ) ; r . eax : = $0c ; r . ecx : = 0 ; r . edx : = 0 ; r . es : = 0 ; r e a l i n t r ( mouseint , r ) ; f r e e _ r m _ c a l l b a c k ( mouse_seginfo ) ; i f ( u s e r p r o c _ i n s t a l l e d ) then begin unlock_code ( userproc_proc , u s e r p r o c _ l e n g t h ) ; userproc_proc : = n i l ; userproc_length : = 0 ; userproc_installed : = false ; end ; u n l o c k _ d a t a ( mouse_x , s i z e o f ( mouse_x ) ) ; u n l o c k _ d a t a ( mouse_y , s i z e o f ( mouse_y ) ) ; u n l o c k _ d a t a ( mouse_b , s i z e o f ( mouse_b ) ) ; u n l o c k _ d a t a ( mouse_action , s i z e o f ( mouse_action ) ) ; u n l o c k _ d a t a ( userproc_proc , s i z e o f ( u s er p ro c _p r oc ) ) ; unlock_data ( u s e r p r o c _ i n s t a l l e d , sizeof ( u s e r p r o c _ i n s t a l l e d ) ) ; u n l o c k _ d a t a ( mouse_regs , s i z e o f ( mouse_regs ) ) ; u n l o c k _ d a t a ( mouse_seginfo , s i z e o f ( mouse_seginfo ) ) ; unlock_code ( @callback_handler , l o n g i n t (@mouse_dummy)− l o n g i n t ( @callback_handler ) ) ; f i l l c h a r ( mouse_seginfo , s i z e o f ( mouse_seginfo ) , 0 ) ; end ;

begin i n s t a l l _ m o u s e ( @textuserproc , 4 0 0 ) ; W r i t e l n ( ’ Press any key t o e x i t . . . ’ ) ; while ( not keypressed ) do begin gotoxy ( 1 , wherey ) ; w r i t e ( ’ MouseX : ’ , mouse_x : 2 , ’ MouseY : ’ B u t t o n s : ’ , mouse_b : 2 ) ; end ; remove_mouse ;

’ , mouse_y : 2 ,

end .

get_rm_interrupt Declaration: Function get_rm_interrupt (vector : : boolean; 98

byte; var intaddr :

tseginfo)

CHAPTER 7. THE GO32 UNIT

Description: Returns the contents of the current machine’s real mode interrupt vector for the specified interrupt. Parameters: vector: interrupt vector number. intaddr: buffer to store real mode segment:offset address. Return values: True if successful, False otherwise. Notes: The returned address is a real mode segment address, which isn’t valid in protected mode. Errors: Check the int31error variable. See also: set_rm_interrupt (108), set_pm_interrupt (107), get_pm_interrupt (95)

get_run_mode Declaration: Function get_run_mode :

Word;

Description: Returns the current mode your application runs with. Return values: One of the constants used by this function. Errors: None. See also: constants returned by get_run_mode (99) Listing: go32ex/getrunmd.pp uses go32 ; begin case ( get_run_mode ) of rm_unknown : W r i t e l n ( ’ Unknown environment found ’ ) ; rm_raw : W r i t e l n ( ’ You are c u r r e n t l y r u n n i n g i n raw mode ’ , ’ ( w i t h o u t HIMEM) ’ ) ; rm_xms : W r i t e l n ( ’ You are c u r r e n t l y u s i n g HIMEM . SYS o n l y ’ ) ; rm_vcpi : W r i t e l n ( ’ VCPI s e r v e r d e t e c t e d . You ’ ’ r e u s i n g HIMEM and ’ , ’EMM386 ’ ) ; rm_dpmi : W r i t e l n ( ’ DPMI d e t e c t e d . You ’ ’ r e u s i n g a DPMI h o s t l i k e ’ , ’ a windows DOS box o r CWSDPMI ’ ) ; end ; end .

get_segment_base_address Declaration: Function get_segment_base_address (d :

Word) :

Longint;

Description: Returns the 32-bit linear base address from the descriptor table for the specified segment. Parameters: d: selector of the descriptor you want the base address of. Return values: Linear base address of specified descriptor. 99

CHAPTER 7. THE GO32 UNIT

Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), set_segment_base_address (109), allocate_ldt_descriptors (86), set_segment_limit (109), get_segment_limit (100) For an example, see allocate_ldt_descriptors (86).

get_segment_limit Declaration: Function get_segment_limit (d :

Word) :

Longint;

Description: Returns a descriptors segment limit. Parameters: d: selector. Return value: Limit of the descriptor in bytes. Errors: Returns zero if descriptor is invalid. See also: allocate_ldt_descriptors (86), set_segment_limit (109), set_segment_base_address (109), get_segment_base_address (99),

get_ss Declaration: Function get_ss :

Word;

Description: Returns the ss selector. Parameters: None. Return values: The content of the ss segment register. Errors: None. See also: get_ds (93), get_cs (93)

global_dos_alloc Declaration: Function global_dos_alloc (bytes :

Longint) :

Longint;

Description: Allocates a block of DOS real mode memory. Parameters: bytes: size of requested real mode memory. Return values: The low word of the returned value contains the selector to the allocated DOS memory block, the high word the corresponding real mode segment value. The offset value is always zero. This function allocates memory from DOS memory pool, i.e. memory below the 1 MB boundary that is controlled by DOS. Such memory blocks are typically used to exchange data with real mode programs, TSRs, or device drivers. The function returns both the real mode segment base address of the block and one descriptor that can be used by protected mode applications to access the block. This function should only used for temporary buffers to get real mode information (e.g. interrupts that need a data structure in ES:(E)DI), because every single block needs an unique selector. The returned selector should only be freed by a global_dos_free (102) call. Errors: Check the int31error variable. See also: global_dos_free (102) Listing: go32ex/buffer.pp

100

CHAPTER 7. THE GO32 UNIT

uses go32 ; procedure d o s a l l o c ( var s e l e c t o r : word ; var segment : word ; s i z e : l o n g i n t ) ; var res : l o n g i n t ; begin res : = global_dos_alloc ( size ) ; s e l e c t o r : = word ( r e s ) ; segment : = word ( r e s shr 1 6 ) ; end ; procedure d o s f r e e ( s e l e c t o r : word ) ; begin global_dos_free ( selector ) ; end ; type VBEInfoBuf = packed record S i g n a t u r e : array [ 0 . . 3 ] of char ; V e r s i o n : Word ; r e s e r v e d : array [ 0 . . 5 0 5 ] of b y t e ; end ; var selector , segment : Word ; r : trealregs ; i n f o b u f : VBEInfoBuf ; begin f i l l c h a r ( r , sizeof ( r ) , 0 ) ; f i l l c h a r ( i n f o b u f , s i z e o f ( VBEInfoBuf ) , 0 ) ; d o s a l l o c ( s e l e c t o r , segment , s i z e o f ( VBEInfoBuf ) ) ; i f ( i n t 3 1 e r r o r < >0) then begin W r i t e l n ( ’ E r r o r w h i l e a l l o c a t i n g r e a l mode memory , h a l t i n g ’ ) ; halt ; end ; i n f o b u f . S i g n a t u r e : = ’VBE2 ’ ; dosmemput ( segment , 0 , i n f o b u f , s i z e o f ( i n f o b u f ) ) ; r . ax : = $4f00 ; r . es : = segment ; r e a l i n t r ( $10 , r ) ; dosmemget ( segment , 0 , i n f o b u f , s i z e o f ( i n f o b u f ) ) ; dosfree ( s e l e c t o r ) ; i f ( r . ax < > $ 4 f ) then begin W r i t e l n ( ’VBE BIOS e x t e n s i o n n o t a v a i l a b l e , f u n c t i o n c a l l ’ , ’ failed ’ ); halt ; end ; i f ( i n f o b u f . s i g n a t u r e [ 0 ] = ’V ’ ) and ( i n f o b u f . s i g n a t u r e [ 1 ] = ’E ’ ) and ( i n f o b u f . s i g n a t u r e [ 2 ] = ’S ’ ) and ( i n f o b u f . s i g n a t u r e [ 3 ] = ’A ’ ) then begin W r i t e l n ( ’VBE v e r s i o n ’ , h i ( i n f o b u f . v e r s i o n ) , ’ . ’ , lo ( i n f o b u f . version ) , ’ detected ’ ) ; end ;

101

CHAPTER 7. THE GO32 UNIT

end .

global_dos_free Declaration: Function global_dos_free (selector :Word) :

boolean;

Description: Frees a previously allocated DOS memory block. Parameters: selector: selector to the DOS memory block. Return value: True if successful, False otherwise. Notes: The descriptor allocated for the memory block is automatically freed and hence invalid for further use. This function should only be used for memory allocated by global_dos_alloc (100). Errors: Check the int31error variable. See also: global_dos_alloc (100) For an example, see global_dos_alloc (100).

inportb Declaration: Function inportb (port :

Word) :

byte;

Description: Reads 1 byte from the selected I/O port. Parameters: port: the I/O port number which is read. Return values: Current I/O port value. Errors: None. See also: outportb (104), inportw (102), inportl (102)

inportl Declaration: Function inportl (port :

Word) :

Longint;

Description: Reads 1 longint from the selected I/O port. Parameters: port: the I/O port number which is read. Return values: Current I/O port value. Errors: None. See also: outportb (104), inportb (102), inportw (102)

inportw Declaration: Function inportw (port :

Word) :

Word;

Description: Reads 1 word from the selected I/O port. Parameters: port: the I/O port number which is read. Return values: Current I/O port value. Errors: None. See also: outportw (104) inportb (102), inportl (102) 102

CHAPTER 7. THE GO32 UNIT

lock_code Declaration: Function lock_code (functionaddr :

pointer; size :

Longint) :

boolean;

Description: Locks a memory range which is in the code segment selector. Parameters: functionaddr: address of the function to be locked. size: size in bytes to be locked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: lock_linear_region (103), lock_data (103), unlock_linear_region (110), unlock_data (110), unlock_code (110) For an example, see get_rm_callback (96).

lock_data Declaration: Function lock_data (var data; size :

Longint) :

boolean;

Description: Locks a memory range which resides in the data segment selector. Parameters: data: address of data to be locked. size: length of data to be locked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: lock_linear_region (103), lock_code (103), unlock_linear_region (110), unlock_data (110), unlock_code (110) For an example, see get_rm_callback (96).

lock_linear_region Declaration: Function lock_linear_region (linearaddr, size :

Longint) :

boolean;

Description: Locks a memory region to prevent swapping of it. Parameters: linearaddr: the linear address of the memory are to be locked. size: size in bytes to be locked. Return value: True if successful, False otherwise. Errors: Check the int31error variable. See also: lock_data (103), lock_code (103), unlock_linear_region (110), unlock_data (110), unlock_code (110)

103

CHAPTER 7. THE GO32 UNIT

outportb Declaration: Procedure outportb (port :

Word; data :

byte);

Description: Sends 1 byte of data to the specified I/O port. Parameters: port: the I/O port number to send data to. data: value sent to I/O port. Return values: None. Errors: None. See also: inportb (102), outportl (104), outportw (104) Listing: go32ex/outport.pp uses crt , go32 ; begin o u t p o r t b ( $61 , $ f f ) ; delay ( 5 0 ) ; o u t p o r t b ( $61 , $0 ) ; end .

outportl Declaration: Procedure outportl (port :

Word; data :

Longint);

Description: Sends 1 longint of data to the specified I/O port. Parameters: port: the I/O port number to send data to. data: value sent to I/O port. Return values: None. Errors: None. See also: inportl (102), outportw (104), outportb (104) For an example, see outportb (104).

outportw Declaration: Procedure outportw (port :

Word; data :

Description: Sends 1 word of data to the specified I/O port. Parameters: port: the I/O port number to send data to. data: value sent to I/O port. Return values: None. Errors: None. See also: inportw (102), outportl (104), outportb (104) For an example, see outportb (104). 104

Word);

CHAPTER 7. THE GO32 UNIT

realintr Declaration: Function realintr (intnr:

Word; var regs :

trealregs) :

boolean;

Description: Simulates an interrupt in real mode. Parameters: intnr: interrupt number to issue in real mode. regs: registers data structure. Return values: The supplied registers data structure contains the values that were returned by the real mode interrupt. True if successful, False if not. Notes: The function transfers control to the address specified by the real mode interrupt vector of intnr. The real mode handler must return by executing an IRET. Errors: Check the int31error variable. See also: Listing: go32ex/flags.pp uses go32 ; var r : trealregs ; begin r . ax : = $5300 ; r . bx : = 0 ; r e a l i n t r ( $15 , r ) ; i f ( ( r . f l a g s and c a r r y f l a g ) = 0 ) then begin W r i t e l n ( ’APM v ’ , ( r . ah and $ f ) , ’ . ’ , ( r . a l shr 4 ) , ( r . a l and $ f ) , ’ d e t e c t e d ’ ) ; end else W r i t e l n ( ’APM n o t p r e s e n t ’ ) ; end .

seg_fillchar Declaration: Procedure seg_fillchar (seg : c : char);

Word; ofs :

Longint; count :

Longint;

Description: Sets a memory area to a specific value. Parameters: seg: selector to memory area. ofs: offset to memory. count: number of bytes to set. c: byte data which is set. Return values: None. Notes: No range check is done in any way. Errors: None. See also: seg_move (107), seg_fillword (106), dosmemfillchar (89), dosmemfillword (90), dosmemget (91), dosmemput (91), dosmemmove (91) Listing: go32ex/vgasel.pp 105

CHAPTER 7. THE GO32 UNIT

uses go32 ; var v g a s e l : Word ; r : trealregs ; begin r . eax : = $13 ; r e a l i n t r ( $10 , r ) ; v g a s e l : = s e g m e n t _ t o _ d e s c r i p t o r ( $A000 ) ; s e g _ f i l l c h a r ( vgasel , 0 , 6 4 0 0 0 , # 1 5 ) ; readln ; r . eax : = $3 ; r e a l i n t r ( $10 , r ) ; end .

seg_fillword Declaration: Procedure seg_fillword (seg : w :Word);

Word; ofs :

Longint; count :

Longint;

Description: Sets a memory area to a specific value. Parameters: seg: selector to memory area. ofs: offset to memory. count: number of words to set. w: word data which is set. Return values: None. Notes: No range check is done in any way. Errors: None. See also: seg_move (107), seg_fillchar (105), dosmemfillchar (89), dosmemfillword (90), dosmemget (91), dosmemput (91), dosmemmove (91) For an example, see allocate_ldt_descriptors (86).

segment_to_descriptor Declaration: Function segment_to_descriptor (seg :

Word) :

Word;

Description: Maps a real mode segment (paragraph) address onto an descriptor that can be used by a protected mode program to access the same memory. Parameters: seg: the real mode segment you want the descriptor to. Return values: Descriptor to real mode segment address. Notes: The returned descriptors limit will be set to 64 kB. Multiple calls to this function with the same segment address will return the same selector. Descriptors created by this function can never be modified or freed. Programs which need to examine various real mode addresses using the same selector should use the function allocate_ldt_descriptors (86) and change the base address as necessary. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), free_ldt_descriptor (92), set_segment_base_address (109) For an example, see seg_fillchar (105). 106

CHAPTER 7. THE GO32 UNIT

seg_move Declaration: Procedure seg_move (sseg : Word; source : : Longint; count : Longint);

Longint; dseg :

Word; dest

Description: Copies data between two memory locations. Parameters: sseg: source selector. source: source offset. dseg: destination selector. dest: destination offset. count: size in bytes to copy. Return values: None. Notes: Overlapping is only checked if the source selector is equal to the destination selector. No range check is done. Errors: None. See also: seg_fillchar (105), seg_fillword (106), dosmemfillchar (89), dosmemfillword (90), dosmemget (91), dosmemput (91), dosmemmove (91) For an example, see allocate_ldt_descriptors (86).

set_descriptor_access_rights Declaration: Function set_descriptor_access_rights (d :

Word; w :

Word) :

Longint;

Description: Sets the access rights of a descriptor. Parameters: d: selector. w: new descriptor access rights. Return values: This function doesn’t return anything useful. Errors: Check the int31error variable. See also: get_descriptor_access_rights (93)

set_pm_interrupt Declaration: Function set_pm_interrupt (vector : : boolean;

byte; const intaddr :

tseginfo)

Description: Sets the address of the protected mode handler for an interrupt. Parameters: vector: number of protected mode interrupt to set. intaddr: selector:offset address to the interrupt vector. Return values: True if successful, False otherwise. Notes: The address supplied must be a valid selector:offset protected mode address. Errors: Check the int31error variable. See also: get_pm_interrupt (95), set_rm_interrupt (108), get_rm_interrupt (98) Listing: go32ex/intpm.pp 107

CHAPTER 7. THE GO32 UNIT

uses crt , go32 ; const i n t 1 c = $1c ; var oldint1c : tseginfo ; newint1c : t s e g i n f o ; int1c_counter : Longint ; i n t 1 c _ d s : Word ; e x t e r n a l name ’ _ _ _ v 2 p r t 0 _ d s _ a l i a s ’ ; procedure i n t 1 c _ h a n d l e r ; assembler ; asm cli pushw %ds pushw %ax movw %cs : i n t 1 c _ d s , % ax movw %ax , % ds i n c l int1c_counter popw %ax popw %ds sti iret end ; var i : L o n g i n t ; begin newint1c . o f f s e t : = @int1c_handler ; newint1c . segment : = get_cs ; get_pm_interrupt ( int1c , oldint1c ) ; W r i t e l n ( ’−− Press any key t o e x i t −− ’ ) ; s e t _ p m _ i n t e r r u p t ( i n t 1 c , newint1c ) ; while ( not keypressed ) do begin gotoxy ( 1 , wherey ) ; w r i t e ( ’ Number o f i n t e r r u p t s occured : end ; set_pm_interrupt ( int1c , oldint1c ) ;

’ , int1c_counter ) ;

end .

set_rm_interrupt Declaration: Function set_rm_interrupt (vector : : boolean;

byte; const intaddr :

tseginfo)

Description: Sets a real mode interrupt handler. Parameters: vector: the interrupt vector number to set. intaddr: address of new interrupt vector. Return values: True if successful, otherwise False. Notes: The address supplied MUST be a real mode segment address, not a selector:offset address. So the interrupt handler must either 108

CHAPTER 7. THE GO32 UNIT

reside in DOS memory (below 1 Mb boundary) or the application must allocate a real mode callback address with get_rm_callback (96). Errors: Check the int31error variable. See also: get_rm_interrupt (98), set_pm_interrupt (107), get_pm_interrupt (95), get_rm_callback (96)

set_segment_base_address Declaration: Function set_segment_base_address (d :

Word; s :

Longint) :

boolean;

Description: Sets the 32-bit linear base address of a descriptor. Parameters: d: selector. s: new base address of the descriptor. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), get_segment_base_address (99), allocate_ldt_descriptors (86), set_segment_limit (109), get_segment_base_address (99), get_segment_limit (100)

set_segment_limit Declaration: Function set_segment_limit (d :

Word; s :

Longint) :

boolean;

Description: Sets the limit of a descriptor. Parameters: d: selector. s: new limit of the descriptor. Return values: Returns True if successful, else False. Notes: The new limit specified must be the byte length of the segment - 1. Segment limits bigger than or equal to 1MB must be page aligned, they must have the lower 12 bits set. Errors: Check the int31error variable. See also: allocate_ldt_descriptors (86), set_segment_base_address (109), get_segment_limit (100), set_segment_limit (109) For an example, see allocate_ldt_descriptors (86).

tb_size Declaration: Function tb_size :

Longint;

Description: Returns the size of the pre-allocated DOS memory buffer. Parameters: None. Return values: The size of the pre-allocated DOS memory buffer. Notes: This block always seems to be 16k in size, but don’t rely on this. Errors: None. See also: transfer_buffer (110), copyfromdos (88) copytodos (88)

109

CHAPTER 7. THE GO32 UNIT

transfer_buffer Declaration: Function transfer_buffer :

Longint;

Description: transfer_buffer returns the offset of the transfer buffer. Errors: None. See also: tb_size (109)

unlock_code Declaration: Function unlock_code (functionaddr :

pointer; size :

Longint) :

boolean;

Description: Unlocks a memory range which resides in the code segment selector. Parameters: functionaddr: address of function to be unlocked. size: size bytes to be unlocked. Return value: True if successful, False otherwise. Errors: Check the int31error variable. See also: unlock_linear_region (110), unlock_data (110), lock_linear_region (103), lock_data (103), lock_code (103) For an example, see get_rm_callback (96).

unlock_data Declaration: Function unlock_data (var data; size :

Longint) :

boolean;

Description: Unlocks a memory range which resides in the data segment selector. Paramters: data: address of memory to be unlocked. size: size bytes to be unlocked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: unlock_linear_region (110), unlock_code (110), lock_linear_region (103), lock_data (103), lock_code (103) For an example, see get_rm_callback (96).

unlock_linear_region Declaration: Function unlock_linear_region (linearaddr, size :

Longint) :

boolean;

Description: Unlocks a previously locked linear region range to allow it to be swapped out again if needed. Parameters: linearaddr: linear address of the memory to be unlocked. size: size bytes to be unlocked. Return values: True if successful, False otherwise. 110

CHAPTER 7. THE GO32 UNIT

Errors: Check the int31error variable. See also: unlock_data (110), unlock_code (110), lock_linear_region (103), lock_data (103), lock_code (103)

111

Chapter 8

The GRAPH unit. This document describes the GRAPH unit for Free Pascal, for all platforms. The unit was first written for DOS by Florian klämpfl, but was later completely rewritten by Carl-Eric Codere to be completely portable. The unit is provided for compatibility only: It is recommended to use more modern graphical systems. The graph unit will allow to recompile old programs, they will work to some extent, but if the application has heavy graphical needs, it’s recommended to use another set of graphical routines, suited to the platform the program should work on. This chapter is divided in 4 sections. • The first section gives an introduction to the graph unit. • The second section lists the pre-defined constants, types and variables. • The second section describes the functions which appear in the interface part of the GRAPH unit. • The last part describes some system-specific issues.

8.1

Introduction

Requirements The unit Graph exports functions and procedures for graphical output. It requires at least a VGAcompatible Card or a VGA-Card with software-driver (min. 512Kb video memory).

A word about mode selection The graph unit was implemented for compatibility with the old Turbo Pascal graph unit. For this reason, the mode constants as they were defined in the Turbo Pascal graph unit are retained. However, since 1. Video cards have evolved very much 2. Free Pascal runs on multiple platforms it was decided to implement new mode and graphic driver constants, which are more independent of the specific platform the program runs on. In this section we give a short explanation of the new mode system. the following drivers were defined: 112

CHAPTER 8. THE GRAPH UNIT.

D1bit = 11; D2bit = 12; D4bit = 13; D6bit = 14; D8bit = 15; D12bit = 16; D15bit = 17; D16bit = 18; D24bit = 19; D32bit = 20; D64bit = 21;

{ 64 colors Half-brite mode - Amiga } { 4096 color modes HAM mode - Amiga }

{ not yet supported } { not yet supported } { not yet supported }

lowNewDriver = 11; highNewDriver = 21; Each of these drivers specifies a desired color-depth. The following modes have been defined: detectMode = 30000; m320x200 = 30001; m320x256 = 30002; { m320x400 = 30003; { m512x384 = 30004; { m640x200 = 30005; { m640x256 = 30006; { m640x350 = 30007; { m640x400 = 30008; m640x480 = 30009; m800x600 = 30010; m832x624 = 30011; { m1024x768 = 30012; m1280x1024 = 30013; m1600x1200 = 30014; m2048x1536 = 30015;

amiga resolution (PAL) } amiga/atari resolution } mac resolution } vga resolution } amiga resolution (PAL) } vga resolution }

mac resolution }

lowNewMode = 30001; highNewMode = 30015; These modes start at 30000 because Borland specified that the mode number should be ascending with increasing X resolution, and the new constants shouldn’t interfere with the old ones. The above constants can be used to set a certain color depth and resultion, as demonstrated in the following example: Listing: graphex/inigraph1.pp Program i n i g r a p h 1 ; { Program t o demonstrate s t a t i c g r a p h i c s mode s e l e c t i o n } uses graph ;

const TheLine = ’We are now i n 6 4 0 x 4 8 0 x 2 5 6 c o l o r s ! ’ + ’ ( press < Return > t o c o n t i n u e ) ’ ;

113

CHAPTER 8. THE GRAPH UNIT.

var gd , gm , lo , hi , e r r o r , tw , t h : i n t e g e r ; found : boolean ; begin { We want an 8 b i t mode } gd : = D 8 b i t ; gm : = m640x480 ; i n i t g r a p h ( gd , gm, ’ ’ ) ; { Make sure you always check g r a p h r e s u l t ! } e r r o r : = graphResult ; i f ( e r r o r < > grOk ) Then begin w r i t e l n ( ’ 640x480x256 i s n o t supported ! ’ ) ; halt (1) end ; { We are now i n 640 x480x256 } s e t C o l o r ( cyan ) ; r e c t a n g l e ( 0 , 0 , getmaxx , getmaxy ) ; { W r i t e a n i c e message i n t h e c e n t e r o f t h e screen } setTextStyle ( defaultFont , horizDir , 1 ) ; tw : = TextWidth ( TheLine ) ; t h : = T e x t H e i g h t ( TheLine ) ; outTextXY ( ( getMaxX − TW) div 2 , ( getMaxY − TH ) div 2 , TheLine ) ; { Wait f o r r e t u r n } readln ; { Back t o t e x t mode } closegraph ; end .

If other modes than the ones above are supported by the graphics card, you will not be able to select them with this mechanism. For this reason, there is also a ’dynamic’ mode number, which is assigned at run-time. This number increases with increasing X resolution. It can be queried with the getmoderange call. This call will return the range of modes which are valid for a certain graphics driver. The numbers are guaranteed to be consecutive, and can be used to search for a certain resolution, as in the following example: Listing: graphex/inigraph2.pp Program i n i g r a p h 2 ; { Program t o demonstrate dynamic g r a p h i c s mode s e l e c t i o n } uses graph ; const TheLine = ’We are now i n 6 4 0 x 4 8 0 x 2 5 6 c o l o r s ! ’ + ’ ( press < Return > t o c o n t i n u e ) ’ ; var th , tw , gd , gm , lo , hi , e r r o r : i n t e g e r ; found : boolean ; begin { We want an 8 b i t mode }

114

CHAPTER 8. THE GRAPH UNIT.

gd : = D 8 b i t ; { Get a l l a v a i l a b l e r e s o l u t i o n s f o r t h i s b i t d e p t h } getmoderange ( gd , lo , h i ) ; { I f t h e h i g h e s t a v a i l a b l e mode number i s −1 , no r e s o l u t i o n s are supported f o r t h i s b i t d e p t h } i f h i = − 1 then begin w r i t e l n ( ’ no 8 b i t modes supported ! ’ ) ; halt end ; found : = f a l s e ; { Search a l l r e s o l u t i o n s f o r 640 x480 } f o r gm : = l o to h i do begin i n i t g r a p h ( gd , gm, ’ ’ ) ; { Make sure you always check g r a p h r e s u l t ! } e r r o r : = graphResult ; i f ( e r r o r = grOk ) and ( getmaxx = 6 3 9 ) and ( getmaxy = 4 7 9 ) then begin found : = t r u e ; break ; end ; end ; i f not found then begin w r i t e l n ( ’ 640x480x256 i s n o t supported ! ’ ) ; halt (1) end ; { We are now i n 640 x480x256 } s e t C o l o r ( cyan ) ; r e c t a n g l e ( 0 , 0 , getmaxx , getmaxy ) ; { W r i t e a n i c e message i n t h e c e n t e r o f t h e screen } setTextStyle ( defaultFont , horizDir , 1 ) ; TW: = TextWidth ( TheLine ) ; TH: = T e x t H e i g h t ( TheLine ) ; outTextXY ( ( getMaxX − TW) div 2 , ( getMaxY − TH ) div 2 , TheLine ) ; { Wait f o r r e t u r n } readln ; { Back t o t e x t mode } closegraph ; end .

Thus, the getmoderange function can be used to detect all available modes and drivers, as in the following example: Listing: graphex/modrange.pp Program GetModeRange_Example ; { T h i s program demonstrates how t o f i n d a l l a v a i l a b l e graph modes } uses graph ; const { C u r r e n t l y , o n l y 4 , 8 , 1 5 and 1 6 b i t modes are supported b u t t h i s may change i n t h e f u t u r e } gdnames : array [ D 4 b i t . . D 1 6 b i t ] of s t r i n g [ 6 ] =

115

CHAPTER 8. THE GRAPH UNIT.

( ’ 4 b i t ’ , ’ 6 b i t ’ , ’ 8 b i t ’ , ’ 12 b i t ’ , ’ 15 b i t ’ , ’ 16 b i t ’ ) ; var t : text ; l i n e : string ; gd , c , low , high , r e s : i n t e g e r ; begin a s s i g n ( t , ’ modes . t x t ’ ) ; rewrite ( t ) ; close ( t ) ; f o r gd : = D 4 b i t to D 1 6 b i t do begin { Get t h e a v a i l a b l e mode numbers f o r t h i s d r i v e r } getModeRange ( gd , low , high ) ; append ( t ) ; w r i t e ( t , gdnames [ gd ] ) ; W r i t e l n ( t , ’ : low modenr = ’ , low , ’ , h i g h modenr = ’ , high ) ; close ( t ) ; { I f h i g h i s −1 , no r e s o l u t i o n s are supported f o r t h i s b i t d e p t h } i f high = − 1 then begin append ( t ) ; w r i t e l n ( t , ’ No modes supported ! ’ ) ; writeln ( t ) ; close ( t ) ; end else { E n t e r a l l supported r e s o l u t i o n s f o r t h i s b i t d e p t h and w r i t e t h e i r c h a r a c t e r i s t i c s t o t h e f i l e } f o r c : = low to high do begin append ( t ) ; w r i t e l n ( t , ’ t e s t i n g mode n r ’ , c ) ; close ( t ) ; i n i t g r a p h ( gd , c , ’ ’ ) ; res : = graph resul t ; append ( t ) ; { An e r r o r o c c u r r e d when e n t e r i n g t h e mode ? } i f r e s < > grok then w r i t e l n ( t , grapherrormsg ( r e s ) ) else begin w r i t e ( t , ’ maxx : ’ , getmaxx , ’ , maxy : ’ , getmaxy ) ; W r i t e l n ( t , ’ , maxcolor : ’ , getmaxcolor ) ; closegraph ; end ; writeln ( t ) ; close ( t ) ; end ; append ( t ) ; writeln ( t ) ; close ( t ) ; end ; W r i t e l n ( ’ A l l supported modes are l i s t e d i n modes . t x t f i l e s ’ ) ; end .

116

CHAPTER 8. THE GRAPH UNIT.

8.2

Constants, Types and Variables

Types ArcCoordsType = record X,Y,Xstart,Ystart,Xend,Yend : Integer; end; FillPatternType = Array [1..8] of Byte; FillSettingsType = Record Pattern,Color : Word end; LineSettingsType = Record LineStyle,Pattern, Width : Word; end; RGBRec = packed record Red: smallint; Green: smallint; Blue : smallint; end; PaletteType = record Size : longint; Colors : array[0..MaxColors] of RGBRec; end; PointType = Record X,Y : Integer; end; TextSettingsType = Record Font,Direction, CharSize, Horiz, Vert : Word end; ViewPortType = Record X1,Y1,X2,Y2 : Integer; Clip : Boolean end;

8.3

Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where you can find the function.

Initialization Initialization of the graphics screen. Name

Description

Page

ClearDevice

Empty the graphics screen

121

CloseGraph

Finish drawing session, return to text mode

121

DetectGraph

Detect graphical modes

122

GetAspectRatio

Get aspect ratio of screen

123

GetModeRange

Get range of valid modes for current driver

126

GraphDefaults

Set defaults

127 117

CHAPTER 8. THE GRAPH UNIT.

GetDriverName

Return name of graphical driver

124

GetGraphMode

Return current or last used graphics mode

124

GetMaxMode

Get maximum mode for current driver

125

GetModeName

Get name of current mode

125

GraphErrorMsg

String representation of graphical error

127

GraphResult

Result of last drawing operation

128

InitGraph

Initialize graphics drivers

128

InstallUserDriver

Install a new driver

129

RegisterBGIDriver

Register a new driver

131

RestoreCRTMode

Go back to text mode

132

SetGraphBufSize

Set buffer size for graphical operations

134

SetGraphMode

Set graphical mode

134

screen management General drawing screen management functions. Name

Description

Page

ClearViewPort

Clear the current viewport

121

GetImage

Copy image from screen to memory

124

GetMaxX

Get maximum X coordinate

125

GetMaxY

Get maximum Y coordinate

125

GetX

Get current X position

127

GetY

Get current Y position

127

ImageSize

Get size of selected image

128

GetViewSettings

Get current viewport settings

127

PutImage

Copy image from memory to screen

131

SetActivePage

Set active video page

132

SetAspectRatio

Set aspect ratio for drawing routines

133

SetViewPort

Set current viewport

136

SetVisualPage

Set visual page

136

SetWriteMode

Set write mode for screen operations

137

Color management All functions related to color management. Name

Description

Page

GetBkColor

Get current background color

123

GetColor

Get current foreground color

123

GetDefaultPalette

Get default palette entries

123

GetMaxColor

Get maximum valid color

125

118

CHAPTER 8. THE GRAPH UNIT.

GetPaletteSize

Get size of palette for current mode

126

GetPixel

Get color of selected pixel

126

GetPalette

Get palette entry

126

SetAllPallette

Set all colors in palette

132

SetBkColor

Set background color

133

SetColor

Set foreground color

133

SetPalette

Set palette entry

135

SetRGBPalette

Set palette entry with RGB values

135

Drawing primitives Functions for simple drawing. Name

Description

Page

Arc

Draw an arc

120

Circle

Draw a complete circle

121

DrawPoly

Draw a polygone with N points

122

Ellipse

Draw an ellipse

122

GetArcCoords

Get arc coordinates

123

GetLineSettings

Get current line drawing settings

124

Line

Draw line between 2 points

129

LineRel

Draw line relative to current position

129

LineTo

Draw line from current position to absolute position

130

MoveRel

Move cursor relative to current position

130

MoveTo

Move cursor to absolute position

130

PieSlice

Draw a pie slice

131

PutPixel

Draw 1 pixel

131

Rectangle

Draw a non-filled rectangle

131

Sector

Draw a sector

132

SetLineStyle

Set current line drawing style

134

Filled drawings Functions for drawing filled regions. Name

Description

Page

Bar3D

Draw a filled 3D-style bar

121

Bar

Draw a filled rectangle

120

FloodFill

Fill starting from coordinate

123

FillEllipse

Draw a filled ellipse

122

FillPoly

Draw a filled polygone

122

GetFillPattern

Get current fill pattern

124 119

CHAPTER 8. THE GRAPH UNIT.

GetFillSettings

Get current fill settings

124

SetFillPattern

Set current fill pattern

133

SetFillStyle

Set current fill settings

133

Text and font handling Functions to set texts on the screen. Name

Description

Page

GetTextSettings

Get current text settings

126

InstallUserFont

Install a new font

129

OutText

Write text at current cursor position

130

OutTextXY

Write text at coordinates X,Y

130

RegisterBGIFont

Register a new font

132

SetTextJustify

Set text justification

135

SetTextStyle

Set text style

135

SetUserCharSize

Set text size

136

TextHeight

Calculate height of text

137

TextWidth

Calculate width of text

137

8.4

Functions and procedures

Arc Declaration: Procedure Arc (X,Y : Integer; start,stop, radius :

Word);

Description: Arc draws part of a circle with center at (X,Y), radius radius, starting from angle start, stopping at angle stop. These angles are measured counterclockwise. Errors: None. See also: Circle (121),Ellipse (122) GetArcCoords (123),PieSlice (131), Sector (132)

Bar Declaration: Procedure Bar (X1,Y1,X2,Y2 :

Integer);

Description: Draws a rectangle with corners at (X1,Y1) and (X2,Y2) and fills it with the current color and fill-style. Errors: None. See also: Bar3D (121), Rectangle (131)

120

CHAPTER 8. THE GRAPH UNIT.

Bar3D Declaration: Procedure Bar3D (X1,Y1,X2,Y2 :

Integer; depth :

Word; Top :

Boolean);

Description: Draws a 3-dimensional Bar with corners at (X1,Y1) and (X2,Y2) and fills it with the current color and fill-style. Depth specifies the number of pixels used to show the depth of the bar. If Top is true; then a 3-dimensional top is drawn. Errors: None. See also: Bar (120), Rectangle (131)

Circle Declaration: Procedure Circle (X,Y : Integer; Radius :

Word);

Description: Circle draws part of a circle with center at (X,Y), radius radius. Errors: None. See also: Ellipse (122),Arc (120) GetArcCoords (123),PieSlice (131), Sector (132)

ClearDevice Declaration: Procedure ClearDevice ; Description: Clears the graphical screen (with the current background color), and sets the pointer at (0,0) Errors: None. See also: ClearViewPort (121), SetBkColor (133)

ClearViewPort Declaration: Procedure ClearViewPort ; Description: Clears the current viewport. The current background color is used as filling color. The pointer is set at (0,0) Errors: None. See also: ClearDevice (121),SetViewPort (136), SetBkColor (133)

CloseGraph Declaration: Procedure CloseGraph ; Description: Closes the graphical system, and restores the screen modus which was active before the graphical modus was activated. Errors: None. See also: InitGraph (128)

121

CHAPTER 8. THE GRAPH UNIT.

DetectGraph Declaration: Procedure DetectGraph (Var Driver, Modus :

Integer);

Description: Checks the hardware in the PC and determines the driver and screen-modus to be used. These are returned in Driver and Modus, and can be fed to InitGraph. See the InitGraph for a list of drivers and modi. Errors: None. See also: InitGraph (128)

DrawPoly Declaration: Procedure DrawPoly (NumberOfPoints :

Word; Var PolyPoints;

Description: Draws a polygone with NumberOfPoints corner points, using the current color and line-style. PolyPoints is an array of type PointType. Errors: None. See also: Bar (120), seepBar3D, Rectangle (131)

Ellipse Declaration: Procedure Ellipse (X,Y : Integer; Start,Stop,XRadius,YRadius :

Word);

Description: Ellipse draws part of an ellipse with center at (X,Y). XRadius and Yradius are the horizontal and vertical radii of the ellipse. Start and Stop are the starting and stopping angles of the part of the ellipse. They are measured counterclockwise from the X-axis (3 o’clock is equal to 0 degrees). Only positive angles can be specified. Errors: None. See also: Arc (120) Circle (121), FillEllipse (122)

FillEllipse Declaration: Procedure FillEllipse (X,Y : Integer; Xradius,YRadius:

Word);

Description: Ellipse draws an ellipse with center at (X,Y). XRadius and Yradius are the horizontal and vertical radii of the ellipse. The ellipse is filled with the current color and fill-style. Errors: None. See also: Arc (120) Circle (121), GetArcCoords (123),PieSlice (131), Sector (132)

FillPoly Declaration: Procedure FillPoly (NumberOfPoints :

Word; Var PolyPoints);

Description: Draws a polygone with NumberOfPoints corner points and fills it using the current color and line-style. PolyPoints is an array of type PointType. Errors: None. See also: Bar (120), seepBar3D, Rectangle (131)

122

CHAPTER 8. THE GRAPH UNIT.

FloodFill Declaration: Procedure FloodFill (X,Y : Integer; BorderColor :

Word);

Description: Fills the area containing the point (X,Y), bounded by the color BorderColor. Errors: None See also: SetColor (133), SetBkColor (133)

GetArcCoords Declaration: Procedure GetArcCoords (Var ArcCoords :

ArcCoordsType);

Description: GetArcCoords returns the coordinates of the latest Arc or Ellipse call. Errors: None. See also: Arc (120), Ellipse (122)

GetAspectRatio Declaration: Procedure GetAspectRatio (Var Xasp,Yasp :

Word);

Description: GetAspectRatio determines the effective resolution of the screen. The aspect ration can the be calculated as Xasp/Yasp. Errors: None. See also: InitGraph (128),SetAspectRatio (133)

GetBkColor Declaration: Function GetBkColor :

Word;

Description: GetBkColor returns the current background color (the palette entry). Errors: None. See also: GetColor (123),SetBkColor (133)

GetColor Declaration: Function GetColor :

Word;

Description: GetColor returns the current drawing color (the palette entry). Errors: None. See also: GetColor (123),SetBkColor (133)

GetDefaultPalette Declaration: Procedure GetDefaultPalette (Var Palette : Description: Returns the current palette in Palette. Errors: None. See also: GetColor (123), GetBkColor (123) 123

PaletteType);

CHAPTER 8. THE GRAPH UNIT.

GetDriverName Declaration: Function GetDriverName :

String;

Description: GetDriverName returns a string containing the name of the current driver. Errors: None. See also: GetModeName (125), InitGraph (128)

GetFillPattern Declaration: Procedure GetFillPattern (Var FillPattern :

FillPatternType);

Description: GetFillPattern returns an array with the current fill-pattern in FillPattern Errors: None See also: SetFillPattern (133)

GetFillSettings Declaration: Procedure GetFillSettings (Var FillInfo :

FillSettingsType);

Description: GetFillSettings returns the current fill-settings in FillInfo Errors: None. See also: SetFillPattern (133)

GetGraphMode Declaration: Function GetGraphMode :

Integer;

Description: GetGraphMode returns the current graphical modus Errors: None. See also: InitGraph (128)

GetImage Declaration: Procedure GetImage (X1,Y1,X2,Y2 :

Integer, Var Bitmap;

Description: GetImage Places a copy of the screen area (X1,Y1) to X2,Y2 in BitMap Errors: Bitmap must have enough room to contain the image. See also: ImageSize (128), PutImage (131)

GetLineSettings Declaration: Procedure GetLineSettings (Var LineInfo :

LineSettingsType);

Description: GetLineSettings returns the current Line settings in LineInfo Errors: None. See also: SetLineStyle (134) 124

CHAPTER 8. THE GRAPH UNIT.

GetMaxColor Declaration: Function GetMaxColor :

Word;

Description: GetMaxColor returns the maximum color-number which can be set with SetColor. Contrary to Turbo Pascal, this color isn’t always guaranteed to be white (for instance in 256+ color modes). Errors: None. See also: SetColor (133), GetPaletteSize (126)

GetMaxMode Declaration: Function GetMaxMode :

Word;

Description: GetMaxMode returns the highest modus for the current driver. Errors: None. See also: InitGraph (128)

GetMaxX Declaration: Function GetMaxX : Word; Description: GetMaxX returns the maximum horizontal screen length Errors: None. See also: GetMaxY (125)

GetMaxY Declaration: Function GetMaxY : Word; Description: GetMaxY returns the maximum number of screen lines Errors: None. See also: GetMaxY (125)

GetModeName Declaration: Function GetModeName (Var modus :

Integer) :

Description: Returns a string with the name of modus Modus Errors: None. See also: GetDriverName (124), InitGraph (128)

125

String;

CHAPTER 8. THE GRAPH UNIT.

GetModeRange Declaration: Procedure GetModeRange (Driver : LoModus, HiModus: Integer);

Integer;

Description: GetModeRange returns the Lowest and Highest modus of the currently installed driver. If no modes are supported for this driver, HiModus will be -1. Errors: None. See also: InitGraph (128)

GetPalette Declaration: Procedure GetPalette (Var Palette :

PaletteType);

Description: GetPalette returns in Palette the current palette. Errors: None. See also: GetPaletteSize (126), SetPalette (135)

GetPaletteSize Declaration: Function GetPaletteSize :

Word;

Description: GetPaletteSize returns the maximum number of entries in the current palette. Errors: None. See also: GetPalette (126), SetPalette (135)

GetPixel Declaration: Function GetPixel (X,Y : Integer) :

Word;

Description: GetPixel returns the color of the point at (X,Y) Errors: None. See also:

GetTextSettings Declaration: Procedure GetTextSettings (Var TextInfo :

TextSettingsType);

Description: GetTextSettings returns the current text style settings : The font, direction, size and placement as set with SetTextStyle and SetTextJustify Errors: None. See also: SetTextStyle (135), SetTextJustify (135)

126

CHAPTER 8. THE GRAPH UNIT.

GetViewSettings Declaration: Procedure GetViewSettings (Var ViewPort :

ViewPortType);

Description: GetViewSettings returns the current viewport and clipping settings in ViewPort. Errors: None. See also: SetViewPort (136)

GetX Declaration: Function GetX : Integer; Description: GetX returns the X-coordinate of the current position of the graphical pointer Errors: None. See also: GetY (127)

GetY Declaration: Function GetY : Integer; Description: GetY returns the Y-coordinate of the current position of the graphical pointer Errors: None. See also: GetX (127)

GraphDefaults Declaration: Procedure GraphDefaults ; Description: GraphDefaults resets all settings for viewport, palette, foreground and background pattern, line-style and pattern, filling style, filling color and pattern, font, text-placement and text size. Errors: None. See also: SetViewPort (136), SetFillStyle (133), SetColor (133), SetBkColor (133), SetLineStyle (134)

GraphErrorMsg Declaration: Function GraphErrorMsg (ErrorCode :

Integer) :

String;

Description: GraphErrorMsg returns a string describing the error Errorcode. This string can be used to let the user know what went wrong. Errors: None. See also: GraphResult (128)

127

CHAPTER 8. THE GRAPH UNIT.

GraphResult Declaration: Function GraphResult :

Integer;

Description: GraphResult returns an error-code for the last graphical operation. If the returned value is zero, all went well. A value different from zero means an error has occurred. besides all operations which draw something on the screen, the following procedures also can produce a GraphResult different from zero: •InstallUserFont (129) •SetLineStyle (134) •SetWriteMode (137) •SetFillStyle (133) •SetTextJustify (135) •SetGraphMode (134) •SetTextStyle (135) Errors: None. See also: GraphErrorMsg (127)

ImageSize Declaration: Function ImageSize (X1,Y1,X2,Y2 :

Integer) :

Word;

Description: ImageSize returns the number of bytes needed to store the image in the rectangle defined by (X1,Y1) and (X2,Y2). Errors: None. See also: GetImage (124)

InitGraph Declaration: Procedure InitGraph (var GraphDriver,GraphModus : const PathToDriver : string);

integer;

Description: InitGraph initializes the graph package. GraphDriver has two valid values: GraphDriver=0 which performs an auto detect and initializes the highest possible mode with the most colors. 1024x768x64K is the highest possible resolution supported by the driver, if you need a higher resolution, you must edit MODES.PPI. If you need another mode, then set GraphDriver to a value different from zero and graphmode to the mode you wish (VESA modes where 640x480x256 is 101h etc.). PathToDriver is only needed, if you use the BGI fonts from Borland. Free Pascal does not offer BGI fonts like Borland, these must be obtained separately. Errors: None. See also: Introduction, (page 112), DetectGraph (122), CloseGraph (121), GraphResult (128) Example:

128

CHAPTER 8. THE GRAPH UNIT.

var gd,gm : integer; PathToDriver : string; begin gd:=detect; { highest possible resolution } gm:=0; { not needed, auto detection } PathToDriver:=’C:\PP\BGI’; { path to BGI fonts, drivers aren’t needed } InitGraph(gd,gm,PathToDriver); if GraphResultgrok then halt; ..... { whatever you need } CloseGraph; { restores the old graphics mode } end.

InstallUserDriver Declaration: Function InstallUserDriver (DriverPath : AutoDetectPtr: Pointer) : Integer;

String;

Description: InstallUserDriver adds the device-driver DriverPath to the list of .BGI drivers. AutoDetectPtr is a pointer to a possible auto-detect function. Errors: None. See also: InitGraph (128), InstallUserFont (129)

InstallUserFont Declaration: Function InstallUserFont (FontPath :

String) :

Integer;

Description: InstallUserFont adds the font in FontPath to the list of fonts of the .BGI system. Errors: None. See also: InitGraph (128), InstallUserDriver (129)

Line Declaration: Procedure Line (X1,Y1,X2,Y2 :

Integer);

Description: Line draws a line starting from (X1,Y1 to (X2,Y2), in the current line style and color. The current position is put to (X2,Y2) Errors: None. See also: LineRel (129),LineTo (130)

LineRel Declaration: Procedure LineRel (DX,DY : Integer); Description: LineRel draws a line starting from the current pointer position to the point(DX,DY, relative to the current position, in the current line style and color. The Current Position is set to the endpoint of the line. Errors: None. 129

CHAPTER 8. THE GRAPH UNIT.

See also: Line (129), LineTo (130)

LineTo Declaration: Procedure LineTo (DX,DY : Integer); Description: LineTo draws a line starting from the current pointer position to the point(DX,DY, relative to the current position, in the current line style and color. The Current position is set to the end of the line. Errors: None. See also: LineRel (129),Line (129)

MoveRel Declaration: Procedure MoveRel (DX,DY : Integer; Description: MoveRel moves the pointer to the point (DX,DY), relative to the current pointer position Errors: None. See also: MoveTo (130)

MoveTo Declaration: Procedure MoveTo (X,Y : Integer; Description: MoveTo moves the pointer to the point (X,Y). Errors: None. See also: MoveRel (130)

OutText Declaration: Procedure OutText (Const TextString :

String);

Description: OutText puts TextString on the screen, at the current pointer position, using the current font and text settings. The current position is moved to the end of the text. Errors: None. See also: OutTextXY (130)

OutTextXY Declaration: Procedure OutTextXY (X,Y : Integer; Const TextString :

String);

Description: OutText puts TextString on the screen, at position (X,Y), using the current font and text settings. The current position is moved to the end of the text. Errors: None. See also: OutText (130)

130

CHAPTER 8. THE GRAPH UNIT.

PieSlice Declaration: Procedure PieSlice (X,Y : Integer; Start,Stop,Radius : Word); Description: PieSlice draws and fills a sector of a circle with center (X,Y) and radius Radius, starting at angle Start and ending at angle Stop. Errors: None. See also: Arc (120), Circle (121), Sector (132)

PutImage Declaration: Procedure PutImage (X1,Y1 :

Integer; Var Bitmap; How :

word) ;

Description: PutImage Places the bitmap in Bitmap on the screen at (X1,Y1). How determines how the bitmap will be placed on the screen. Possible values are : •CopyPut •XORPut •ORPut •AndPut •NotPut Errors: None See also: ImageSize (128),GetImage (124)

PutPixel Declaration: Procedure PutPixel (X,Y : Integer; Color :

Word);

Description: Puts a point at (X,Y) using color Color Errors: None. See also: GetPixel (126)

Rectangle Declaration: Procedure Rectangle (X1,Y1,X2,Y2 :

Integer);

Description: Draws a rectangle with corners at (X1,Y1) and (X2,Y2), using the current color and style. Errors: None. See also: Bar (120), Bar3D (121)

RegisterBGIDriver Declaration: Function RegisterBGIDriver (Driver : Description: Registers a user-defined BGI driver Errors: None. See also: InstallUserDriver (129), RegisterBGIFont (132) 131

Pointer) :

Integer;

CHAPTER 8. THE GRAPH UNIT.

RegisterBGIFont Declaration: Function RegisterBGIFont (Font :

Pointer) :

Integer;

Description: Registers a user-defined BGI driver Errors: None. See also: InstallUserFont (129), RegisterBGIDriver (131)

RestoreCRTMode Declaration: Procedure RestoreCRTMode ; Description: Restores the screen modus which was active before the graphical modus was started. To get back to the graph mode you were last in, you can use SetGraphMode(GetGraphMode) Errors: None. See also: InitGraph (128)

Sector Declaration: Procedure Sector (X,Y : Integer; Start,Stop,XRadius,YRadius : Word); Description: Sector draws and fills a sector of an ellipse with center (X,Y) and radii XRadius and YRadius, starting at angle Start and ending at angle Stop. Errors: None. See also: Arc (120), Circle (121), PieSlice (131)

SetActivePage Declaration: Procedure SetActivePage (Page :

Word);

Description: Sets Page as the active page for all graphical output. Errors: None. See also:

SetAllPallette Declaration: Procedure SetAllPallette (Var Palette); Description: Sets the current palette to Palette. Palette is an untyped variable, usually pointing to a record of type PaletteType Errors: None. See also: GetPalette (126)

132

CHAPTER 8. THE GRAPH UNIT.

SetAspectRatio Declaration: Procedure SetAspectRatio (Xasp,Yasp :

Word);

Description: Sets the aspect ratio of the current screen to Xasp/Yasp. Errors: None See also: InitGraph (128), GetAspectRatio (123)

SetBkColor Declaration: Procedure SetBkColor (Color :

Word);

Description: Sets the background color to Color. Errors: None. See also: GetBkColor (123), SetColor (133)

SetColor Declaration: Procedure SetColor (Color :

Word);

Description: Sets the foreground color to Color. Errors: None. See also: GetColor (123), SetBkColor (133)

SetFillPattern Declaration: Procedure SetFillPattern (FillPattern : Color : Word);

FillPatternType,

Description: SetFillPattern sets the current fill-pattern to FillPattern, and the filling color to Color The pattern is an 8x8 raster, corresponding to the 64 bits in FillPattern. Errors: None See also: GetFillPattern (124), SetFillStyle (133)

SetFillStyle Declaration: Procedure SetFillStyle (Pattern,Color :

word);

Description: SetFillStyle sets the filling pattern and color to one of the predefined filling patterns. Pattern can be one of the following predefined constants : •EmptyFill Uses backgroundcolor. •SolidFill Uses filling color •LineFill Fills with horizontal lines. •ltSlashFill Fills with lines from left-under to top-right. •SlashFill Idem as previous, thick lines. •BkSlashFill Fills with thick lines from left-Top to bottom-right. 133

CHAPTER 8. THE GRAPH UNIT.

•LtBkSlashFill Idem as previous, normal lines. •HatchFill Fills with a hatch-like pattern. •XHatchFill Fills with a hatch pattern, rotated 45 degrees. •InterLeaveFill •WideDotFill Fills with dots, wide spacing. •CloseDotFill Fills with dots, narrow spacing. •UserFill Fills with a user-defined pattern. Errors: None. See also: SetFillPattern (133)

SetGraphBufSize Declaration: Procedure SetGraphBufSize (BufSize :

Word);

Description: SetGraphBufSize is a dummy function which does not do anything; it is no longer needed. Errors: None. See also:

SetGraphMode Declaration: Procedure SetGraphMode (Mode :

Integer);

Description: SetGraphMode sets the graphical mode and clears the screen. Errors: None. See also: InitGraph (128)

SetLineStyle Declaration: Procedure SetLineStyle (LineStyle,Pattern,Width :

Word);

Description: SetLineStyle sets the drawing style for lines. You can specify a LineStyle which is one of the following pre-defined constants: •Solidln=0; draws a solid line. •Dottedln=1; Draws a dotted line. •Centerln=2; draws a non-broken centered line. •Dashedln=3; draws a dashed line. •UserBitln=4; Draws a User-defined bit pattern. If UserBitln is specified then Pattern contains the bit pattern. In all another cases, Pattern is ignored. The parameter Width indicates how thick the line should be. You can specify one of the following pre-defined constants: •NormWidth=1 •ThickWidth=3 Errors: None. See also: GetLineSettings (124) 134

CHAPTER 8. THE GRAPH UNIT.

SetPalette Declaration: Procedure SetPalette (ColorNr :

Word; NewColor :

ShortInt);

Description: SetPalette changes the ColorNr-th entry in the palette to NewColor Errors: None. See also: SetAllPallette (132),SetRGBPalette (135)

SetRGBPalette Declaration: Procedure SetRGBPalette (ColorNr,Red,Green,Blue :

Integer);

Description: SetRGBPalette sets the ColorNr-th entry in the palette to the color with RGB-values Red, Green Blue. Errors: None. See also: SetAllPallette (132), SetPalette (135)

SetTextJustify Declaration: Procedure SetTextJustify (Horizontal,Vertical :

Word);

Description: SetTextJustify controls the placement of new text, relative to the (graphical) cursor position. Horizontal controls horizontal placement, and can be one of the following pre-defined constants: •LeftText=0; Text is set left of the pointer. •CenterText=1; Text is set centered horizontally on the pointer. •RightText=2; Text is set to the right of the pointer. Vertical controls the vertical placement of the text, relative to the (graphical) cursor position. Its value can be one of the following pre-defined constants : •BottomText=0; Text is placed under the pointer. •CenterText=1; Text is placed centered vertically on the pointer. •TopText=2;Text is placed above the pointer. Errors: None. See also: OutText (130), OutTextXY (130)

SetTextStyle Declaration: Procedure SetTextStyle (Font,Direction,Magnitude :

Word);

Description: SetTextStyle controls the style of text to be put on the screen. pre-defined constants for Font are: DefaultFont TriplexFont SmallFont SansSerifFont GothicFont

= = = = =

0; 1; 2; 3; 4; 135

CHAPTER 8. THE GRAPH UNIT.

ScriptFont SimpleFont TSCRFont LCOMFont EuroFont BoldFont

= = = = = =

5; 6; 7; 8; 9; 10;

Pre-defined constants for Direction are : •HorizDir=0; •VertDir=1; Errors: None. See also: GetTextSettings (126)

SetUserCharSize Declaration: Procedure SetUserCharSize (Xasp1,Xasp2,Yasp1,Yasp2 :

Word);

Description: Sets the width and height of vector-fonts. The horizontal size is given by Xasp1/Xasp2, and the vertical size by Yasp1/Yasp2. Errors: None. See also: SetTextStyle (135)

SetViewPort Declaration: Procedure SetViewPort (X1,Y1,X2,Y2 :

Integer; Clip :

Boolean);

Description: Sets the current graphical viewport (window) to the rectangle defined by the top-left corner (X1,Y1) and the bottom-right corner (X2,Y2). If Clip is true, anything drawn outside the viewport (window) will be clipped (i.e. not drawn). Coordinates specified after this call are relative to the top-left corner of the viewport. Errors: None. See also: GetViewSettings (127)

SetVisualPage Declaration: Procedure SetVisualPage (Page :

Word);

Description: SetVisualPage sets the video page to page number Page. Errors: None See also: SetActivePage (132)

136

CHAPTER 8. THE GRAPH UNIT.

SetWriteMode Declaration: Procedure SetWriteMode (Mode :

Integer);

Description: SetWriteMode controls the drawing of lines on the screen. It controls the binary operation used when drawing lines on the screen. Mode can be one of the following pre-defined constants: •CopyPut=0; •XORPut=1; Errors: None. See also:

TextHeight Declaration: Function TextHeight (S : String) :

Word;

Description: TextHeight returns the height (in pixels) of the string S in the current font and text-size. Errors: None. See also: TextWidth (137)

TextWidth Declaration: Function TextWidth (S : String) :

Word;

Description: TextHeight returns the width (in pixels) of the string S in the current font and text-size. Errors: None. See also: TextHeight (137)

8.5

Target specific issues

In what follows we describe some things that are different on the various platforms:

DOS

VESA modes (i.e., anything but 320x200x256 and 640x480x16) do not work under most installations of Windows NT, Windows 2000 and Windows XP. They also do not work for some people under Windows 98 and Windows ME, depending on their graphics drivers. However, the graph unit cannot detect this, because no errors are returned from the system. In such cases, the screen simply turns black, or will show garbage. Nothing can be done about this, the reason is missing or buggy support in the graphics drivers of the operating system.

137

CHAPTER 8. THE GRAPH UNIT.

W INDOWS The windows version of the Graph units is not very performant. It works, thus allowing to port old TP programs to Windows, but that is all what can be expected from it. Further, it is windowed only: A separate window is opened in which the graphics are displayed. This means that the normal keyboard/mouse handling as provided by the crt and/or keyboard/mouse units wil not work in the graphical window. If keyboard and mouse input are needed the winmouse and the wincrt unit should be used instead. To hide the console window, compile with the {$apptype gui} switch. Further, the following extra modes are available: mLargestWindow16 = $f0; mLargestWindow256 = $f1; mLargestWindow32k = $f2; mLargestWindow64k = $f3; mLargestWindow16M = $f4; mMaximizedWindow16 = $f5; mMaximizedWindow256 = $f6; mMaximizedWindow32k = $f7; mMaximizedWindow64k = $f8; mMaximizedWindow16M = $f9;

LINUX

There are several issues on Linux that need to be taken care of: 1. The Linux version of the Graph unit uses the libvga library. This library works on the console, not under X. 2. If you get an error similar to /usr/bin/ld: cannot find -lvga This can mean one of two things: either libvga is not installed properly, or the directory where it is installed is not in the linker path. To remedy the former, you should install both the libvga package and libvga-devel package (or compile and install from scratch). To remedy the latter, you should add the path to the compiler command-line using the -Fl option. 3. Programs using libvga need root privileges to run. You can make them setuid root with the following command: chown root.root myprogram chmod u+s myprogram The libvga library will give up the root privileges after it is initialized. 4. there is an experimental version of the Graphics library available that uses GGI to do all the drawing, but it is not well tested. It’s called ggigraph and is distributed in source form only. 5. Do not use the CRT unit together with the Graph unit: the console may end up in an unusable state. Instead, the ncurses unit may function fine.

138

Chapter 9

The HEAPTRC unit. This chapter describes the HEAPTRC unit for Free Pascal. It was written by Pierre Muller. It is system independent, and works on all supported systems.

9.1

Purpose

The HEAPTRC unit can be used to debug your memory allocation/deallocation. It keeps track of the calls to getmem/freemem, and, implicitly, of New/Dispose statements. When the program exits, or when you request it explicitly. It displays the total memory used, and then dumps a list of blocks that were allocated but not freed. It also displays where the memory was allocated. If there are any inconsistencies, such as memory blocks being allocated or freed twice, or a memory block that is released but with wrong size, this will be displayed also. The information that is stored/displayed can be customized using some constants.

9.2

Usage

All that you need to do is to include heaptrc in the uses clause of your program. Make sure that it is the first unit in the clause, otherwise memory allocated in initialization code of units that precede the heaptrc unit will not be accounted for, causing an incorrect memory usage report. If you use the -gh switch, the compiler will insert the unit by itself, so you don’t have to include it in your uses clause. The following example shows how to use the heaptrc unit. Listing: heapex/heapex.pp Program heapex ; { Program used t o demonstrate t h e usage o f h e a p t r c u n i t } Uses h e a p t r c ; Var P1 : ^ L o n g i n t ; P2 : P o i n t e r ; I : longint ;

139

CHAPTER 9. THE HEAPTRC UNIT.

begin New( P1 ) ; / / causes p r e v i o u s a l l o c a t i o n n o t t o be de−a l l o c a t e d New( P1 ) ; Dispose ( P1 ) ; For I : = 1 to 1 0 do begin GetMem ( P2 , 1 2 8 ) ; / / When I i s even , d e a l l o c a t e b l o c k . We l o o s e 5 t i m e s 128 / / b y t e s t h i s way . I f ( I mod 2 ) = 0 Then FreeMem ( P2 , 1 2 8 ) ; end ; GetMem( P2 , 1 2 8 ) ; / / T h i s w i l l provoke an e r r o r and a memory dump Freemem ( P2 , 6 4 ) ; end .

This is the memory dump shown when running this program: Marked memory at 0040FA50 invalid Wrong size : 128 allocated 64 freed 0x00408708 0x0040CB49 0x0040C481 Call trace for block 0x0040FA50 size 128 0x0040CB3D 0x0040C481 If you use the lineinfo unit (or use the -gl switch) as well, then heaptrc will also give you the filenames and line-numbers of the procedures in the backtrace: Marked memory at 00410DA0 invalid Wrong size : 128 allocated 64 freed 0x004094B8 0x0040D8F9 main, line 25 of heapex.pp 0x0040D231 Call trace for block 0x00410DA0 size 128 0x0040D8ED main, line 23 of heapex.pp 0x0040D231 If lines without filename/line-number occur, this means there is a unit which has no debug info included.

9.3

Constants, Types and variables

The FillExtraInfoType is a procedural type used in the SetExtraInfo (142) call. type FillExtraInfoType = procedure(p : pointer); The following typed constants allow to fine-tune the standard dump of the memory usage by DumpHeap (141):

140

CHAPTER 9. THE HEAPTRC UNIT.

const tracesize = 8; quicktrace : boolean = true; HaltOnError : boolean = true; keepreleased : boolean = false; add_tail : boolean = true; usecrc : boolean = true Tracesize specifies how many levels of calls are displayed of the call stack during the memory dump. If you specify keepreleased:=True then half the TraceSize is reserved for the GetMem call stack, and the other half is reserved for the FreeMem call stack. For example, the default value of 8 will cause eight levels of call frames to be dumped for the getmem call if keepreleased is False. If KeepReleased is true, then 4 levels of call frames will be dumped for the GetMem call and 4 frames wil be dumped for the FreeMem call. If you want to change this value, you must recode the heaptrc unit. Quicktrace determines whether the memory manager checks whether a block that is about to be released is allocated correctly. This is a rather time consuming search, and slows program execution significantly, so by default it is set to False. If HaltOnError is set to True then an illegal call to FreeMem will cause the memory manager to execute a halt(1) instruction, causing a memory dump. By Default it is set to True. If keepreleased is set to true, then a list of freed memory blocks is kept. This is useful if you suspect that the same memory block is released twice. However, this option is very memory intensive, so use it sparingly, and only when it’s really necessary. If add_tail is True (the default) then a check is also performed on the memory location just behind the allocated memory. If usecrc is True (the default) then a crc check is performed on locations before and after the allocated memory. This is useful to detect memory overwrites.

9.4

Functions and procedures

DumpHeap Declaration: procedure DumpHeap; Description: DumpHeap dumps to standard output a summary of memory usage. It is called automatically by the heaptrc unit when your program exits (by instaling an exit procedure), but it can be called at any time Errors: None. See also: MarkHeap (141)

MarkHeap Declaration: procedure MarkHeap; Description: MarkHeap marks all memory blocks with a special signature. You can use this if you think that you corruped the memory. Errors: None. See also: DumpHeap (141)

141

CHAPTER 9. THE HEAPTRC UNIT.

SetExtraInfo Declaration: procedure SetExtraInfo( size :

longint;func :

FillExtraInfoType);

Description: You can use SetExtraInfo to store extra info in the blocks that the heaptrc unit reserves when tracing getmem calls. Size indicates the size (in bytes) that the trace mechanism should reserve for your extra information. For each call to getmem, func will be called, and passed a pointer to the memory reserved. When dumping the memory summary, the extra info is shown as Longint values. Errors: You can only call SetExtraInfo if no memroy has been allocated yet. If memory was already allocated prior to the call to SetExtraInfo, then an error will be displayed on standard error output, and a DumpHeap (141) is executed. See also: DumpHeap (141),SetHeapTraceOutput (143) Listing: heapex/setinfo.pp Program heapex ; { Program used t o demonstrate t h e usage o f h e a p t r c u n i t } Uses h e a p t r c ; Var P1 : ^ L o n g i n t ; P2 : P o i n t e r ; I : longint ; Marker : L o n g i n t ; Procedure SetMarker ( P : p o i n t e r ) ; Type PLongint = ^ L o n g i n t ; begin PLongint ( P ) ^ : = Marker ; end ; Procedure

Part1 ;

begin / / Blocks a l l o c a t e d here are marked w i t h $FFAAFFAA = −5570646 Marker : = $FFAAFFAA ; New( P1 ) ; New( P1 ) ; Dispose ( P1 ) ; For I : = 1 to 1 0 do begin GetMem ( P2 , 1 2 8 ) ; I f ( I mod 2 ) = 0 Then FreeMem ( P2 , 1 2 8 ) ; end ; GetMem( P2 , 1 2 8 ) ; end ; Procedure

Part2 ;

begin / / Blocks a l l o c a t e d here are marked w i t h $FAFAFAFA = −84215046 Marker : = $FAFAFAFA ; New( P1 ) ;

142

CHAPTER 9. THE HEAPTRC UNIT.

New( P1 ) ; Dispose ( P1 ) ; For I : = 1 to 1 0 do begin GetMem ( P2 , 1 2 8 ) ; I f ( I mod 2 ) = 0 Then FreeMem ( P2 , 1 2 8 ) ; end ; GetMem( P2 , 1 2 8 ) ; end ; begin S e t E x t r a I n f o ( SizeOf ( Marker ) , @SetMarker ) ; Writeln ( ’ Part 1 ’ ) ; part1 ; Writeln ( ’ Part 2 ’ ) ; part2 ; end .

SetHeapTraceOutput Declaration: Procedure SetHeapTraceOutput(const name :

string);

Description: SetHeapTraceOutput sets the filename into which heap trace info will be written. By default information is written to standard output, this function allows you to redirect the information to a file with full filename name. Errors: If the file cannot be written to, errors will occur when writing the trace. See also: SetExtraInfo (142)

143

Chapter 10

The IPC unit. This chapter describes the IPC unit for Free Pascal. It was written for LINUX by Michaël Van Canneyt. It gives all the functionality of system V Inter-Process Communication: shared memory, semaphores and messages. It works only on the LINUX operating system. The chapter is divided in 2 sections: • The first section lists types, constants and variables from the interface part of the unit. • The second section describes the functions defined in the unit.

10.1

Types, Constants and variables :

Variables Var IPCerror : longint; The IPCerror variable is used to report errors, by all calls.

Constants Many constants here are provided for completeness only, and should under normal circumstances not be used by the programmer. Const IPC_CREAT = IPC_EXCL = IPC_NOWAIT =

1 shl 9; 2 shl 9; 4 shl 9;

{ create if key is nonexistent } { fail if key exists } { return error on wait }

These constants are used in the various xxxget calls. IPC_RMID IPC_SET IPC_STAT IPC_INFO

= = = =

0; 1; 2; 3;

{ { { {

remove resource } set ipc_perm options } get ipc_perm options } see ipcs }

These constants can be passed to the various xxxctl calls.

144

CHAPTER 10. THE IPC UNIT.

const MSG_NOERROR = 1 shl 12; MSG_EXCEPT = 2 shl 12; MSGMNI = 128; MSGMAX = 4056; MSGMNB = 16384; These constants are used in the messaging system, they are not for use by the programmer. const SEM_UNDO = $1000; GETPID = 11; GETVAL = 12; GETALL = 13; GETNCNT = 14; GETZCNT = 15; SETVAL = 16; SETALL = 17; These constants call be specified in the semop (153) call. SEMMNI SEMMSL SEMMNS SEMOPM SEMVMX

= = = = =

128; 32; (SEMMNI * SEMMSL); 32; 32767;

These constanst are used internally by the semaphore system, they should not be used by the programmer. const SHM_R SHM_W SHM_RDONLY SHM_RND SHM_REMAP SHM_LOCK SHM_UNLOCK

= = = = = = =

4 shl 2 shl 1 shl 2 shl 4 shl 11; 12;

6; 6; 12; 12; 12;

These constants are used in the shmctl (159) call.

Types The following two types are provided because they are needed. One they they should be defined in the system unit, however. Type PULong = ^Cardinal; PWord = ^Word; Type TKey

= Longint;

TKey is the type returned by the ftok (149) key generating function. 145

CHAPTER 10. THE IPC UNIT.

type PIPC_Perm = ^TIPC_Perm; TIPC_Perm = record key : TKey; uid, gid, cuid, cgid, mode, seq : Word; end; The TIPC_Perm structure is used in all IPC systems to specify the permissions. Type PSHMid_DS = ^TSHMid_ds; TSHMid_ds = record shm_perm : TIPC_Perm; shm_segsz : longint; shm_atime : longint; shm_dtime : longint; shm_ctime : longint; shm_cpid : word; shm_lpid : word; shm_nattch : integer; shm_npages : word; shm_pages : Pointer; attaches : pointer; end; The TSHMid_ds strucure is used in the shmctl (159) call to set or retrieve settings concerning shared memory. type PSHMinfo TSHMinfo shmmax shmmin shmmni shmseg shmall end;

= = : : : : :

^TSHMinfo; record longint; longint; longint; longint; longint;

The TSHMinfo record is used by the shared memory system, and should not be accessed by the programer directly. type PMSG = ^TMSG; TMSG = record msg_next : msg_type : msg_spot : msg_stime : msg_ts : end;

PMSG; Longint; PChar; Longint; Integer;

146

CHAPTER 10. THE IPC UNIT.

The TMSG record is used in the handling of message queues. There should be few cases where the programmer needs to access this data. type PMSQid_ds = ^TMSQid_ds; TMSQid_ds = record msg_perm : TIPC_perm; msg_first : PMsg; msg_last : PMsg; msg_stime : Longint; msg_rtime : Longint; msg_ctime : Longint; wwait : Pointer; rwait : pointer; msg_cbytes : word; msg_qnum : word; msg_qbytes : word; msg_lspid : word; msg_lrpid : word; end; The TMSQid_ds record is returned by the msgctl (150) call, and contains all data about a message queue. PMSGbuf TMSGbuf mtype mtext end;

= = : :

^TMSGbuf; record longint; array[0..0] of char;

The TMSGbuf record is a record containing the data of a record. you should never use this record directly, instead you should make your own record that follows the structure of the TMSGbuf record, but that has a size that is big enough to accomodate your messages. The mtype field should always be present, and should always be filled. Type PMSGinfo = ^TMSGinfo; TMSGinfo = record msgpool : Longint; msgmap : Longint; msgmax : Longint; msgmnb : Longint; msgmni : Longint; msgssz : Longint; msgtql : Longint; msgseg : Word; end; The TMSGinfo record is used internally by the message queue system, and should not be used by the programmer directly. Type PSEMid_ds = ^PSEMid_ds; TSEMid_ds = record 147

CHAPTER 10. THE IPC UNIT.

sem_perm : tipc_perm; sem_otime : longint; sem_ctime : longint; sem_base : pointer; sem_pending : pointer; sem_pending_last : pointer; undo : pointer; sem_nsems : word; end; The TSEMid_ds structure is returned by the semctl (154) call, and contains all data concerning a semahore. Type PSEMbuf = TSEMbuf = sem_num sem_op sem_flg end;

^TSEMbuf; record : word; : integer; : integer;

The TSEMbuf record us use in the semop (153) call, and is used to specify which operations you want to do. Type PSEMinfo TSEMinfo semmap semmni semmns semmnu semmsl semopm semume semusz semvmx semaem end;

= = : : : : : : : : : :

^TSEMinfo; record longint; longint; longint; longint; longint; longint; longint; longint; longint; longint;

The TSEMinfo record is used internally by the semaphore system, and should not be used directly. Type PSEMun = ^TSEMun; TSEMun = record case longint of 0 : ( val : longint ); 1 : ( buf : PSEMid_ds ); 2 : ( arr : PWord ); 3 : ( padbuf : PSeminfo ); 4 : ( padpad : pointer ); end; The TSEMun variant record (actually a C union) is used in the semctl (154) call.

148

CHAPTER 10. THE IPC UNIT.

10.2

Functions and procedures

ftok Declaration: Function ftok (Path :

String; ID : char) :

TKey;

Description: ftok returns a key that can be used in a semget (153),shmget (158) or msgget (149) call to access a new or existing IPC resource. Path is the name of a file in the file system, ID is a character of your choice. The ftok call does the same as it’s C couterpart, so a pascal program and a C program will access the same resource if they use the same Path and ID Errors: ftok returns -1 if the file in Path doesn’t exist. See also: semget (153),shmget (158),msgget (149) For an example, see msgctl (150), semctl (154), shmctl (159).

msgget Declaration: Function msgget(key:

TKey; msgflg:longint):longint;

Description: msgget returns the ID of the message queue described by key. Depending on the flags in msgflg, a new queue is created. msgflg can have one or more of the following values (combined by ORs): IPC_CREATThe queue is created if it doesn’t already exist. IPC_EXCLIf used in combination with IPC_CREAT, causes the call to fail if the queue already exists. It cannot be used by itself. Optionally, the flags can be ORed with a permission mode, which is the same mode that can be used in the file system. Errors: On error, -1 is returned, and IPCError is set. See also: ftok (149),msgsnd (149), msgrcv (150), msgctl (150), semget (2) For an example, see msgctl (150).

msgsnd Declaration: Function msgsnd(msqid:longint; msgp: Boolean;

PMSGBuf; msgsz:

longint; msgflg:longint):

Description: msgsend sends a message to a message queue with ID msqid. msgp is a pointer to a message buffer, that should be based on the TMsgBuf type. msgsiz is the size of the message (NOT of the message buffer record !) The msgflg can have a combination of the following values (ORed together): 0No special meaning. The message will be written to the queue. If the queue is full, then the process is blocked. IPC_NOWAITIf the queue is full, then no message is written, and the call returns immediatly. The function returns True if the message was sent successfully, False otherwise.

149

CHAPTER 10. THE IPC UNIT.

Errors: In case of error, the call returns False, and IPCerror is set. See also: msgget (149), msgrcv (150), seefmsgctl For an example, see msgctl (150).

msgrcv Declaration: Function msgrcv(msqid:longint; msgp: msgflg:longint): Boolean;

PMSGBuf; msgsz:

longint; msgtyp:longint;

Description: msgrcv retrieves a message of type msgtyp from the message queue with ID msqid. msgtyp corresponds to the mtype field of the TMSGbuf record. The message is stored in the MSGbuf structure pointed to by msgp. The msgflg parameter can be used to control the behaviour of the msgrcv call. It consists of an ORed combination of the following flags: 0No special meaning. IPC_NOWAITif no messages are available, then the call returns immediatly, with the ENOMSG error. MSG_NOERRORIf the message size is wrong (too large), no error is generated, instead the message is truncated. Normally, in such cases, the call returns an error (E2BIG) The function returns True if the message was received correctly, False otherwise. Errors: In case of error, False is returned, and IPCerror is set. See also: msgget (149), msgsnd (149), msgctl (150) For an example, see msgctl (150).

msgctl Declaration: Function msgctl(msqid:longint; cmd:

longint; buf:

PMSQid_ds):

Boolean;

Description: msgctl performs various operations on the message queue with id ID. Which operation is performed, depends on the cmd parameter, which can have one of the following values: IPC_STATIn this case, the msgctl call fills the TMSQid_ds structure with information about the message queue. IPC_SETin this case, the msgctl call sets the permissions of the queue as specified in the ipc_perm record inside buf. IPC_RMIDIf this is specified, the message queue will be removed from the system. buf contains the data that are needed by the call. It can be Nil in case the message queue should be removed. The function returns True if successfull, False otherwise. Errors: On error, False is returned, and IPCerror is set accordingly. See also: msgget (149), msgsnd (149), msgrcv (150) Listing: ipcex/msgtool.pp

150

CHAPTER 10. THE IPC UNIT.

program msgtool ; Uses i p c ; Type PMyMsgBuf TMyMsgBuf mtype : mtext : end ;

= ^ TMyMsgBuf ; = record Longint ; string [ 2 5 5 ] ;

Procedure DoError ( Const Msg : s t r i n g ) ; begin W r i t e l n ( msg , ’ r e t u r n e d an e r r o r : halt ( 1 ) ; end ;

’ , ipcerror );

Procedure SendMessage ( I d : L o n g i n t ; Var Buf : TMyMsgBuf ; MType : L o n g i n t ; Const MText : S t r i n g ) ; begin W r i t e l n ( ’ Sending message . ’ ) ; Buf . mtype : = mtype ; Buf . Mtext : = mtext ; I f not msgsnd ( Id , PMsgBuf ( @Buf ) , 2 5 6 , 0 ) then DoError ( ’ msgsnd ’ ) ; end ; Procedure ReadMessage ( ID : L o n g i n t ; Var Buf : TMyMsgBuf ; MType : l o n g i n t ) ; begin W r i t e l n ( ’ Reading message . ’ ) ; Buf . MType : = MType ; I f msgrcv ( ID , PMSGBuf ( @Buf) , 2 5 6 , mtype , 0 ) then W r i t e l n ( ’ Type : ’ , b u f . mtype , ’ Text : ’ , b u f . mtext ) else DoError ( ’ msgrcv ’ ) ; end ; Procedure RemoveQueue ( ID : L o n g i n t ) ; begin I f m s g c t l ( i d , IPC_RMID , N i l ) then W r i t e l n ( ’ Removed Queue w i t h i d ’ , I d ) ; end ; Procedure ChangeQueueMode ( ID , mode : l o n g i n t ) ; Var QueueDS : TMSQid_ds ; begin I f Not m s g c t l ( Id , IPC_STAT ,@QueueDS ) then DoError ( ’ m s g c t l : s t a t ’ ) ;

151

CHAPTER 10. THE IPC UNIT.

W r i t e l n ( ’ Old p e r m i s s i o n s : ’ ,QueueDS . msg_perm . mode ) ; QueueDS . msg_perm . mode: =Mode ; i f m s g c t l ( ID , IPC_SET ,@QueueDS ) then W r i t e l n ( ’New p e r m i s s i o n s : ’ ,QueueDS . msg_perm . mode ) else DoError ( ’ m s g c t l : IPC_SET ’ ) ; end ; procedure usage ; begin Writeln ( Writeln ( Writeln ( Writeln ( halt ( 1 ) ; end ;

’ Usage : msgtool s ( end ) < t e x t > ( max 2 5 5 c h a r a c t e r s ) ’ ) ; ’ r ( e c e i v e ) < type > ’ ) ; ’ d( elete ) ’ ) ; ’ m( ode ) < decimal mode> ’ ) ;

Function S t r T o I n t ( S : S t r i n g ) : l o n g i n t ; Var M : l o n g i n t ; C : Integer ; begin v a l ( S ,M, C ) ; I f C< >0 Then DoError ( ’ S t r T o I n t : S t r T o I n t : =M; end ;

’ +S ) ;

Var Key : TKey ; ID : l o n g i n t ; Buf : TMyMsgBuf ; begin I f Paramcount 2 then Usage else ReadMessage ( i d , buf , s t r t o i n t ( Paramstr ( 2 ) ) ) ; ’D ’ : I f ParamCount< >1 then Usage else RemoveQueue ( ID ) ; ’M ’ : I f ParamCount< >2 then Usage else ChangeQueueMode ( i d , s t r t o i n t ( paramstr ( 2 ) ) ) ; else Usage

152

CHAPTER 10. THE IPC UNIT.

end ; end .

semget Declaration: Function semget(key:Tkey; nsems:longint; semflg:longint):

longint;

Description: msgget returns the ID of the semaphore set described by key. Depending on the flags in semflg, a new queue is created. semflg can have one or more of the following values (combined by ORs): IPC_CREATThe queue is created if it doesn’t already exist. IPC_EXCLIf used in combination with IPC_CREAT, causes the call to fail if the set already exists. It cannot be used by itself. Optionally, the flags can be ORed with a permission mode, which is the same mode that can be used in the file system. if a new set of semaphores is created, then there will be nsems semaphores in it. Errors: On error, -1 is returned, and IPCError is set. See also: ftok (149), semop (153), semctl (154)

semop Declaration: Function semop(semid:longint; sops:

pointer; nsops:

cardinal):

Boolean;

Description: semop performs a set of operations on a message queue. sops points to an array of type TSEMbuf. The array should contain nsops elements. The fields of the TSEMbuf structure TSEMbuf = sem_num sem_op sem_flg

record : word; : integer; : integer;

should be filled as follows: sem_numThe number of the semaphore in the set on which the operation must be performed. sem_opThe operation to be performed. The operation depends on the sign of sem_op 1.A positive number is simply added to the current value of the semaphore. 2.If 0 (zero) is specified, then the process is suspended until the specified semaphore reaches zero. 3.If a negative number is specified, it is substracted from the current value of the semaphore. If the value would become negative then the process is suspended until the value becomes big enough, unless IPC_NOWAIT is specified in the sem_flg. sem_flgOptional flags: if IPC_NOWAIT is specified, then the calling process will never be suspended. The function returns True if the operations were successful, False otherwise. Errors: In case of error, False is returned, and IPCerror is set. See also: semget (153), semctl (154) 153

CHAPTER 10. THE IPC UNIT.

semctl Declaration: Function semctl(semid:longint; semnum:longint; cmd:longint; var arg: tsemun): longint; Description: semctl performs various operations on the semaphore semnum w ith semaphore set id ID. The arg parameter supplies the data needed for each call. This is a variant record that should be filled differently, according to the command: Type TSEMun = record case longint of 0 : ( val : longint ); 1 : ( buf : PSEMid_ds ); 2 : ( arr : PWord ); 3 : ( padbuf : PSeminfo ); 4 : ( padpad : pointer ); end; Which operation is performed, depends on the cmd parameter, which can have one of the following values: IPC_STATIn this case, the arg record should have it’s buf field set to the address of a TSEMid_ds record. The semctl call fills this TSEMid_ds structure with information about the semaphore set. IPC_SETIn this case, the arg record should have it’s buf field set to the address of a TSEMid_ds record. The semctl call sets the permissions of the queue as specified in the ipc_perm record. IPC_RMIDIf this is specified, the semaphore set is removed from from the system. GETALLIn this case, the arr field of arg should point to a memory area where the values of the semaphores will be stored. The size of this memory area is SizeOf(Word)* Number of semaphores in the set. This call will then fill the memory array with all the values of the semaphores. GETNCNTThis will fill the val field of the arg union with the bumber of processes waiting for resources. GETPIDsemctl returns the process ID of the process that performed the last semop (153) call. GETVALsemctl returns the value of the semaphore with number semnum. GETZCNTsemctl returns the number of processes waiting for semaphores that reach value zero. SETALLIn this case, the arr field of arg should point to a memory area where the values of the semaphores will be retrieved from. The size of this memory area is SizeOf(Word)* Number of semaphores in the set. This call will then set the values of the semaphores from the memory array. SETVALThis will set the value of semaphore semnum to the value in the val field of the arg parameter. The function returns -1 on error. Errors: The function returns -1 on error, and IPCerror is set accordingly. See also: semget (153), semop (153) Listing: ipcex/semtool.pp

154

CHAPTER 10. THE IPC UNIT.

Program semtool ; { Program t o demonstrat t h e use o f semaphores } Uses i p c ; Const MaxSemValue = 5 ; Procedure DoError ( Const Msg : S t r i n g ) ; begin Writeln ( ’ Error : Halt ( 1 ) ; end ;

’ ,msg , ’ Code :

’ , IPCerror ) ;

Function getsemval ( ID , Member : l o n g i n t ) : l o n g i n t ; Var S : TSEMun ; begin GetSemVal : = SemCtl ( i d , member , GETVAL, S ) ; end ; Procedure DispVal ( ID , member : l o n g i n t ) ; begin w r i t e l n ( ’ Value f o r member ’ ,member , ’ i s end ;

’ , GetSemVal ( ID , Member ) ) ;

Function GetMemberCount ( ID : L o n g i n t ) : l o n g i n t ; Var o p t s : TSEMun ; semds : TSEMid_ds ; begin o p t s . b u f : =@semds ; I f s e m c t l ( Id , 0 , IPC_STAT , o p t s )−1 then GetMemberCount : = semds . sem_nsems else GetMemberCount := −1; end ; Function OpenSem ( Key : TKey ) : L o n g i n t ; begin OpenSem: = semget ( Key , 0 , 4 3 8 ) ; I f OpenSem=−1 then DoError ( ’OpenSem ’ ) ; end ; Function CreateSem ( Key : TKey ; Members : L o n g i n t ) : L o n g i n t ; Var Count : L o n g i n t ; Semopts : TSemun ; begin I f members>semmsl then DoError ( ’ Sorry , maximum number o f semaphores i n s e t exceeded ’ ) ;

155

CHAPTER 10. THE IPC UNIT.

W r i t e l n ( ’ T r y i n g t o c r e a t e a new semaphore s e t w i t h ’ , members , ’ members . ’ ) ; CreateSem : = semget ( key , members , IPC_CREAT or IPC_Excl or 4 3 8 ) ; I f CreateSem=−1 then DoError ( ’ Semaphore s e t a l r e a d y e x i s t s . ’ ) ; Semopts . v a l : = MaxSemValue ; { I n i t i a l v a l u e o f semaphores } For Count : = 0 to Members−1 do s e m c t l ( CreateSem , count , s e t v a l , semopts ) ; end ; Procedure lockSem ( ID , Member : L o n g i n t ) ; Var l o c k : TSEMbuf ; begin With l o c k do begin sem_num : = 0 ; sem_op:= −1; sem_flg : =IPC_NOWAIT ; end ; i f ( member < 0 ) or ( member>GetMemberCount ( ID ) − 1) then DoError ( ’ semaphore member o u t o f range ’ ) ; i f getsemval ( ID , member ) = 0 then DoError ( ’ Semaphore r e s o u r c e s exhausted ( no l o c k ) ’ ) ; l o c k . sem_num: = member ; W r i t e l n ( ’ A t t e m p t i n g t o l o c k member ’ ,member , ’ o f semaphore ’ , ID ) ; i f not semop ( Id , @lock , 1 ) then DoError ( ’ Lock f a i l e d ’ ) else W r i t e l n ( ’ Semaphore r e s o u r c e s decremented by one ’ ) ; d i s p v a l ( ID , Member ) ; end ; Procedure UnlockSem ( ID , Member : L o n g i n t ) ; Var Unlock : TSEMbuf ; begin With Unlock do begin sem_num : = 0 ; sem_op : = 1 ; sem_flg : =IPC_NOWAIT ; end ; i f ( member < 0 ) or ( member>GetMemberCount ( ID ) − 1) then DoError ( ’ semaphore member o u t o f range ’ ) ; i f getsemval ( ID , member)= MaxSemValue then DoError ( ’ Semaphore n o t l o c k e d ’ ) ; Unlock . sem_num: = member ; W r i t e l n ( ’ A t t e m p t i n g t o u n l o c k member ’ ,member , ’ o f semaphore ’ , ID ) ; i f not semop ( Id , @unlock , 1 ) then DoError ( ’ Unlock f a i l e d ’ ) else W r i t e l n ( ’ Semaphore r e s o u r c e s incremented by one ’ ) ; d i s p v a l ( ID , Member ) ; end ; Procedure RemoveSem ( ID : l o n g i n t ) ;

156

CHAPTER 10. THE IPC UNIT.

var S : TSemun ; begin I f s e m c t l ( Id , 0 , IPC_RMID , s)−1 then W r i t e l n ( ’ Semaphore removed ’ ) else DoError ( ’ Couldn ’ ’ t remove semaphore ’ ) ; end ;

Procedure ChangeMode ( ID , Mode : l o n g i n t ) ; Var r c : l o n g i n t ; o p t s : TSEMun ; semds : TSEMid_ds ; begin o p t s . b u f : =@semds ; I f not s e m c t l ( Id , 0 , IPC_STAT , o p t s )−1 then DoError ( ’ Couldn ’ ’ t s t a t semaphore ’ ) ; W r i t e l n ( ’ Old p e r m i s s i o n s were : ’ , semds . sem_perm . mode ) ; semds . sem_perm . mode: =mode ; I f s e m c t l ( i d , 0 , IPC_SET , o p t s )−1 then W r i t e l n ( ’ Set p e r m i s s i o n s t o ’ ,mode ) else DoError ( ’ Couldn ’ ’ t s e t p e r m i s s i o n s ’ ) ; end ; Procedure PrintSem ( ID : l o n g i n t ) ; Var I , c n t : l o n g i n t ; begin c n t : = getmembercount ( ID ) ; W r i t e l n ( ’ Semaphore ’ , ID , ’ has ’ , cnt , ’ Members ’ ) ; For I : = 0 to cnt −1 Do DispVal ( i d , i ) ; end ; Procedure USage ; begin Writeln ( Writeln ( Writeln ( Writeln ( Writeln ( halt ( 1 ) ; end ;

’ Usage : semtool c ( r e a t e ) < count > ’ ) ; ’ l ( ock ) < member> ’ ) ; ’ u ( n l o c k ) < member> ’ ) ; ’ d( elete ) ’ ) ; ’ m( ode ) < mode> ’ ) ;

Function S t r T o I n t ( S : S t r i n g ) : l o n g i n t ; Var M : l o n g i n t ; C : Integer ; begin v a l ( S ,M, C ) ;

157

CHAPTER 10. THE IPC UNIT.

I f C< >0 Then DoError ( ’ S t r T o I n t : S t r T o I n t : =M; end ;

’ +S ) ;

Var Key : TKey ; ID : L o n g i n t ; begin I f ParamCount 2 then usage ; CreateSem ( key , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ’ L ’ : begin i f paramcount < >2 then usage ; ID : =OpenSem ( key ) ; LockSem ( ID , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ’U ’ : begin i f paramcount < >2 then usage ; ID : =OpenSem ( key ) ; UnLockSem ( ID , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ’M ’ : begin i f paramcount < >2 then usage ; ID : =OpenSem ( key ) ; ChangeMode ( ID , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ’D ’ : Begin ID : =OpenSem( Key ) ; RemoveSem( I d ) ; end ; ’P ’ : begin ID : =OpenSem( Key ) ; PrintSem ( I d ) ; end ; else Usage end ; end .

shmget Declaration: Function shmget(key:

Tkey; Size:longint; flag:longint):longint;

Description: shmget returns the ID of a shared memory block, described by key. Depending on the flags in flag, a new memory block is created. flag can have one or more of the following values (combined by ORs): IPC_CREATThe queue is created if it doesn’t already exist. IPC_EXCLIf used in combination with IPC_CREAT, causes the call to fail if the queue already exists. It cannot be used by itself. Optionally, the flags can be ORed with a permission mode, which is the same mode that can be used in the file system. 158

CHAPTER 10. THE IPC UNIT.

if a new memory block is created, then it will have size Size semaphores in it. Errors: On error, -1 is returned, and IPCError is set. See also:

shmat Declaration: Function shmat (shmid:longint; shmaddr:pchar; shmflg:longint):pchar; Description: shmat attaches a shared memory block with identified shmid to the current process. The function returns a pointer to the shared memory block. If shmaddr is Nil, then the system chooses a free unmapped memory region, as high up in memory space as possible. If shmaddr is non-nil, and SHM_RND is in shmflg, then the returned address is shmaddr, rounded down to SHMLBA. If SHM_RND is not specified, then shmaddr must be a page-aligned address. The parameter shmflg can be used to control the behaviour of the shmat call. It consists of a ORed combination of the following costants: SHM_RNDThe suggested address in shmaddr is rounded down to SHMLBA. SHM_RDONLYthe shared memory is attached for read access only. Otherwise the memory is attached for read-write. The process then needs read-write permissions to access the shared memory. Errors: If an error occurs, -1 is returned, and IPCerror is set. See also: shmget (158), shmdt (159), shmctl (159) For an example, see shmctl (159).

shmdt Declaration: Function shmdt (shmaddr:pchar):boolean; Description: shmdt detaches the shared memory at address shmaddr. This shared memory block is unavailable to the current process, until it is attached again by a call to shmat (159). The function returns True if the memory block was detached successfully, False otherwise. Errors: On error, False is returned, and IPCerror is set. See also: shmget (158), shmat (159), shmctl (159)

shmctl Declaration: Function shmctl(shmid:longint; cmd:longint; buf:

pshmid_ds):

Boolean;

Description: shmctl performs various operations on the shared memory block identified by identifier shmid. The buf parameter points to a TSHMid_ds record. The cmd parameter is used to pass which operation is to be performed. It can have one of the following values : IPC_STATshmctl fills the TSHMid_ds record that buf points to with the available information about the shared memory block.

159

CHAPTER 10. THE IPC UNIT.

IPC_SETapplies the values in the ipc_perm record that buf points to, to the shared memory block. IPC_RMIDthe shared memory block is destroyed (after all processes to which the block is attached, have detached from it). If successful, the function returns True, False otherwise. Errors: If an error occurs, the function returns False, and IPCerror is set. See also: shmget (158), shmat (159), shmdt (159) Listing: ipcex/shmtool.pp Program shmtool ; uses i p c , s t r i n g s ; Const SegSize = 1 0 0 ; var key : Tkey ; shmid , c n t r : l o n g i n t ; s e g p t r : pchar ; Procedure USage ; begin Writeln ( writeln ( writeln ( writeln ( halt ( 1 ) ; end ;

’ Usage : shmtool w( r i t e ) t e x t ’ ) ; ’ r ( ead ) ’ ) ; ’ d( elete ) ’ ) ; ’ m( ode change ) mode ’ ) ;

Procedure Writeshm ( ID : L o n g i n t ; p t r : pchar ; S : s t r i n g ) ; begin strpcopy ( ptr , s ) ; end ; Procedure Readshm ( ID : l o n g i n t ; p t r : pchar ) ; begin W r i t e l n ( ’ Read : end ;

’ , ptr ) ;

Procedure removeshm ( ID : L o n g i n t ) ; begin s h m c t l ( ID , IPC_RMID , N i l ) ; w r i t e l n ( ’ Shared memory marked f o r d e l e t i o n ’ ) ; end ; Procedure CHangeMode ( ID : l o n g i n t ; mode : S t r i n g ) ; Var m : word ; code : i n t e g e r ; data : TSHMid_ds ; begin

160

CHAPTER 10. THE IPC UNIT.

v a l ( mode ,m, code ) ; i f code < >0 then usage ; I f Not s h m c t l ( shmid , IPC_STAT , @data ) then begin writeln ( ’ Error : shmctl : ’ , i p c e r r o r ) ; halt ( 1 ) ; end ; w r i t e l n ( ’ Old p e r m i s s i o n s : ’ , data . shm_perm . mode ) ; data . shm_perm . mode: =m; I f Not s h m c t l ( shmid , IPC_SET , @data ) then begin writeln ( ’ Error : shmctl : ’ , i p c e r r o r ) ; halt ( 1 ) ; end ; w r i t e l n ( ’New p e r m i s s i o n s : ’ , data . shm_perm . mode ) ; end ; begin i f paramcount KbfnKey ) then W r i t e l n ( ’ Not a f u n c t i o n key ’ ) else begin Write ( ’ Got key ( ’ , GetKeyEventCode (K ) ) ; W r i t e l n ( ’ ) : ’ , KeyEventToString (K ) ) ; end ; U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyboard ; end .

167

CHAPTER 11. THE KEYBOARD UNIT

GetKeyEventFlags Declaration: function GetKeyEventFlags(KeyEvent:

TKeyEvent):

Byte;

Description: GetKeyEventFlags returns the flags part of the given KeyEvent. Errors: None. See also: GetKeyEventUniCode (169), GetKeyEventShiftState (168), GetKeyEventCode (167), GetKeyEventChar (167), GetKeyEvent (166) For an example, see GetKeyEvent (166)

GetKeyEventShiftState Declaration: function GetKeyEventShiftState(KeyEvent:

TKeyEvent):

Byte;

Description: GetKeyEventShiftState returns the shift-state values of the given KeyEvent. This can be used to detect which of the modifier keys Shift, Alt or Ctrl were pressed. If none were pressed, zero is returned. Note that this function does not always return expected results; In a unix X-Term, the modifier keys do not always work. Errors: None. See also: GetKeyEventUniCode (169), GetKeyEventFlags (168), GetKeyEventCode (167), GetKeyEventChar (167), GetKeyEvent (166) Listing: kbdex/ex3.pp Program Example3 ; { Program t o demonstrate t h e G e t K e y E v e n t S h i f t S t a t e f u n c t i o n . } Uses keyboard ; Var K : TKeyEvent ; S : Byte ; begin InitKeyBoard ; Write ( ’ Press keys combined w i t h CTRL / SHIFT / ALT ’ ) ; W r i t e l n ( ’ , o r press " q " t o end . ’ ) ; Repeat K: = GetKeyEvent ; K: = TranslateKeyEvent ( K ) ; S: = G e t K e y E v e n t S h i f t S t a t e ( K ) ; I f ( S= 0 ) then W r i t e l n ( ’ No s p e c i a l keys pressed ’ ) else begin W r i t e l n ( ’ Detected s p e c i a l keys : ’ , S h i f t S t a t e T o S t r i n g ( K , False ) ) ; W r i t e l n ( ’ Got key : ’ , KeyEventToString (K ) ) ; end ; U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyboard ; end .

168

CHAPTER 11. THE KEYBOARD UNIT

GetKeyEventUniCode Declaration: function GetKeyEventUniCode(KeyEvent:

TKeyEvent):

Word;

Description: GetKeyEventUniCode returns the unicode part of the given KeyEvent if it contains a translated unicode character. Errors: None. See also: GetKeyEventShiftState (168), GetKeyEventFlags (168), GetKeyEventCode (167), GetKeyEventChar (167), GetKeyEvent (166) No example available yet.

InitKeyBoard Declaration: procedure InitKeyboard; Description: InitKeyboard initializes the keyboard driver. If the driver is already active, it does nothing. When the driver is initialized, it will do everything necessary to ensure the functioning of the keyboard, including allocating memory, initializing the terminal etc. This function should be called once, before using any of the keyboard functions. When it is called, the DoneKeyboard (165) function should also be called before exiting the program or changing the keyboard driver with SetKeyboardDriver (172). Errors: None. See also: DoneKeyboard (165), SetKeyboardDriver (172) For an example, see most other functions.

IsFunctionKey Declaration: function IsFunctionKey(KeyEvent:

TKeyEvent):

Boolean;

Description: IsFunctionKey returns True if the given key event in KeyEvent was a function key or not. Errors: None. See also: GetKeyEvent (166) Listing: kbdex/ex7.pp program example1 ; { T h i s program demonstrates t h e GetKeyEvent f u n c t i o n } uses keyboard ; Var K : TKeyEvent ; begin InitKeyBoard ; W r i t e l n ( ’ Press keys , press " q " t o end . ’ ) ; Repeat K: = GetKeyEvent ;

169

CHAPTER 11. THE KEYBOARD UNIT

K: = TranslateKeyEvent ( K ) ; I f I s F u n c t i o n K e y ( K ) then W r i t e l n ( ’ Got f u n c t i o n key : ’ , KeyEventToString (K ) ) else W r i t e l n ( ’ n o t a f u n c t i o n key . ’ ) ; U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyBoard ; end .

KeyEventToString Declaration: Function KeyEventToString(KeyEvent :

TKeyEvent) :

String;

Description: KeyEventToString translates the key event in KeyEvent to a human-readable description of the pressed key. It will use the constants described in the constants section to do so. Errors: If an unknown key is passed, the scancode is returned, prefixed with the SScanCode string. See also: FunctionKeyName (165), ShiftStateToString (173) For an example, see most other functions.

PollKeyEvent Declaration: function PollKeyEvent:

TKeyEvent;

Description: PollKeyEvent checks whether a key event is available, and returns it if one is found. If no event is pending, it returns 0. Note that this does not remove the key from the pending keys. The key should still be retrieved from the pending key events list with the GetKeyEvent (166) function. Errors: None. See also: PutKeyEvent (171), GetKeyEvent (166) Listing: kbdex/ex4.pp program example4 ; { T h i s program demonstrates t h e PollKeyEvent f u n c t i o n } uses keyboard ; Var K : TKeyEvent ; begin InitKeyBoard ; W r i t e l n ( ’ Press keys , press " q " t o end . ’ ) ; Repeat K: = PollKeyEvent ; I f k < >0 then begin K: = GetKeyEvent ; K: = TranslateKeyEvent ( K ) ; writeln ;

170

CHAPTER 11. THE KEYBOARD UNIT

W r i t e l n ( ’ Got key : ’ , KeyEventToString (K ) ) ; end else write ( ’ . ’ ) ; U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyBoard ; end .

PollShiftStateEvent Declaration: function PollShiftStateEvent:

TKeyEvent;

Description: PollShiftStateEvent returns the current shiftstate in a keyevent. This will return 0 if there is no key event pending. Errors: None. See also: PollKeyEvent (170), GetKeyEvent (166) Listing: kbdex/ex6.pp program example6 ; { T h i s program demonstrates t h e P o l l S h i f t S t a t e E v e n t f u n c t i o n } uses keyboard ; Var K : TKeyEvent ; begin InitKeyBoard ; W r i t e l n ( ’ Press keys , press " q " t o end . ’ ) ; Repeat K: = PollKeyEvent ; I f k < >0 then begin K: = P o l l S h i f t S t a t e E v e n t ; W r i t e l n ( ’ Got s h i f t s t a t e : ’ , S h i f t S t a t e T o S t r i n g ( K , False ) ) ; / / Consume t h e key . K: = GetKeyEvent ; K: = TranslateKeyEvent ( K ) ; end { else write ( ’ . ’ ) } ; U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyBoard ; end .

PutKeyEvent Declaration: procedure PutKeyEvent(KeyEvent:

TKeyEvent);

Description: PutKeyEvent adds the given KeyEvent to the input queue. Please note that depending on the implementation this can hold only one value, i.e. when calling PutKeyEvent multiple times, only the last pushed key will be remembered. 171

CHAPTER 11. THE KEYBOARD UNIT

Errors: None See also: PollKeyEvent (170), GetKeyEvent (166) Listing: kbdex/ex5.pp program example5 ; { T h i s program demonstrates t h e PutKeyEvent f u n c t i o n } uses keyboard ; Var K , k2 : TKeyEvent ; begin InitKeyBoard ; W r i t e l n ( ’ Press keys , press " q " t o end . ’ ) ; K2 : = 0 ; Repeat K: = GetKeyEvent ; I f k < >0 then begin i f ( k2 mod 2 ) = 0 then K2 : =K+1 else K2 : = 0 ; K: = TranslateKeyEvent ( K ) ; W r i t e l n ( ’ Got key : ’ , KeyEventToString (K ) ) ; i f ( K2< >0) then begin PutKeyEvent ( k2 ) ; K2 : = TranslateKeyEVent ( K2 ) ; W r i t e l n ( ’ Put key : ’ , KeyEventToString ( K2 ) ) end end U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyBoard ; end .

SetKeyboardDriver Declaration: Function SetKeyboardDriver (Const Driver :

TKeyboardDriver) :

Boolean;

Description: SetKeyBoardDriver sets the keyboard driver to Driver, if the current keyboard driver is not yet initialized. If the current keyboard driver is initialized, then SetKeyboardDriver does nothing. Before setting the driver, the currently active driver should be disabled with a call to DoneKeyboard (165). The function returns True if the driver was set, False if not. For more information on setting the keyboard driver, see section 11.4, page 174. Errors: None. See also: GetKeyboardDriver (166), DoneKeyboard (165).

172

CHAPTER 11. THE KEYBOARD UNIT

ShiftStateToString Declaration: Function ShiftStateToString(KeyEvent : : String;

TKeyEvent; UseLeftRight :

Boolean)

Description: ShiftStateToString returns a string description of the shift state of the key event KeyEvent. This can be an empty string. The shift state is described using the strings in the SShift constant. Errors: None. See also: FunctionKeyName (165), KeyEventToString (170) For an example, see PollShiftStateEvent (171).

TranslateKeyEvent Declaration: function TranslateKeyEvent(KeyEvent:

TKeyEvent):

TKeyEvent;

Description: TranslateKeyEvent performs ASCII translation of the KeyEvent. It translates a physical key to a function key if the key is a function key, and translates the physical key to the ordinal of the ascii character if there is an equivalent character key. Errors: None. See also: TranslateKeyEventUniCode (173) For an example, see GetKeyEvent (166)

TranslateKeyEventUniCode Declaration: function TranslateKeyEventUniCode(KeyEvent:

TKeyEvent):

TKeyEvent;

Description: TranslateKeyEventUniCode performs Unicode translation of the KeyEvent. It is not yet implemented for all platforms. Errors: If the function is not yet implemented, then the ErrorCode of the system unit will be set to errKbdNotImplemented See also: No example available yet.

11.3

Keyboard scan codes

Special physical keys are encoded with the DOS scan codes for these keys in the second byte of the TKeyEvent type. A complete list of scan codes can be found in table (11.2). This is the list of keys that is used by the default key event translation mechanism. When writing a keyboard driver, either these constants should be returned by the various key event functions, or the TranslateKeyEvent hook should be implemented by the driver. A list of scan codes for special keys and combinations with the SHIFT, ALT and CTRL keys can be found in table (11.3); They are for quick reference only.

173

CHAPTER 11. THE KEYBOARD UNIT

11.4

Writing a keyboard driver

Writing a keyboard driver means that hooks must be created for most of the keyboard unit functions. The TKeyBoardDriver record contains a field for each of the possible hooks: TKeyboardDriver = Record InitDriver : Procedure; DoneDriver : Procedure; GetKeyEvent : Function : TKeyEvent; PollKeyEvent : Function : TKeyEvent; GetShiftState : Function : Byte; TranslateKeyEvent : Function (KeyEvent: TKeyEvent): TKeyEvent; TranslateKeyEventUniCode: Function (KeyEvent: TKeyEvent): TKeyEvent; end; The meaning of these hooks is explained below: InitDriver Called to initialize and enable the driver. Guaranteed to be called only once. This should initialize all needed things for the driver. DoneDriver Called to disable and clean up the driver. Guaranteed to be called after a call to initDriver. This should clean up all things initialized by InitDriver. GetKeyEvent Called by GetKeyEvent (166). Must wait for and return the next key event. It should NOT store keys. PollKeyEvent Called by PollKeyEvent (170). It must return the next key event if there is one. Should not store keys. GetShiftState Called by PollShiftStateEvent (171). Must return the current shift state. TranslateKeyEvent Should translate a raw key event to a cOrrect key event, i.e. should fill in the shiftstate and convert function key scancodes to function key keycodes. If the TranslateKeyEvent is not filled in, a default translation function will be called which converts the known scancodes from the tables in the previous section to a correct keyevent. TranslateKeyEventUniCode Should translate a key event to a unicode key representation. Strictly speaking, only the GetKeyEvent and PollKeyEvent hooks must be implemented for the driver to function correctly. The following unit demonstrates how a keyboard driver can be installed. It takes the installed driver, and hooks into the GetKeyEvent function to register and log the key events in a file. This driver can work on top of any other driver, as long as it is inserted in the uses clause after the real driver unit, and the real driver unit should set the driver record in its initialization section. Listing: kbdex/logkeys.pp unit logkeys ; interface Procedure S t a r t K e y L o g g i n g ; Procedure StopKeyLogging ; Function IsKeyLogging : Boolean ; Procedure SetKeyLogFileName ( FileName : S t r i n g ) ;

174

CHAPTER 11. THE KEYBOARD UNIT

implementation uses s y s u t i l s , keyboard ; var NewKeyBoardDriver , OldKeyBoardDriver : TKeyboardDriver ; A c t i v e , Logging : Boolean ; LogFileName : S t r i n g ; KeyLog : Text ; Function TimeStamp : S t r i n g ; begin TimeStamp : = FormatDateTime ( ’ hh : nn : ss ’ , Time ( ) ) ; end ; Procedure S t a r t K e y L o g g i n g ; begin Logging : = True ; W r i t e l n ( KeyLog , ’ S t a r t l o g g i n g k e y s t r o k e s a t : ’ , TimeStamp ) ; end ; Procedure StopKeyLogging ; begin W r i t e l n ( KeyLog , ’ Stop l o g g i n g k e y s t r o k e s a t : ’ , TimeStamp ) ; Logging : = False ; end ; Function IsKeyLogging : Boolean ; begin IsKeyLogging : = Logging ; end ; Function LogGetKeyEvent : TKeyEvent ; Var K : TKeyEvent ; begin K: = O l d k e y b o a r d D r i v e r . GetKeyEvent ( ) ; I f Logging then begin Write ( KeyLog , TimeStamp , ’ : Key event : ’ ) ; W r i t e l n ( KeyLog , KeyEventToString ( TranslateKeyEvent (K ) ) ) ; end ; LogGetKeyEvent : =K ; end ; Procedure L o g I n i t K e y B o a r d ; begin OldKeyBoardDriver . I n i t D r i v e r ( ) ; Assign ( KeyLog , logFileName ) ; Rewrite ( KeyLog ) ;

175

CHAPTER 11. THE KEYBOARD UNIT

A c t i v e : = True ; StartKeyLogging ; end ; Procedure LogDoneKeyBoard ; begin StopKeyLogging ; Close ( KeyLog ) ; A c t i v e : = False ; OldKeyBoardDriver . DoneDriver ( ) ; end ; Procedure SetKeyLogFileName ( FileName : S t r i n g ) ; begin I f Not A c t i v e then LogFileName : = FileName ; end ; Initialization GetKeyBoardDriver ( OldKeyBoardDriver ) ; NewKeyBoardDriver : = OldKeyBoardDriver ; NewKeyBoardDriver . GetKeyEvent : = @LogGetKeyEvent ; NewKeyBoardDriver . I n i t D r i v e r : = @LogInitKeyboard ; NewKeyBoardDriver . DoneDriver : = @LogDoneKeyboard ; LogFileName : = ’ keyboard . l o g ’ ; Logging : = False ; SetKeyboardDriver ( NewKeyBoardDriver ) ; end .

The following program demonstrates the use of the unit: Listing: kbdex/ex9.pp program example9 ; { T h i s program demonstrates t h e l o g k e y s u n i t } uses keyboard , l o g k e y s ; Var K : TKeyEvent ; begin InitKeyBoard ; W r i t e l n ( ’ Press keys , press " q " t o end , " s " t o g g l e s l o g g i n g . ’ ) ; Repeat K: = GetKeyEvent ; K: = TranslateKeyEvent ( K ) ; W r i t e l n ( ’ Got key : ’ , KeyEventToString (K ) ) ; i f GetKeyEventChar ( K)= ’ s ’ then i f IsKeyLogging then StopKeyLogging else StartKeyLogging ; U n t i l ( GetKeyEventChar ( K)= ’ q ’ ) ; DoneKeyBoard ; end .

176

CHAPTER 11. THE KEYBOARD UNIT

Note that with a simple extension of this unit could be used to make a driver that is capable of recording and storing a set of keyboard strokes, and replaying them at a later time, so a ’keyboard macro’ capable driver. This driver could sit on top of any other driver.

177

CHAPTER 11. THE KEYBOARD UNIT

Table 11.2: Physical keys scan codes Code 00 01 02 04 05 06 07 08 09 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1E 1F 20 21 22 23 24 25 26 27 28 29 2B 2C 2D 2E 2F 30 31 32 33 34 35 37 3B 3C

Key NoKey ALT-Esc ALT-Space CTRL-Ins SHIFT-Ins CTRL-Del SHIFT-Del ALT-Back ALT-SHIFT-Back SHIFT-Tab ALT-Q ALT-W ALT-E ALT-R ALT-T ALT-Y ALT-U ALT-I ALT-O ALT-P ALT-LftBrack ALT-RgtBrack ALT-A ALT-S ALT-D ALT-F ALT-G ALT-H ALT-J ALT-K ALT-L ALT-SemiCol ALT-Quote ALT-OpQuote ALT-BkSlash ALT-Z ALT-X ALT-C ALT-V ALT-B ALT-N ALT-M ALT-Comma ALT-Period ALT-Slash ALT-GreyAst F1 F2

Code 3D 3E 3F 40 41 42 43 44 47 48 49 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F

Key F3 F4 F5 F6 F7 F8 F9 F10 Home Up PgUp Left Center Right ALT-GrayPlus end Down PgDn Ins Del SHIFT-F1 SHIFT-F2 SHIFT-F3 SHIFT-F4 SHIFT-F5 SHIFT-F6 SHIFT-F7 SHIFT-F8 SHIFT-F9 SHIFT-F10 CTRL-F1 CTRL-F2 CTRL-F3 CTRL-F4 CTRL-F5 CTRL-F6 CTRL-F7 CTRL-F8 CTRL-F9 CTRL-F10 ALT-F1 ALT-F2 ALT-F3 ALT-F4 ALT-F5 ALT-F6 ALT-F7 ALT-F8

178

Code 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 94 97 98 99 9B 9D 9F A0 A1 A2 A3 A5

Key ALT-F9 ALT-F10 CTRL-PrtSc CTRL-Left CTRL-Right CTRL-end CTRL-PgDn CTRL-Home ALT-1 ALT-2 ALT-3 ALT-4 ALT-5 ALT-6 ALT-7 ALT-8 ALT-9 ALT-0 ALT-Minus ALT-Equal CTRL-PgUp F11 F12 SHIFT-F11 SHIFT-F12 CTRL-F11 CTRL-F12 ALT-F11 ALT-F12 CTRL-Up CTRL-Minus CTRL-Center CTRL-GreyPlus CTRL-Down CTRL-Tab ALT-Home ALT-Up ALT-PgUp ALT-Left ALT-Right ALT-end ALT-Down ALT-PgDn ALT-Ins ALT-Del ALT-Tab

CHAPTER 11. THE KEYBOARD UNIT

Table 11.3: Special keys scan codes Key NoKey F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 Home Up PgUp Left Center Right end Down PgDn Ins Del Tab GreyPlus

Code 00 3B 3C 3D 3E 3F 40 41 42 43 44 85 86 47 48 49 4B 4C 4D 4F 50 51 52 53 8

SHIFT-Key

CTRL-Key

Alt-Key

54 55 56 57 58 59 5A 5A 5B 5C 87 88

5E 5F 60 61 62 63 64 65 66 67 89 8A 77 8D 84 73 8F 74 75 91 76 04 06 94 90

68 69 6A 6B 6C 6D 6E 6F 70 71 8B 8C 97 98 99 9B

05 07 0F

179

9D 9F A0 A1 A2 A3 A5 4E

Chapter 12

The LINUX unit. This chapter describes the LINUX unit for Free Pascal. The unit was written by Michaël van Canneyt. It works only on the Linux operating system. This chapter is divided in 3 sections: • The first section lists all constants, types and variables, as listed in the interface section of the LINUX unit. • The second section gives and overview of all available functions, grouped by category. • The third section describes all procedures and functions in the LINUX unit.

12.1

Type, Variable and Constant declarations

Types PGlob and TGlob are 2 types used in the Glob (228) function: PGlob = ^TGlob; TGlob = record Name : PChar; Next : PGlob; end; The following types are used in the signal-processing procedures. tfpreg = record significand: array[0..3] of word; exponent: word; end; pfpstate = ^tfpstate; tfpstate = record cw, sw, tag, ipoff, cssel, dataoff, datasel: cardinal; st: array[0..7] of tfpreg; status: cardinal; end; PSigContextRec = ^SigContextRec; SigContextRec = record 180

CHAPTER 12. THE LINUX UNIT.

gs, __gsh: word; fs, __fsh: word; es, __esh: word; ds, __dsh: word; edi: cardinal; esi: cardinal; ebp: cardinal; esp: cardinal; ebx: cardinal; edx: cardinal; ecx: cardinal; eax: cardinal; trapno: cardinal; err: cardinal; eip: cardinal; cs, __csh: word; eflags: cardinal; esp_at_signal: cardinal; ss, __ssh: word; fpstate: pfpstate; oldmask: cardinal; cr2: cardinal; end; The above records contain information about the processor state and process state at the moment a signal is sent to your program. The records below are used in catching signals. TSigAction = procedure(Sig: Longint; SigContext: SigContextRec);cdecl; SignalHandler = Procedure ( Sig : Integer);cdecl; PSignalHandler = SignalHandler; SignalRestorer = Procedure;cdecl; PSignalrestorer = SignalRestorer; SigActionRec = packed record Handler : record case byte of 0: (Sh: SignalHandler); 1: (Sa: TSigAction); end; Sa_Mask : SigSet; Sa_Flags : Longint; Sa_restorer : SignalRestorer; { Obsolete - Don’t use } end; PSigActionRec = ^SigActionRec; Stat is used to store information about a file. It is defined in the syscalls unit. stat = record dev : word; pad1 : word; ino : longint; mode : word; nlink : word; 181

CHAPTER 12. THE LINUX UNIT.

uid : word; gid : word; rdev : word; pad2 : word; size : longint; blksze : Longint; blocks : Longint; atime : Longint; unused1 : longint; mtime : Longint; unused2 : longint; ctime : Longint; unused3 : longint; unused4 : longint; unused5 : longint; end;

Statfs is used to store information about a filesystem. It is defined in the syscalls unit. statfs = record fstype : longint; bsize : longint; blocks : longint; bfree : longint; bavail : longint; files : longint; ffree : longint; fsid : longint; namelen : longint; spare : array [0..6] of longint; end Dir and PDir are used in the OpenDir (239) and ReadDir (241) functions. TDir =record fd : integer; loc : longint; size : integer; buf : pdirent; nextoff: longint; dd_max : integer; lock : pointer; end; PDir =^TDir; Dirent, PDirent are used in the ReadDir (241) function to return files in a directory. PDirent = ^Dirent; Dirent = Record ino, off : longint; reclen : word; name : string[255] end; 182

CHAPTER 12. THE LINUX UNIT.

Termio and Termios are used with iotcl() calls for terminal handling. Const

NCCS = 19; NCC = 8;

Type termio = record c_iflag,{ input mode flags } c_oflag,{ output mode flags } c_cflag,{ control mode flags } c_lflag : Word; { local mode flags } c_line : Word; { line discipline - careful, only High byte in use} c_cc : array [0..NCC-1] of char; { control characters } end; termios = record c_iflag, { input mode flags } c_oflag, { output mode flags } c_cflag, { control mode flags } c_lflag : Cardinal; { local mode flags } c_line : char; { line discipline } c_cc : array [0..NCCS-1] of char; { control characters } end; Utimbuf is used in the Utime (257) call to set access and modificaton time of a file. utimbuf = record actime,modtime : Longint; end; For the Select (244) call, the following 4 types are needed: FDSet = Array [0..31] of longint; PFDSet = ^FDSet; TimeVal = Record sec,usec : Longint; end; PTimeVal = ^TimeVal; The timespec record is needed in the NanoSleep (237) function: timespec = packed record tv_sec,tv_nsec:longint; end; The Uname (257) function uses the utsname to return information about the current kernel : utsname =record sysname,nodename,release, version,machine,domainname : Array[0..64] of char; end; Its elements are null-terminated C style strings, you cannot access them directly !

Variables Linuxerror is the variable in which the procedures in the linux unit report errors. 183

CHAPTER 12. THE LINUX UNIT.

LinuxError : Longint; StdErr Is a Text variable, corresponding to Standard Error or diagnostic output. It is connected to file descriptor 2. It can be freely used, and will be closed on exit. StdErr : Text;

Constants Constants for setting/getting process priorities : Prio_Process = 0; Prio_PGrp = 1; Prio_User = 2; For testing access rights: R_OK W_OK X_OK F_OK

= = = =

4; 2; 1; 0;

For signal handling functions : SA_NOCLDSTOP = 1; SA_SHIRQ = $04000000; SA_STACK = $08000000; SA_RESTART = $10000000; SA_INTERRUPT = $20000000; SA_NOMASK = $40000000; SA_ONESHOT = $80000000; SIG_BLOCK = 0; SIG_UNBLOCK = 1; SIG_SETMASK = 2; SIG_DFL = 0 ; SIG_IGN = 1 ; SIG_ERR = -1; SIGHUP = 1; SIGINT = 2; SIGQUIT = 3; SIGILL = 4; SIGTRAP = 5; SIGABRT = 6; SIGIOT = 6; SIGBUS = 7; SIGFPE = 8; SIGKILL = 9; SIGUSR1 = 10; SIGSEGV = 11; SIGUSR2 = 12; SIGPIPE = 13;

184

CHAPTER 12. THE LINUX UNIT.

SIGALRM = 14; SIGTERM = 15; SIGSTKFLT = 16; SIGCHLD = 17; SIGCONT = 18; SIGSTOP = 19; SIGTSTP = 20; SIGTTIN = 21; SIGTTOU = 22; SIGURG = 23; SIGXCPU = 24; SIGXFSZ = 25; SIGVTALRM = 26; SIGPROF = 27; SIGWINCH = 28; SIGIO = 29; SIGPOLL = SIGIO; SIGPWR = 30; SIGUNUSED = 31; For file control mechanism : F_GetFd F_SetFd F_GetFl F_SetFl F_GetLk F_SetLk F_SetLkW F_GetOwn F_SetOwn

= = = = = = = = =

1; 2; 3; 4; 5; 6; 7; 8; 9;

For Terminal handling : TCGETS = $5401 ; TCSETS = $5402 ; TCSETSW = $5403 ; TCSETSF = $5404 ; TCGETA = $5405 ; TCSETA = $5406 ; TCSETAW = $5407 ; TCSETAF = $5408 ; TCSBRK = $5409 ; TCXONC = $540A ; TCFLSH = $540B ; TIOCEXCL = $540C ; TIOCNXCL = $540D ; TIOCSCTTY = $540E ; TIOCGPGRP = $540F ; TIOCSPGRP = $5410 ; TIOCOUTQ = $5411 ; TIOCSTI = $5412 ; TIOCGWINSZ = $5413 ; TIOCSWINSZ = $5414 ; 185

CHAPTER 12. THE LINUX UNIT.

TIOCMGET = $5415 ; TIOCMBIS = $5416 ; TIOCMBIC = $5417 ; TIOCMSET = $5418 ; TIOCGSOFTCAR = $5419 ; TIOCSSOFTCAR = $541A ; FIONREAD = $541B ; TIOCINQ = FIONREAD; TIOCLINUX = $541C ; TIOCCONS = $541D ; TIOCGSERIAL = $541E ; TIOCSSERIAL = $541F ; TIOCPKT = $5420 ; FIONBIO = $5421 ; TIOCNOTTY = $5422 ; TIOCSETD = $5423 ; TIOCGETD = $5424 ; TCSBRKP = $5425 ; TIOCTTYGSTRUCT = $5426 ; FIONCLEX = $5450 ; FIOCLEX = $5451 ; FIOASYNC = $5452 ; TIOCSERCONFIG = $5453 ; TIOCSERGWILD = $5454 ; TIOCSERSWILD = $5455 ; TIOCGLCKTRMIOS = $5456 ; TIOCSLCKTRMIOS = $5457 ; TIOCSERGSTRUCT = $5458 ; TIOCSERGETLSR = $5459 ; TIOCSERGETMULTI = $545A ; TIOCSERSETMULTI = $545B ; TIOCMIWAIT = $545C ; TIOCGICOUNT = $545D ; TIOCPKT_DATA = 0; TIOCPKT_FLUSHREAD = 1; TIOCPKT_FLUSHWRITE = 2; TIOCPKT_STOP = 4; TIOCPKT_START = 8; TIOCPKT_NOSTOP = 16; TIOCPKT_DOSTOP = 32; Other than that, all constants for setting the speed and control flags of a terminal line, as described in the termios (2) man page, are defined in the linux unit. It would take too much place to list them here. To check the mode field of a stat record, you ca use the following constants : { Constants STAT_IFMT STAT_IFSOCK STAT_IFLNK STAT_IFREG STAT_IFBLK STAT_IFDIR STAT_IFCHR STAT_IFIFO

to check = $f000; = $c000; = $a000; = $8000; = $6000; = $4000; = $2000; = $1000;

stat.mode } {00170000} {0140000} {0120000} {0100000} {0060000} {0040000} {0020000} {0010000} 186

CHAPTER 12. THE LINUX UNIT.

STAT_ISUID = $0800; {0004000} STAT_ISGID = $0400; {0002000} STAT_ISVTX = $0200; {0001000} { Constants to check permissions } STAT_IRWXO = $7; STAT_IROTH = $4; STAT_IWOTH = $2; STAT_IXOTH = $1; STAT_IRWXG = STAT_IRWXO shl 3; STAT_IRGRP = STAT_IROTH shl 3; STAT_IWGRP = STAT_IWOTH shl 3; STAT_IXGRP = STAT_IXOTH shl 3; STAT_IRWXU = STAT_IRWXO shl 6; STAT_IRUSR = STAT_IROTH shl 6; STAT_IWUSR = STAT_IWOTH shl 6; STAT_IXUSR = STAT_IXOTH shl 6; You can test the type of a filesystem returned by a FSStat (216) call with the following constants: fs_old_ext2 fs_ext2 fs_ext fs_iso fs_minix fs_minix_30 fs_minux_V2 fs_msdos fs_nfs fs_proc fs_xia

= = = = = = = = = = =

$ef51; $ef53; $137d; $9660; $137f; $138f; $2468; $4d44; $6969; $9fa0; $012FD16D;

the FLock (214) call uses the following mode constants : LOCK_SH LOCK_EX LOCK_UN LOCK_NB

= = = =

1; 2; 8; 4;

The MMap (235) function uses the following constants to specify access to mapped memory: PROT_READ PROT_WRITE PROT_EXEC PROT_NONE

= = = =

$1; $2; $4; $0;

{ { { {

page page page page

can can can can

be read } be written } be executed } not be accessed }

and the following constants to specify the type of mapping. MAP_SHARED MAP_PRIVATE MAP_TYPE MAP_FIXED MAP_ANONYMOUS

= = = = =

$1; $2; $f; $10; $20;

{ { { { {

Share changes } Changes are private } Mask for type of mapping } Interpret addr exactly } don’t use a file }

187

CHAPTER 12. THE LINUX UNIT.

12.2

Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where you can find the function.

File Input/Output routines Functions for handling file input/output. Name

Description

Page

Dup

Duplicate a file handle

203

Dup2

Copy one file handle to another

203

Fcntl

General file control

219

fdClose

Close file descriptor

210

fdFlush

Flush file descriptor

210

fdOpen

Open new file descriptor

211

fdRead

Read from file descriptor

212

fdSeek

Position in file

213

fdTruncate

Truncate file

213

fdWrite

Write to file descriptor

213

GetFS

Get file descriptor of pascal file

223

Select

Wait for input from file descriptor

244

SelectText

Wait for input from pascal file

245

General File handling routines Functions for handling files on disk. Name

Description

Page

Access

Check access rights on file

192

BaseName

Return name part of file

196

Chown

Change owner of file

197

Chmod

Change access rights on file

198

DirName

Return directory part of file

202

FSplit

Split filename in parts

215

FExpand

Return full-grown filename

214

FLock

Set lock on a file

214

FNMatch

Match filename to searchpattern

214

FSearch

Search for a file in a path

215

FSStat

Return filesystem information

216

FStat

Return file information

217

FRename

Rename file

219

LStat

Return information on a link

232

188

CHAPTER 12. THE LINUX UNIT.

Link

Create a link

233

ReadLink

Read contents of a symbolic link

241

SymLink

Create a symbolic link

251

Umask

Set the file creation mask

256

UnLink

Remove a file

257

Utime

Change file timestamps

257

Pipes, FIFOs and streams Functions for creating and managing pipes. Name

Description

Page

AssignPipe

Create a pipe

194

AssignStream

Create pipes to program’s input and output

194

MkFifo

Make a fifo

235

PClose

Close a pipe

240

POpen

Open a pipe for to program’s input or output

240

Directory handling routines Functions for reading and searching directories. Name

Description

Page

CloseDir

Close directory handle

201

Glob

Return files matching a search expression

228

GlobFree

Free result of Glob

228

OpenDir

Open directory for reading

239

ReadDir

Read directory entry

241

SeekDir

Seek directory

244

TellDir

Seek directory

256

Process handling Functions for managing processes and programs. Name

Description

Page

Clone

Create a thread

199

Execl

Execute process with command-line list

205

Execle

Execute process with command-line list and environment

205

Execlp

Search in path and execute process with command list

206

Execv

Execute process

207

Execve

Execute process with environment

207

Execvp

Search in path and execute process

208

189

CHAPTER 12. THE LINUX UNIT.

Fork

Spawn child process

219

GetEGid

Get effective group id

221

GetEnv

Get environment variable

222

GetEUid

Get effective user id

222

GetGid

Get group id

224

GetPid

Get process id

225

GetPPid

Get parent process id

225

GetPriority

Get process priority

225

GetUid

Get user id

227

Nice

Change priority of process

238

SetPriority

Change priority of process

246

Shell

Execute shell command

246

WaitPid

Wait for child process to terminate

258

Signals Functions for managing and responding to signals. Name

Description

Page

Alarm

Send alarm signal to self

193

Kill

Send arbitrary signal to process

232

pause

Wait for signal to arrive

240

SigAction

Set signal action

247

Signal

Set signal action

249

SigPending

See if signals are waiting

248

SigProcMask

Set signal processing mask

248

SigRaise

Send signal to self

248

SigSuspend

Sets signal mask and waits for signal

249

NanoSleep

Waits for a specific amount of time

237

System information Functions for retrieving system information such as date and time. Name

Description

Page

GetDate

Return system date

220

GetDateTime

Return system date and time

220

GetDomainName

Return system domain name

221

GetEpochTime

Return epoch time

223

GetHostName

Return system host name

224

GetLocalTimezone

Return system timezone

224

GetTime

Return system time

226 190

CHAPTER 12. THE LINUX UNIT.

GetTimeOfDay

Return system time

227

GetTimezoneFile

Return name of timezone file

227

ReadTimezoneFile

Read timezone file contents

244

SysInfo

Return general system information

252

Uname

Return system information

257

Terminal functions Functions for controlling the terminal to which the process is connected. Name

Description

Page

CFMakeRaw

Set terminal to raw mode

196

CFSetISpeed

Set terminal reading speed

197

CFSetOSpeed

Set terminal writing speed

197

IOCtl

General IO control call

228

IsATTY

See if filedescriptor is a terminal

229

TCDrain

Wait till all output was written

253

TCFlow

Suspend transmission or receipt of data

253

TCFlush

Discard data written to terminal

254

TCGetAttr

Get terminal attributes

254

TCGetPGrp

Return PID of foreground process

255

TCSendBreak

Send data for specific time

255

TCSetAttr

Set terminal attributes

255

TCSetPGrp

Set foreground process

256

TTYName

Name of tty file

256

Port input/output Functions for reading and writing to the hardware ports. Name

Description

Page

IOperm

Set permissions for port access

229

ReadPort

Read data from port

243

ReadPortB

Read 1 byte from port

243

ReadPortL

Read 4 bytes from port

243

ReadPortW

Read 2 bytes from port

244

WritePort

Write data to port

259

WritePortB

Write 1 byte to port

259

WritePortL

Write 4 bytes to port

259

WritePortW

Write 2 bytes to port

260

191

CHAPTER 12. THE LINUX UNIT.

Utility routines Auxiliary functions that are useful in connection with the other functions. Name

Description

Page

CreateShellArgV

Create an array of pchars from string

201

EpochToLocal

Convert epoch time to local time

204

FD_Clr

Clear item of select filedescriptors

209

FD_IsSet

Check item of select filedescriptors

210

FD_Set

Set item of select filedescriptors

210

FD_ZERO

Clear all items in select filedecriptors

209

LocalToEpoch

Convert local time to epoch time

234

MMap

Map a file into memory

235

MUnMap

Unmap previously mapped memory file

237

Octal

Convert octal to digital

238

S_ISBLK

Check file mode for block device

230

S_ISCHR

Check file mode for character device

230

S_ISDIR

Check file mode for directory

230

S_ISFIFO

Check file mode for FIFO

230

S_ISLNK

Check file mode for symboloc link

231

S_ISREG

Check file mode for regular file

231

S_ISSOCK

Check file mode for socket

231

StringToPPchar

Create an array of pchars from string

250

12.3

Functions and procedures

Access Declaration: Function Access (Path :

Pathstr; Mode :

integer) :

Boolean;

Description: Tests user’s access rights on the specified file. Mode is a mask existing of one or more of R_OKUser has read rights. W_OKUser has write rights. X_OKUser has execute rights. F_OKUser has search rights in the directory where the file is. The test is done with the real user ID, instead of the effective user ID. If access is denied, or an error occurred, false is returned. Errors: LinuxError is used to report errors: sys_eaccessThe requested access is denied, either to the file or one of the directories in its path. sys_einvalMode was incorrect. sys_enoentA directory component in Path doesn’t exist or is a dangling symbolic link. sys_enotdirA directory component in Path is not a directory.

192

CHAPTER 12. THE LINUX UNIT.

sys_enomemInsufficient kernel memory. sys_eloopPath has a circular symbolic link. See also: Chown (197), Chmod (198), Access (2) Listing: linuxex/ex26.pp Program Example26 ; { Program t o demonstrate t h e Access f u n c t i o n . } Uses BaseUnix ; begin i f fpAccess ( ’ / e t c / passwd ’ ,W_OK) = 0 then begin W r i t e l n ( ’ B e t t e r check your system . ’ ) ; W r i t e l n ( ’ I can w r i t e t o t h e / e t c / passwd f i l e ! ’ ) ; end ; end .

Alarm Declaration: Function Alarm(Sec :

longint) :

Longint;

Description: Alarm schedules an alarm signal to be delivered to your process in Sec seconds. When Sec seconds have elapsed, Linux will send a SIGALRM signal to the current process. If Sec is zero, then no new alarm will be set. Whatever the value of Sec, any previous alarm is cancelled. The function returns the number of seconds till the previously scheduled alarm was due to be delivered, or zero if there was none. Errors: None Listing: linuxex/ex59.pp Program Example59 ; { Program t o demonstrate t h e Alarm f u n c t i o n . } Uses BaseUnix ; Procedure AlarmHandler ( Sig : c i n t ) ; cdecl ; begin W r i t e l n ( ’ Got t o alarm h a n d l e r ’ ) ; end ; begin W r i t e l n ( ’ S e t t i n g alarm h a n d l e r ’ ) ; f p S i g n a l ( SIGALRM, S i g n a l H a n d l e r ( @AlarmHandler ) ) ; W r i t e l n ( ’ Scheduling Alarm i n 1 0 seconds ’ ) ; fpAlarm ( 1 0 ) ; W r i t e l n ( ’ Pausing ’ ) ; fpPause ; W r i t e l n ( ’ Pause r e t u r n e d ’ ) ; end .

193

CHAPTER 12. THE LINUX UNIT.

AssignPipe Declaration: Function AssignPipe(var pipe_in,pipe_out:longint):boolean; Function AssignPipe(var pipe_in,pipe_out:text):boolean; Function AssignPipe(var pipe_in,pipe_out:file):boolean; Description: AssignePipe creates a pipe, i.e. two file objects, one for input, one for output. What is written to Pipe_out, can be read from Pipe_in. This call is overloaded. The in and out pipe can take three forms: an typed or untyped file, a text file or a file descriptor. If a text file is passed then reading and writing from/to the pipe can be done through the usual Readln(Pipe_in,...) and Writeln (Pipe_out,...) procedures. The function returns True if everything went succesfully, False otherwise. Errors: In case the function fails and returns False, LinuxError is used to report errors: sys_emfileToo many file descriptors for this process. sys_enfileThe system file table is full. See also: POpen (240), MkFifo (235), pipe (2) Listing: linuxex/ex36.pp Program Example36 ; { Program t o demonstrate t h e AssignPipe f u n c t i o n . } Uses BaseUnix , Unix ; Var p i p i , p i p o : Text ; s : String ; begin W r i t e l n ( ’ A s s i g n i n g Pipes . ’ ) ; I f a s s i g n p i p e ( p i p i , p i p o ) < >0 then Writeln ( ’ Error assigning pipes ! ’ , f pgeterrno ) ; W r i t e l n ( ’ W r i t i n g t o pipe , and f l u s h i n g . ’ ) ; W r i t e l n ( pipo , ’ T h i s i s a t e x t s t r i n g ’ ) ; c l o s e ( p i p o ) ; W r i t e l n ( ’ Reading from p i p e . ’ ) ; While not eof ( p i p i ) do begin Readln ( p i p i , s ) ; W r i t e l n ( ’ Read from p i p e : ’ , s ) ; end ; close ( p i p i ) ; w r i t e l n ( ’ Closed p i p e s . ’ ) ; writeln end .

AssignStream Declaration: Function AssignStream(Var StreamIn,Streamout:text; Const Prog:String) : longint; Function AssignStream(var StreamIn, StreamOut, StreamErr: Text; const prog: String): LongInt;

194

CHAPTER 12. THE LINUX UNIT.

Description: AssignStream creates a 2 or 3 pipes, i.e. two (or three) file objects, one for input, one for output,(and one for standard error) the other ends of these pipes are connected to standard input and output (and standard error) of Prog. Prog is the name of a program (including path) with options, which will be executed. What is written to StreamOut, will go to the standard input of Prog. Whatever is written by Prog to it’s standard output can be read from StreamIn. Whatever is written by Prog to it’s standard error read from StreamErr, if present. Reading and writing happens through the usual Readln(StreamIn,...) and Writeln (StreamOut,...) procedures. Remark: You should not use Reset or Rewrite on a file opened with POpen. This will close the file before re-opening it again, thereby closing the connection with the program. The function returns the process ID of the spawned process, or -1 in case of error. Errors: In case of error (return value -1) LinuxError is used to report errors: sys_emfileToo many file descriptors for this process. sys_enfileThe system file table is full. Other errors include the ones by the fork and exec programs See also: AssignPipe (194), POpen (240),pipe (2) Listing: linuxex/ex38.pp Program Example38 ; { Program t o demonstrate t h e AssignStream f u n c t i o n . } Uses BaseUnix , Unix ; Var Si , So : Text ; S : String ; i : longint ; begin i f not ( paramstr ( 1 ) = ’−son ’ ) then begin W r i t e l n ( ’ C a l l i n g son ’ ) ; Assignstream ( Si , So , ’ . / ex38 −son ’ ) ; i f f p g e t e r r n o < >0 then begin w r i t e l n ( ’ AssignStream f a i l e d ! ’ ) ; halt ( 1 ) ; end ; W r i t e l n ( ’ Speaking t o son ’ ) ; For i : = 1 to 1 0 do begin w r i t e l n ( so , ’ H e l l o son ! ’ ) ; i f i o r e s u l t < >0 then w r i t e l n ( ’ Can ’ ’ t speak t o son . . . ’ ) ; end ; For i : = 1 to 3 do w r i t e l n ( so , ’ H e l l o chap ! ’ ) ; c l o s e ( so ) ; while not eof ( s i ) do begin readln ( s i , s ) ; w r i t e l n ( ’ F a t h e r : Son s a i d : ’ ,S ) ; end ;

195

CHAPTER 12. THE LINUX UNIT.

W r i t e l n ( ’ Stopped c o n v e r s a t i o n ’ ) ; Close ( S i ) ; W r i t e l n ( ’ Put down phone ’ ) ; end Else begin W r i t e l n ( ’ T h i s i s t h e son ’ ) ; While not eof ( i n p u t ) do begin readln ( s ) ; i f pos ( ’ H e l l o son ! ’ ,S) < >0 then W r i t e l n ( ’ H e l l o Dad ! ’ ) else w r i t e l n ( ’Who are you ? ’ ) ; end ; close ( output ) ; end end .

BaseName Declaration: Function BaseName (Const Path;Const Suf :

Pathstr) :

Pathstr;

Description: Returns the filename part of Path, stripping off Suf if it exists. The filename part is the whole name if Path contains no slash, or the part of Path after the last slash. The last character of the result is not a slash, unless the directory is the root directory. Errors: None. See also: DirName (202), FExpand (214), Basename (1) Listing: linuxex/ex48.pp Program Example48 ; { Program t o demonstrate t h e BaseName f u n c t i o n . } Uses Unix , U n i x U t i l ; Var S : S t r i n g ; begin S: = FExpand ( Paramstr ( 0 ) ) ; W r i t e l n ( ’ T h i s program i s c a l l e d : end .

’ , Basename ( S , ’ ’ ) ) ;

CFMakeRaw Declaration: Procedure CFMakeRaw (var Tios:TermIOS); Description: CFMakeRaw Sets the flags in the Termios structure Tios to a state so that the terminal will function in Raw Mode. Errors: None. See also: CFSetOSpeed (197), CFSetISpeed (197), termios (2) For an example, see TCGetAttr (254). 196

CHAPTER 12. THE LINUX UNIT.

CFSetISpeed Declaration: Procedure CFSetISpeed (var Tios:TermIOS;Speed:Longint); Description: CFSetISpeed Sets the input baudrate in the TermIOS structure Tios to Speed. Errors: None. See also: CFSetOSpeed (197), CFMakeRaw (196), termios (2)

CFSetOSpeed Declaration: Procedure CFSetOSpeed (var Tios:TermIOS;Speed:Longint); Description: CFSetOSpeed Sets the output baudrate in the Termios structure Tios to Speed. Errors: None. See also: CFSetISpeed (197), CFMakeRaw (196), termios (2)

Chown Declaration: Function Chown (Path :

Pathstr;NewUid,NewGid :

Longint) :

Boolean;

Description: Chown sets the User ID and Group ID of the file in Path to NewUid, NewGid. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. sys_epermThe effective UID doesn’t match the ownership of the file, and is not zero. Owner or group were not specified correctly. sys_eaccessOne of the directories in Path has no search (=execute) permission. sys_enoentA directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory. sys_enotdirA directory entry in OldPath or NewPath is nor a directory. sys_enomemInsufficient kernel memory. sys_erofsThe file is on a read-only filesystem. sys_eloopPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. See also: Chmod (198), Access (192), Chown (() 2) Listing: linuxex/ex24.pp Program Example24 ; { Program t o demonstrate t h e Chown f u n c t i o n . } Uses BaseUnix ; Var UID : TUid ; GID : TGid ; F : Text ; begin

197

CHAPTER 12. THE LINUX UNIT.

W r i t e l n ( ’ T h i s w i l l o n l y work i f you are r o o t . ’ ) ; Write ( ’ E n t e r a UID : ’ ) ; readln ( UID ) ; Write ( ’ E n t e r a GID : ’ ) ; readln ( GID ) ; Assign ( f , ’ t e s t . t x t ’ ) ; Rewrite ( f ) ; W r i t e l n ( f , ’ The owner o f t h i s f i l e should become : ’ ) ; W r i t e l n ( f , ’ UID : ’ , UID ) ; W r i t e l n ( f , ’ GID : ’ , GID ) ; Close ( F ) ; i f fpChown ( ’ t e s t . t x t ’ , UID , GID) < >0 then i f f p g e t e r r n o =ESysEPERM then W r i t e l n ( ’ You are n o t r o o t ! ’ ) else W r i t e l n ( ’Chmod f a i l e d w i t h e x i t code : ’ , f p g e t e r r n o ) else W r i t e l n ( ’ Changed owner s u c c e s s f u l l y ! ’ ) ; end .

Chmod Declaration: Function Chmod (Path :

Pathstr;NewMode :

Longint) :

Boolean;

Description: Chmod Sets the Mode bits of the file in Path to NewMode. Newmode can be specified by ’or’-ing the following: S_ISUIDSet user ID on execution. S_ISGIDSet Group ID on execution. S_ISVTXSet sticky bit. S_IRUSRRead by owner. S_IWUSRWrite by owner. S_IXUSRExecute by owner. S_IRGRPRead by group. S_IWGRPWrite by group. S_IXGRPExecute by group. S_IROTHRead by others. S_IWOTHWrite by others. S_IXOTHExecute by others. S_IRWXORead, write, execute by others. S_IRWXGRead, write, execute by groups. S_IRWXURead, write, execute by user. Errors: Errors are returned in LinuxError. sys_epermThe effective UID doesn’t match the ownership of the file, and is not zero. Owner or group were not specified correctly. sys_eaccessOne of the directories in Path has no search (=execute) permission. sys_enoentA directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory. sys_enotdirA directory entry in OldPath or NewPath is nor a directory. sys_enomemInsufficient kernel memory. 198

CHAPTER 12. THE LINUX UNIT.

sys_erofsThe file is on a read-only filesystem. sys_eloopPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. See also: Chown (197), Access (192), Chmod (() 2), Octal (238) Listing: linuxex/ex23.pp Program Example23 ; { Program t o demonstrate t h e Chmod f u n c t i o n . } Uses BaseUnix , Unix ; Var F : Text ; begin { Create a f i l e } Assign ( f , ’ t e s t e x 2 1 ’ ) ; Rewrite ( F ) ; W r i t e l n ( f , ’ # ! / b i n / sh ’ ) ; W r i t e l n ( f , ’ echo Some t e x t f o r t h i s f i l e ’ ) ; Close ( F ) ; fpChmod ( ’ t e s t e x 2 1 ’ , & 7 7 7 ) ; { F i l e i s now e x e c u t a b l e } execl ( ’ . / testex21 ’ ) ; end .

Clone

Declaration: TCloneFunc=function(args:pointer):longint;cdecl; Clone(func:TCloneFunc;sp:pointer;flags Description: Clone creates a child process which is a copy of the parent process, just like Fork (219) does. In difference with Fork, however, the child process shares some parts of it’s execution context with its parent, so it is suitable for the implementation of threads: many instances of a program that share the same memory. When the child process is created, it starts executing the function Func, and passes it Args. The return value of Func is either the explicit return value of the function, or the exit code of the child process. The sp pointer points to the memory reserved as stack space for the child process. This address should be the top of the memory block to be used as stack. The Flags determine the behaviour of the Clone call. The low byte of the Flags contains the number of the signal that will be sent to the parent when the child dies. This may be bitwise OR’ed with the following constants: CLONE_VMParent and child share the same memory space, including memory (un)mapped with subsequent mmap calls. CLONE_FSParent and child have the same view of the filesystem; the chroot, chdir and umask calls affect both processes. CLONE_FILESthe file descriptor table of parent and child is shared. CLONE_SIGHANDthe parent and child share the same table of signal handlers. The signal masks are different, though. CLONE_PIDPArent and child have the same process ID. 199

CHAPTER 12. THE LINUX UNIT.

Clone returns the process ID in the parent process, and -1 if an error occurred. Errors: On error, -1 is returned to the parent, and no child is created. sys_eagainToo many processes are running. sys_enomemNot enough memory to create child process. See also: Fork (219), clone (2) Listing: linuxex/ex71.pp program TestC { l o n e } ; { $ i f d e f Linux } / / c l o s e i s v e r y L i n u x s p e c i f i c . 1 . 9 . x t h r e a d i n g i s done v i a p t h r e a d s . uses Linux , E r r o r s , c r t ; const Ready : Boolean = f a l s e ; aChar : Char = ’a ’ ; function CloneProc ( Arg : P o i n t e r ) : L o n g I n t ; Cdecl ; begin WriteLn ( ’ H e l l o from t h e c l o n e ’ , PChar ( Arg ) ) ; repeat Write ( aChar ) ; Select (0 ,0 ,0 ,0 ,600); u n t i l Ready ; WriteLn ( ’ Clone f i n i s h e d . ’ ) ; CloneProc : = 1 ; end ; var PID : L o n g I n t ; procedure MainProc ; begin WriteLn ( ’ cloned process PID : ’ , PID ) ; WriteLn ( ’ Press t o k i l l . . . ’ ) ; repeat Write ( ’ . ’ ) ; Select (0 ,0 ,0 ,0 ,300); i f KeyPressed then case ReadKey of # 2 7 : Ready : = t r u e ; ’ a ’ : aChar : = ’A ’ ; ’A ’ : aChar : = ’ a ’ ; ’ b ’ : aChar : = ’ b ’ ; ’B ’ : aChar : = ’B ’ ; end ; u n t i l Ready ; WriteLn ( ’ Ready . ’ ) ; end ; const StackSze = 1 6 3 8 4 ; t h e F l a g s = CLONE_VM+CLONE_FS+CLONE_FILES+CLONE_SIGHAND ;

200

CHAPTER 12. THE LINUX UNIT.

aMsg

: PChar = ’ Oops ! ’ ;

var theStack : Pointer ; E x i t S t a t : LongInt ; begin GetMem( theStack , StackSze ) ; PID : = Clone ( @CloneProc , P o i n t e r ( L o n g I n t ( t h e S t a c k )+ StackSze ) , theFlags , aMsg ) ; i f PID < 0 then WriteLn ( ’ E r r o r : ’ , L i n u x E r r o r , ’ when c l o n i n g . ’ ) else begin MainProc ; case WaitPID ( 0 , @ExitStat , Wait_Untraced or w a i t _ c l o n e ) of −1: WriteLn ( ’ e r r o r : ’ , L i n u x E r r o r , ’ ; ’ , S t r E r r o r ( L i n u x E r r o r ) ) ; 0 : WriteLn ( ’ e r r o r : ’ , L i n u x E r r o r , ’ ; ’ , S t r E r r o r ( L i n u x E r r o r ) ) ; else WriteLn ( ’ Clone e x i t e d w i t h : ’ , E x i t S t a t shr 8 ) ; end ; end ; FreeMem ( theStack , StackSze ) ; { $else } begin { $endif } end .

CloseDir Declaration: Function CloseDir (p:pdir) :

integer;

Description: CloseDir closes the directory pointed to by p. It returns zero if the directory was closed succesfully, -1 otherwise. Errors: Errors are returned in LinuxError. See also: OpenDir (239), ReadDir (241), SeekDir (244), TellDir (256), closedir (3) For an example, see OpenDir (239).

CreateShellArgV Declaration: function CreateShellArgV(const prog:string):ppchar; function CreateShellArgV(const prog:Ansistring):ppchar; Description: CreateShellArgV creates an array of 3 PChar pointers that can be used as arguments to ExecVE the first elements in the array will contain /bin/sh, the second will contain -c, and the third will contain prog. The function returns a pointer to this array, of type PPChar. Errors: None. See also: Shell (246) 201

CHAPTER 12. THE LINUX UNIT.

Listing: linuxex/ex61.pp Program ex61 ; { Example program t o demonstrate t h e CreateShellArgV f u n c t i o n } / / note : CreateShellArgV i s r e a s o n b l y o b s o l e t e i n 1 . 9 . x due t o

t h e new fpexec f u n c t i o n s

uses Unix ; Var S : String ; PP : PPchar ; I : longint ; begin S: = ’ s c r i p t −a −b −c −d −e f g h i j k ’ ; PP: = CreateShellArgV ( S ) ; I :=0; I f PP N i l then While PP [ i ] < > N i l do begin W r i t e l n ( ’ Got : " ’ ,PP [ i ] , ’ " ’ ) ; Inc ( i ) ; end ; end .

DirName Declaration: Function DirName (Const Path :

Pathstr) :

Pathstr;

Description: Returns the directory part of Path. The directory is the part of Path before the last slash, or empty if there is no slash. The last character of the result is not a slash, unless the directory is the root directory. Errors: None. See also: BaseName (196), FExpand (214), Dirname (1) Listing: linuxex/ex47.pp Program Example47 ; { Program t o demonstrate t h e DirName f u n c t i o n . } Uses Unix , U n i x U t i l ; Var S : S t r i n g ; begin S: = FExpand ( Paramstr ( 0 ) ) ; W r i t e l n ( ’ T h i s program i s i n d i r e c t o r y : end .

202

’ , Dirname (S ) ) ;

CHAPTER 12. THE LINUX UNIT.

Dup Declaration: Function Dup(oldfile:longint;var newfile:longint):Boolean; Function Dup(var oldfile,newfile:text):Boolean; Function Dup(var oldfile,newfile:file):Boolean; Description: Makes NewFile an exact copy of OldFile, after having flushed the buffer of OldFile in case it is a Text file or untyped file. Due to the buffering mechanism of Pascal, this has not the same functionality as the dup (2) call in C. The internal Pascal buffers are not the same after this call, but when the buffers are flushed (e.g. after output), the output is sent to the same file. Doing an lseek will, however, work as in C, i.e. doing a lseek will change the fileposition in both files. The function returns False in case of an error, True if successful. Errors: In case of errors, Linuxerror is used to report errors. sys_ebadfOldFile hasn’t been assigned. sys_emfileMaximum number of open files for the process is reached. See also: Dup2 (203), Dup (2) Listing: linuxex/ex31.pp program Example31 ; { Program t o demonstrate t h e Dup f u n c t i o n . } uses baseunix ; var f : t e x t ; begin i f fpdup ( o u t p u t , f ) < >0 then W r i t e l n ( ’ Dup F a i l e d ! ’ ) ; writeln ( ’ This i s w r i t t e n to stdout . ’ ) ; w r i t e l n ( f , ’ T h i s i s w r i t t e n t o t h e dup f i l e , and f l u s h e d ’ ) ; f l u s h ( f ) ; writeln end .

Dup2

Declaration: Function Dup2(oldfile,newfile:longint):Boolean; Function Dup2(var oldfile,newfile:text) Function Dup2(var oldfile,newfile:file):Boolean; Description: Makes NewFile an exact copy of OldFile, after having flushed the buffer of OldFile in the case of text or untyped files. NewFile can be an assigned file. If newfile was open, it is closed first. Due to the buffering mechanism of Pascal, this has not the same functionality as the dup2 (2) call in C. The internal Pascal buffers are not the same after this call, but when the buffers are flushed (e.g. after output), the output is sent to the same file. Doing an lseek will, however, work as in C, i.e. doing a lseek will change the fileposition in both files. The function returns True if succesful, false otherwise. Errors: In case of error, Linuxerror is used to report errors. sys_ebadfOldFile hasn’t been assigned. sys_emfileMaximum number of open files for the process is reached.

203

CHAPTER 12. THE LINUX UNIT.

See also: Dup (203), Dup2 (2) Listing: linuxex/ex32.pp program Example31 ; { Program t o demonstrate t h e Dup f u n c t i o n . } uses BaseUnix ; var f : t e x t ; i : longint ; begin Assign ( f , ’ t e x t . t x t ’ ) ; Rewrite ( F ) ; For i : = 1 to 1 0 do w r i t e l n ( F , ’ L i n e : ’ , i ) ; i f fpdup2 ( o u t p u t , f ) < >0 then W r i t e l n ( ’ Dup2 F a i l e d ! ’ ) ; writeln ( ’ This i s w r i t t e n to stdout . ’ ) ; w r i t e l n ( f , ’ T h i s i s w r i t t e n t o t h e dup f i l e , and f l u s h e d ’ ) ; flush ( f ) ; writeln ; { Remove f i l e . Comment t h i s i f you want t o check f l u s h i n g . } fpUnlink ( ’ text . t x t ’ ) ; end .

EpochToLocal Declaration: Procedure EpochToLocal (Epoch : : Word);

Longint; var Year,Month,Day,Hour,Minute,Second

Description: Converts the epoch time (=Number of seconds since 00:00:00 , January 1, 1970, corrected for your time zone ) to local date and time. This function takes into account the timzeone settings of your system. Errors: None See also: GetEpochTime (223), LocalToEpoch (234), GetTime (226),GetDate (220) Listing: linuxex/ex3.pp Program Example3 ; { Program t o demonstrate t h e EpochToLocal f u n c t i o n . } Uses Unix , U n i x U t i l ; Var Year , month , day , hour , minute , seconds : Word ; begin EpochToLocal ( GetEpochTime , Year , month , day , hour , minute , seconds ) ; W r i t e l n ( ’ C u r r e n t date : ’ , Day : 2 , ’ / ’ , Month : 2 , ’ / ’ , Year : 4 ) ; W r i t e l n ( ’ C u r r e n t t i m e : ’ , Hour : 2 , ’ : ’ , minute : 2 , ’ : ’ , seconds : 2 ) ; end .

204

CHAPTER 12. THE LINUX UNIT.

Execl Declaration: Procedure Execl (Path :

pathstr);

Description: Replaces the currently running program with the program, specified in path. Path is split into a command and it’s options. The executable in path is NOT searched in the path. The current environment is passed to the program. On success, execl does not return. Errors: Errors are reported in LinuxError: sys_eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys_epermThe file system is mounted noexec. sys_e2bigArgument list too big. sys_enoexecThe magic number in the file is incorrect. sys_enoentThe file does not exist. sys_enomemNot enough memory for kernel, or to split command line. sys_enotdirA component of the path is not a directory. sys_eloopThe path contains a circular reference (via symlinks). See also: Execve (207), Execv (207), Execvp (208), Execle (205), Execlp (206), Fork (219), execvp (3) Listing: linuxex/ex10.pp Program Example10 ; { Program t o demonstrate t h e Execl f u n c t i o n . } Uses unix , s t r i n g s ; begin { Execute ’ l s − l ’ , w i t h c u r r e n t environment . } { ’ l s ’ i s NOT looked f o r i n PATH environment v a r i a b l e . } Execl ( ’ / b i n / l s − l ’ ) ; end .

Execle Declaration: Procedure Execle (Path :

pathstr, Ep :

ppchar);

Description: Replaces the currently running program with the program, specified in path. Path is split into a command and it’s options. The executable in path is searched in the path, if it isn’t an absolute filename. The environment in ep is passed to the program. On success, execle does not return. Errors: Errors are reported in LinuxError: sys_eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys_epermThe file system is mounted noexec. sys_e2bigArgument list too big. sys_enoexecThe magic number in the file is incorrect. sys_enoentThe file does not exist. sys_enomemNot enough memory for kernel, or to split command line. 205

CHAPTER 12. THE LINUX UNIT.

sys_enotdirA component of the path is not a directory. sys_eloopThe path contains a circular reference (via symlinks). See also: Execve (207), Execv (207), Execvp (208), Execl (205), Execlp (206), Fork (219), execvp (3) Listing: linuxex/ex11.pp Program Example11 ; { Program t o demonstrate t h e Execle f u n c t i o n . } Uses Unix , s t r i n g s ; begin { Execute ’ l s − l ’ , w i t h c u r r e n t environment . } { ’ l s ’ i s NOT looked f o r i n PATH environment v a r i a b l e . } { envp i s d e f i n e d i n t h e system u n i t . } Execle ( ’ / b i n / l s − l ’ , envp ) ; end .

Execlp Declaration: Procedure Execlp (Path :

pathstr);

Description: Replaces the currently running program with the program, specified in path. Path is split into a command and it’s options. The executable in path is searched in the path, if it isn’t an absolute filename. The current environment is passed to the program. On success, execlp does not return. Errors: Errors are reported in LinuxError: sys_eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys_epermThe file system is mounted noexec. sys_e2bigArgument list too big. sys_enoexecThe magic number in the file is incorrect. sys_enoentThe file does not exist. sys_enomemNot enough memory for kernel, or to split command line. sys_enotdirA component of the path is not a directory. sys_eloopThe path contains a circular reference (via symlinks). See also: Execve (207), Execv (207), Execvp (208), Execle (205), Execl (205), Fork (219), execvp (3) Listing: linuxex/ex12.pp Program Example12 ; { Program t o demonstrate t h e Execlp f u n c t i o n . } Uses Unix , s t r i n g s ; begin { Execute ’ l s − l ’ , w i t h c u r r e n t environment . } { ’ l s ’ i s looked f o r i n PATH environment v a r i a b l e . } { envp i s d e f i n e d i n t h e system u n i t . } Execlp ( ’ l s − l ’ , envp ) ; end .

206

CHAPTER 12. THE LINUX UNIT.

Execv Declaration: Procedure Execv (Path :

pathstr; args :

ppchar);

Description: Replaces the currently running program with the program, specified in path. It gives the program the options in args. This is a pointer to an array of pointers to null-terminated strings. The last pointer in this array should be nil. The current environment is passed to the program. On success, execv does not return. Errors: Errors are reported in LinuxError: sys_eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys_epermThe file system is mounted noexec. sys_e2bigArgument list too big. sys_enoexecThe magic number in the file is incorrect. sys_enoentThe file does not exist. sys_enomemNot enough memory for kernel. sys_enotdirA component of the path is not a directory. sys_eloopThe path contains a circular reference (via symlinks). See also: Execve (207), Execvp (208), Execle (205), Execl (205), Execlp (206), Fork (219), execv (3) Listing: linuxex/ex8.pp Program Example8 ; { Program t o demonstrate t h e Execv f u n c t i o n . } Uses Unix , s t r i n g s ; Const Arg0 : PChar = ’ / b i n / l s ’ ; Arg1 : Pchar = ’− l ’ ; Var PP : PPchar ;

begin GetMem ( PP, 3 ∗ SizeOf ( Pchar ) ) ; PP [ 0 ] : = Arg0 ; PP [ 1 ] : = Arg1 ; PP [ 3 ] : = N i l ; { Execute ’ / b i n / l s − l ’ , w i t h c u r r e n t environment } fpExecv ( ’ / b i n / l s ’ , pp ) ; end .

Execve Declaration: Procedure Execve(Path:pchar;args:ppchar;ep:ppchar); Procedure Execve (Path : pathstr; args,ep : ppchar); Description: Replaces the currently running program with the program, specified in path. It gives the program the options in args, and the environment in ep. They are pointers to an array of pointers to nullterminated strings. The last pointer in this array should be nil. On success, execve does not return.

207

CHAPTER 12. THE LINUX UNIT.

Errors: Errors are reported in LinuxError: eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys_ epermThe file system is mounted noexec. sys_ e2bigArgument list too big. sys_ enoexecThe magic number in the file is incorrect. sys_ enoentThe file does not exist. sys_ enomemNot enough memory for kernel. sys_ enotdirA component of the path is not a directory. sys_ eloopThe path contains a circular reference (via symlinks). See also: Execve (207), Execv (207), Execvp (208) Execle (205), Execl (205), Execlp (206), Fork (219), execve (2) Listing: linuxex/ex7.pp Program Example7 ; { Program t o demonstrate t h e Execve f u n c t i o n . } Uses BaseUnix , s t r i n g s ; Const Arg0 : PChar = ’ / b i n / l s ’ ; Arg1 : Pchar = ’− l ’ ; Var PP : PPchar ;

begin GetMem ( PP, 3 ∗ SizeOf ( Pchar ) ) ; PP [ 0 ] : = Arg0 ; PP [ 1 ] : = Arg1 ; PP [ 3 ] : = N i l ; { Execute ’ / b i n / l s − l ’ , w i t h c u r r e n t environment } { Envp i s d e f i n e d i n system . i n c } fpExecVe ( ’ / b i n / l s ’ , pp , envp ) ; end .

Execvp Declaration: Procedure Execvp (Path :

pathstr; args :

ppchar);

Description: Replaces the currently running program with the program, specified in path. The executable in path is searched in the path, if it isn’t an absolute filename. It gives the program the options in args. This is a pointer to an array of pointers to null-terminated strings. The last pointer in this array should be nil. The current environment is passed to the program. On success, execvp does not return. Errors: Errors are reported in LinuxError: sys_eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys_epermThe file system is mounted noexec. 208

CHAPTER 12. THE LINUX UNIT.

sys_e2bigArgument list too big. sys_enoexecThe magic number in the file is incorrect. sys_enoentThe file does not exist. sys_enomemNot enough memory for kernel. sys_enotdirA component of the path is not a directory. sys_eloopThe path contains a circular reference (via symlinks). See also: Execve (207), Execv (207), Execle (205), Execl (205), Execlp (206), Fork (219), execvp (3) Listing: linuxex/ex9.pp Program Example9 ; { Program t o demonstrate t h e Execvp f u n c t i o n . } Uses Unix , s t r i n g s ; Const Arg0 : PChar = ’ l s ’ ; Arg1 : Pchar = ’− l ’ ; Var PP : PPchar ;

begin GetMem ( PP, 3 ∗ SizeOf ( Pchar ) ) ; PP [ 0 ] : = Arg0 ; PP [ 1 ] : = Arg1 ; PP [ 3 ] : = N i l ; { Execute ’ l s − l ’ , w i t h c u r r e n t environment . } { ’ l s ’ i s looked f o r i n PATH environment v a r i a b l e . } { Envp i s d e f i n e d i n t h e system u n i t . } fpExecvpe ( ’ l s ’ , pp , envp ) ; end .

FD_ZERO Declaration: Procedure FD_ZERO (var fds:fdSet); Description: FD_ZERO clears all the filedescriptors in the file descriptor set fds. Errors: None. See also: Select (244), SelectText (245), GetFS (223), FD_Clr (209), FD_Set (210), FD_IsSet (210) For an example, see Select (244).

FD_Clr Declaration: Procedure FD_Clr (fd:longint;var fds:fdSet); Description: FD_Clr clears file descriptor fd in filedescriptor s et fds. Errors: None. See also: Select (244), SelectText (245), GetFS (223), FD_ZERO (209), FD_Set (210), FD_IsSet (210) For an example, see Select (244). 209

CHAPTER 12. THE LINUX UNIT.

FD_IsSet Declaration: Function FD_IsSet (fd:longint;var fds:fdSet) :

boolean;

Description: FD_Set Checks whether file descriptor fd in filedescriptor set fds is set. Errors: None. See also: Select (244), SelectText (245), GetFS (223), FD_ZERO (209), FD_Clr (209), FD_Set (210) For an example, see Select (244).

FD_Set Declaration: Procedure FD_Set (fd:longint;var fds:fdSet); Description: FD_Set sets file descriptor fd in filedescriptor set fds. Errors: None. See also: Select (244), SelectText (245), GetFS (223),FD_ZERO (209), FD_Clr (209), FD_IsSet (210) For an example, see Select (244).

fdClose Declaration: Function fdClose (fd:longint) :

boolean;

Description: fdClose closes a file with file descriptor Fd. The function returns True if the file was closed successfully, False otherwise. Errors: Errors are returned in LinuxError See also: fdOpen (211), fdRead (212), fdWrite (213),fdTruncate (213), fdFlush (210), seefFdSeek For an example, see fdOpen (211).

fdFlush Declaration: Function fdFlush (fd:Longint) :

boolean;

Description: fdflush flushes the Linux kernel file buffer, so the file is actually written to disk. This is NOT the same as the internal buffer, maintained by Free Pascal. The function returns True if the call was successful, false if an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (211), fdClose (210), fdRead (212),fdWrite (213), fdTruncate (213), fdSeek (213) For an example, see fdRead (212).

210

CHAPTER 12. THE LINUX UNIT.

fdOpen Declaration: Function fdOpen(PathName:String;flags:longint):longint; Function fdOpen(PathName:Pchar ;flags:longint):longint; Function fdOpen(PathName:String;flags,mode:longint):longint; Function fdOpen(PathName:Pchar ;flags,mode:longint):longint; Description: fdOpen opens a file in PathName with flags flags One of the following: Open_RdOnlyFile is opened Read-only. Open_WrOnlyFile is opened Write-only. Open_RdWrFile is opened Read-Write. The flags may beOR-ed with one of the following constants: Open_AccmodeFile is opened Open_CreatFile is created if it doesn’t exist. Open_ExclIf the file is opened with Open_Creat and it already exists, the call wil fail. Open_NoCttyIf the file is a terminal device, it will NOT become the process’ controlling terminal. Open_TruncIf the file exists, it will be truncated. Open_Appendthe file is opened in append mode. Before each write, the file pointer is positioned at the end of the file. Open_NonBlockThe file is opened in non-blocking mode. No operation on the file descriptor will cause the calling process to wait till. Open_NDelayIdem as Open_NonBlock Open_SyncThe file is opened for synchronous IO. Any write operation on the file will not return untill the data is physically written to disk. Open_NoFollowif the file is a symbolic link, the open fails. (LINUX 2.1.126 and higher only) Open_Directoryif the file is not a directory, the open fails. (LINUX 2.1.126 and higher only) PathName can be of type PChar or String. The optional mode argument specifies the permissions to set when opening the file. This is modified by the umask setting. The real permissions are Mode and not umask. The return value of the function is the filedescriptor, or a negative value if there was an error. Errors: Errors are returned in LinuxError See also: fdClose (210), fdRead (212), fdWrite (213),fdTruncate (213), fdFlush (210), fdSeek (213) Listing: linuxex/ex19.pp Program Example19 ; { Program t o demonstrate t h e fdOpen , f d w r i t e and fdCLose f u n c t i o n s . } Uses BaseUnix ; Const L i n e : S t r i n g [ 8 0 ] = ’ T h i s i s easy w r i t i n g ! ’ ; Var FD : C i n t ; begin FD: = fpOpen ( ’ Test . d a t ’ , O_WrOnly or O_Creat ) ; i f FD>0 then begin i f length ( L i n e ) < > f p w r i t e ( FD, L i n e [ 1 ] , Length ( L i n e ) ) then

211

CHAPTER 12. THE LINUX UNIT.

W r i t e l n ( ’ E r r o r when w r i t i n g t o f i l e ! ’ ) ; f p C l o s e (FD ) ; end ; end .

fdRead Declaration: Function fdRead (fd:longint;var buf;size:longint) :

longint;

Description: fdRead reads at most size bytes from the file descriptor fd, and stores them in buf. The function returns the number of bytes actually read, or -1 if an error occurred. No checking on the length of buf is done. Errors: Errors are returned in LinuxError. See also: fdOpen (211), fdClose (210), fdWrite (213),fdTruncate (213), fdFlush (210), fdSeek (213) Listing: linuxex/ex20.pp Program Example20 ; { Program t o demonstrate t h e fdRead and f d T r u n c a t e f u n c t i o n s . } Uses BaseUnix ; Const Data : s t r i n g [ 1 0 ] = ’ 1234567890 ’ ; Var FD : c i n t ; l : longint ; begin FD: = fpOpen ( ’ t e s t . d a t ’ , o_wronly or o_creat , & 6 6 6 ) ; i f fd >0 then begin { F i l l f i l e w i t h data } f o r l : = 1 to 1 0 do i f f p W r i t e ( FD, Data [ 1 ] , 1 0 ) < > 1 0 then begin w r i t e l n ( ’ E r r o r when w r i t i n g ! ’ ) ; halt ( 1 ) ; end ; f p C l o s e (FD ) ; FD: = fpOpen ( ’ t e s t . d a t ’ , o _ r d o n l y ) ; { Read data again } I f FD>0 then begin For l : = 1 to 5 do i f fpRead ( FD, Data [ 1 ] , 1 0 ) < > 1 0 then begin W r i t e l n ( ’ E r r o r when Reading ! ’ ) ; Halt ( 2 ) ; end ; f p C l o s e (FD ) ; { Truncating f i l e at 6 0 bytes } { For t r u n c a t i n g , f i l e must be open o r w r i t e } FD: = fpOpen ( ’ t e s t . d a t ’ , o_wronly , & 6 6 6 ) ; i f FD>0 then

212

CHAPTER 12. THE LINUX UNIT.

begin i f f p f T r u n c a t e ( FD,60) < >0 then W r i t e l n ( ’ E r r o r when t r u n c a t i n g ! ’ ) ; f p C l o s e ( FD ) ; end ; end ; end ; end .

fdSeek Declaration: Function fdSeek (fd,Pos,SeekType:longint) :

longint;

Description: fdSeek sets the current fileposition of file fd to Pos, starting from SeekType, which can be one of the following: Seek_Set Pos is the absolute position in the file. Seek_Cur Pos is relative to the current position. Seek_end Pos is relative to the end of the file. The function returns the new fileposition, or -1 of an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (211), fdWrite (213), fdClose (210), fdRead (212),fdTruncate (213), fdFlush (210) For an example, see fdOpen (211).

fdTruncate Declaration: Function fdTruncate (fd,size:longint) :

boolean;

Description: fdTruncate sets the length of a file in fd on size bytes, where size must be less than or equal to the current length of the file in fd. The function returns True if the call was successful, false if an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (211), fdClose (210), fdRead (212),fdWrite (213),fdFlush (210), fdSeek (213)

fdWrite Declaration: Function fdWrite (fd:longint;var buf;size:longint) :

longint;

Description: fdWrite writes at most size bytes from buf to file descriptor fd. The function returns the number of bytes actually written, or -1 if an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (211), fdClose (210), fdRead (212),fdTruncate (213), fdSeek (213), fdFlush (210)

213

CHAPTER 12. THE LINUX UNIT.

FExpand Declaration: Function FExpand (Const Path:

Pathstr) :

pathstr;

Description: Expands Path to a full path, starting from root, eliminating directory references such as . and .. from the result. Errors: None See also: BaseName (196),DirName (202) Listing: linuxex/ex45.pp Program Example45 ; { Program t o demonstrate t h e FExpand f u n c t i o n . } Uses Unix ; begin W r i t e l n ( ’ T h i s program i s i n : end .

’ , FExpand ( Paramstr ( 0 ) ) ) ;

FLock Declaration: Function Flock (fd,mode : longint) : boolean; Function Flock (var T : text;mode : longint) : boolean; Function Flock (var F : File;mode : longint) : boolean; Description: FLock implements file locking. it sets or removes a lock on the file F. F can be of type Text or File, or it can be a LINUX filedescriptor (a longint) Mode can be one of the following constants : LOCK_SH sets a shared lock. LOCK_EX sets an exclusive lock. LOCK_UN unlocks the file. LOCK_NB This can be OR-ed together with the other. If this is done the application doesn’t block when locking. The function returns True if successful, False otherwise. Errors: If an error occurs, it is reported in LinuxError. See also: Fcntl (218), flock (2)

FNMatch Declaration: Function FNMatch(const Pattern,Name:string):Boolean; Description: FNMatch returns True if the filename in Name matches the wildcard pattern in Pattern, False otherwise. Pattern can contain the wildcards * (match zero or more arbitrary characters) or ? (match a single character). Errors: None. See also: FSearch (215), FExpand (214) 214

CHAPTER 12. THE LINUX UNIT.

Listing: linuxex/ex69.pp Program Example69 ; { Program t o demonstrate t h e FNMatch f u n c t i o n . } Uses u n i x u t i l ; Procedure TestMatch ( P a t t e r n ,Name : S t r i n g ) ; begin Write ( ’ " ’ ,Name, ’ " ’ ) ; I f FNMatch ( P a t t e r n ,Name ) then Write ( ’ matches ’ ) else Write ( ’ does n o t match ’ ) ; Writeln ( ’ " ’ , Pattern , ’ " . ’ ) ; end ; begin TestMatch ( TestMatch ( TestMatch ( TestMatch ( TestMatch ( TestMatch ( TestMatch ( TestMatch ( end .

’ ∗ ’ , ’ FileName ’ ) ; ’ . ∗ ’ , ’ FileName ’ ) ; ’ ∗a∗ ’ , ’ FileName ’ ) ; ’ ? i l e ∗ ’ , ’ FileName ’ ) ; ’ ? ’ , ’ FileName ’ ) ; ’ . ? ’ , ’ FileName ’ ) ; ’ ?a∗ ’ , ’ FileName ’ ) ; ’ ??∗me? ’ , ’ FileName ’ ) ;

FSearch Declaration: Function FSearch (Path :

pathstr;DirList :

string) :

Pathstr;

Description: Searches in DirList, a colon separated list of directories, for a file named Path. It then returns a path to the found file. Errors: An empty string if no such file was found. See also: BaseName (196), DirName (202), FExpand (214), FNMatch (214) Listing: linuxex/ex46.pp Program Example46 ; { Program t o demonstrate t h e FSearch f u n c t i o n . } Uses BaseUnix , Unix , S t r i n g s ; begin Writeln ( ’ l s i s i n : end .

’ , FSearch ( ’ l s ’ , strpas ( fpGetenv ( ’PATH ’ ) ) ) ) ;

FSplit Declaration: Procedure FSplit(const Path:PathStr; Var Dir:DirStr;Var Name:NameStr;Var Ext:ExtStr); 215

CHAPTER 12. THE LINUX UNIT.

Description: FSplit splits a full file name into 3 parts : A Path, a Name and an extension (in ext). The extension is taken to be all letters after the last dot (.). Errors: None. See also: FSearch (215) Listing: linuxex/ex67.pp Program Example67 ; uses U n i x U t i l ; { Program t o demonstrate t h e F S p l i t f u n c t i o n . } var Path , Name, Ext : s t r i n g ; begin F S p l i t ( ParamStr ( 1 ) , Path , Name, Ext ) ; WriteLn ( ’ S p l i t ’ , ParamStr ( 1 ) , ’ i n : ’ ) ; WriteLn ( ’ Path : ’ , Path ) ; WriteLn ( ’Name : ’ ,Name ) ; WriteLn ( ’ E x t e n s i o n : ’ , Ext ) ; end .

FSStat Declaration: Function FSStat (Path : Pathstr; Var Info : statfs) : FSStat (Fd:longint;Var Info:stat) : Boolean;

Boolean; Function

Description: Return in Info information about the filesystem on which the file Path resides, or on which the file with file descriptor fd resides. Info is of type statfs. The function returns True if the call was succesfull, False if the call failed. Errors: LinuxError is used to report errors. sys_enotdirA component of Path is not a directory. sys_einvalInvalid character in Path. sys_enoentPath does not exist. sys_eaccessSearch permission is denied for component in Path. sys_eloopA circular symbolic link was encountered in Path. sys_eioAn error occurred while reading from the filesystem. See also: FStat (217), LStat (232), statfs (2) Listing: linuxex/ex30.pp program Example30 ; { Program t o demonstrate t h e FSStat f u n c t i o n . } uses BaseUnix , Unix ; var s : s t r i n g ; info : tstatfs ;

216

CHAPTER 12. THE LINUX UNIT.

begin w r i t e l n ( ’ I n f o about c u r r e n t p a r t i t i o n : ’ ) ; s := ’ . ’ ; while s ’ q ’ do begin i f s t a t f s ( s , i n f o ) < >0 then begin w r i t e l n ( ’ F s t a t f a i l e d . Errno : ’ , f p g e t e r r n o ) ; halt ( 1 ) ; end ; writeln ; w r i t e l n ( ’ R e s u l t o f f s s t a t on f i l e ’ ’ ’ , s , ’ ’ ’ . ’ ) ; writeln ( ’ fstype : ’ , info . ftype ) ; writeln ( ’ bsize : ’ , i n f o . bsize ) ; writeln ( ’ bfree : ’ , i n f o . bfree ) ; writeln ( ’ bavail : ’ , info . bavail ) ; writeln ( ’ f i l e s : ’ , info . files ); writeln ( ’ f f r e e : ’ , info . ffree ); { $ i f d e f FreeBSD } writeln ( ’ f s i d : ’ , info . fsid [ 0 ] ) ; { $else } writeln ( ’ f s i d : ’ , info . fsid ); w r i t e l n ( ’ Namelen : ’ , i n f o . namelen ) ; { $endif } w r i t e ( ’ Type name o f f i l e t o do f s s t a t . ( q q u i t s ) : ’ ) ; readln ( s ) end ; end .

FStat Declaration: Function FStat(Path:Pathstr;Var Info:stat):Boolean; Function FStat(Fd:longint;Var Info:stat):Boolean; Function FStat(var F:Text;Var Info:stat):Boolean; Function FStat(var F:File;Var Info:stat):Boolean; Description: FStat gets information about the file specified in one of the following: Patha file on the filesystem. Fda valid file descriptor. Fan opened text file or untyped file. and stores it in Info, which is of type stat. The function returns True if the call was succesfull, False if the call failed. Errors: LinuxError is used to report errors. sys_enoentPath does not exist. See also: FSStat (216), LStat (232), stat (2) Listing: linuxex/ex28.pp program example28 ; { Program t o demonstrate t h e F S t a t f u n c t i o n . }

217

CHAPTER 12. THE LINUX UNIT.

uses BaseUnix ; var f : t e x t ; i : byte ; info : stat ; begin { Make a f i l e } assign ( f , ’ t e s t . f i l ’ ) ; rewrite ( f ) ; f o r i : = 1 to 1 0 do w r i t e l n ( f , ’ T e s t l i n e # ’ , i ) ; close ( f ) ; { Do t h e c a l l on made f i l e . } i f f p s t a t ( ’ t e s t . f i l ’ , i n f o ) < >0 then begin w r i t e l n ( ’ F s t a t f a i l e d . Errno : ’ , f p g e t e r r n o ) ; halt ( 1 ) ; end ; writeln ; w r i t e l n ( ’ R e s u l t o f f s t a t on f i l e ’ ’ t e s t . f i l ’ ’ . ’ ) ; w r i t e l n ( ’ Inode : ’ , info . st_ino ) ; w r i t e l n ( ’ Mode : ’ , i n f o . st_mode ) ; writeln ( ’ nlink : ’ , info . st_nlink ); writeln ( ’ uid : ’ , info . st_uid ) ; writeln ( ’ gid : ’ , info . st_gid ) ; w r i t e l n ( ’ rdev : ’ , i n f o . st_rdev ) ; w r i t e l n ( ’ Size : ’ , info . st_size ) ; writeln ( ’ Blksize : ’ , info . st_blksize ) ; w r i t e l n ( ’ Blocks : ’ , info . st_blocks ) ; w r i t e l n ( ’ atime : ’ , i n f o . st_atime ) ; w r i t e l n ( ’ mtime : ’ , i n f o . st_mtime ) ; writeln ( ’ ctime : ’ , i n f o . st_ctime ) ; { Remove f i l e } erase ( f ) ; end .

Fcntl

Declaration: Function Fcntl(Fd:longint;Cmd:Integer):integer; Function Fcntl(var Fd:Text;Cmd:Integer) Description: Read a file’s attributes. Fd is an assigned file, or a valid file descriptor. Cmd speciefies what to do, and is one of the following: F_GetFdRead the close_on_exec flag. If the low-order bit is 0, then the file will remain open across execve calls. F_GetFlRead the descriptor’s flags. F_GetOwnGet the Process ID of the owner of a socket. Errors: LinuxError is used to report errors. sys_ebadfFd has a bad file descriptor. See also: Fcntl (219), Fcntl (2)

218

CHAPTER 12. THE LINUX UNIT.

Fcntl Declaration: Procedure Fcntl (Fd : text, Cmd : Integer; Arg : Fcntl (Fd:longint;Cmd:longint;Arg:Longint);

longint); Procedure

Description: Read or Set a file’s attributes. Fd is an assigned file or a valid file descriptor. Cmd speciefies what to do, and is one of the following: F_SetFdSet the close_on_exec flag of Fd. (only the least siginificant bit is used). F_GetLkReturn the flock record that prevents this process from obtaining the lock, or set the l_type field of the lock of there is no obstruction. Arg is a pointer to a flock record. F_SetLkSet the lock or clear it (depending on l_type in the flock structure). if the lock is held by another process, an error occurs. F_GetLkwSame as for F_Setlk, but wait until the lock is released. F_SetOwnSet the Process or process group that owns a socket. Errors: LinuxError is used to report errors. sys_ebadfFd has a bad file descriptor. sys_eagain or sys_eaccessFor F_SetLk, if the lock is held by another process. See also: Fcntl (218), Fcntl (2) , seefFLock

Fork Declaration: Function Fork :

Longint;

Description: Fork creates a child process which is a copy of the parent process. Fork returns the process ID in the parent process, and zero in the child’s process. (you can get the parent’s PID with GetPPid (225)). Errors: On error, -1 is returned to the parent, and no child is created. sys_eagainNot enough memory to create child process. See also: Execve (207), Clone (199), fork (2)

FRename Declaration: Function FReName (OldName,NewName : Pchar) : (OldName,NewName : String) : Boolean;

Boolean; Function FReName

Description: FRename renames the file OldName to NewName. NewName can be in a different directory than OldName, but it cannot be on another partition (device). Any existing file on the new location will be replaced. If the operation fails, then the OldName file will be preserved. The function returns True on succes, False on failure. Errors: On error, errors are reported in LinuxError. Possible errors include: sys_eisdirNewName exists and is a directory, but OldName is not a directory. sys_exdevNewName and OldName are on different devices. sys_enotempty or sys_eexistNewName is an existing, non-empty directory. sys_ebusyOldName or NewName is a directory and is in use by another process. sys_einvalNewName is part of OldName. 219

CHAPTER 12. THE LINUX UNIT.

sys_emlinkOldPath or NewPath already have tha maximum amount of links pointing to them. sys_enotdirpart of OldName or NewName is not directory. sys_efaultFor the pchar case: One of the pointers points to an invalid address. sys_eaccessaccess is denied when attempting to move the file. sys_enametoolongEither OldName or NewName is too long. sys_enoenta directory component in OldName or NewName didn’t exist. sys_enomemnot enough kernel memory. sys_erofsNewName or OldName is on a read-only file system. sys_elooptoo many symbolic links were encountered trying to expand OldName or NewName sys_enospcthe filesystem has no room for the new directory entry. See also: UnLink (257)

GetDate Declaration: Procedure GetDate (Var Year, Month, Day :

Word) ;

Description: Returns the current date. Errors: None See also: GetEpochTime (223), GetTime (226), GetDateTime (220), EpochToLocal (204) Listing: linuxex/ex6.pp Program Example6 ; { Program t o demonstrate t h e GetDate f u n c t i o n . } Uses Unix ; Var Year , Month , Day : Word ; begin GetDate ( Year , Month , Day ) ; W r i t e l n ( ’ Date : ’ , Day : 2 , ’ / ’ , Month : 2 , ’ / ’ , Year : 4 ) ; end .

GetDateTime Declaration: Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word); Description: Returns the current date and time. The time is corrected for the local time zone. This procedure is equivalent to the GetDate (220) and GetTime calls. Errors: None See also: GetEpochTime (223), GetTime (226), EpochToLocal (204), GetDate (220) Listing: linuxex/ex60.pp

220

CHAPTER 12. THE LINUX UNIT.

Program Example6 ; { Program t o demonstrate t h e GetDateTime f u n c t i o n . } Uses Unix ; Var Year , Month , Day , Hour , min , sec : Word ; begin GetDateTime ( Year , Month , Day , Hour , min , sec ) ; W r i t e l n ( ’ Date : ’ , Day : 2 , ’ / ’ , Month : 2 , ’ / ’ , Year : 4 ) ; W r i t e l n ( ’ Time : ’ , Hour : 2 , ’ : ’ , Min : 2 , ’ : ’ , Sec : 2 ) ; end .

GetDomainName Declaration: Function GetDomainName :

String;

Description: Get the domain name of the machine on which the process is running. An empty string is returned if the domain is not set. Errors: None. See also: GetHostName (224),seemGetdomainname2 Listing: linuxex/ex39.pp Program Example39 ; { Program t o demonstrate t h e GetDomainName f u n c t i o n . } Uses Unix ; begin W r i t e l n ( ’ Domain name o f t h i s machine i s : end .

’ , GetDomainName ) ;

GetEGid Declaration: Function GetEGid :

Longint;

Description: Get the effective group ID of the currently running process. Errors: None. See also: GetGid (224), getegid (2) Listing: linuxex/ex18.pp Program Example18 ; { Program t o demonstrate t h e GetGid and GetEGid f u n c t i o n s . } Uses BaseUnix ;

221

CHAPTER 12. THE LINUX UNIT.

begin w r i t e l n ( ’ Group I d = ’ , f p g e t g i d , ’ E f f e c t i v e group I d = ’ , f p g e t e g i d ) ; end .

GetEUid Declaration: Function GetEUid :

Longint;

Description: Get the effective user ID of the currently running process. Errors: None. See also: GetEUid (222), geteuid (2) Listing: linuxex/ex17.pp Program Example17 ; { Program t o demonstrate t h e GetUid and GetEUid f u n c t i o n s . } Uses BaseUnix ; begin w r i t e l n ( ’ User I d = ’ , f p g e t u i d , ’ E f f e c t i v e user I d = ’ , f p g e t e u i d ) ; end .

GetEnv Declaration: Function GetEnv (P : String) :

PChar;

Description: Returns the value of the environment variable in P. If the variable is not defined, nil is returned. The value of the environment variable may be the empty string. A PChar is returned to accomodate for strings longer than 255 bytes, TERMCAP and LS_COLORS, for instance. Errors: None. See also: sh (1) , csh (1) Listing: linuxex/ex41.pp Program Example41 ; { Program t o demonstrate t h e GetEnv f u n c t i o n . } Uses BaseUnix ; begin W r i t e l n ( ’ Path i s : end .

’ , fpGetenv ( ’PATH ’ ) ) ;

222

CHAPTER 12. THE LINUX UNIT.

GetEpochTime Declaration: Function GetEpochTime :

longint;

Description: returns the number of seconds since 00:00:00 gmt, january 1, 1970. it is adjusted to the local time zone, but not to DST. Errors: no errors See also: EpochToLocal (204), GetTime (226), time (2) Listing: linuxex/ex1.pp Program Example1 ; { Program t o demonstrate t h e GetEpochTime f u n c t i o n . } Uses Unix ; begin Write ( ’ Secs p a s t t h e s t a r t o f t h e Epoch ( 0 0 : 0 0 1 / 1 / 1 9 8 0 ) : ’ ) ; W r i t e l n ( GetEpochTime ) ; end .

GetFS Declaration: Function GetFS (Var F : Any File Type) :

Longint;

Description: GetFS returns the file selector that the kernel provided for your file. In principle you don’ need this file selector. Only for some calls it is needed, such as the Select (244) call or so. Errors: In case the file was not opened, then -1 is returned. See also: Select (244) Listing: linuxex/ex34.pp Program Example33 ; { Program t o demonstrate t h e S e l e c t T e x t f u n c t i o n . } Uses Unix ; Var t v : TimeVal ; begin W r i t e l n ( ’ Press t h e t o c o n t i n u e t h e program . ’ ) ; { Wait u n t i l F i l e d e s c r i p t o r 0 ( = I n p u t ) changes } SelectText ( Input , n i l ) ; { Get r i d o f i n b u f f e r } readln ; W r i t e l n ( ’ Press key i n l e s s than 2 seconds . . . ’ ) ; t v . tv_sec : = 2 ; t v . tv_sec : = 0 ; i f S e l e c t T e x t ( I n p u t , @tv ) > 0 then W r i t e l n ( ’ Thank you ! ’ ) else W r i t e l n ( ’ Too l a t e ! ’ ) ; end .

223

CHAPTER 12. THE LINUX UNIT.

GetGid Declaration: Function GetGid :

Longint;

Description: Get the real group ID of the currently running process. Errors: None. See also: GetEGid (221), getgid (2) Listing: linuxex/ex18.pp Program Example18 ; { Program t o demonstrate t h e GetGid and GetEGid f u n c t i o n s . } Uses BaseUnix ; begin w r i t e l n ( ’ Group I d = ’ , f p g e t g i d , ’ E f f e c t i v e group I d = ’ , f p g e t e g i d ) ; end .

GetHostName Declaration: Function GetHostName :

String;

Description: Get the hostname of the machine on which the process is running. An empty string is returned if hostname is not set. Errors: None. See also: GetDomainName (221),seemGethostname2 Listing: linuxex/ex40.pp Program Example40 ; { Program t o demonstrate t h e GetHostName f u n c t i o n . } Uses u n i x ; begin W r i t e l n ( ’Name o f t h i s machine i s : end .

’ , GetHostName ) ;

GetLocalTimezone Declaration: procedure GetLocalTimezone(timer:longint;var leap_correct,leap_hit:longint); procedure GetLocalTimezone(timer:longint); Description: GetLocalTimeZone returns the local timezone information. It also initializes the TZSeconds variable, which is used to correct the epoch time to local time. There should never be any need to call this function directly. It is called by the initialization routines of the Linux unit. See also: GetTimezoneFile (227), ReadTimezoneFile (244) 224

CHAPTER 12. THE LINUX UNIT.

GetPid Declaration: Function GetPid :

Longint;

Description: Get the Process ID of the currently running process. Errors: None. See also: GetPPid (225), getpid (2) Listing: linuxex/ex16.pp Program Example16 ; { Program t o demonstrate t h e GetPid , GetPPid f u n c t i o n . } Uses BaseUnix ; begin W r i t e l n ( ’ Process I d = ’ , f p g e t p i d , ’ Parent process I d = ’ , f p g e t p p i d ) ; end .

GetPPid Declaration: Function GetPPid :

Longint;

Description: Get the Process ID of the parent process. Errors: None. See also: GetPid (225), getppid (2) Listing: linuxex/ex16.pp Program Example16 ; { Program t o demonstrate t h e GetPid , GetPPid f u n c t i o n . } Uses BaseUnix ; begin W r i t e l n ( ’ Process I d = ’ , f p g e t p i d , ’ Parent process I d = ’ , f p g e t p p i d ) ; end .

GetPriority Declaration: Function GetPriority (Which,Who :

Integer) :

Integer;

Description: GetPriority returns the priority with which a process is running. Which process(es) is determined by the Which and Who variables. Which can be one of the pre-defined Prio_Process, Prio_PGrp, Prio_User, in which case Who is the process ID, Process group ID or User ID, respectively. Errors: Error checking must be done on LinuxError, since a priority can be negative. sys_esrchNo process found using which and who. sys_einvalWhich was not one of Prio_Process, Prio_Grp or Prio_User. 225

CHAPTER 12. THE LINUX UNIT.

See also: SetPriority (246), Nice (238), Getpriority (2) For an example, see Nice (238).

GetTime Declaration: procedure GetTime(var hour,min,sec,msec,usec:word); procedure GetTime(var hour,min,sec,sec100:word); procedure GetTime(var hour,min,sec:word); Description: Returns the current time of the day, adjusted to local time. Upon return, the parameters are filled with hourHours since 00:00 today. minminutes in current hour. secseconds in current minute. sec100hundreds of seconds in current second. msecmilliseconds in current second. usecmicroseconds in current second. Errors: None See also: GetEpochTime (223), GetDate (220), GetDateTime (220), EpochToLocal (204) Listing: linuxex/ex5.pp Program Example5 ; { Program t o demonstrate t h e GetTime f u n c t i o n . } Uses Unix ; Var Hour , Minute , Second : Word ; begin GetTime ( Hour , Minute , Second ) ; W r i t e l n ( ’ Time : ’ , Hour : 2 , ’ : ’ , Minute : 2 , ’ : ’ , Second : 2 ) ; end .

GetTimeOfDay Declaration: Procedure GetTimeOfDay(var tv:timeval); Description: GetTimeOfDay returns the number of seconds since 00:00, January 1 1970, GMT in a timeval record. This time NOT corrected any way, not taking into account timezones, daylight savings time and so on. It is simply a wrapper to the kernel system call. To get the local time, GetTime (226). Errors: None. See also: GetTime (226), GetTimeOfDay (227)

226

CHAPTER 12. THE LINUX UNIT.

GetTimeOfDay Declaration: Function GetTimeOfDay:longint; Description: GetTimeOfDay returns the number of seconds since 00:00, January 1 1970, GMT. This time NOT corrected any way, not taking into account timezones, daylight savings time and so on. It is simply a wrapper to the kernel system call. To get the local time, GetTime (226). Errors: None. See also: GetTimeOfDay (226), GetTime (226)

GetTimezoneFile Declaration: function GetTimezoneFile:string; Description: GetTimezoneFile returns the location of the current timezone file. The location of file is determined as follows: 1.If /etc/timezone exists, it is read, and the contents of this file is returned. This should work on Debian systems. 2.If /usr/lib/zoneinfo/localtime exists, then it is returned. (this file is a symlink to the timezone file on SuSE systems) 3.If /etc/localtime exists, then it is returned. (this file is a symlink to the timezone file on RedHat systems) Errors: If no file was found, an empty string is returned. See also: ReadTimezoneFile (244)

GetUid Declaration: Function GetUid :

Longint;

Description: Get the real user ID of the currently running process. Errors: None. See also: GetEUid (222), getuid (2) Listing: linuxex/ex17.pp Program Example17 ; { Program t o demonstrate t h e GetUid and GetEUid f u n c t i o n s . } Uses BaseUnix ; begin w r i t e l n ( ’ User I d = ’ , f p g e t u i d , ’ E f f e c t i v e user I d = ’ , f p g e t e u i d ) ; end .

227

CHAPTER 12. THE LINUX UNIT.

Glob Declaration: Function Glob (Const Path :

Pathstr) :

PGlob;

Description: Glob returns a pointer to a glob structure which contains all filenames which exist and match the pattern in Path. The pattern can contain wildcard characters, which have their usual meaning. Errors: Returns nil on error, and LinuxError is set. sys_enomemNo memory on heap for glob structure. othersAs returned by the opendir call, and sys_readdir. See also: GlobFree (228), Glob (3) Listing: linuxex/ex49.pp Program Example49 ; { Program t o demonstrate t h e Glob and GlobFree f u n c t i o n s . } Uses BaseUnix , Unix ; Var G1, G2 : PGlob ; begin G1: = Glob ( ’ ∗ ’ ) ; i f f p g e t e r r n o =0 then begin G2: =G1 ; Writeln ( ’ F i l e s i n t h i s d i r e c t o r y : While g2 N i l do begin W r i t e l n ( g2 ^ . name ) ; g2 : = g2 ^ . n e x t ; end ; GlobFree ( g1 ) ; end ; end .

’ );

GlobFree Declaration: Procedure GlobFree (Var P : Pglob); Description: Releases the memory, occupied by a pglob structure. P is set to nil. Errors: None See also: Glob (228) For an example, see Glob (228).

IOCtl Declaration: Procedure IOCtl (Handle,Ndx:

Longint; Data:

228

Pointer);

CHAPTER 12. THE LINUX UNIT.

Description: This is a general interface to the Unix/ LINUX ioctl call. It performs various operations on the filedescriptor Handle. Ndx describes the operation to perform. Data points to data needed for the Ndx function. The structure of this data is function-dependent, so we don’t elaborate on this here. For more information on this, see various manual pages under linux. Errors: Errors are reported in LinuxError. They are very dependent on the used function, that’s why we don’t list them here See also: ioctl (2) Listing: linuxex/ex54.pp Program Example54 ; uses BaseUnix , Termio ; { Program t o demonstrate t h e I O C t l f u n c t i o n . } var t i o s : Termios ; begin { $ i f d e f FreeBSD } f p I O C t l ( 1 ,TIOCGETA, @tios ) ; { $endif } WriteLn ( WriteLn ( WriteLn ( WriteLn ( end .

’ I n p u t Flags : ’ Output Flags : ’ L i n e Flags : ’ C o n t r o l Flags :

$’ $’ $’ $’

/ / these c o n s t a n t s are v e r y OS dependant . / / see t h e t c g e t a t t r example f o r a b e t t e r way

, hexstr ( , hexstr ( , hexstr ( , hexstr (

tios tios tios tios

. c_iflag . c_oflag . c_lflag . c_cflag

,8)); ,8)); ,8)); ,8));

IOperm Declaration: Function IOperm (From,Num :

Cadinal; Value :

Longint) :

boolean;

Description: IOperm sets permissions on Num ports starting with port From to Value. The function returns True if the call was successfull, False otherwise. Remark: •This works ONLY as root. •Only the first 0x03ff ports can be set. •When doing a Fork (219), the permissions are reset. When doing a Execve (207) they are kept. Errors: Errors are returned in LinuxError See also: ioperm (2)

IsATTY Declaration: Function IsATTY (var f) :

Boolean;

Description: Check if the filehandle described by f is a terminal. f can be of type 1.longint for file handles; 2.Text for text variables such as input etc.

229

CHAPTER 12. THE LINUX UNIT.

Returns True if f is a terminal, False otherwise. Errors: No errors are reported See also: IOCtl (228),TTYName (256)

S_ISBLK Declaration: Function S_ISBLK (m:integer) :

boolean;

Description: S_ISBLK checks the file mode m to see whether the file is a block device file. If so it returns True. Errors: FStat (217), S_ISLNK (231), S_ISREG (231), S_ISDIR (230), S_ISCHR (230), S_ISFIFO (230), S_ISSOCK (231) See also: ISLNK.

S_ISCHR Declaration: Function S_ISCHR (m:integer) :

boolean;

Description: S_ISCHR checks the file mode m to see whether the file is a character device file. If so it returns True. Errors: FStat (217), S_ISLNK (231), S_ISREG (231), S_ISDIR (230), S_ISBLK (230), S_ISFIFO (230), S_ISSOCK (231) See also: ISLNK.

S_ISDIR Declaration: Function S_ISDIR (m:integer) :

boolean;

Description: S_ISDIR checks the file mode m to see whether the file is a directory. If so it returns True Errors: FStat (217), S_ISLNK (231), S_ISREG (231), S_ISCHR (230), S_ISBLK (230), S_ISFIFO (230), S_ISSOCK (231) See also: ISLNK.

S_ISFIFO Declaration: Function S_ISFIFO (m:integer) :

boolean;

Description: S_ISFIFO checks the file mode m to see whether the file is a fifo (a named pipe). If so it returns True. Errors: FStat (217), S_ISLNK (231), S_ISREG (231), S_ISDIR (230), S_ISCHR (230), S_ISBLK (230), S_ISSOCK (231) See also: ISLNK.

230

CHAPTER 12. THE LINUX UNIT.

S_ISLNK Declaration: Function S_ISLNK (m:integer) :

boolean;

Description: S_ISLNK checks the file mode m to see whether the file is a symbolic link. If so it returns True Errors: FStat (217), S_ISREG (231), S_ISDIR (230), S_ISCHR (230), S_ISBLK (230), S_ISFIFO (230), S_ISSOCK (231) See also: Listing: linuxex/ex53.pp Program Example53 ; { Program t o demonstrate t h e S_ISLNK f u n c t i o n . } Uses BaseUnix , Unix ; Var I n f o : S t a t ; begin i f f p L S t a t ( paramstr ( 1 ) , @info ) = 0 then begin i f fpS_ISLNK ( i n f o . st_mode ) then Writeln ( ’ F i l e i s a l i n k ’ ) ; i f fpS_ISREG ( i n f o . st_mode ) then Writeln ( ’ F i l e i s a r e g u l a r f i l e ’ ) ; i f fpS_ISDIR ( i n f o . st_mode ) then Writeln ( ’ F i l e i s a d i r e c t o r y ’ ) ; i f fpS_ISCHR ( i n f o . st_mode ) then Writeln ( ’ F i l e i s a character device f i l e ’ ) ; i f fpS_ISBLK ( i n f o . st_mode ) then Writeln ( ’ F i l e i s a block device f i l e ’ ) ; i f fpS_ISFIFO ( i n f o . st_mode ) then W r i t e l n ( ’ F i l e i s a named p i p e ( FIFO ) ’ ) ; i f fpS_ISSOCK ( i n f o . st_mode ) then Writeln ( ’ F i l e i s a socket ’ ) ; end ; end .

S_ISREG Declaration: Function S_ISREG (m:integer) :

boolean;

Description: S_ISREG checks the file mode m to see whether the file is a regular file. If so it returns True Errors: FStat (217), S_ISLNK (231), S_ISDIR (230), S_ISCHR (230), S_ISBLK (230), S_ISFIFO (230), S_ISSOCK (231) See also: ISLNK.

S_ISSOCK Declaration: Function S_ISSOCK (m:integer) :

boolean;

Description: S_ISSOCK checks the file mode m to see whether the file is a socket. If so it returns True.

231

CHAPTER 12. THE LINUX UNIT.

Errors: FStat (217), S_ISLNK (231), S_ISREG (231), S_ISDIR (230), S_ISCHR (230), S_ISBLK (230), S_ISFIFO (230) See also: ISLNK.

Kill Declaration: Function Kill (Pid :

Longint; Sig :

Integer) :

Integer;

Description: Send a signal Sig to a process or process group. If Pid>0 then the signal is sent to Pid, if it equals -1, then the signal is sent to all processes except process 1. If Pid0 then begin

232

CHAPTER 12. THE LINUX UNIT.

w r i t e l n ( ’ F s t a t f a i l e d . Errno : ’ , f p g e t e r r n o ) ; halt ( 1 ) ; end ; writeln ; w r i t e l n ( ’ R e s u l t o f s t a t on f i l e ’ ’ t e s t . f i l ’ ’ . ’ ) ; w r i t e l n ( ’ Inode : ’ , info . st_ino ) ; w r i t e l n ( ’ Mode : ’ , i n f o . st_mode ) ; writeln ( ’ nlink : ’ , info . st_nlink ); writeln ( ’ uid : ’ , info . st_uid ) ; writeln ( ’ gid : ’ , info . st_gid ) ; w r i t e l n ( ’ rdev : ’ , i n f o . st_rdev ) ; w r i t e l n ( ’ Size : ’ , info . st_size ) ; writeln ( ’ Blksize : ’ , info . st_blksize ) ; w r i t e l n ( ’ Blocks : ’ , info . st_blocks ) ; w r i t e l n ( ’ atime : ’ , i n f o . st_atime ) ; w r i t e l n ( ’ mtime : ’ , i n f o . st_mtime ) ; writeln ( ’ ctime : ’ , i n f o . st_ctime ) ; If

fpSymLink ( ’ t e s t . f i l ’ , ’ t e s t . l n k ’ ) < >0 then w r i t e l n ( ’ L i n k f a i l e d ! Errno : ’ , f p g e t e r r n o ) ;

if

f p l s t a t ( ’ t e s t . l n k ’ , @info ) < >0 then begin w r i t e l n ( ’ L S t a t f a i l e d . Errno : ’ , f p g e t e r r n o ) ; halt ( 1 ) ; end ; writeln ; w r i t e l n ( ’ R e s u l t o f f s t a t on f i l e ’ ’ t e s t . l n k ’ ’ . ’ ) ; w r i t e l n ( ’ Inode : ’ , info . st_ino ) ; w r i t e l n ( ’ Mode : ’ , i n f o . st_mode ) ; writeln ( ’ nlink : ’ , info . st_nlink ); writeln ( ’ uid : ’ , info . st_uid ) ; writeln ( ’ gid : ’ , info . st_gid ) ; w r i t e l n ( ’ rdev : ’ , i n f o . st_rdev ) ; w r i t e l n ( ’ Size : ’ , info . st_size ) ; writeln ( ’ Blksize : ’ , info . st_blksize ) ; w r i t e l n ( ’ Blocks : ’ , info . st_blocks ) ; w r i t e l n ( ’ atime : ’ , i n f o . st_atime ) ; w r i t e l n ( ’ mtime : ’ , i n f o . st_mtime ) ; writeln ( ’ ctime : ’ , i n f o . st_ctime ) ; { Remove f i l e and l i n k } erase ( f ) ; fpunlink ( ’ test . lnk ’ ) ; end .

Link Declaration: Function Link (OldPath,NewPath :

pathstr) :

Boolean;

Description: Link makes NewPath point to the same file als OldPath. The two files then have the same inode number. This is known as a ’hard’ link. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. sys_exdevOldPath and NewPath are not on the same filesystem. sys_epermThe filesystem containing oldpath and newpath doesn’t support linking files. 233

CHAPTER 12. THE LINUX UNIT.

sys_eaccessWrite access for the directory containing Newpath is disallowed, or one of the directories in OldPath or NewPath has no search (=execute) permission. sys_enoentA directory entry in OldPath or NewPath does not exist or is a symbolic link pointing to a non-existent directory. sys_enotdirA directory entry in OldPath or NewPath is nor a directory. sys_enomemInsufficient kernel memory. sys_erofsThe files are on a read-only filesystem. sys_eexistNewPath already exists. sys_emlinkOldPath has reached maximal link count. sys_eloopOldPath or NewPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. sys_enospcThe device containing NewPath has no room for anothe entry. sys_epermOldPath points to . or .. of a directory. See also: SymLink (251), UnLink (257), Link (2) Listing: linuxex/ex21.pp Program Example21 ; { Program t o demonstrate t h e L i n k and UnLink f u n c t i o n s . } Uses BaseUnix ; Var F : Text ; S : String ; begin Assign ( F , ’ t e s t . t x t ’ ) ; Rewrite ( F ) ; Writeln ( F , ’ This i s w r i t t e n to t e s t . t x t ’ ) ; Close ( f ) ; { new . t x t and t e s t . t x t are now t h e same f i l e } i f f p L i n k ( ’ t e s t . t x t ’ , ’ new . t x t ’ ) < >0 then w r i t e l n ( ’ E r r o r when l i n k i n g ! ’ ) ; { Removing t e s t . t x t s t i l l l e a v e s new . t x t } I f f p U n l i n k ( ’ t e s t . t x t ’ ) < >0 then W r i t e l n ( ’ E r r o r when u n l i n k i n g ! ’ ) ; Assign ( f , ’ new . t x t ’ ) ; Reset ( F ) ; While not EOF( f ) do begin Readln ( F , S ) ; Writeln ( ’ > ’ , s ) ; end ; Close ( f ) ; { Remove new . t x t a l s o } I f not FPUnlink ( ’ new . t x t ’ ) < >0 then W r i t e l n ( ’ E r r o r when u n l i n k i n g ! ’ ) ; end .

LocalToEpoch Declaration: Function LocalToEpoch (Year,Month,Day,Hour,Minute,Second : longint; 234

Word) :

CHAPTER 12. THE LINUX UNIT.

Description: Converts the Local time to epoch time (=Number of seconds since 00:00:00 , January 1, 1970 ). Errors: None See also: GetEpochTime (223), EpochToLocal (204), GetTime (226),GetDate (220) Listing: linuxex/ex4.pp Program Example4 ; { Program t o demonstrate t h e LocalToEpoch f u n c t i o n . } Uses U n i x U t i l ; Var year , month , day , hour , minute , second : Word ; begin Write ( ’ Year : ’ ) ; readln ( Year ) ; Write ( ’ Month : ’ ) ; readln ( Month ) ; Write ( ’ Day : ’ ) ; readln ( Day ) ; Write ( ’ Hour : ’ ) ; readln ( Hour ) ; Write ( ’ Minute : ’ ) ; readln ( Minute ) ; Write ( ’ Seonds : ’ ) ; readln ( Second ) ; Write ( ’ T h i s i s : ’ ) ; Write ( LocalToEpoch ( year , month , day , hour , minute , second ) ) ; W r i t e l n ( ’ seconds p a s t 0 0 : 0 0 1 / 1 / 1 9 8 0 ’ ) ; end .

MkFifo Declaration: Function MkFifo (PathName:

String; Mode :

Longint) :

Boolean;

Description: MkFifo creates named a named pipe in the filesystem, with name PathName and mode Mode. Errors: LinuxError is used to report errors: sys_emfileToo many file descriptors for this process. sys_enfileThe system file table is full. See also: POpen (240), MkFifo (235), mkfifo (4)

MMap Declaration: Function MMap(const m:tmmapargs):longint; Description: MMap maps or unmaps files or devices into memory. The different fields of the argument m determine what and how the mmap maps this: addressAddress where to mmap the device. This address is a hint, and may not be followed. sizeSize (in bytes) of area to be mapped. protProtection of mapped memory. This is a OR-ed combination of the following constants: PROT_EXECThe memory can be executed. PROT_READThe memory can be read. PROT_WRITEThe memory can be written. PROT_NONEThe memory can not be accessed. 235

CHAPTER 12. THE LINUX UNIT.

flagsContains some options for the mmap call. It is an OR-ed combination of the following constants: MAP_FIXEDDo not map at another address than the given address. If the address cannot be used, MMap will fail. MAP_SHAREDShare this map with other processes that map this object. MAP_PRIVATECreate a private map with copy-on-write semantics. MAP_ANONYMOUSfd does not have to be a file descriptor. One of the options MAP_SHARED and MAP_PRIVATE must be present, but not both at the same time. fdFile descriptor from which to map. offsetOffset to be used in file descriptor fd. The function returns a pointer to the mapped memory, or a -1 in case of en error. Errors: On error, -1 is returned and LinuxError is set to the error code: Sys_EBADFfd is not a valid file descriptor and MAP_ANONYMOUS was not specified. Sys_EACCESMAP_PRIVATE was specified, but fd is not open for reading. Or MAP_SHARED was asked and PROT_WRITE is set, fd is not open for writing Sys_EINVALOne of the record fields Start, length or offset is invalid. Sys_ETXTBUSYMAP_DENYWRITE was set but the object specified by fd is open for writing. Sys_EAGAINfd is locked, or too much memory is locked. Sys_ENOMEMNot enough memory for this operation. See also: MUnMap (237), mmap (2) Listing: linuxex/ex66.pp Program Example66 ; { Program t o demonstrate t h e MMap f u n c t i o n . } Uses BaseUnix , Unix ; Var S : fd : Len : // args P :

String ; cint ; longint ; : tmmapargs ; PChar ;

begin s := ’ This i s the s t r i n g ’ ; Len : = Length ( S ) ; f d : = fpOpen ( ’ t e s t f i l e . t x t ’ , O_wrOnly or o _ c r e a t ) ; I f f d =−1 then Halt ( 1 ) ; I f f p W r i t e ( fd , S [ 1 ] , Len)= −1 then Halt ( 2 ) ; fpClose ( fd ) ; f d : = fpOpen ( ’ t e s t f i l e . t x t ’ , O_rdOnly ) ; i f f d =−1 then Halt ( 3 ) ; P: = Pchar ( fpmmap ( n i l , l e n + 1 ,PROT_READ or PROT_WRITE, MAP_PRIVATE, fd , 0 ) ) ; I f l o n g i n t ( P)= −1 then

236

CHAPTER 12. THE LINUX UNIT.

Halt ( 4 ) ; W r i t e l n ( ’ Read i n memory : ’ ,P ) ; fpclose ( fd ) ; i f fpMUnMap ( P , Len ) < >0 Then Halt ( fpgeterrno ) ; end .

MUnMap Declaration: function MUnMap (P : Pointer; Size :

Longint) :

Boolean;

Description: MUnMap unmaps the memory block of size Size, pointed to by P, which was previously allocated with MMap (235). The function returns True if successful, False otherwise. Errors: In case of error the function returns False and LinuxError is set to an error value. See MMap (235) for possible error values. See also: MMap (235), munmap (2) For an example, see MMap (235).

NanoSleep Declaration: Function NanoSleep(const req :

timespec;var rem :

timespec) :

longint;

Description: NanoSleep suspends the process till a time period as specified in req has passed. Then the function returns. If the call was interrupted (e.g. by some signal) then the function may return earlier, and rem will contain the remaining time till the end of the intended period. In this case the return value will be -1, and LinuxError will be set to EINTR If the function returns without error, the return value is zero. Errors: If the call was interrupted, -1 is returned, and LinuxError is set to EINTR. If invalid time values were specified, then -1 is returned and LinuxError is set to EINVAL. See also: Pause (??), Alarm (193) Listing: linuxex/ex70.pp Program Example70 ; { Program t o demonstrate t h e StringToPPchar f u n c t i o n . } Uses U n i x U t i l ; Var S : S t r i n g ; P : PPChar ; I : longint ; begin / / remark whitespace a t end . S: = ’ T h i s i s a s t r i n g w i t h words . ’ ; P: = StringToPPChar ( S , 0 ) ; I :=0; While P [ i ] < > N i l do

237

CHAPTER 12. THE LINUX UNIT.

begin W r i t e l n ( ’ Word ’ , i , ’ : ’ ,P [ i ] ) ; Inc ( I ) ; end ; FreeMem ( P , i ∗ SizeOf ( Pchar ) ) ; end .

Nice Declaration: Procedure Nice ( N : Integer); Description: Nice adds -N to the priority of the running process. The lower the priority numerically, the less the process is favored. Only the superuser can specify a negative N, i.e. increase the rate at which the process is run. Errors: Errors are returned in LinuxError sys_epermA non-superuser tried to specify a negative N, i.e. do a priority increase. See also: GetPriority (225), SetPriority (246), Nice (2) Listing: linuxex/ex15.pp Program Example15 ; { Program t o demonstrate t h e Nice and Get / S e t P r i o r i t y f u n c t i o n s . } Uses BaseUnix , Unix ; begin writeln ( ’ Setting p r i o r i t y to 5 ’ ) ; f p s e t p r i o r i t y ( prio_process , fpgetpid , 5 ) ; w r i t e l n ( ’New p r i o r i t y = ’ , f p g e t p r i o r i t y ( p r i o _ p r o c e s s , f p g e t p i d ) ) ; w r i t e l n ( ’ Doing n i c e 1 0 ’ ) ; fpnice ( 1 0 ) ; w r i t e l n ( ’New P r i o r i t y = ’ , f p g e t p r i o r i t y ( p r i o _ p r o c e s s , f p g e t p i d ) ) ; end .

Octal Declaration: Function Octal(l:longint):longint; Description: Octal will convert a number specified as an octal number to it’s decimal value. This is useful for the Chmod (198) call, where permissions are specified as octal numbers. Errors: No checking is performed whether the given number is a correct Octal number. e.g. specifying 998 is possible; the result will be wrong in that case. See also: Chmod (198). Listing: linuxex/ex68.pp Program Example68 ; { Program t o demonstrate t h e O c t a l f u n c t i o n . }

238

CHAPTER 12. THE LINUX UNIT.

begin W r i t e l n ( ’ Mode 7 7 7 : ’ , & 7 7 7 ) ; W r i t e l n ( ’ Mode 6 4 4 : ’ , & 5 4 4 ) ; W r i t e l n ( ’ Mode 7 5 5 : ’ , & 7 5 5 ) ; end .

OpenDir Declaration: Function OpenDir (f:pchar) :

pdir; Function OpenDir (f:string) :

pdir;

Description: OpenDir opens the directory f, and returns a pdir pointer to a Dir record, which can be used to read the directory structure. If the directory cannot be opened, nil is returned. Errors: Errors are returned in LinuxError. See also: CloseDir (201), ReadDir (241), SeekDir (244), TellDir (256), opendir (3) Listing: linuxex/ex35.pp Program Example35 ; { Program t o demonstrate t h e OpenDir , ReadDir , SeekDir and T e l l D i r f u n c t i o n s . } Uses BaseUnix ; Var TheDir : PDir ; ADirent : PDirent ; Entry : Longint ; begin TheDir : = fpOpenDir ( ’ . / . ’ ) ; Repeat // E n t r y : = f p T e l l D i r ( TheDir ) ; A D i r e n t : = fpReadDir ( TheDir ^ ) ; I f ADirent N i l then With A D i r e n t ^ do begin W r i t e l n ( ’ E n t r y No : ’ , E n t r y ) ; W r i t e l n ( ’ Inode : ’ , d_fileno ) ; // Writeln ( ’ Offset : ’ , d_off ) ; W r i t e l n ( ’ Reclen : ’ , d_reclen ) ; W r i t e l n ( ’Name : ’ , pchar (@d_name [ 0 ] ) ) ; end ; Until ADirent=Nil ; Repeat Write ( ’ E n t r y No . you would l i k e t o see again ( − 1 t o s t o p ) : ’ ) ; ReadLn ( E n t r y ) ; I f Entry −1 then begin // f p S e e k D i r ( TheDir , E n t r y ) ; / / n o t implemented f o r v a r i o u s p l a t f o r m s A D i r e n t : = fpReadDir ( TheDir ^ ) ; I f ADirent N i l then With A D i r e n t ^ do begin W r i t e l n ( ’ E n t r y No : ’ , E n t r y ) ; W r i t e l n ( ’ Inode : ’ , d_fileno ) ;

239

CHAPTER 12. THE LINUX UNIT.

//

Writeln ( ’ Offset : ’ , off ); W r i t e l n ( ’ Reclen : ’ , d_reclen ) ; W r i t e l n ( ’Name : ’ , pchar (@d_name [ 0 ] ) ) ; end ;

end ; U n t i l E n t r y =−1; f p C l o s e D i r ( TheDir ^ ) ; end .

pause Declaration: Procedure Pause; Description: Pause puts the process to sleep and waits until the application receives a signal. If a signal handler is installed for the received sigal, the handler will be called and after that pause will return control to the process. Errors: None. For an example, see Alarm (193).

PClose Declaration: Function PClose (Var F : FileType) :

longint;

Description: PClose closes a file opened with POpen. It waits for the command to complete, and then returns the exit status of the command. Errors: LinuxError is used to report errors. If it is different from zero, the exit status is not valid. See also: POpen (240) For an example, see POpen (240)

POpen Declaration: Procedure POpen (Var F : FileType; Cmd :

pathstr; rw :

char);

Description: Popen runs the command specified in Cmd, and redirects the standard in or output of the command to the other end of the pipe F. The parameter rw indicates the direction of the pipe. If it is set to ’W’, then F can be used to write data, which will then be read by the command from stdinput. If it is set to ’R’, then the standard output of the command can be read from F. F should be reset or rewritten prior to using it. F can be of type Text or File. A file opened with POpen can be closed with Close, but also with PClose (240). The result is the same, but PClose returns the exit status of the command Cmd. Errors: Errors are reported in LinuxError and are essentially those of the Execve, Dup and AssignPipe commands. See also: AssignPipe (194), popen (3) , PClose (240) Listing: linuxex/ex37.pp

240

CHAPTER 12. THE LINUX UNIT.

Program Example37 ; { Program t o demonstrate t h e Popen f u n c t i o n . } uses BaseUnix , Unix ; var f : t e x t ; i : longint ; begin w r i t e l n ( ’ C r e a t i n g a s h e l l s c r i p t t o which echoes i t s arguments ’ ) ; w r i t e l n ( ’ and i n p u t back t o s t d o u t ’ ) ; assign ( f , ’ test21a ’ ) ; rewrite ( f ) ; w r i t e l n ( f , ’ # ! / b i n / sh ’ ) ; w r i t e l n ( f , ’ echo t h i s i s t h e c h i l d speaking . . . . ’ ) ; w r i t e l n ( f , ’ echo g o t arguments \ ∗ " $ ∗ " \ ∗ ’ ) ; writeln ( f , ’ cat ’ ) ; writeln ( f , ’ e x i t 2 ’ ) ; writeln ( f ) ; close ( f ) ; fpchmod ( ’ t e s t 2 1 a ’ , & 7 5 5 ) ; popen ( f , ’ . / t e s t 2 1 a arg1 arg2 ’ , ’W’ ) ; i f f p g e t e r r n o < >0 then w r i t e l n ( ’ e r r o r from POpen : e r r n o : ’ , f p g e t e r r n o ) ; f o r i : = 1 to 1 0 do w r i t e l n ( f , ’ T h i s i s w r i t t e n t o t h e pipe , and should appear on s t d o u t . ’ ) ; Flush ( f ) ; W r i t e l n ( ’ The s c r i p t e x i t e d w i t h s t a t u s : ’ , PClose ( f ) ) ; writeln ; w r i t e l n ( ’ Press < r e t u r n > t o remove s h e l l s c r i p t . ’ ) ; readln ; assign ( f , ’ test21a ’ ) ; erase ( f ) end .

ReadDir Declaration: Function ReadDir (p:pdir) :

pdirent;

Description: ReadDir reads the next entry in the directory pointed to by p. It returns a pdirent pointer to a structure describing the entry. If the next entry can’t be read, Nil is returned. Errors: Errors are returned in LinuxError. See also: CloseDir (201), OpenDir (239), SeekDir (244), TellDir (256), readdir (3) For an example, see OpenDir (239).

ReadLink Declaration: Function ReadLink(name,linkname:pchar;maxlen:longint):longint; Function ReadLink(name:pathstr):pathstr;

241

CHAPTER 12. THE LINUX UNIT.

Description: ReadLink returns the file the symbolic link name is pointing to. The first form of this function accepts a buffer linkname of length maxlen where the filename will be stored. It returns the actual number of characters stored in the buffer. The second form of the function returns simply the name of the file. Errors: On error, the first form of the function returns -1; the second one returns an empty string. LinuxError is set to report errors: SYS_ENOTDIRA part of the path in Name is not a directory. SYS_EINVALmaxlen is not positive, or the file is not a symbolic link. SYS_ENAMETOOLONGA pathname, or a component of a pathname, was too long. SYS_ENOENTthe link name does not exist. SYS_EACCESNo permission to search a directory in the path SYS_ELOOPToo many symbolic links were encountered in trans lating the pathname. SYS_EIOAn I/O error occurred while reading from the file system. SYS_EFAULTThe buffer is not part of the the process’s memory space. SYS_ENOMEMNot enough kernel memory was available. See also: SymLink (251) Listing: linuxex/ex62.pp Program Example62 ; { Program t o demonstrate t h e ReadLink f u n c t i o n . } Uses BaseUnix , Unix ; Var F : Text ; S : String ; begin Assign ( F , ’ t e s t . t x t ’ ) ; Rewrite ( F ) ; Writeln ( F , ’ This i s w r i t t e n to t e s t . t x t ’ ) ; Close ( f ) ; { new . t x t and t e s t . t x t are now t h e same f i l e } i f fpSymLink ( ’ t e s t . t x t ’ , ’ new . t x t ’ ) < >0 then w r i t e l n ( ’ E r r o r when s y m l i n k i n g ! ’ ) ; S: = fpReadLink ( ’ new . t x t ’ ) ; I f S= ’ ’ then Writeln ( ’ Error reading l i n k ! ’ ) Else W r i t e l n ( ’ L i n k p o i n t s t o : ’ ,S ) ; { Now remove l i n k s } I f f p U n l i n k ( ’ new . t x t ’ ) < >0 then W r i t e l n ( ’ E r r o r when u n l i n k i n g ! ’ ) ; I f f p U n l i n k ( ’ t e s t . t x t ’ ) < >0 then W r i t e l n ( ’ E r r o r when u n l i n k i n g ! ’ ) ; end .

242

CHAPTER 12. THE LINUX UNIT.

ReadPort Declaration: Procedure ReadPort (Port : Longint; Var Value : Byte); Procedure ReadPort (Port : Longint; Var Value : Word); Procedure ReadPort (Port : Longint; Var Value : Longint); Description: ReadPort reads one Byte, Word or Longint from port Port into Value. Note that you need permission to read a port. This permission can be set by the root user with the IOperm (229) call. Errors: In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), ReadPortB (243), ReadPortW (244), ReadPortL (243),WritePort (259), WritePortB (259), WritePortL (259), WritePortW (260)

ReadPortB Declaration: Procedure ReadPortB (Port : Longint; Var Buf; Count: ReadPortB (Port : Longint): Byte;

longint); Function

Description: The procedural form of ReadPortB reads Count bytes from port Port and stores them in Buf. There must be enough memory allocated at Buf to store Count bytes. The functional form of ReadPortB reads 1 byte from port B and returns the byte that was read. Note that you need permission to read a port. This permission can be set by the root user with the IOperm (229) call. Errors: In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), ReadPort (243), ReadPortW (244), ReadPortL (243),WritePort (259), WritePortB (259), WritePortL (259), WritePortW (260)

ReadPortL Declaration: function ReadPortL (Port : Longint): LongInt; Procedure ReadPortL (Port : Longint; Var Buf; Count: longint); Description: The procedural form of ReadPortL reads Count longints from port Port and stores them in Buf. There must be enough memory allocated at Buf to store Count Longints. The functional form of ReadPortB reads 1 longint from port B and returns the longint that was read. Note that you need permission to read a port. This permission can be set by the root user with the IOperm (229) call. Errors: In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), ReadPort (243), ReadPortW (244), ReadPortB (243),WritePort (259), WritePortB (259), WritePortL (259), WritePortW (260)

243

CHAPTER 12. THE LINUX UNIT.

ReadPortW Declaration: Procedure ReadPortW (Port : Longint; Var Buf; Count: ReadPortW (Port : Longint): Word;

longint); function

Description: The procedural form of ReadPortB reads Count words from port Port and stores them in Buf. There must be enough memory allocated at Buf to store Count words. The functional form of ReadPortB reads 1 word from port B and returns the word that was read. Note that you need permission to read a port. This permission can be set by the root user with the IOperm (229) call. Errors: In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), ReadPort (243), ReadPortB (243), ReadPortL (243),WritePort (259), WritePortB (259), WritePortL (259), WritePortW (260)

ReadTimezoneFile Declaration: procedure ReadTimezoneFile(fn:string); Description: ReadTimeZoneFile reads the timezone file fn and initializes the local time routines based on the information found there. There should be no need to call this function. The initialization routines of the linux unit call this routine at unit startup. Errors: None. See also: GetTimezoneFile (227), GetLocalTimezone (224)

SeekDir Declaration: Procedure SeekDir (p:pdir;off:longint); Description: SeekDir sets the directory pointer to the off-th entry in the directory structure pointed to by p. Errors: Errors are returned in LinuxError. See also: CloseDir (201), ReadDir (241), OpenDir (239), TellDir (256), seekdir (3) For an example, see OpenDir (239).

Select Declaration: Function Select (N : Longint; var readfds,writefds,exceptfds :

PFDset; Var Timeout) :

Longint;

Description: Select checks one of the file descriptors in the FDSets to see if its status changed. readfds, writefds and exceptfds are pointers to arrays of 256 bits. If you want a file descriptor to be checked, you set the corresponding element in the array to 1. The other elements in the array must be set to zero. Three arrays are passed : The entries in readfds are checked to see if characters become available for reading. The entries in writefds are checked to see if it is OK to write to them, while entries in exceptfds are cheked to see if an exception occorred on them. You can use the functions FD_ZERO (209), FD_Clr (209), FD_Set (210), FD_IsSet (210) to manipulate the individual elements of a set. The pointers can be nil. N is the largest index of a nonzero entry plus 1. (= the largest file-descriptor + 1). TimeOut can be used to set a time limit. If TimeOut can be two types : 244

CHAPTER 12. THE LINUX UNIT.

1.TimeOut is of type PTime and contains a zero time, the call returns immediately. If TimeOut is Nil, the kernel will wait forever, or until a status changed. 2.TimeOut is of type Longint. If it is -1, this has the same effect as a Timeout of type PTime which is Nil. Otherwise, TimeOut contains a time in milliseconds. When the TimeOut is reached, or one of the file descriptors has changed, the Select call returns. On return, it will have modified the entries in the array which have actually changed, and it returns the number of entries that have been changed. If the timout was reached, and no decsriptor changed, zero is returned; The arrays of indexes are undefined after that. On error, -1 is returned. Errors: On error, the function returns -1, and Errors are reported in LinuxError : SYS_EBADF An invalid descriptot was specified in one of the sets. SYS_EINTR A non blocked signal was caught. SYS_EINVAL N is negative or too big. SYS_ENOMEM Select was unable to allocate memory for its internal tables. See also: SelectText (245), GetFS (223), FD_ZERO (209), FD_Clr (209), FD_Set (210), FD_IsSet (210) Listing: linuxex/ex33.pp Program Example33 ; { Program t o demonstrate t h e S e l e c t f u n c t i o n . } Uses BaseUnix ; Var FDS : s i g s e t _ t ; begin f p s i g e m p t y s e t ( FDS ) ; f p s i g a d d s e t ( FDS , 0 ) ; W r i t e l n ( ’ Press t h e t o c o n t i n u e t h e program . ’ ) ; { Wait u n t i l F i l e d e s c r i p t o r 0 ( = I n p u t ) changes } f p S e l e c t ( 1 ,@FDS, n i l , n i l , n i l ) ; { Get r i d o f i n b u f f e r } readln ; W r i t e l n ( ’ Press key i n l e s s than 2 seconds . . . ’ ) ; f p s i g e m p t y s e t ( FDS ) ; f p s i g a d d s e t ( FDS , 0 ) ; i f f p S e l e c t ( 1 ,@FDS, n i l , n i l , 2 0 0 0 ) > 0 then W r i t e l n ( ’ Thank you ! ’ ) { FD_ISSET ( 0 ,FDS ) would be t r u e here . } else W r i t e l n ( ’ Too l a t e ! ’ ) ; end .

SelectText Declaration: Function SelectText ( var T : Text; TimeOut :PTime) :

Longint;

Description: SelectText executes the Select (244) call on a file of type Text. You can specify a timeout in TimeOut. The SelectText call determines itself whether it should check for read or write, depending on how the file was opened : With Reset it is checked for reading, with Rewrite and Append it is checked for writing. 245

CHAPTER 12. THE LINUX UNIT.

Errors: See Select (244). SYS_EBADF can also mean that the file wasn’t opened. See also: Select (244), GetFS (223)

SetPriority Declaration: Function SetPriority (Which,Who,Prio :

Integer) :

Integer;

Description: SetPriority sets the priority with which a process is running. Which process(es) is determined by the Which and Who variables. Which can be one of the pre-defined Prio_Process, Prio_PGrp, Prio_User, in which case Who is the process ID, Process group ID or User ID, respectively. Prio is a value in the range -20 to 20. Errors: Error checking must be done on LinuxError, since a priority can be negative. sys_esrchNo process found using which and who. sys_einvalWhich was not one of Prio_Process, Prio_Grp or Prio_User. sys_epermA process was found, but neither its effective or real user ID match the effective user ID of the caller. sys_eaccesA non-superuser tried to a priority increase. See also: GetPriority (225), Nice (238), Setpriority (2) For an example, see Nice (238).

Shell Declaration: Function Shell (Command :

String) :

Longint;

Description: Shell invokes the bash shell (/bin/sh), and feeds it the command Command (using the -c option). The function then waits for the command to complete, and then returns the exit status of the command, or 127 if it could not complete the Fork (219) or Execve (207) calls. Errors: Errors are reported in LinuxError. See also: POpen (240), Fork (219), Execve (207), system (3) Listing: linuxex/ex56.pp program example56 ; uses Unix ; { Program t o demonstrate t h e S h e l l f u n c t i o n } Var S : L o n g i n t ; begin W r i t e l n ( ’ Output o f l s − l ∗ . pp ’ ) ; S: = S h e l l ( ’ l s − l ∗ . pp ’ ) ; W r i t e l n ( ’Command e x i t e d wwith s t a t u s : end .

246

’ ,S ) ;

CHAPTER 12. THE LINUX UNIT.

SigAction Declaration: Procedure SigAction (Signum :

Integer; Var Act,OldAct :

PSigActionRec);

Description: Changes the action to take upon receipt of a signal. Act and Oldact are pointers to a SigActionRec record. SigNum specifies the signal, and can be any signal except SIGKILL or SIGSTOP. If Act is non-nil, then the new action for signal SigNum is taken from it. If OldAct is non-nil, the old action is stored there. Sa_Handler may be SIG_DFL for the default action or SIG_IGN to ignore the signal. Sa_Mask Specifies which signals should be ignord during the execution of the signal handler. Sa_Flags Speciefies a series of flags which modify the behaviour of the signal handler. You can ’or’ none or more of the following : SA_NOCLDSTOPIf signum is SIGCHLD do not receive notification when child processes stop. SA_ONESHOT or SA_RESETHANDRestore the signal action to the default state once the signal handler has been called. SA_RESTARTFor compatibility with BSD signals. SA_NOMASK or SA_NODEFERDo not prevent the signal from being received from within its own signal handler. Errors: LinuxError is used to report errors. sys_einvalan invalid signal was specified, or it was SIGKILL or SIGSTOP. sys_efaultAct,OldAct point outside this process address space sys_eintrSystem call was interrupted. See also: SigProcMask (248), SigPending (248), SigSuspend (249), Kill (232), Sigaction (2) Listing: linuxex/ex57.pp Program example57 ; { Program t o demonstrate t h e S i g A c t i o n f u n c t i o n . } { do a k i l l −USR1 p i d from a n o t h e r t e r m i n a l t o see what happens . r e p l a c e p i d w i t h t h e r e a l p i d o f t h i s program . You can g e t t h i s p i d by r u n n i n g ’ ps ’ . } uses BaseUnix ; Var oa , na : PSigActionRec ; Procedure DoSig ( s i g : c i n t ) ; cdecl ; begin writeln ( ’ Receiving s i g n a l : ’ , sig ) ; end ; begin new( na ) ; new( oa ) ; na ^ . sa_Handler : = T S i g a c t i o n ( @DoSig ) ; f i l l c h a r ( na ^ . Sa_Mask , s i z e o f ( na ^ . sa_mask ) , # 0 ) ; na ^ . Sa_Flags : = 0 ; { $ i f d e f Linux } / / Linux s p e c i f i c

247

CHAPTER 12. THE LINUX UNIT.

na ^ . Sa_Restorer : = N i l ; { $endif } i f f p S i g A c t i o n ( SigUsr1 , na , oa ) < >0 then begin writeln ( ’ Error : ’ , fpgeterrno , ’ . ’ ) ; halt ( 1 ) ; end ; W r i t e l n ( ’ Send USR1 s i g n a l o r press t o e x i t ’ ) ; readln ; end .

SigPending Declaration: Function SigPending :

SigSet;

Description: Sigpending allows the examination of pending signals (which have been raised while blocked.) The signal mask of pending signals is returned. Errors: None See also: SigAction (247), SigProcMask (248), SigSuspend (249), Signal (249), Kill (232), Sigpending (2)

SigProcMask Declaration: Procedure SigProcMask (How :

Integer; SSet,OldSSet :

PSigSet);

Description: Changes the list of currently blocked signals. The behaviour of the call depends on How : SIG_BLOCKThe set of blocked signals is the union of the current set and the SSet argument. SIG_UNBLOCKThe signals in SSet are removed from the set of currently blocked signals. SIG_SETMASKThe list of blocked signals is set so SSet. If OldSSet is non-nil, then the old set is stored in it. Errors: LinuxError is used to report errors. sys_efaultSSet or OldSSet point to an adress outside the range of the process. sys_eintrSystem call was interrupted. See also: SigAction (247), SigPending (248), SigSuspend (249), Kill (232), Sigprocmask (2)

SigRaise Declaration: Procedure SigRaise(Sig:integer); Description: SigRaise sends a Sig signal to the current process. Errors: None. See also: Kill (232), GetPid (225) Listing: linuxex/ex65.pp

248

CHAPTER 12. THE LINUX UNIT.

Program example64 ; { Program t o demonstrate t h e SigRaise f u n c t i o n . } uses Unix , BaseUnix ; Var oa , na : PSigActionRec ; Procedure DoSig ( s i g : L o n g i n t ) ; cdecl ; begin writeln ( ’ Receiving s i g n a l : ’ , sig ) ; end ; begin new( na ) ; new( oa ) ; na ^ . sa_handler : = T S i g a c t i o n ( @DoSig ) ; f i l l c h a r ( na ^ . Sa_Mask , s i z e o f ( na ^ . Sa_Mask ) , # 0 ) ; na ^ . Sa_Flags : = 0 ; { $ i f d e f Linux } / / t h i s member i s l i n u x only , and a f a i k even t h e r e arcane na ^ . Sa_Restorer : = N i l ; { $endif } i f f p S i g A c t i o n ( SigUsr1 , na , oa ) < >0 then begin writeln ( ’ Error : ’ , fpgeterrno ) ; halt ( 1 ) ; end ; W r i t e l n ( ’ Sending USR1 ( ’ , s i g u s r 1 , ’ ) s i g n a l t o s e l f . ’ ) ; SigRaise ( s i g u s r 1 ) ; end .

SigSuspend Declaration: Procedure SigSuspend (Mask :

SigSet);

Description: SigSuspend temporarily replaces the signal mask for the process with the one given in Mask, and then suspends the process until a signal is received. Errors: None See also: SigAction (247), SigProcMask (248), SigPending (248), Signal (249), Kill (232), SigSuspend (2)

Signal Declaration: Function Signal (SigNum :

Integer; Handler :

SignalHandler) :

SignalHandler;

Description: Signal installs a new signal handler for signal SigNum. This call has the same functionality as the SigAction call. The return value for Signal is the old signal handler, or nil on error. Errors: LinuxError is used to report errors : SIG_ERRAn error occurred. 249

CHAPTER 12. THE LINUX UNIT.

See also: SigAction (247),Kill (232), Signal (2) Listing: linuxex/ex58.pp Program example58 ; { Program t o demonstrate t h e S i g n a l f u n c t i o n . } { do a k i l l −USR1 p i d from a n o t h e r t e r m i n a l t o see what happens . r e p l a c e p i d w i t h t h e r e a l p i d o f t h i s program . You can g e t t h i s p i d by r u n n i n g ’ ps ’ . } uses BaseUnix ; Procedure DoSig ( s i g : c i n t ) ; cdecl ; begin writeln ( ’ Receiving s i g n a l : ’ , sig ) ; end ; begin i f f p S i g n a l ( SigUsr1 , S i g n a l H a n d l e r ( @DoSig ) ) = s i g n a l h a n d l e r ( SIG_ERR ) then begin w r i t e l n ( ’ E r r o r : ’ , fpGetErrno , ’ . ’ ) ; halt ( 1 ) ; end ; W r i t e l n ( ’ Send USR1 s i g n a l o r press t o e x i t ’ ) ; readln ; end .

StringToPPchar Declaration: Function StringToPPChar(Var S:STring):ppchar; Description: StringToPPChar splits the string S in words, replacing any whitespace with zero characters. It returns a pointer to an array of pchars that point to the first letters of the words in S. This array is terminated by a Nil pointer. The function does not add a zero character to the end of the string unless it ends on whitespace. The function reserves memory on the heap to store the array of PChar; The caller is responsible for freeing this memory. This function can be called to create arguments for the various Exec calls. Errors: None. See also: CreateShellArgV (201), Execve (207), Execv (207) Listing: linuxex/ex70.pp Program Example70 ; { Program t o demonstrate t h e StringToPPchar f u n c t i o n . } Uses U n i x U t i l ;

250

CHAPTER 12. THE LINUX UNIT.

Var S : S t r i n g ; P : PPChar ; I : longint ; begin / / remark whitespace a t end . S: = ’ T h i s i s a s t r i n g w i t h words . ’ ; P: = StringToPPChar ( S , 0 ) ; I :=0; While P [ i ] < > N i l do begin W r i t e l n ( ’ Word ’ , i , ’ : ’ ,P [ i ] ) ; Inc ( I ) ; end ; FreeMem ( P , i ∗ SizeOf ( Pchar ) ) ; end .

SymLink Declaration: Function SymLink (OldPath,NewPath :

pathstr) :

Boolean;

Description: SymLink makes Newpath point to the file in OldPath, which doesn’t necessarily exist. The two files DO NOT have the same inode number. This is known as a ’soft’ link. The permissions of the link are irrelevant, as they are not used when following the link. Ownership of the file is only checked in case of removal or renaming of the link. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. sys_epermThe filesystem containing oldpath and newpath doesn’t support linking files. sys_eaccessWrite access for the directory containing Newpath is disallowed, or one of the directories in OldPath or NewPath has no search (=execute) permission. sys_enoentA directory entry in OldPath or NewPath does not exist or is a symbolic link pointing to a non-existent directory. sys_enotdirA directory entry in OldPath or NewPath is nor a directory. sys_enomemInsufficient kernel memory. sys_erofsThe files are on a read-only filesystem. sys_eexistNewPath already exists. sys_eloopOldPath or NewPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. sys_enospcThe device containing NewPath has no room for anothe entry. See also: Link (233), UnLink (257), ReadLink (241), Symlink (2) Listing: linuxex/ex22.pp Program Example22 ; { Program t o demonstrate t h e SymLink and UnLink f u n c t i o n s . } Uses baseunix , Unix ; Var F : Text ;

251

CHAPTER 12. THE LINUX UNIT.

S : String ; begin Assign ( F , ’ t e s t . t x t ’ ) ; Rewrite ( F ) ; Writeln ( F , ’ This i s w r i t t e n to t e s t . t x t ’ ) ; Close ( f ) ; { new . t x t and t e s t . t x t are now t h e same f i l e } i f fpSymLink ( ’ t e s t . t x t ’ , ’ new . t x t ’ ) < >0 then w r i t e l n ( ’ E r r o r when s y m l i n k i n g ! ’ ) ; { Removing t e s t . t x t s t i l l l e a v e s new . t x t P o i n t i n g now t o a non−e x i s t e n t f i l e ! } I f f p U n l i n k ( ’ t e s t . t x t ’ ) < >0 then W r i t e l n ( ’ E r r o r when u n l i n k i n g ! ’ ) ; Assign ( f , ’ new . t x t ’ ) ; { T h i s should f a i l , s i n c e t h e s y m b o l i c l i n k p o i n t s t o a non−e x i s t e n t f i l e ! } { $ i −} Reset ( F ) ; { $i+} I f IOResult =0 then W r i t e l n ( ’ T h i s shouldn ’ ’ t happen ’ ) ; { Now remove new . t x t a l s o } I f f p U n l i n k ( ’ new . t x t ’ ) < >0 then W r i t e l n ( ’ E r r o r when u n l i n k i n g ! ’ ) ; end .

SysInfo Declaration: Function SysInfo(var Info:TSysinfo):Boolean; Description: SysInfo returns system information in Info. Returned information in Info includes: uptimeNumber of seconds since boot. loads1, 5 and 15 minute load averages. totalramtotal amount of main memory. freeramamount of free memory. sharedramamount of shared memory bufferramamount of memory used by buffers. totalswaptotal amount of swapspace. freeswapamount of free swapspace. procsnumber of current processes. Errors: None. See also: Uname (257) Listing: linuxex/ex64.pp program Example64 ; { Example t o demonstrate t h e S y s I n f o f u n c t i o n . S y s i n f o i s Linux−o n l y . }

252

CHAPTER 12. THE LINUX UNIT.

{ $ i f d e f Linux } Uses L i n u x ; Function Mb( L : L o n g i n t ) : l o n g i n t ; begin Mb: = L div ( 1 0 2 4 ∗ 1 0 2 4 ) ; end ; Var I n f o : TSysInfo ; D,M, Secs , H : l o n g i n t ; { $endif } begin { $ i f d e f Linux } I f Not S y s I n f o ( I n f o ) then Halt ( 1 ) ; With I n f o do begin D: = Uptime div ( 3 6 0 0 ∗ 2 4 ) ; UpTime : = UpTime mod ( 3 6 0 0 ∗ 2 4 ) ; h : = uptime div 3 6 0 0 ; uptime : = uptime mod 3 6 0 0 ; m: = uptime div 6 0 ; secs : = uptime mod 6 0 ; W r i t e l n ( ’ Uptime : ’ , d , ’ days , ’ , h , ’ hours , ’ ,m, ’ min , ’ , secs , ’ s . ’ ) ; W r i t e l n ( ’ Loads : ’ , Loads [ 1 ] , ’ / ’ , Loads [ 2 ] , ’ / ’ , Loads [ 3 ] ) ; W r i t e l n ( ’ T o t a l Ram : ’ ,Mb( t o t a l r a m ) , ’Mb. ’ ) ; W r i t e l n ( ’ Free Ram : ’ ,Mb( freeram ) , ’Mb. ’ ) ; W r i t e l n ( ’ Shared Ram : ’ ,Mb( sharedram ) , ’Mb. ’ ) ; W r i t e l n ( ’ B u f f e r Ram : ’ ,Mb( b u f f e r r a m ) , ’Mb. ’ ) ; W r i t e l n ( ’ T o t a l Swap : ’ ,Mb( t o t a l s w a p ) , ’Mb. ’ ) ; W r i t e l n ( ’ Free Swap : ’ ,Mb( freeswap ) , ’Mb. ’ ) ; end ; { $endif } end .

TCDrain Declaration: Function TCDrain (Fd:longint) :

Boolean;

Description: TCDrain waits until all data to file descriptor Fd is transmitted. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError See also: termios (2)

TCFlow Declaration: Function TCFlow (Fd,Act:longint) :

Boolean;

Description: TCFlow suspends/resumes transmission or reception of data to or from the file descriptor Fd, depending on the action Act. This can be one of the following pre-defined values: TCOOFF suspend reception/transmission,

253

CHAPTER 12. THE LINUX UNIT.

TCOON resume reception/transmission, TCIOFF transmit a stop character to stop input from the terminal, TCION transmit start to resume input from the terminal. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError. See also: termios (2)

TCFlush Declaration: Function TCFlush (Fd,QSel:longint) :

Boolean;

Description: TCFlush discards all data sent or received to/from file descriptor fd. QSel indicates which queue should be discard. It can be one of the following pre-defined values : TCIFLUSH input, TCOFLUSH output, TCIOFLUSH both input and output. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError. See also: termios (2)

TCGetAttr Declaration: Function TCGetAttr (fd:longint;var tios:TermIOS) : Boolean; Description: TCGetAttr gets the terminal parameters from the terminal referred to by the file descriptor fd and returns them in a TermIOS structure tios. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError See also: TCSetAttr (255), termios (2) Listing: linuxex/ex55.pp Program Example55 ; uses TermIO ; { Program t o demonstrate t h e TCGetAttr / T C S e t A t t r / CFMakeRaw f u n c t i o n s . } procedure ShowTermios ( var begin WriteLn ( ’ I n p u t Flags : WriteLn ( ’ Output Flags : WriteLn ( ’ L i n e Flags : WriteLn ( ’ C o n t r o l Flags : end ;

t i o s : Termios ) ; $’ $’ $’ $’

, hexstr ( , hexstr ( , hexstr ( , hexstr (

tios tios tios tios

. c_iflag . c_oflag . c_lflag . c_cflag

var oldios ,

254

,8)+#13); ,8)); ,8)); ,8));

CHAPTER 12. THE LINUX UNIT.

t i o s : Termios ; begin WriteLn ( ’ Old a t t r i b u t e s : ’ ) ; TCGetAttr ( 1 , t i o s ) ; ShowTermios ( t i o s ) ; oldios := t i o s ; W r i t e l n ( ’ S e t t i n g raw t e r m i n a l mode ’ ) ; CFMakeRaw( t i o s ) ; T C S e t A t t r ( 1 ,TCSANOW, t i o s ) ; WriteLn ( ’ C u r r e n t a t t r i b u t e s : ’ ) ; TCGetAttr ( 1 , t i o s ) ; ShowTermios ( t i o s ) ; T C S e t A t t r ( 1 ,TCSANOW, o l d i o s ) ; end .

TCGetPGrp Declaration: Function TCGetPGrp (Fd:longint;var Id:longint) :

boolean;

Description: TCGetPGrp returns the process group ID of a foreground process group in Id The function returns True if the call was succesfull, False otherwise Errors: Errors are reported in LinuxError See also: termios (2)

TCSendBreak Declaration: Function TCSendBreak (Fd,Duration:longint) :

Boolean;

Description: TCSendBreak Sends zero-valued bits on an asynchrone serial connection decsribed by filedescriptor Fd, for duration Duration. The function returns True if the action was performed successfully, False otherwise. Errors: Errors are reported in LinuxError. See also: termios (2)

TCSetAttr Declaration: Function TCSetAttr (Fd:longint;OptAct:longint;var Tios:TermIOS) : Boolean; Description: TCSetAttr Sets the terminal parameters you specify in a TermIOS structure Tios for the terminal referred to by the file descriptor Fd. OptAct specifies an optional action when the set need to be done, this could be one of the following pre-defined values: TCSANOW set immediately. TCSADRAIN wait for output. TCSAFLUSH wait for output and discard all input not yet read. The function Returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError. See also: TCGetAttr (254), termios (2) For an example, see TCGetAttr (254). 255

CHAPTER 12. THE LINUX UNIT.

TCSetPGrp Declaration: Function TCSetPGrp (Fd,Id:longint) :

boolean;

Description: TCSetPGrp Sets the Process Group Id to Id. The function returns True if the call was successful, False otherwise. Errors: Errors are returned in LinuxError. See also: TCGetPGrp (255), termios (2) For an example, see TCGetPGrp (255).

TTYName Declaration: Function TTYName (var f) :

String;

Description: Returns the name of the terminal pointed to by f. f must be a terminal. f can be of type: 1.longint for file handles; 2.Text for text variables such as input etc. Errors: Returns an empty string in case of an error. Linuxerror may be set to indicate what error occurred, but this is uncertain. See also: IsATTY (229),IOCtl (228)

TellDir Declaration: Function TellDir (p:pdir) :

longint;

Description: TellDir returns the current location in the directory structure pointed to by p. It returns -1 on failure. Errors: Errors are returned in LinuxError. See also: CloseDir (201), ReadDir (241), SeekDir (244), OpenDir (239), telldir (3) For an example, see OpenDir (239).

Umask Declaration: Function Umask (Mask :

Integer) :

Integer;

Description: Change the file creation mask for the current user to Mask. The current mask is returned. Errors: None See also: Chmod (198), Umask (2) Listing: linuxex/ex27.pp Program Example27 ; { Program t o demonstrate t h e Umask f u n c t i o n . } Uses BaseUnix ;

256

CHAPTER 12. THE LINUX UNIT.

begin W r i t e l n ( ’ Old Umask was : ’ , fpUmask ( & 1 1 1 ) ) ; WRiteln ( ’New Umask i s : ’ ,&111); end .

Uname Declaration: Procedure Uname (var unamerec:utsname); Description: Uname gets the name and configuration of the current LINUX kernel, and returns it in unamerec. Errors: LinuxError is used to report errors. See also: GetHostName (224), GetDomainName (221), uname (2)

UnLink Declaration: Function UnLink (Var Path) :

Boolean;

Description: UnLink decreases the link count on file Path. Path can be of type PathStr or PChar. If the link count is zero, the file is removed from the disk. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. sys_eaccessYou have no write access right in the directory containing Path, or you have no search permission in one of the directory components of Path. sys_epermThe directory containing pathname has the sticky-bit set and the process’s effective uid is neither the uid of the file to be deleted nor that of the directory containing it. sys_enoentA component of the path doesn’t exist. sys_enotdirA directory component of the path is not a directory. sys_eisdirPath refers to a directory. sys_enomemInsufficient kernel memory. sys_erofsPath is on a read-only filesystem. See also: Link (233), SymLink (251), Unlink (2) For an example, see Link (233).

Utime Declaration: Function Utime (path :

pathstr; utim :

utimbuf) :

Boolean;

Description: Utime sets the access and modification times of a file. the utimbuf record contains 2 fields, actime, and modtime, both of type Longint. They should be filled with an epoch-like time, specifying, respectively, the last access time, and the last modification time. For some filesystem (most notably, FAT), these times are the same. Errors: Errors are returned in LinuxError. sys_eaccessOne of the directories in Path has no search (=execute) permission.

257

CHAPTER 12. THE LINUX UNIT.

sys_enoentA directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory. Other errors may occur, but aren’t documented. See also: GetEpochTime (223), Chown (197), Access (192), utime (() 2) Listing: linuxex/ex25.pp Program Example25 ; { Program t o demonstrate t h e UTime f u n c t i o n . } Uses BaseUnix , Unix , U n i x U t i l ; Var u t i m : u t i m b u f ; year , month , day , hour , minute , second : Word ; begin { Set access and m o d i f i c a t i o n t i m e o f e x e c u t a b l e source } GetTime ( hour , minute , second ) ; GetDate ( year , month , day ) ; u t i m . actime : = LocalToEpoch ( year , month , day , hour , minute , second ) ; u t i m . modtime : = u t i m . actime ; i f Fputime ( ’ ex25 . pp ’ , @utim) < >0 then w r i t e l n ( ’ C a l l t o UTime f a i l e d ! ’ ) else begin Write ( ’ Set access and m o d i f i c a t i o n t i m e s t o : ’ ) ; Write ( Hour : 2 , ’ : ’ , minute : 2 , ’ : ’ , second , ’ , ’ ) ; W r i t e l n ( Day : 2 , ’ / ’ , month : 2 , ’ / ’ , year : 4 ) ; end ; end .

WaitPid Declaration: Function WaitPid (Pid : : Longint;

longint; Status :

pointer; Options :

Longint)

Description: WaitPid waits for a child process with process ID Pid to exit. The value of Pid can be one of the following: Pid < -1Causes WaitPid to wait for any child process whose process group ID equals the absolute value of pid. Pid = -1Causes WaitPid to wait for any child process. Pid = 0Causes WaitPid to wait for any child process whose process group ID equals the one of the calling process. Pid > 0Causes WaitPid to wait for the child whose process ID equals the value of Pid. The Options parameter can be used to specify further how WaitPid behaves: WNOHANGCauses Waitpid to return immediately if no child has exited. WUNTRACEDCauses WaitPid to return also for children which are stopped, but whose status has not yet been reported. __WCLONECauses WaitPid also to wait for threads created by the Clone (199) call. 258

CHAPTER 12. THE LINUX UNIT.

Upon return, it returns the exit status of the process, or -1 in case of failure. Errors: Errors are returned in LinuxError. See also: Fork (219), Execve (207), waitpid (2) For an example, see Fork (219).

WritePort Declaration: Procedure WritePort (Port : Longint; Value : Byte); Procedure WritePort (Port : Longint; Value : Word); Procedure WritePort (Port : Longint; Value : Longint); Description: WritePort writes Value – 1 byte, Word or longint – to port Port. Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call. Errors: In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), WritePortB (259), WritePortL (259), WritePortW (260), ReadPortB (243), ReadPortL (243), ReadPortW (244)

WritePortB Declaration: Procedure WritePortB (Port : Longint; Value : (Port : Longint; Var Buf; Count: longint);

Byte); Procedure WritePortB

Description: The first form of WritePortB writes 1 byte to port Port. The second form writes Count bytes from Buf to port Port. Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call. Errors: In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), WritePort (259), WritePortL (259), WritePortW (260), ReadPortB (243), ReadPortL (243), ReadPortW (244)

WritePortL Declaration: Procedure WritePortL (Port : Longint; Value : Longint); Procedure WritePortL (Port : Longint; Var Buf; Count: longint); Description: The first form of WritePortB writes 1 byte to port Port. The second form writes Count bytes from Buf to port Port. Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call. Errors: In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), WritePort (259), WritePortB (259), WritePortW (260), ReadPortB (243), ReadPortL (243), ReadPortW (244) 259

CHAPTER 12. THE LINUX UNIT.

WritePortW Declaration: Procedure WritePortW (Port : Longint; Var Buf; Count: WritePortW (Port : Longint; Value : Word);

longint); Procedure

Description: The first form of WritePortB writes 1 byte to port Port. The second form writes Count bytes from Buf to port Port. Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call. Errors: In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur. See also: IOperm (229), WritePort (259), WritePortL (259), WritePortB (259), ReadPortB (243), ReadPortL (243), ReadPortW (244)

260

Chapter 13

The MATH unit This chapter describes the math unit. The math unit was initially written by Florian Klämpfl. It provides mathematical functions which aren’t covered by the system unit. This chapter starts out with a definition of all types and constants that are defined, after which an overview is presented of the available functions, grouped by category, and the last part contains a complete explanation of each function. The following things must be taken into account when using this unit: 1. This unit is compiled in Object Pascal mode so all integers are 32 bit. 2. Some overloaded functions exist for data arrays of integers and floats. When using the address operator (@) to pass an array of data to such a function, make sure the address is typecasted to the right type, or turn on the ’typed address operator’ feature. failing to do so, will cause the compiler not be able to decide which function you want to call.

13.1

Constants and types

The following types are defined in the math unit: Type Float = Extended; PFloat = ^FLoat All calculations are done with the Float type. This allows to recompile the unit with a different float type to obtain a desired precision. The pointer type is used in functions that accept an array of values of arbitrary length. Type TPaymentTime = (PTEndOfPeriod,PTStartOfPeriod); TPaymentTime is used in the financial calculations. Type EInvalidArgument = Class(EMathError); The EInvalidArgument exception is used to report invalid arguments.

261

CHAPTER 13. THE MATH UNIT

13.2

Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where you can find the function.

Min/max determination Functions to determine the minimum or maximum of numbers: Name

Description

Page

max

Maximum of 2 values

275

maxIntValue

Maximum of an array of integer values

276

maxvalue

Maximum of an array of values

276

min

Minimum of 2 values

279

minIntValue

Minimum of an array of integer values

279

minvalue

Minimum of an array of values

280

Angle conversion Name

Description

Page

cycletorad

convert cycles to radians

268

degtograd

convert degrees to grads

269

degtorad

convert degrees to radians

269

gradtodeg

convert grads to degrees

271

gradtorad

convert grads to radians

271

radtocycle

convert radians to cycles

284

radtodeg

convert radians to degrees

284

radtograd

convert radians to grads

285

Trigoniometric functions Name

Description

Page

arccos

calculate reverse cosine

264

arcsin

calculate reverse sine

265

arctan2

calculate reverse tangent

266

cotan

calculate cotangent

268

sincos

calculate sine and cosine

286

tan

calculate tangent

290

262

CHAPTER 13. THE MATH UNIT

Hyperbolic functions Name

Description

Page

arcosh

caculate reverse hyperbolic cosine

264

arsinh

caculate reverse hyperbolic sine

266

artanh

caculate reverse hyperbolic tangent

267

cosh

calculate hyperbolic cosine

268

sinh

calculate hyperbolic sine

286

tanh

calculate hyperbolic tangent

290

Exponential and logarithmic functions Name intpower

Description

Page

Raise float to integer power

272

p

ldexp

Calculate 2 x

273

lnxp1

calculate log(x+1)

273

log10

calculate 10-base log

274

log2

calculate 2-base log

274

logn

calculate N-base log

275

power

raise float to arbitrary power

283

Description

Page

Number converting Name ceil

Round to infinity

267

floor

Round to minus infinity

270

frexp

Return mantissa and exponent

270

Statistical functions Name

Description

Page

mean

Mean of values

277

meanandstddev

Mean and standard deviation of values

278

momentskewkurtosis

Moments, skew and kurtosis

281

popnstddev

Population standarddeviation

282

popnvariance

Population variance

283

randg

Gaussian distributed randum value

285

stddev

Standard deviation

287

sum

Sum of values

288

sumofsquares

Sum of squared values

288 263

CHAPTER 13. THE MATH UNIT

sumsandsquares

Sum of values and squared values

289

totalvariance

Total variance of values

291

variance

variance of values

291

Geometrical functions Name

Description

Page

hypot

Hypotenuse of triangle

272

norm

Euclidian norm

281

13.3

Functions and Procedures

arccos Declaration: Function arccos(x :

float) :

float;

Description: Arccos returns the inverse cosine of its argument x. The argument x should lie between -1 and 1 (borders included). Errors: If the argument x is not in the allowed range, an EInvalidArgument exception is raised. See also: arcsin (265), arcosh (264), arsinh (266), artanh (267) Listing: mathex/ex1.pp Program Example1 ; { Program t o demonstrate t h e arccos f u n c t i o n . } Uses math ; Procedure WriteRadDeg ( X : f l o a t ) ; begin W r i t e l n ( X : 8 : 5 , ’ rad = ’ , radtodeg ( x ) : 8 : 5 , ’ degrees . ’ ) end ; begin WriteRadDeg WriteRadDeg WriteRadDeg WriteRadDeg WriteRadDeg WriteRadDeg end .

( arccos ( 1 ) ) ; ( arccos ( s q r t ( 3 ) / 2 ) ) ; ( arccos ( s q r t ( 2 ) / 2 ) ) ; ( arccos ( 1 / 2 ) ) ; ( arccos ( 0 ) ) ; ( arccos ( − 1 ) ) ;

arcosh Declaration: Function arcosh(x : float;

float) :

float; Function arccosh(x :

264

float) :

CHAPTER 13. THE MATH UNIT

Description: Arcosh returns the inverse hyperbolic cosine of its argument x. The argument x should be larger than 1. The arccosh variant of this function is supplied for Delphicompatibility. Errors: If the argument x is not in the allowed range, an EInvalidArgument exception is raised. See also: cosh (268), sinh (286), arcsin (265), arsinh (266), artanh (267), tanh (290) Listing: mathex/ex3.pp Program Example3 ; { Program t o demonstrate t h e arcosh f u n c t i o n . } Uses math ; begin W r i t e l n ( arcosh ( 1 ) ) ; W r i t e l n ( arcosh ( 2 ) ) ; end .

arcsin Declaration: Function arcsin(x :

float) :

float;

Description: Arcsin returns the inverse sine of its argument x. The argument x should lie between -1 and 1. Errors: If the argument x is not in the allowed range, an EInvalidArgument exception is raised. See also: arccos (264), arcosh (264), arsinh (266), artanh (267) Listing: mathex/ex2.pp Program Example1 ; { Program t o demonstrate t h e a r c s i n f u n c t i o n . } Uses math ; Procedure WriteRadDeg ( X : f l o a t ) ; begin W r i t e l n ( X : 8 : 5 , ’ rad = ’ , radtodeg ( x ) : 8 : 5 , ’ degrees . ’ ) end ; begin WriteRadDeg WriteRadDeg WriteRadDeg WriteRadDeg WriteRadDeg WriteRadDeg end .

( ( ( ( ( (

arcsin ( 1 ) ) ; a r c s i n ( sqrt ( 3 ) / 2 ) ) ; a r c s i n ( sqrt ( 2 ) / 2 ) ) ; arcsin ( 1 / 2 ) ) ; arcsin ( 0 ) ) ; arcsin ( −1));

265

CHAPTER 13. THE MATH UNIT

arctan2 Declaration: Function arctan2(x,y :

float) :

float;

Description: arctan2 calculates arctan(y/x), and returns an angle in the correct quadrant. The returned angle will be in the range −π to π radians. The values of x and y must be between -2ˆ64 and 2ˆ64, moreover x should be different from zero. On Intel systems this function is implemented with the native intel fpatan instruction. Errors: If x is zero, an overflow error will occur. See also: arccos (264), arcosh (264), arsinh (266), artanh (267) Listing: mathex/ex6.pp Program Example6 ; { Program t o demonstrate t h e a r c t a n 2 f u n c t i o n . } Uses math ; Procedure WriteRadDeg ( X : f l o a t ) ; begin W r i t e l n ( X : 8 : 5 , ’ rad = ’ , radtodeg ( x ) : 8 : 5 , ’ degrees . ’ ) end ; begin WriteRadDeg ( a r c t a n 2 ( 1 , 1 ) ) ; end .

arsinh Declaration: Function arsinh(x : float;

float) :

float; Function arcsinh(x :

Description: arsinh returns the inverse hyperbolic sine of its argument x. The arscsinh variant of this function is supplied for Delphicompatibility. Errors: None. See also: arcosh (264), arccos (264), arcsin (265), artanh (267) Listing: mathex/ex4.pp Program Example4 ; { Program t o demonstrate t h e a r s i n h f u n c t i o n . } Uses math ; begin Writeln ( arsinh ( 0 ) ) ; Writeln ( arsinh ( 1 ) ) ; end .

266

float) :

CHAPTER 13. THE MATH UNIT

artanh Declaration: Function artanh(x : float;

float) :

float; Function arctanh(x :

float) :

Description: artanh returns the inverse hyperbolic tangent of its argument x, where x should lie in the interval [-1,1], borders included. The arctanh variant of this function is supplied for Delphicompatibility. Errors: In case x is not in the interval [-1,1], an EInvalidArgument exception is raised. See also: arcosh (264), arccos (264), arcsin (265), artanh (267) Errors: See also: Listing: mathex/ex5.pp Program Example5 ; { Program t o demonstrate t h e a r t a n h f u n c t i o n . } Uses math ; begin Writeln ( artanh ( 0 ) ) ; Writeln ( artanh ( 0 . 5 ) ) ; end .

ceil Declaration: Function ceil(x :

float) :

longint;

Description: Ceil returns the lowest integer number greater than or equal to x. The absolute value of x should be less than maxint. Errors: If the asolute value of x is larger than maxint, an overflow error will occur. See also: floor (270) Listing: mathex/ex7.pp Program Example7 ; { Program t o demonstrate t h e C e i l f u n c t i o n . } Uses math ; begin W r i t e l n ( C e i l ( − 3 . 7 ) ) ; / / should be −3 Writeln ( C e i l ( 3 . 7 ) ) ; / / should be 4 W r i t e l n ( C e i l ( − 4 . 0 ) ) ; / / should be −4 end .

267

CHAPTER 13. THE MATH UNIT

cosh Declaration: Function cosh(x :

float) :

float;

Description: Cosh returns the hyperbolic cosine of it’s argument x. Errors: None. See also: arcosh (264), sinh (286), arsinh (266) Listing: mathex/ex8.pp Program Example8 ; { Program t o demonstrate t h e cosh f u n c t i o n . } Uses math ; begin W r i t e l n ( Cosh ( 0 ) ) ; W r i t e l n ( Cosh ( 1 ) ) ; end .

cotan Declaration: Function cotan(x :

float) :

float;

Description: Cotan returns the cotangent of it’s argument x. x should be different from zero. Errors: If x is zero then a overflow error will occur. See also: tanh (290) Listing: mathex/ex9.pp Program Example9 ; { Program t o demonstrate t h e cotan f u n c t i o n . } Uses math ; begin w r i t e l n ( cotan ( p i / 2 ) ) ; W r i t e l n ( cotan ( p i / 3 ) ) ; W r i t e l n ( cotan ( p i / 4 ) ) ; end .

cycletorad Declaration: Function cycletorad(cycle :

float) :

float;

Description: Cycletorad transforms it’s argument cycle (an angle expressed in cycles) to radians. (1 cycle is 2π radians). Errors: None. See also: degtograd (269), degtorad (269), radtodeg (284), radtograd (285), radtocycle (284) 268

CHAPTER 13. THE MATH UNIT

Listing: mathex/ex10.pp Program Example10 ; { Program t o demonstrate t h e c y c l e t o r a d f u n c t i o n . } Uses math ; begin w r i t e l n ( cos ( c y c l e t o r a d ( 1 / 6 ) ) ) ; / / Should p r i n t 1 / 2 w r i t e l n ( cos ( c y c l e t o r a d ( 1 / 8 ) ) ) ; / / should be s q r t ( 2 ) / 2 end .

degtograd Declaration: Function degtograd(deg :

float) :

float;

Description: Degtograd transforms it’s argument deg (an angle in degrees) to grads. (90 degrees is 100 grad.) Errors: None. See also: cycletorad (268), degtorad (269), radtodeg (284), radtograd (285), radtocycle (284) Listing: mathex/ex11.pp Program Example11 ; { Program t o demonstrate t h e degtograd f u n c t i o n . } Uses math ; begin w r i t e l n ( degtograd ( 9 0 ) ) ; w r i t e l n ( degtograd ( 1 8 0 ) ) ; w r i t e l n ( degtograd ( 2 7 0 ) ) end .

degtorad Declaration: Function degtorad(deg :

float) :

float;

Description: Degtorad converts it’s argument deg (an angle in degrees) to radians. (pi radians is 180 degrees) Errors: None. See also: cycletorad (268), degtograd (269), radtodeg (284), radtograd (285), radtocycle (284) Listing: mathex/ex12.pp Program Example12 ; { Program t o demonstrate t h e degtorad f u n c t i o n . } Uses math ;

269

CHAPTER 13. THE MATH UNIT

begin w r i t e l n ( degtorad ( 4 5 ) ) ; w r i t e l n ( degtorad ( 9 0 ) ) ; w r i t e l n ( degtorad ( 1 8 0 ) ) ; w r i t e l n ( degtorad ( 2 7 0 ) ) ; w r i t e l n ( degtorad ( 3 6 0 ) ) ; end .

floor Declaration: Function floor(x :

float) :

longint;

Description: Floor returns the largest integer smaller than or equal to x. The absolute value of x should be less than maxint. Errors: If x is larger than maxint, an overflow will occur. See also: ceil (267) Listing: mathex/ex13.pp Program Example13 ; { Program t o demonstrate t h e f l o o r f u n c t i o n . } Uses math ; begin W r i t e l n ( C e i l ( − 3 . 7 ) ) ; / / should be −4 Writeln ( C e i l ( 3 . 7 ) ) ; / / should be 3 W r i t e l n ( C e i l ( − 4 . 0 ) ) ; / / should be −4 end .

frexp Declaration: Procedure frexp(x :

float;var mantissa :

float; var exponent :

Description: Frexp returns the mantissa and exponent of it’s argument x in mantissa and exponent. Errors: None See also: Listing: mathex/ex14.pp Program Example14 ; { Program t o demonstrate t h e f r e x p f u n c t i o n . } Uses math ; Procedure d o f r e x p ( Const X : extended ) ; var man : extended ; exp : l o n g i n t ;

270

integer);

CHAPTER 13. THE MATH UNIT

begin man : = 0 ; exp : = 0 ; f r e x p ( x , man , exp ) ; w r i t e ( x , ’ has ’ ) ; W r i t e l n ( ’ mantissa ’ ,man , ’ and exponent ’ , exp ) ; end ;

begin // dofrexp ( 1 . 0 0 ) ; d o f r e x p ( 1 . 0 2 e −1); d o f r e x p ( 1 . 0 3 e −2); d o f r e x p ( 1 . 0 2 e1 ) ; d o f r e x p ( 1 . 0 3 e2 ) ; end .

gradtodeg Declaration: Function gradtodeg(grad :

float) :

float;

Description: Gradtodeg converts its argument grad (an angle in grads) to degrees. (100 grad is 90 degrees) Errors: None. See also: cycletorad (268), degtograd (269), radtodeg (284), radtograd (285), radtocycle (284), gradtorad (271) Listing: mathex/ex15.pp Program Example15 ; { Program t o demonstrate t h e gradtodeg f u n c t i o n . } Uses math ; begin w r i t e l n ( gradtodeg ( 1 0 0 ) ) ; w r i t e l n ( gradtodeg ( 2 0 0 ) ) ; w r i t e l n ( gradtodeg ( 3 0 0 ) ) ; end .

gradtorad Declaration: Function gradtorad(grad :

float) :

float;

Description: Gradtorad converts its argument grad (an angle in grads) to radians. (200 grad is pi degrees). Errors: None. See also: cycletorad (268), degtograd (269), radtodeg (284), radtograd (285), radtocycle (284), gradtodeg (271) 271

CHAPTER 13. THE MATH UNIT

Listing: mathex/ex16.pp Program Example16 ; { Program t o demonstrate t h e g r a d t o r a d f u n c t i o n . } Uses math ; begin writeln ( gradtorad ( 1 0 0 ) ) ; writeln ( gradtorad ( 2 0 0 ) ) ; writeln ( gradtorad ( 3 0 0 ) ) ; end .

hypot Declaration: Function hypot(x,y :

float) :

float;

Description: Hypot returns the hypotenuse of the triangle where the sides adjacent to the square angle have lengths x and y. The function uses Pythagoras’ rule for this. Errors: None. See also: Listing: mathex/ex17.pp Program Example17 ; { Program t o demonstrate t h e hypot f u n c t i o n . } Uses math ; begin W r i t e l n ( hypot ( 3 , 4 ) ) ; / / should be 5 end .

intpower Declaration: Function intpower(base :

float;exponent :

longint) :

float;

Description: Intpower returns base to the power exponent, where exponent is an integer value. Errors: If base is zero and the exponent is negative, then an overflow error will occur. See also: power (283) Listing: mathex/ex18.pp Program Example18 ; { Program t o demonstrate t h e i n t p o w e r f u n c t i o n . } Uses math ;

272

CHAPTER 13. THE MATH UNIT

Procedure DoIntpower ( X : extended ; Pow : I n t e g e r ) ; begin w r i t e l n ( X : 8 : 4 , ’ ^ ’ ,Pow : 2 , ’ = ’ , i n t p o w e r ( X , pow ) : 8 : 4 ) ; end ; begin dointpower ( 0 . 0 , 0 ) ; dointpower ( 1 . 0 , 0 ) ; dointpower ( 2 . 0 , 5 ) ; dointpower ( 4 . 0 , 3 ) ; dointpower (2.0 , −1); dointpower (2.0 , −2); dointpower ( −2.0 ,4); dointpower ( −4.0 ,3); end .

ldexp Declaration: Function ldexp(x :

float;p :

longint) :

float;

Description: Ldexp returns 2p x. Errors: None. See also: lnxp1 (273), log10 (274),log2 (274),logn (275) Listing: mathex/ex19.pp Program Example19 ; { Program t o demonstrate t h e l d e x p f u n c t i o n . } Uses math ; begin writeln ( ldexp ( 2 , 4 ) : 8 : 4 ) ; writeln ( ldexp ( 0 . 5 , 3 ) : 8 : 4 ) ; end .

lnxp1 Declaration: Function lnxp1(x :

float) :

float;

Description: Lnxp1 returns the natural logarithm of 1+X. The result is more precise for small values of x. x should be larger than -1. Errors: If x ≤ −1 then an EInvalidArgument exception will be raised. See also: ldexp (273), log10 (274),log2 (274),logn (275) Listing: mathex/ex20.pp Program Example20 ; { Program t o demonstrate t h e l n x p 1 f u n c t i o n . }

273

CHAPTER 13. THE MATH UNIT

Uses math ; begin writeln ( lnxp1 ( 0 ) ) ; writeln ( lnxp1 ( 0 . 5 ) ) ; writeln ( lnxp1 ( 1 ) ) ; end .

log10 Declaration: Function log10(x :

float) :

float;

Description: Log10 returns the 10-base logarithm of X. Errors: If x is less than or equal to 0 an ’invalid fpu operation’ error will occur. See also: ldexp (273), lnxp1 (273),log2 (274),logn (275) Listing: mathex/ex21.pp Program Example21 ; { Program t o demonstrate t h e log10 f u n c t i o n . } Uses math ; begin W r i t e l n ( Log10 ( 1 0 ) : 8 : 4 ) ; W r i t e l n ( Log10 ( 1 0 0 ) : 8 : 4 ) ; W r i t e l n ( Log10 ( 1 0 0 0 ) : 8 : 4 ) ; W r i t e l n ( Log10 ( 1 ) : 8 : 4 ) ; W r i t e l n ( Log10 ( 0 . 1 ) : 8 : 4 ) ; W r i t e l n ( Log10 ( 0 . 0 1 ) : 8 : 4 ) ; W r i t e l n ( Log10 ( 0 . 0 0 1 ) : 8 : 4 ) ; end .

log2 Declaration: Function log2(x :

float) :

float;

Description: Log2 returns the 2-base logarithm of X. Errors: If x is less than or equal to 0 an ’invalid fpu operation’ error will occur. See also: ldexp (273), lnxp1 (273),log10 (274),logn (275) Listing: mathex/ex22.pp Program Example22 ; { Program t o demonstrate t h e l o g 2 f u n c t i o n . } Uses math ; begin

274

CHAPTER 13. THE MATH UNIT

W r i t e l n ( Log2 ( 2 ) : 8 : 4 ) ; W r i t e l n ( Log2 ( 4 ) : 8 : 4 ) ; W r i t e l n ( Log2 ( 8 ) : 8 : 4 ) ; W r i t e l n ( Log2 ( 1 ) : 8 : 4 ) ; W r i t e l n ( Log2 ( 0 . 5 ) : 8 : 4 ) ; W r i t e l n ( Log2 ( 0 . 2 5 ) : 8 : 4 ) ; W r i t e l n ( Log2 ( 0 . 1 2 5 ) : 8 : 4 ) ; end .

logn Declaration: Function logn(n,x :

float) :

float;

Description: Logn returns the n-base logarithm of X. Errors: If x is less than or equal to 0 an ’invalid fpu operation’ error will occur. See also: ldexp (273), lnxp1 (273),log10 (274),log2 (274) Listing: mathex/ex23.pp Program Example23 ; { Program t o demonstrate t h e l o g n f u n c t i o n . } Uses math ; begin W r i t e l n ( Logn ( 3 , 4 ) : 8 : 4 ) ; W r i t e l n ( Logn ( 2 , 4 ) : 8 : 4 ) ; W r i t e l n ( Logn ( 6 , 9 ) : 8 : 4 ) ; W r i t e l n ( Logn ( exp ( 1 ) , exp ( 1 ) ) : 8 : 4 ) ; W r i t e l n ( Logn ( 0 . 5 , 1 ) : 8 : 4 ) ; W r i t e l n ( Logn ( 0 . 2 5 , 3 ) : 8 : 4 ) ; W r i t e l n ( Logn ( 0 . 1 2 5 , 5 ) : 8 : 4 ) ; end .

max Declaration: Function max(Int1,Int2:Cardinal):Cardinal; Function max(Int1,Int2:Integer):Integer; Description: Max returns the maximum of Int1 and Int2. Errors: None. See also: min (279), maxIntValue (276), maxvalue (276) Listing: mathex/ex24.pp Program Example24 ; { Program t o demonstrate t h e max f u n c t i o n . } Uses math ; Var

275

CHAPTER 13. THE MATH UNIT

A,B : Cardinal ; begin A: = 1 ; b : = 2 ; w r i t e l n ( max ( a , b ) ) ; end .

maxIntValue Declaration: function MaxIntValue(const Data:

array of Integer):

Integer;

Description: MaxIntValue returns the largest integer out of the Data array. This function is provided for Delphicompatibility, use the maxvalue (276) function instead. Errors: None. See also: maxvalue (276), minvalue (280), minIntValue (279) Listing: mathex/ex25.pp Program Example25 ; { Program t o demonstrate t h e MaxIntValue f u n c t i o n . } { Make sore i n t e g e r i s 3 2 b i t } { $mode o b j f p c } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of I n t e g e r ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = Random( I )−Random( 1 0 0 ) ; W r i t e l n ( MaxIntValue ( ExArray ) ) ; end .

maxvalue Declaration: Function maxvalue(const data data : array of Integer) : PFloat; Const N : Integer) : PInteger; Const N : Integer)

: array of float) : float; Function maxvalue(const Integer; Function maxvalue(const data : float; Function maxvalue(const data : : Integer;

Description: Maxvalue returns the largest value in the data array with integer or float values. The return value has the same type as the elements of the array. The third and fourth forms accept a pointer to an array of N integer or float values. Errors: None. 276

CHAPTER 13. THE MATH UNIT

See also: maxIntValue (276), minvalue (280), minIntValue (279) Listing: mathex/ex26.pp Program Example26 ; { Program t o demonstrate t h e MaxValue f u n c t i o n . } { Make sore i n t e g e r i s 3 2 b i t } { $mode o b j f p c } Uses math ; Type T E x F l o a t A r r a y = Array [ 1 . . 1 0 0 ] of F l o a t ; T E x I n t A r r a y = Array [ 1 . . 1 0 0 ] of I n t e g e r ; Var I : Integer ; ExFloatArray : TExFloatArray ; ExIntArray : TExIntArray ; AFLoatArray : PFLoat ; AIntArray : PInteger ; begin Randomize ; A F l o a t A r r a y : = @ExFloatArray [ 1 ] ; A I n t A r r a y : = @ExIntArray [ 1 ] ; f o r I : = 1 to 1 0 0 do E x F l o a t A r r a y [ i ] : = ( Random−Random) ∗ 1 0 0 ; f o r I : = 1 to 1 0 0 do E x I n t A r r a y [ i ] : = Random( I )−Random( 1 0 0 ) ; W r i t e l n ( ’ Max F l o a t : ’ , MaxValue ( E x F l o a t A r r a y ) : 8 : 4 ) ; W r i t e l n ( ’ Max F l o a t ( b ) : ’ , MaxValue ( A F l o a t A r r a y , 1 0 0 ) : 8 : 4 ) ; W r i t e l n ( ’ Max I n t e g e r : ’ , MaxValue ( E x I n t A r r a y ) : 8 ) ; W r i t e l n ( ’ Max I n t e g e r ( b ) : ’ , MaxValue ( A I n t A r r a y , 1 0 0 ) : 8 ) ; end .

mean Declaration: Function mean(const data : array of float) : data : PFloat; Const N : longint) : float; Description: Mean returns the average value of data. The second form accepts a pointer to an array of N values. Errors: None. See also: meanandstddev (278), momentskewkurtosis (281), sum (288) Listing: mathex/ex27.pp Program Example27 ; { Program t o demonstrate t h e Mean f u n c t i o n . } Uses math ;

277

float; Function mean(const

CHAPTER 13. THE MATH UNIT

Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; W r i t e l n ( ’ Max : ’ , MaxValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Min : ’ , MinValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Mean : ’ ,Mean ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Mean ( b ) : ’ ,Mean ( @ExArray [ 1 ] , 1 0 0 ) : 8 : 4 ) ; end .

meanandstddev Declaration: Procedure meanandstddev(const data : array of float; var mean,stddev : float); procedure meanandstddev(const data : PFloat; Const N : Longint;var mean,stddev : float); Description: meanandstddev calculates the mean and standard deviation of data and returns the result in mean and stddev, respectively. Stddev is zero if there is only one value. The second form accepts a pointer to an array of N values. Errors: None. See also: mean (277),sum (288), sumofsquares (288), momentskewkurtosis (281) Listing: mathex/ex28.pp Program Example28 ; { Program t o demonstrate t h e Meanandstddev f u n c t i o n . } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of Extended ; Var I : Integer ; ExArray : TExArray ; Mean , stddev : Extended ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; MeanAndStdDev ( ExArray , Mean , StdDev ) ; W r i t e l n ( ’ Mean : ’ ,Mean : 8 : 4 ) ; W r i t e l n ( ’ StdDev : ’ , StdDev : 8 : 4 ) ; MeanAndStdDev ( @ExArray [ 1 ] , 1 0 0 , Mean , StdDev ) ; W r i t e l n ( ’ Mean ( b ) : ’ ,Mean : 8 : 4 ) ; W r i t e l n ( ’ StdDev ( b ) : ’ , StdDev : 8 : 4 ) ;

278

CHAPTER 13. THE MATH UNIT

end .

min Declaration: Function min(Int1,Int2:Cardinal):Cardinal; Function min(Int1,Int2:Integer):Integer; Description: min returns the smallest value of Int1 and Int2; Errors: None. See also: max (275) Listing: mathex/ex29.pp Program Example29 ; { Program t o demonstrate t h e min f u n c t i o n . } Uses math ; Var A,B : Cardinal ; begin A: = 1 ; b : = 2 ; w r i t e l n ( min ( a , b ) ) ; end .

minIntValue Declaration: Function minIntValue(const Data:

array of Integer):

Description: MinIntvalue returns the smallest value in the Data array. This function is provided for Delphicompatibility, use minvalue instead. Errors: None See also: minvalue (280), maxIntValue (276), maxvalue (276) Listing: mathex/ex30.pp Program Example30 ; { Program t o demonstrate t h e M i n I n t V a l u e f u n c t i o n . } { Make sore i n t e g e r i s 3 2 b i t } { $mode o b j f p c } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of I n t e g e r ; Var I : Integer ; ExArray : TExArray ;

279

Integer;

CHAPTER 13. THE MATH UNIT

begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = Random( I )−Random( 1 0 0 ) ; W r i t e l n ( M i n I n t V a l u e ( ExArray ) ) ; end .

minvalue Declaration: Function minvalue(const data data : array of Integer) : PFloat; Const N : Integer) : PInteger; Const N : Integer)

: array of float) : float; Function minvalue(const Integer; Function minvalue(const data : float; Function minvalue(const data : : Integer;

Description: Minvalue returns the smallest value in the data array with integer or float values. The return value has the same type as the elements of the array. The third and fourth forms accept a pointer to an array of N integer or float values. Errors: None. See also: maxIntValue (276), maxvalue (276), minIntValue (279) Listing: mathex/ex31.pp Program Example26 ; { Program t o demonstrate t h e MinValue f u n c t i o n . } { Make sore i n t e g e r i s 3 2 b i t } { $mode o b j f p c } Uses math ; Type T E x F l o a t A r r a y = Array [ 1 . . 1 0 0 ] of F l o a t ; T E x I n t A r r a y = Array [ 1 . . 1 0 0 ] of I n t e g e r ; Var I : Integer ; ExFloatArray : TExFloatArray ; AFloatArray : PFloat ; ExIntArray : TExIntArray ; AintArray : PInteger ; begin Randomize ; A F l o a t A r r a y : = @ExFloatArray [ 0 ] ; A I n t A r r a y : = @ExIntArray [ 0 ] ; f o r I : = 1 to 1 0 0 do E x F l o a t A r r a y [ i ] : = ( Random−Random) ∗ 1 0 0 ; f o r I : = 1 to 1 0 0 do E x I n t A r r a y [ i ] : = Random( I )−Random( 1 0 0 ) ; W r i t e l n ( ’ Min F l o a t : ’ , MinValue ( E x F l o a t A r r a y ) : 8 : 4 ) ; W r i t e l n ( ’ Min F l o a t ( b ) : ’ , MinValue ( A F l o a t A r r a y , 1 0 0 ) : 8 : 4 ) ; W r i t e l n ( ’ Min I n t e g e r : ’ , MinValue ( E x I n t A r r a y ) : 8 ) ; W r i t e l n ( ’ Min I n t e g e r ( b ) : ’ , MinValue ( A i n t A r r a y , 1 0 0 ) : 8 ) ;

280

CHAPTER 13. THE MATH UNIT

end .

momentskewkurtosis

Declaration: procedure momentskewkurtosis(const data : array of float; var m1,m2,m3,m4,skew,kurtosi : float); procedure momentskewkurtosis(const data : PFloat; Const N : Integer; var m1,m2,m3,m4,skew,kurtosis : float); Description: momentskewkurtosis calculates the 4 first moments of the distribution of valuesin data and returns them in m1,m2,m3 and m4, as well as the skew and kurtosis. Errors: None. See also: mean (277), meanandstddev (278) Listing: mathex/ex32.pp Program Example32 ; { Program t o demonstrate t h e momentskewkurtosis f u n c t i o n . } Uses math ; Var D i s t A r r a y : Array [ 1 . . 1 0 0 0 ] of f l o a t ; I : longint ; m1, m2, m3, m4, skew , k u r t o s i s : f l o a t ; begin randomize ; f o r I : = 1 to 1 0 0 0 do d i s t a r r a y [ i ] : = random ; momentskewkurtosis ( D i s t A r r a y , m1, m2, m3, m4, skew , k u r t o s i s ) ; Writeln Writeln Writeln Writeln Writeln Writeln end .

( ( ( ( ( (

’ 1 s t moment ’ 2nd moment ’ 3 r d moment ’ 4 t h moment ’ Skew ’ kurtosis

: : : : : :

’ ’ ’ ’ ’ ’

,m1 : 8 : 6 ) ; ,m2 : 8 : 6 ) ; ,m3 : 8 : 6 ) ; ,m4 : 8 : 6 ) ; , skew : 8 : 6 ) ; , kurtosis :8:6);

norm Declaration: Function norm(const data : array of float) : data : PFloat; Const N : Integer) : float;

float; Function norm(const

Description: Norm calculates the Euclidian norm of the array of data. This equals sqrt(sumofsquares(data)). The second form accepts a pointer to an array of N values. Errors: None. See also: sumofsquares (288) Listing: mathex/ex33.pp 281

CHAPTER 13. THE MATH UNIT

Program Example33 ; { Program t o demonstrate t h e norm f u n c t i o n . } Uses math ; Type TVector = Array [ 1 . . 1 0 ] of F l o a t ; Var AVector : T v e c t o r ; I : longint ; begin f o r I : = 1 to 1 0 do A v e c t o r [ i ] : = Random ; W r i t e l n ( Norm ( AVector ) ) ; end .

popnstddev Declaration: Function popnstddev(const data : array of float) : float; Function popnstddev(const data : PFloat; Const N : Integer) : float; Description: Popnstddev returns the square root of the population variance of the values in the Data array. It returns zero if there is only one value. The second form of this function accepts a pointer to an array of N values. Errors: None. See also: popnvariance (283), mean (277), meanandstddev (278), stddev (287), momentskewkurtosis (281) Listing: mathex/ex35.pp Program Example35 ; { Program t o demonstrate t h e PopnStdDev f u n c t i o n . } Uses Math ; Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; W r i t e l n ( ’ Max : ’ , MaxValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Min : ’ , MinValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Pop . stddev . : ’ , PopnStdDev ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Pop . stddev . ( b ) : ’ , PopnStdDev ( @ExArray [ 1 ] , 1 0 0 ) : 8 : 4 ) ; end .

282

CHAPTER 13. THE MATH UNIT

popnvariance Declaration: Function popnvariance(const data : array of float) : float; Function popnvariance(const data : PFloat; Const N : Integer) : float; Description: Popnvariance returns the square root of the population variance of the values in the Data array. It returns zero if there is only one value. The second form of this function accepts a pointer to an array of N values. Errors: None. See also: popnstddev (282), mean (277), meanandstddev (278), stddev (287), momentskewkurtosis (281) Listing: mathex/ex36.pp Program Example36 ; { Program t o demonstrate t h e PopnVariance f u n c t i o n . } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; W r i t e l n ( ’ Max : ’ , MaxValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Min : ’ , MinValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Pop . v a r . : ’ , PopnVariance ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Pop . v a r . ( b ) : ’ , PopnVariance ( @ExArray [ 1 ] , 1 0 0 ) : 8 : 4 ) ; end .

power Declaration: Function power(base,exponent :

float) :

float;

Description: power raises base to the power power. This is equivalent to exp(power*ln(base)). Therefore base should be non-negative. Errors: None. See also: intpower (272) Listing: mathex/ex34.pp Program Example34 ; { Program t o demonstrate t h e power f u n c t i o n . } Uses Math ;

283

CHAPTER 13. THE MATH UNIT

procedure dopower ( x , y : f l o a t ) ; begin w r i t e l n ( x : 8 : 6 , ’ ^ ’ , y : 8 : 6 , ’ = ’ , power ( x , y ) : 8 : 6 ) end ; begin dopower ( 2 , 2 ) ; dopower ( 2 , − 2 ) ; dopower ( 2 , 0 . 0 ) ; end .

radtocycle Declaration: Function radtocycle(rad :

float) :

float;

Description: Radtocycle converts its argument rad (an angle expressed in radians) to an angle in cycles. (1 cycle equals 2 pi radians) Errors: None. See also: degtograd (269), degtorad (269), radtodeg (284), radtograd (285), cycletorad (268) Listing: mathex/ex37.pp Program Example37 ; { Program t o demonstrate t h e r a d t o c y c l e f u n c t i o n . } Uses math ; begin w r i t e l n ( r a d t o c y c l e (2∗ p i ) : 8 : 6 ) ; writeln ( radtocycle ( pi ) : 8 : 6 ) ; writeln ( radtocycle ( pi / 2 ) : 8 : 6 ) ; end .

radtodeg Declaration: Function radtodeg(rad :

float) :

float;

Description: Radtodeg converts its argument rad (an angle expressed in radians) to an angle in degrees. (180 degrees equals pi radians) Errors: None. See also: degtograd (269), degtorad (269), radtocycle (284), radtograd (285), cycletorad (268) Listing: mathex/ex38.pp Program Example38 ; { Program t o demonstrate t h e radtodeg f u n c t i o n . } Uses math ;

284

CHAPTER 13. THE MATH UNIT

begin w r i t e l n ( radtodeg (2∗ p i ) : 8 : 6 ) ; w r i t e l n ( radtodeg ( p i ) : 8 : 6 ) ; w r i t e l n ( radtodeg ( p i / 2 ) : 8 : 6 ) ; end .

radtograd Declaration: Function radtograd(rad :

float) :

float;

Description: Radtodeg converts its argument rad (an angle expressed in radians) to an angle in grads. (200 grads equals pi radians) Errors: None. See also: degtograd (269), degtorad (269), radtocycle (284), radtodeg (284), cycletorad (268) Listing: mathex/ex39.pp Program Example39 ; { Program t o demonstrate t h e r a d t o g r a d f u n c t i o n . } Uses math ; begin w r i t e l n ( r a d t o g r a d (2∗ p i ) : 8 : 6 ) ; writeln ( radtograd ( pi ) : 8 : 6 ) ; writeln ( radtograd ( pi / 2 ) : 8 : 6 ) ; end .

randg Declaration: Function randg(mean,stddev :

float) :

float;

Description: randg returns a random number which - when produced in large quantities - has a Gaussian distribution with mean mean and standarddeviation stddev. Errors: None. See also: mean (277), stddev (287), meanandstddev (278) Listing: mathex/ex40.pp Program Example40 ; { Program t o demonstrate t h e randg f u n c t i o n . } Uses Math ; Type TExArray = Array [ 1 . . 1 0 0 0 0 ] of F l o a t ; Var I : Integer ;

285

CHAPTER 13. THE MATH UNIT

ExArray : TExArray ; Mean , stddev : F l o a t ; begin Randomize ; f o r I : = 1 to 1 0 0 0 0 do ExArray [ i ] : = Randg ( 1 , 0 . 2 ) ; MeanAndStdDev ( ExArray , Mean , StdDev ) ; W r i t e l n ( ’ Mean : ’ ,Mean : 8 : 4 ) ; W r i t e l n ( ’ StdDev : ’ , StdDev : 8 : 4 ) ; end .

sincos Declaration: Procedure sincos(theta :

float;var sinus,cosinus :

float);

Description: Sincos calculates the sine and cosine of the angle theta, and returns the result in sinus and cosinus. On Intel hardware, This calculation will be faster than making 2 calls to clculatet he sine and cosine separately. Errors: None. See also: arcsin (265), arccos (264). Listing: mathex/ex41.pp Program Example41 ; { Program t o demonstrate t h e s i n c o s f u n c t i o n . } Uses math ; Procedure dosincos ( Angle : F l o a t ) ; Var Sine , Cosine : F l o a t ; begin s i n c o s ( angle , sine , c o s i n e ) ; Write ( ’ Angle : ’ , Angle : 8 : 6 ) ; Write ( ’ Sine : ’ , s i n e : 8 : 6 ) ; Write ( ’ Cosine : ’ , c o s i n e : 8 : 6 ) ; end ; begin dosincos ( p i ) ; dosincos ( p i / 2 ) ; dosincos ( p i / 3 ) ; dosincos ( p i / 4 ) ; dosincos ( p i / 6 ) ; end .

sinh Declaration: Function sinh(x :

float) :

float; 286

CHAPTER 13. THE MATH UNIT

Description: Sinh returns the hyperbolic sine of its argument x. Errors: See also: cosh (268), arsinh (266), tanh (290), artanh (267) Listing: mathex/ex42.pp Program Example42 ; { Program t o demonstrate t h e s i n h f u n c t i o n . } Uses math ; begin writeln ( sinh ( 0 ) ) ; writeln ( sinh ( 1 ) ) ; writeln ( sinh ( −1)); end .

stddev Declaration: Function stddev(const data : array of float) : data : PFloat; Const N : Integer) : float;

float; Function stddev(const

Description: Stddev returns the standard deviation of the values in Data. It returns zero if there is only one value. The second form of the function accepts a pointer to an array of N values. Errors: None. See also: mean (277), meanandstddev (278), variance (291), totalvariance (291) Listing: mathex/ex43.pp Program Example40 ; { Program t o demonstrate t h e stddev f u n c t i o n . } Uses Math ; Type TExArray = Array [ 1 . . 1 0 0 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 0 0 do ExArray [ i ] : = Randg ( 1 , 0 . 2 ) ; W r i t e l n ( ’ StdDev : ’ , StdDev ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ StdDev ( b ) : ’ , StdDev ( @ExArray [ 0 ] , 1 0 0 0 0 ) : 8 : 4 ) ; end .

287

CHAPTER 13. THE MATH UNIT

sum Declaration: Function sum(const data : array of float) : data : PFloat; Const N : Integer) : float;

float; Function sum(const

Description: Sum returns the sum of the values in the data array. The second form of the function accepts a pointer to an array of N values. Errors: None. See also: sumofsquares (288), sumsandsquares (289), totalvariance (291) , variance (291) Listing: mathex/ex44.pp Program Example44 ; { Program t o demonstrate t h e Sum f u n c t i o n . } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; W r i t e l n ( ’ Max : ’ , MaxValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Min : ’ , MinValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’Sum : ’ ,Sum( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’Sum ( b ) : ’ ,Sum( @ExArray [ 1 ] , 1 0 0 ) : 8 : 4 ) ; end .

sumofsquares Declaration: Function sumofsquares(const data : array of float) : float; Function sumofsquares(const data : PFloat; Const N : Integer) : float; Description: Sumofsquares returns the sum of the squares of the values in the data array. The second form of the function accepts a pointer to an array of N values. Errors: None. See also: sum (288), sumsandsquares (289), totalvariance (291) , variance (291) Listing: mathex/ex45.pp Program Example45 ; { Program t o demonstrate t h e SumOfSquares f u n c t i o n . } Uses math ;

288

CHAPTER 13. THE MATH UNIT

Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; W r i t e l n ( ’ Max : ’ , MaxValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Min : ’ , MinValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’Sum squares : ’ , SumOfSquares ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’Sum squares ( b ) : ’ , SumOfSquares ( @ExArray [ 1 ] , 1 0 0 ) : 8 : 4 ) ; end .

sumsandsquares Declaration: Procedure sumsandsquares(const data : array of float; var sum,sumofsquares : float); Procedure sumsandsquares(const data : PFloat; Const N : Integer; var sum,sumofsquares : float); Description: sumsandsquares calculates the sum of the values and the sum of the squares of the values in the data array and returns the results in sum and sumofsquares. The second form of the function accepts a pointer to an array of N values. Errors: None. See also: sum (288), sumofsquares (288), totalvariance (291) , variance (291) Listing: mathex/ex46.pp Program Example45 ; { Program t o demonstrate t h e SumOfSquares f u n c t i o n . } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; s , ss : f l o a t ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; W r i t e l n ( ’ Max : ’ , MaxValue ( ExArray ) : 8 : 4 ) ; W r i t e l n ( ’ Min : ’ , MinValue ( ExArray ) : 8 : 4 ) ; SumsAndSquares ( ExArray , S , SS ) ; W r i t e l n ( ’Sum : ’ ,S : 8 : 4 ) ; W r i t e l n ( ’Sum squares : ’ ,SS : 8 : 4 ) ; SumsAndSquares ( @ExArray [ 1 ] , 1 0 0 , S , SS ) ;

289

CHAPTER 13. THE MATH UNIT

W r i t e l n ( ’Sum ( b ) : ’ ,S : 8 : 4 ) ; W r i t e l n ( ’Sum squares ( b ) : ’ ,SS : 8 : 4 ) ; end .

tan Declaration: Function tan(x :

float) :

float;

Description: Tan returns the tangent of x. Errors: If x (normalized) is pi/2 or 3pi/2 then an overflow will occur. See also: tanh (290), arcsin (265), sincos (286), arccos (264) Listing: mathex/ex47.pp Program Example47 ; { Program t o demonstrate t h e Tan f u n c t i o n . } Uses math ; Procedure DoTan ( Angle : F l o a t ) ; begin Write ( ’ Angle : ’ , RadToDeg ( Angle ) : 8 : 6 ) ; W r i t e l n ( ’ Tangent : ’ , Tan ( Angle ) : 8 : 6 ) ; end ; begin DoTan ( 0 ) ; DoTan ( Pi ) ; DoTan ( Pi / 3 ) ; DoTAn ( Pi / 4 ) ; DoTan ( Pi / 6 ) ; end .

tanh Declaration: Function tanh(x :

float) :

float;

Description: Tanh returns the hyperbolic tangent of x. Errors: None. See also: arcsin (265), sincos (286), arccos (264) Listing: mathex/ex48.pp Program Example48 ; { Program t o demonstrate t h e Tanh f u n c t i o n . } Uses math ; begin

290

CHAPTER 13. THE MATH UNIT

w r i t e l n ( tanh ( 0 ) ) ; w r i t e l n ( tanh ( 1 ) ) ; w r i t e l n ( tanh ( − 1 ) ) ; end .

totalvariance Declaration: Function totalvariance(const data : array of float) : float; Function totalvariance(const data : PFloat; Const N : Integer) : float; Description: TotalVariance returns the total variance of the values in the data array. It returns zero if there is only one value. The second form of the function accepts a pointer to an array of N values. Errors: None. See also: variance (291), stddev (287), mean (277) Listing: mathex/ex49.pp Program Example49 ; { Program t o demonstrate t h e T o t a l V a r i a n c e f u n c t i o n . } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; TV : f l o a t ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; TV: = T o t a l V a r i a n c e ( ExArray ) ; Writeln ( ’ Total variance : ’ ,TV : 8 : 4 ) ; TV: = T o t a l V a r i a n c e ( @ExArray [ 1 ] , 1 0 0 ) ; W r i t e l n ( ’ T o t a l Variance ( b ) : ’ ,TV : 8 : 4 ) ; end .

variance Declaration: Function variance(const data : array of float) : data : PFloat; Const N : Integer) : float;

float; Function variance(const

Description: Variance returns the variance of the values in the data array. It returns zero if there is only one value. The second form of the function accepts a pointer to an array of N values. Errors: None.

291

CHAPTER 13. THE MATH UNIT

See also: totalvariance (291), stddev (287), mean (277) Listing: mathex/ex50.pp Program Example50 ; { Program t o demonstrate t h e Variance f u n c t i o n . } Uses math ; Type TExArray = Array [ 1 . . 1 0 0 ] of F l o a t ; Var I : Integer ; ExArray : TExArray ; V : float ; begin Randomize ; f o r I : = 1 to 1 0 0 do ExArray [ i ] : = ( Random−Random) ∗ 1 0 0 ; V: = Variance ( ExArray ) ; W r i t e l n ( ’ Variance : ’ ,V : 8 : 4 ) ; V: = Variance ( @ExArray [ 1 ] , 1 0 0 ) ; W r i t e l n ( ’ Variance ( b ) : ’ ,V : 8 : 4 ) ; end .

292

Chapter 14

The MMX unit This chapter describes the MMX unit. This unit allows you to use the MMX capabilities of the Free Pascal compiler. It was written by Florian Klämpfl for the I386 processor. It should work on all platforms that use the Intel processor.

14.1

Variables, Types and constants

The following types are defined in the MMX unit: tmmxshortint = array[0..7] of shortint; tmmxbyte = array[0..7] of byte; tmmxword = array[0..3] of word; tmmxinteger = array[0..3] of integer; tmmxfixed = array[0..3] of fixed16; tmmxlongint = array[0..1] of longint; tmmxcardinal = array[0..1] of cardinal; { for the AMD 3D } tmmxsingle = array[0..1] of single; And the following pointers to the above types: pmmxshortint = ^tmmxshortint; pmmxbyte = ^tmmxbyte; pmmxword = ^tmmxword; pmmxinteger = ^tmmxinteger; pmmxfixed = ^tmmxfixed; pmmxlongint = ^tmmxlongint; pmmxcardinal = ^tmmxcardinal; { for the AMD 3D } pmmxsingle = ^tmmxsingle; The following initialized constants allow you to determine if the computer has MMX extensions. They are set correctly in the unit’s initialization code. is_mmx_cpu : boolean = false; is_amd_3d_cpu : boolean = false;

293

CHAPTER 14. THE MMX UNIT

14.2

Functions and Procedures

Emms Declaration: Procedure Emms ; Description: Emms sets all floating point registers to empty. This procedure must be called after you have used any MMX instructions, if you want to use floating point arithmetic. If you just want to move floating point data around, it isn’t necessary to call this function, the compiler doesn’t use the FPU registers when moving data. Only when doing calculations, you should use this function. Errors: None. See also: Programmers guide Example:: Program MMXDemo; uses mmx; var d1 : double; a : array[0..10000] of double; i : longint; begin d1:=1.0; {$mmx+} { floating point data is used, but we do _no_ arithmetic } for i:=0 to 10000 do a[i]:=d2; { this is done with 64 bit moves } {$mmx-} emms; { clear fpu } { now we can do floating point arithmetic again } end.

294

Chapter 15

The MOUSE unit The Mouse unit implements a platform independent mouse handling interface. It is implemented identically on all platforms supported by Free Pascal and can be enhanced with custom drivers, should this be needed. It is intended to be used only in text-based screens, for instance in conjunction with the keyboard and video unit. No support for graphical screens is implemented, and there are (currently) no plans to implement this.

15.1

Constants, Types and Variables

Constants The following constants can be used when mouse drivers need to report errors: const { We have an errorcode base of 1030 } errMouseBase = 1030; errMouseInitError = errMouseBase + 0; errMouseNotImplemented = errMouseBase + 1; The following constants describe which action a mouse event describes const MouseActionDown = $0001; MouseActionUp = $0002; MouseActionMove = $0004;

{ Mouse down event } { Mouse up event } { Mouse move event }

The following constants describe the used buttons in a mouse event: MouseLeftButton = $01; MouseRightButton = $02; MouseMiddleButton = $04;

{ Left mouse button } { Right mouse button } { Middle mouse button }

The mouse unit has a mechanism to buffer mouse events. The following constant defines the size of the event buffer: MouseEventBufSize = 16;

295

CHAPTER 15. THE MOUSE UNIT

Types The TMouseEvent is the central type of the mouse unit, it is used to describe the mouse events: PMouseEvent=^TMouseEvent; TMouseEvent=packed record { 8 bytes } buttons : word; x,y : word; Action : word; end; The Buttons field describes which buttons were down when the event occurred. The x,y fields describe where the event occurred on the screen. The Action describes what action was going on when the event occurred. The Buttons and Action field can be examined using the above constants. The following record is used to implement a mouse driver in the SetMouseDriver (301) function: TMouseDriver = Record UseDefaultQueue : Boolean; InitDriver : Procedure; DoneDriver : Procedure; DetectMouse : Function : Byte; ShowMouse : Procedure; HideMouse : Procedure; GetMouseX : Function : Word; GetMouseY : Function : Word; GetMouseButtons : Function : Word; SetMouseXY : procedure (x,y:word); GetMouseEvent : procedure (var MouseEvent:TMouseEvent); PollMouseEvent : function (var MouseEvent: TMouseEvent):boolean; PutMouseEvent : procedure (Const MouseEvent:TMouseEvent); end; Its fields will be explained in the section on writing a custom driver.

Variables The following variables are used to keep the current position and state of the mouse. MouseIntFlag : Byte; MouseButtons : Byte; MouseWhereX, MouseWhereY : Word;

15.2

{ Mouse in int flag } { Mouse button state } { Mouse position }

Functions and procedures

DetectMouse Declaration: Function DetectMouse:byte; Description: DetectMouse detects whether a mouse is attached to the system or not. If there is no mouse, then zero is returned. If a mouse is attached, then the number of mouse buttons is returned. This function should be called after the mouse driver was initialized. 296

CHAPTER 15. THE MOUSE UNIT

Errors: None. See also: InitMouse (309),DoneMouse (297), Listing: mouseex/ex1.pp Program Example1 ; { Program t o demonstrate t h e DetectMouse f u n c t i o n . } Uses mouse ; Var B u t t o n s : Byte ; begin InitMouse ; B u t t o n s : = DetectMouse ; I f B u t t o n s =0 then W r i t e l n ( ’ No mouse p r e s e n t . ’ ) else W r i t e l n ( ’ Found mouse w i t h ’ , Buttons , ’ b u t t o n s . ’ ) ; DoneMouse ; end .

DoneMouse Declaration: Procedure DoneMouse; Description: DoneMouse De-initializes the mouse driver. It cleans up any memory allocated when the mouse was initialized, or removes possible mouse hooks from memory. The mouse functions will not work after DoneMouse was called. If DoneMouse is called a second time, it will exit at once. InitMouse should be called before DoneMouse can be called again. Errors: None. See also: DetectMouse (296), InitMouse (309) For an example, see most other mouse functions.

GetMouseButtons Declaration: Function GetMouseButtons:word; Description: GetMouseButtons returns the current button state of the mouse, i.e. it returns a or-ed combination of the following constants: MouseLeftButtonWhen the left mouse button is held down. MouseRightButtonWhen the right mouse button is held down. MouseMiddleButtonWhen the middle mouse button is held down. Errors: None. See also: GetMouseEvent (298), GetMouseX (298), GetMouseY (299) Listing: mouseex/ex2.pp 297

CHAPTER 15. THE MOUSE UNIT

Program Example2 ; { Program t o demonstrate t h e GetMouseButtons f u n c t i o n . } Uses mouse ; begin InitMouse ; W r i t e l n ( ’ Press r i g h t mouse b u t t o n t o e x i t program ’ ) ; While ( GetMouseButtons MouseRightButton ) do ; DoneMouse ; end .

GetMouseDriver Declaration: Procedure GetMouseDriver(Var Driver :

TMouseDriver);

Description: GetMouseDriver returns the currently set mouse driver. It can be used to retrieve the current mouse driver, and override certain callbacks. A more detailed explanation about getting and setting mouse drivers can be found in section 15.3, page 302. Errors: None. See also: SetMouseDriver (301) For an example, see the section on writing a custom mouse driver, section 15.3, page 302

GetMouseEvent Declaration: Procedure GetMouseEvent(var MouseEvent:TMouseEvent); Description: GetMouseEvent returns the next mouse event (a movement, button press or button release), and waits for one if none is available in the queue. Some mouse drivers can implement a mouse event queue which can hold multiple events till they are fetched.; Others don’t, and in that case, a one-event queue is implemented for use with PollMouseEvent (300). Errors: None. See also: GetMouseButtons (297), GetMouseX (298), GetMouseY (299)

GetMouseX Declaration: Function GetMouseX:word; Description: GetMouseX returns the current X position of the mouse. X is measured in characters, starting at 0 for the left side of the screen. Errors: None. See also: GetMouseButtons (297),GetMouseEvent (298), GetMouseY (299) Listing: mouseex/ex4.pp 298

CHAPTER 15. THE MOUSE UNIT

Program Example4 ; { Program t o demonstrate t h e GetMouseX , GetMouseY f u n c t i o n s . } Uses mouse ; Var X , Y : Word ; begin InitMouse ; W r i t e l n ( ’ Move mouse c u r s o r t o square 1 0 , 1 0 t o end ’ ) ; Repeat X: = GetMouseX ; Y: = GetMouseY ; W r i t e l n ( ’ X , Y = ( ’ ,X , ’ , ’ ,Y , ’ ) ’ ) ; U n t i l ( X= 9 ) and ( Y= 9 ) ; DoneMouse ; end .

GetMouseY Declaration: Function GetMouseY:word; Description: GetMouseY returns the current Y position of the mouse. Y is measured in characters, starting at 0 for the top of the screen. Errors: None. See also: GetMouseButtons (297),GetMouseEvent (298), GetMouseX (298) For an example, see GetMouseX (298)

HideMouse Declaration: Procedure HideMouse; Description: HideMouse hides the mouse cursor. This may or may not be implemented on all systems, and depends on the driver. Errors: None. See also: ShowMouse (316) Listing: mouseex/ex5.pp Program Example5 ; { Program t o demonstrate t h e HideMouse f u n c t i o n . } Uses mouse ; Var Event : TMouseEvent ; V i s i b l e : Boolean ;

299

CHAPTER 15. THE MOUSE UNIT

begin InitMouse ; ShowMouse ; V i s i b l e : = True ; W r i t e l n ( ’ Press l e f t mouse b u t t o n t o h i d e / show , r i g h t b u t t o n q u i t s ’ ) ; Repeat GetMouseEvent ( Event ) ; With Event do I f ( B u t t o n s = MouseLeftbutton ) and ( A c t i o n =MouseActionDown ) then begin I f V i s i b l e then HideMouse else ShowMouse ; V i s i b l e : = Not V i s i b l e ; end ; U n t i l ( Event . B u t t o n s =MouseRightButton ) and ( Event . A c t i o n =MouseActionDown ) ; DoneMouse ; end .

InitMouse Declaration: Procedure InitMouse; Description: InitMouse Initializes the mouse driver. This will allocate any data structures needed for the mouse to function. All mouse functions can be used after a call to InitMouse. A call to InitMouse must always be followed by a call to DoneMouse (297) at program exit. Failing to do so may leave the mouse in an unusable state, or may result in memory leaks. Errors: None. See also: DoneMouse (297), DetectMouse (296) For an example, see most other functions.

PollMouseEvent Declaration: Function PollMouseEvent(var MouseEvent:

TMouseEvent):boolean;

Description: PollMouseEvent checks whether a mouse event is available, and returns it in MouseEvent if one is found. The function result is True in that case. If no mouse event is pending, the function result is False, and the contents of MouseEvent is undefined. Note that after a call to PollMouseEvent, the event should still be removed from the mouse event queue with a call to GetMouseEvent. Errors: None. See also: GetMouseEvent (298), PutMouseEvent (300)

PutMouseEvent Declaration: Procedure PutMouseEvent(const MouseEvent:

300

TMouseEvent);

CHAPTER 15. THE MOUSE UNIT

Description: PutMouseEvent adds MouseEvent to the input queue. The next call to GetMouseEvent (298) or PollMouseEvent will then return MouseEvent. Please note that depending on the implementation the mouse event queue can hold only one value. Errors: None. See also: GetMouseEvent (298), PollMouseEvent (300)

SetMouseDriver Declaration: Procedure SetMouseDriver(Const Driver :

TMouseDriver);

Description: SetMouseDriver sets the mouse driver to Driver. This function should be called before InitMouse (309) is called, or after DoneMouse is called. If it is called after the mouse has been initialized, it does nothing. For more information on setting the mouse driver, section 15.3, page 302. Errors: See also: InitMouse (309), DoneMouse (297), GetMouseDriver (298) For an example, see section 15.3, page 302

SetMouseXY Declaration: Procedure SetMouseXY(x,y:word); Description: SetMouseXY places the mouse cursor on X,Y. X and Y are zero based character coordinates: 0,0 is the top-left corner of the screen, and the position is in character cells (i.e. not in pixels). Errors: None. See also: GetMouseX (298), GetMouseY (299) Listing: mouseex/ex7.pp Program Example7 ; { Program t o demonstrate t h e SetMouseXY f u n c t i o n . } Uses mouse ; Var Event : TMouseEvent ; begin InitMouse ; W r i t e l n ( ’ C l i c k r i g h t mouse b u t t o n t o q u i t . ’ ) ; SetMouseXY ( 4 0 , 1 2 ) ; Repeat I f ( GetMouseX > 7 0 ) then SetMouseXY ( 1 0 , GetMouseY ) ; I f ( GetMouseY > 2 0 ) then SetMouseXY ( GetMouseX , 5 ) ; GetMouseEvent ( Event ) ; U n t i l ( Event . B u t t o n s =MouseRightButton ) and ( Event . A c t i o n =MouseActionDown ) ;

301

CHAPTER 15. THE MOUSE UNIT

DoneMouse ; end .

ShowMouse Declaration: Procedure ShowMouse; Description: ShowMouse shows the mouse cursor if it was previously hidden. The capability to hide or show the mouse cursor depends on the driver. Errors: None. See also: HideMouse (309) For an example, see HideMouse (309)

15.3

Writing a custom mouse driver

The mouse has support for adding a custom mouse driver. This can be used to add support for mouses not supported by the standard Free Pascal driver, but also to enhance an existing driver for instance to log mouse events or to implement a record and playback function. The following unit shows how a mouse driver can be enhanced by adding some logging capabilities to the driver. Listing: mouseex/logmouse.pp u n i t logmouse ; interface Procedure Procedure Function Procedure

StartMouseLogging ; StopMouseLogging ; IsMouseLogging : Boolean ; SetMouseLogFileName ( FileName : S t r i n g ) ;

implementation uses s y s u t i l s , Mouse ; var NewMouseDriver , OldMouseDriver : TMouseDriver ; A c t i v e , Logging : Boolean ; LogFileName : S t r i n g ; MouseLog : Text ; Function TimeStamp : S t r i n g ; begin TimeStamp : = FormatDateTime ( ’ hh : nn : ss ’ , Time ( ) ) ; end ; Procedure StartMouseLogging ;

302

CHAPTER 15. THE MOUSE UNIT

begin Logging : = True ; W r i t e l n ( MouseLog , ’ S t a r t l o g g i n g mouse events a t : ’ , TimeStamp ) ; end ; Procedure StopMouseLogging ; begin W r i t e l n ( MouseLog , ’ Stop l o g g i n g mouse events a t : ’ , TimeStamp ) ; Logging : = False ; end ; Function IsMouseLogging : Boolean ; begin IsMouseLogging : = Logging ; end ; Procedure LogGetMouseEvent ( Var Event : TMouseEvent ) ; Var M : TMouseEvent ; begin OldMouseDriver . GetMouseEvent (M) ; I f Logging then begin Write ( MouseLog , TimeStamp , ’ : Mouse ’ ) ; With M do begin Case A c t i o n of MouseActionDown : Write ( MouseLog , ’ down ’ ) ; MouseActionUp : Write ( MouseLog , ’ up ’ ) ; MouseActionMove : Write ( MouseLog , ’ move ’ ) ; end ; Write ( MouseLog , ’ event a t ’ ,X , ’ , ’ ,Y ) ; I f ( Buttons < >0) then begin Write ( MouseLog , ’ f o r b u t t o n s : ’ ) ; I f ( B u t t o n s and MouseLeftbutton ) < >0 then Write ( MouseLog , ’ L e f t ’ ) ; I f ( B u t t o n s and MouseRightbutton ) < >0 then Write ( MouseLog , ’ R i g h t ’ ) ; I f ( B u t t o n s and MouseMiddlebutton ) < >0 then Write ( MouseLog , ’ Middle ’ ) ; end ; W r i t e l n ( MouseLog ) ; end ; end ; end ; Procedure LogInitMouse ; begin OldMouseDriver . I n i t D r i v e r ( ) ; Assign ( MouseLog , logFileName ) ; Rewrite ( MouseLog ) ; A c t i v e : = True ;

303

CHAPTER 15. THE MOUSE UNIT

StartMouseLogging ; end ; Procedure LogDoneMouse ; begin StopMouseLogging ; Close ( MouseLog ) ; A c t i v e : = False ; OldMouseDriver . DoneDriver ( ) ; end ; Procedure SetMouseLogFileName ( FileName : S t r i n g ) ; begin I f Not A c t i v e then LogFileName : = FileName ; end ; Initialization GetMouseDriver ( OldMouseDriver ) ; NewMouseDriver : = OldMouseDriver ; NewMouseDriver . GetMouseEvent : = @LogGetMouseEvent ; NewMouseDriver . I n i t D r i v e r : = @LogInitMouse ; NewMouseDriver . DoneDriver : =@LogDoneMouse ; LogFileName : = ’ Mouse . l o g ’ ; Logging : = False ; SetMouseDriver ( NewMouseDriver ) ; end .

304

Chapter 16

The MsMouse unit The msmouse unit provides basic mouse handling under remarks about the msmouse unit:

DOS

(Go32v1 and Go32v2) Some general

• For maximum portability, it is advisable to use the mouse unit; that unit is portable across platforms, and offers a similar interface. Under no circumstances should the two units be used together. • The mouse driver does not know when the text screen scrolls. This results in unerased mouse cursors on the screen when the screen scrolls while the mouse cursor is visible. The solution is to hide the mouse cursor (using HideMouse) when writing something to the screen and to show it again afterwards (using ShowMouse). • All Functions/Procedures that return and/or accept coordinates of the mouse cursor, always do so in pixels and zero based (so the upper left corner of the screen is (0,0)). To get the (column, row) in standard text mode, divide both x and y by 8 (and add 1 if it must be 1 based). • The real resolution of graphic modes and the one the mouse driver uses can differ. For example, mode 13h (320*200 pixels) is handled by the mouse driver as 640*200, so the X coordinates given to the driver must be multiplied by 2 and divided by 2 when the return from the driver in that mode. • By default the msmouse unit is compiled with the conditional define MouseCheck. This causes every procedure/function of the unit to check the MouseFound variable prior to doing anything. Of course this is not necessary, so when proper checking is added to the calling program, this define may be removed and the unit can be recompiled. • Several procedures/functions have longint sized parameters while only the lower 16 bits are used. This is because FPC is a 32 bit compiler and consequently 32 bit parameters result in faster code.

16.1

Constants, types and variables

The following constants are defined (to be used in e.g. the GetLastButtonPress (306) call). LButton = 1; {left button} RButton = 2; {right button} MButton = 4; {middle button} The following variable exist: 305

CHAPTER 16. THE MSMOUSE UNIT

MouseFound: Boolean; it is set to True or False in the unit’s initialization code.

16.2

Functions and procedures

GetLastButtonPress Declaration: Function GetLastButtonPress (Button:

Longint; Var x,y:Longint) :

Longint;

Description: GetLastButtonPress Stores the position where Button was last pressed in x and y and returns the number of times this button has been pressed since the last call to this function with Button as parameter. For Button the LButton, RButton and MButton constants can be used for resp. the left, right and middle button. With certain mouse drivers, checking the middle button when using a two-button mouse to gives and clears the stats of the right button. Errors: None. See also: GetLastButtonRelease (307) Listing: mmouseex/mouse5.pp { example f o r GetLastButtonPress and GetLastButtonRelease } Uses MsMouse , C r t ; Var x , y , t i m e s : L o n g i n t ; c : Char ; Begin I f MouseFound Then Begin ClrScr ; ShowMouse ; W r i t e l n ( ’ Move t h e mouse and c l i c k t h e b u t t o n s ( press escape t o q u i t ) . ’ ) ; W r i t e l n ( ’ Press t h e L−key t o see t h e s t a t s f o r t h e l e f t b u t t o n . ’ ) ; W r i t e l n ( ’ Press t h e R−key t o see t h e s t a t s f o r t h e r i g h t b u t t o n . ’ ) ; W r i t e l n ( ’ Press t h e M−key t o see t h e s t a t s f o r t h e middle b u t t o n . ’ ) ; GotoXY ( 1 , 1 9 ) ; Write ( ’ Since t h e l a s t c a l l t o GetLastButtonPress w i t h t h i s b u t t o n as parameter , t h e ’ ) ; GotoXY ( 1 , 2 2 ) ; Write ( ’ Since t h e l a s t c a l l t o GetLastButtonRelease w i t h t h i s b u t t o n as parameter , t h e ’ ) ; Repeat I f Keypressed Then Begin c : = UpCase ( Readkey ) ; Case c Of ’L ’ : Begin GotoXY ( 1 , 2 0 ) ; ClrEol ; t i m e s : = GetLastButtonPress ( LButton , x , y ) ; Write ( ’ l e f t b u t t o n has been pressed ’ , times , ’ times , t h e l a s t t i m e a t ( ’ , x , ’ , ’ , y , ’ ) ’ ) ; t i m e s : = GetLastButtonRelease ( LButton , x , y ) ; GotoXY ( 1 , 2 3 ) ; ClrEol ;

306

CHAPTER 16. THE MSMOUSE UNIT

Write ( ’ l e f t b u t t o n has been r e l e a s e d ’ , times , ’ times , t h e l a s t t i m e a t ( ’ , x , ’ , ’ , y , ’ ) ’ ) End ; ’R ’ : Begin GotoXY ( 1 , 2 0 ) ; ClrEol ; t i m e s : = GetLastButtonPress ( RButton , x , y ) ; W r i t e l n ( ’ r i g h t b u t t o n has been pressed ’ , times , ’ times , t h e l a s t t i m e a t ( ’ , x , ’ , ’ , y , ’ ) ’ ) ; t i m e s : = GetLastButtonRelease ( RButton , x , y ) ; GotoXY ( 1 , 2 3 ) ; ClrEol ; Write ( ’ r i g h t b u t t o n has been r e l e a s e d ’ , times , ’ times , t h e l a s t t i m e a t ( ’ , x , ’ , ’ , y , ’ ) ’ ) End ; ’M ’ : Begin GotoXY ( 1 , 2 0 ) ; ClrEol ; t i m e s : = GetLastButtonPress ( MButton , x , y ) ; W r i t e l n ( ’ middle b u t t o n has been pressed ’ , times , ’ times , t h e l a s t t i m e a t ( ’ , x , ’ , ’ , y , ’ ) ’ ) ; t i m e s : = GetLastButtonRelease ( MButton , x , y ) ; GotoXY ( 1 , 2 3 ) ; ClrEol ; Write ( ’ middle b u t t o n has been r e l e a s e d ’ , times , ’ times , t h e l a s t t i m e a t ( ’ , x , ’ , ’ , y , ’ ) ’ ) End End End ; U n t i l ( c = # 2 7 ) ; { escape } While KeyPressed do ReadKey ; GotoXY ( 1 , 2 4 ) ; HideMouse End End .

GetLastButtonRelease Declaration: Function GetLastButtonRelease (Button: Longint;

Longint; Var x,y:Longint) :

Description: GetLastButtonRelease stores the position where Button was last released in x and y and returns the number of times this button has been released since the last call to this function with Button as parameter. For button the LButton, RButton and MButton constants can be used for resp. the left, right and middle button. With certain mouse drivers, checking the middle button when using a two-button mouse to gives and clears the stats of the right button. Errors: None. See also: GetLastButtonPress (306) For an example, see GetLastButtonPress (306).

307

CHAPTER 16. THE MSMOUSE UNIT

GetMouseState Declaration: Procedure GetMouseState (Var x, y, buttons:

Longint);

Description: GetMouseState Returns information on the current mouse position and which buttons are currently pressed. x and y return the mouse cursor coordinates in pixels. Buttons is a bitmask. Check the example program to see how to get the necessary information from it. Errors: None. See also: LPressed (310), MPressed (310), RPressed (310), SetMousePos (312) Listing: mmouseex/mouse3.pp { example f o r GetMouseState , IsLPressed , IsRPressed and IsMPressed } Uses MsMouse , C r t ; Var X , Y , S t a t e : L o n g i n t ; Begin I f MouseFound Then Begin ClrScr ; ShowMouse ; GotoXY ( 5 , 2 4 ) ; Write ( ’ L e f t b u t t o n : ’ ) ; GotoXY ( 3 0 , 2 4 ) ; Write ( ’ R i g h t b u t t o n : ’ ) ; GotoXY ( 5 5 , 2 4 ) ; Write ( ’ Middle b u t t o n : ’ ) ; While KeyPressed do Readkey ; { c l e a r keyboard b u f f e r } Repeat GetMouseState ( x , y , S t a t e ) ; GotoXY ( 2 0 , 2 2 ) ; Write ( ’X : ’ , x : 5 , ’ ( column : ’ , ( x div 8 ) : 2 , ’ ) Y : ’ , y : 5 , ’ ( row : ’ , ( y div 8 ) : 2 , ’ ) ’ ) ; GotoXY ( 1 8 , 2 4 ) ; { l e f t b u t t o n } I f ( S t a t e and LButton ) = LButton Then { o r : " I f LPressed Then " . I f you use t h i s f u n c t i o n , no c a l l t o GetMouseState i s necessary } Write ( ’Down ’ ) Else Write ( ’ Up ’ ) ; GotoXY ( 4 4 , 2 4 ) ; { r i g h t b u t t o n } I f ( S t a t e and RButton ) = RButton Then { o r : " I f RPressed Then " } Write ( ’Down ’ ) Else Write ( ’ Up ’ ) ; GotoXY ( 7 0 , 2 4 ) ; { middle b u t t o n } I f ( S t a t e and MButton ) = MButton Then { o r : " I f MPressed Then " } Write ( ’Down ’ ) Else Write ( ’ Up ’ ) U n t i l KeyPressed ; HideMouse ; While KeyPressed Do Readkey End End .

308

CHAPTER 16. THE MSMOUSE UNIT

HideMouse Declaration: Procedure HideMouse ; Description: HideMouse makes the mouse cursor invisible. Multiple calls to HideMouse will require just as many calls to ShowMouse to make the mouse cursor visible again. Errors: None. See also: ShowMouse (316), SetMouseHideWindow (311) For an example, see ShowMouse (316).

InitMouse Declaration: Procedure InitMouse ; Description: InitMouse Initializes the mouse driver sets the variable MouseFound depending on whether or not a mouse is found. This is Automatically called at the start of a program. Normally it should never be called, unless everything should be reset to its default values. Errors: None. See also: MouseFound variable. Listing: mmouseex/mouse1.pp Program Mouse1 ; { example f o r I n i t M o u s e and MouseFound } Uses MsMouse ; Begin I f MouseFound Then Begin { go i n t o g r a p h i c s mode 1 3 h } Asm movl $0x013 , % eax p u s h l %ebp i n t $0x010 p o p l %ebp End ; InitMouse ; ShowMouse ; { o t h e r w i s e i t s t a y s i n v i s i b l e } W r i t e l n ( ’ Mouse Found ! ( press e n t e r t o q u i t ) ’ ) ; Readln ; { back t o t e x t mode } Asm movl $3 , % eax p u s h l %ebp i n t $0x010 p o p l %ebp End End End .

309

CHAPTER 16. THE MSMOUSE UNIT

LPressed Declaration: Function LPressed :

Boolean;

Description: LPressed returns True if the left mouse button is pressed. This is simply a wrapper for the GetMouseState procedure. Errors: None. See also: GetMouseState (308), MPressed (310), RPressed (310) For an example, see GetMouseState (308).

MPressed Declaration: Function MPressed :

Boolean;

Description: MPressed returns True if the middle mouse button is pressed. This is simply a wrapper for the GetMouseState procedure. Errors: None. See also: GetMouseState (308), LPressed (310), RPressed (310) For an example, see GetMouseState (308).

RPressed Declaration: Function RPressed :

Boolean;

Description: RPressed returns True if the right mouse button is pressed. This is simply a wrapper for the GetMouseState procedure. Errors: None. See also: GetMouseState (308), LPressed (310), MPressed (310) For an example, see GetMouseState (308).

SetMouseAscii Declaration: Procedure SetMouseAscii (Ascii:

Byte);

Description: SetMouseAscii sets the Ascii value of the character that depicts the mouse cursor in text mode. The difference between this one and SetMouseShape (313), is that the foreground and background colors stay the same and that the Ascii code entered is the character that will get on screen; there’s no XOR’ing. Errors: None See also: SetMouseShape (313) Listing: mmouseex/mouse8.pp

310

CHAPTER 16. THE MSMOUSE UNIT

{ example f o r SetMouseAscii } { warning : no e r r o r checking i s performed on t h e i n p u t } Uses MsMouse , C r t ; Var a s c i i : Byte ; x , y : Longint ; Begin I f MouseFound Then Begin ClrScr ; W r i t e l n ( ’ Press any mouse b u t t o n t o q u i t a f t e r you ’ ’ ve e n t e r e d an A s c i i v a l u e . ’ ) ; Writeln ; W r i t e l n ( ’ ASCII v a l u e o f mouse c u r s o r : ’ ) ; ShowMouse ; Repeat GotoXY ( 3 0 , 3 ) ; ClrEol ; Readln ( a s c i i ) ; SetMouseAscii ( a s c i i ) U n t i l ( GetLastButtonPress ( LButton , x , y ) < > 0 ) Or ( GetLastButtonPress ( RButton , x , y ) < > 0 ) Or ( GetLastButtonPress ( MButton , x , y ) < > 0 ) ; HideMouse End ; End .

SetMouseHideWindow Declaration: Procedure SetMouseHideWindow (xmin,ymin,xmax,ymax:

Longint);

Description: SetMouseHideWindow defines a rectangle on screen with top-left corner at (xmin,ymin) and botto-right corner at (xmax,ymax),which causes the mouse cursor to be turned off when it is moved into it. When the mouse is moved into the specified region, it is turned off until call ShowMouse is called again. However, once ShowMouse (316) is called, SetMouseHideWindow must be called again to redefine the hide window... This may be annoying, but it’s the way it’s implemented in the mouse driver. While xmin, ymin, xmax and ymax are Longint parameters, only the lower 16 bits are used. Warning: it seems Win98 SE doesn’t (properly) support this function, maybe this already the case with earlier versions too! Errors: None. See also: ShowMouse (316), HideMouse (309) Listing: mmouseex/mouse9.pp { example f o r SetMouseHideWindow } { warning : when t h e mouse i s moved i n t o t h e s p e c i f i e d r e g i o n , i t i s t u r n e d o f f u n t i l you c a l l ShowMouse again . However , when you ’ ve c a l l e d ShowMouse , you ’ l l have t o c a l l SetMouseHideWindow again t o r e d e f i n e t h e h i d e window . . . I t ’ s n o t our f a u l t , t h a t ’ s t h e way i t ’ s implemented i n t h e mouse d r i v e r .

311

CHAPTER 16. THE MSMOUSE UNIT

Below you can f i n d an example o f how t o d e f i n e a " permanent " h i d e r e g i o n w i t h t h e c u r s o r showing up again when you move i t o u t o f t h e r e g i o n Note : t h e mouse f u n c t i o n s are zero−based , GotoXY i s 1−based } Uses MsMouse , C r t ; Var x , y , b u t t o n s : L o n g i n t ; MouseOn : Boolean ; Begin I f MouseFound Then Begin ClrScr ; For y : = 1 to 2 5 Do Begin GotoXY ( 2 0 , y ) ; Write ( ’ | ’ ) ; GotoXY ( 6 0 , y ) ; Write ( ’ | ’ ) ; End ; MouseOn : = t r u e ; GotoXY ( 3 0 , 2 4 ) ; W r i t e l n ( ’ Press any key t o q u i t ’ ) ; ShowMouse ; SetMousePos ( 1 , 1 ) ; While KeyPressed Do Readkey ; Repeat GetMouseState ( x , y , b u t t o n s ) ; I f Not ( MouseOn ) And ( ( x < = 1 9 ∗ 8 ) or ( x > = 5 9 ∗ 8 ) ) Then Begin ShowMouse ; MouseOn : = t r u e End ; I f MouseOn And ( x > 1 9 ∗ 8 ) And ( x < 5 9 ∗ 8 ) Then Begin SetMouseHideWindow ( 2 0 ∗ 8 , 0 , 6 0 ∗ 8 , 2 5 ∗ 8 ) ; MouseOn : = f a l s e End ; U n t i l KeyPressed ; While KeyPressed Do Readkey ; HideMouse End End .

SetMousePos Declaration: Procedure SetMousePos (x,y:Longint); Description: SetMosusePos sets the position of the mouse cursor on the screen. x is the horizontal position in pixels, y the vertical position in pixels. The upper-left hand corner of the screen is the origin. While x and y are longints, only the lower 16 bits are used. Errors: None. See also: GetMouseState (308)

312

CHAPTER 16. THE MSMOUSE UNIT

Listing: mmouseex/mouse4.pp { example f o r SetMousePos } Uses MsMouse , C r t ; Begin I f MouseFound Then Begin ShowMouse ; While KeyPressed do ReadKey ; Repeat SetMousePos (Random( 8 0 ∗ 8 ) , Random( 2 5 ∗ 8 ) ) ; delay ( 1 0 0 ) ; U n t i l Keypressed ; HideMouse ; While KeyPressed do ReadKey ; End ; End .

SetMouseShape Declaration: Procedure SetMouseShape (ForeColor,BackColor,Ascii:

Byte);

Description: SetMouseShape defines how the mouse cursor looks in textmode The character and its attributes that are on the mouse cursor’s position on screen are XOR’ed with resp. ForeColor, BackColor and Ascii. Set them all to 0 for a "transparent" cursor. Errors: None. See also: SetMouseAscii (310) Listing: mmouseex/mouse7.pp { example f o r SetMouseShape } { warning : no e r r o r checking i s performed on t h e i n p u t } { t h e A s c i i v a l u e you e n t e r i s XOR’ ed w i t h t h e A s c i i v a l u e o f t h e c h a r a c t e r on t h e screen over which you move t h e c u r s o r . To g e t a " t r a n s p a r e n t " c u r s o r , use t h e A s c i i v a l u e 0 } Uses MsMouse , C r t ; Var a s c i i , f c , bc : Byte ; x , y : Longint ; Begin I f MouseFound Then Begin ClrScr ; W r i t e l n ( ’ Press any mouse b u t t o n t o q u i t a f t e r you ’ ’ ve e n t e r e d a sequence o f numbers . ’ ) ; Writeln ; W r i t e l n ( ’ ASCII v a l u e o f mouse c u r s o r : ’ ) ; W r i t e l n ( ’ Forground c o l o r : ’ ) ; W r i t e l n ( ’ Background c o l o r : ’ ) ; ShowMouse ; Repeat

313

CHAPTER 16. THE MSMOUSE UNIT

GotoXY ( 3 0 , 3 ) ; ClrEol ; Readln ( a s c i i ) ; GotoXY ( 1 8 , 4 ) ; ClrEol ; Readln ( f c ) ; GotoXY ( 1 9 , 5 ) ; ClrEol ; Readln ( bc ) ; SetMouseShape ( f c , bc , a s c i i ) U n t i l ( GetLastButtonPress ( LButton , x , y ) < > 0 ) Or ( GetLastButtonPress ( RButton , x , y ) < > 0 ) Or ( GetLastButtonPress ( MButton , x , y ) < > 0 ) ; HideMouse End ; End .

SetMouseSpeed Declaration: Procedure SetMouseSpeed (Horizontal, Vertical:

Longint);

Description: SetMouseSpeed sets the mouse speed in mickeys per 8 pixels. A mickey is the smallest measurement unit handled by a mouse. With this procedure one can set how many mickeys the mouse should move to move the cursor 8 pixels horizontally of vertically. The default values are 8 for horizontal and 16 for vertical movement. While this procedure accepts longint parameters, only the low 16 bits are actually used. Errors: None. See also: Listing: mmouseex/mouse10.pp Uses MsMouse , C r t ; Var hor , v e r t : L o n g i n t ; x , y : Longint ; Begin I f MouseFound Then Begin ClrScr ; W r i t e l n ( ’ C l i c k any b u t t o n t o q u i t a f t e r you ’ ’ ve e n t e r e d a sequence o f numbers . ’ ) ; Writeln ; W r i t e l n ( ’ H o r i z o n t a l mickey ’ ’ s per p i x e l : ’ ) ; W r i t e l n ( ’ V e r t i c a l mickey ’ ’ s per p i x e l : ’ ) ; ShowMouse ; Repeat GotoXY ( 3 2 , 3 ) ; ClrEol ; Readln ( hor ) ; GotoXY ( 3 0 , 4 ) ; ClrEol ; Readln ( v e r t ) ; SetMouseSpeed ( hor , v e r t ) ; U n t i l ( GetLastButtonPress ( LButton , x , y ) < > 0 ) Or ( GetLastButtonPress ( RButton , x , y ) < > 0 ) Or

314

CHAPTER 16. THE MSMOUSE UNIT

( GetLastButtonPress ( MButton , x , y ) < > 0 ) ; End End .

SetMouseWindow Declaration: Procedure SetMouseWindow (xmin,ymin,xmax,ymax:

Longint);

Description: SetMousWindow defines a rectangle on screen with top-left corner at (xmin,ymin) and bottomright corner at (xmax,ymax), out of which the mouse cursor can’t move. This procedure is simply a wrapper for the SetMouseXRange (315) and SetMouseYRange (316) procedures. While xmin, ymin, xmax and ymax are Longint parameters, only the lower 16 bits are used. Errors: None. See also: SetMouseXRange (315), SetMouseYRange (316) For an example, see SetMouseXRange (315).

SetMouseXRange Declaration: Procedure SetMouseXRange (Min, Max:

Longint);

Description: SetMouseXRange sets the minimum (Min) and maximum (Max) horizontal coordinates in between which the mouse cursor can move. While Min and Max are Longint parameters, only the lower 16 bits are used. Errors: None. See also: SetMouseYRange (316), SetMouseWindow (315) Listing: mmouseex/mouse6.pp { example f o r SetMouseXRange , SetMouseYRange and SetMouseWindow } Uses MsMouse , C r t ; Begin I f MouseFound Then Begin SetMouseXRange ( 2 0 ∗ 8 , 5 0 ∗ 8 ) ; SetMouseYRange ( 1 0 ∗ 8 , 1 5 ∗ 8 ) ;

{ c h a r r a c t e r w i d t h and h e i g h t = 8 p i x e l s }

{ t h e two l i n e s o f code have e x a c t l y t h e same e f f e c t as SetMouseWindow (20∗8 ,10∗8 ,50∗8 ,15∗8) } W r i t e l n ( ’ Press any key t o q u i t . ’ ) ; ShowMouse ; While KeyPressed Do ReadKey ; Readkey ; While KeyPressed Do ReadKey ; HideMouse End End .

315

CHAPTER 16. THE MSMOUSE UNIT

SetMouseYRange Declaration: Procedure SetMouseYRange (Min, Max:

Longint);

Description: SetMouseYRange sets the minimum (Min) and maximum (Max) vertical coordinates in between which the mouse cursor can move. While Min and Max are Longint parameters, only the lower 16 bits are used. Errors: None. See also: SetMouseXRange (315), SetMouseWindow (315) For an example, see SetMouseXRange (315).

ShowMouse Declaration: Procedure ShowMouse ; Description: ShowMouse makes the mouse cursor visible. At the start of the program, the mouse cursor is invisible. Errors: None. See also: HideMouse (309),SetMouseHideWindow (311) Listing: mmouseex/mouse2.pp { example f o r ShowMouse and HideMouse } Uses MsMouse ; Begin ClrScr ; I f MouseFound Then Begin W r i t e l n ( ’Now you can see t h e mouse . . . ( press e n t e r t o c o n t i n u e ) ’ ) ; ShowMouse ; Readln ; HideMouse ; W r i t e l n ( ’ And now you can ’ ’ t . . . ( press e n t e r t o q u i t ) ’ ) ; Readln End End .

316

Chapter 17

The Objects unit. This chapter documents the objects unit. The unit was implemented by many people, and was mainly taken from the FreeVision sources. It has been ported to all supported platforms. The methods and fields that are in a Private part of an object declaration have been left out of this documentation.

17.1

Constants

The following constants are error codes, returned by the various stream objects. CONST stOk stError stInitError stReadError stWriteError stGetError stPutError stSeekError stOpenError

= = = = = = = = =

0; -1; -2; -3; -4; -5; -6; -7; -8;

{ { { { { { { { {

No stream error } Access error } Initialize error } Stream read error } Stream write error } Get object error } Put object error } Seek error in stream } Error opening stream }

These constants can be passed to constructors of file streams: CONST stCreate stOpenRead stOpenWrite stOpen

= = = =

$3C00; $3D00; $3D01; $3D02;

{ { { {

Create new file } Read access only } Write access only } Read/write access }

The following constants are error codes, returned by the collection list objects: CONST coIndexError = -1; { Index out of range } coOverflow = -2; { Overflow } Maximum data sizes (used in determining how many data can be used.

317

CHAPTER 17. THE OBJECTS UNIT.

CONST MaxBytes = 128*1024*1024; MaxWords = MaxBytes DIV SizeOf(Word); MaxPtrs = MaxBytes DIV SizeOf(Pointer); MaxCollectionSize = MaxBytes DIV SizeOf(Pointer);

17.2

Types

The follwing auxiliary types are defined: TYPE { Character set } TCharSet = SET Of Char; PCharSet = ^TCharSet; { Byte array } TByteArray = ARRAY [0..MaxBytes-1] Of Byte; PByteArray = ^TByteArray; { Word array } TWordArray = ARRAY [0..MaxWords-1] Of Word; PWordArray = ^TWordArray; { Pointer array } TPointerArray = Array [0..MaxPtrs-1] Of Pointer; PPointerArray = ^TPointerArray; { String pointer } PString = ^String; { Filename array } AsciiZ = Array [0..255] Of Char; Sw_Word = Cardinal; Sw_Integer = LongInt; The following records are used internaly for easy type conversion: TYPE { Word to bytes} WordRec = packed RECORD Lo, Hi: Byte; END; { LongInt to words } LongRec = packed RECORD Lo, Hi: Word; END; { Pointer to words } PtrRec = packed RECORD Ofs, Seg: Word; END; 318

{ { { {

Maximum data size } Max word data size } Max ptr data size } Max collection size }

CHAPTER 17. THE OBJECTS UNIT.

The following record is used when streaming objects: TYPE PStreamRec = ^TStreamRec; TStreamRec = Packed RECORD ObjType: Sw_Word; VmtLink: pointer; Load : Pointer; Store: Pointer; Next : PStreamRec; END; The TPoint basic object is used in the TRect object (see section 17.4, page 322): TYPE PPoint = ^TPoint; TPoint = OBJECT X, Y: Sw_Integer; END;

17.3

Procedures and Functions

NewStr Declaration: Function NewStr (Const S: String):

PString;

Description: NewStr makes a copy of the string S on the heap, and returns a pointer to this copy. The allocated memory is not based on the declared size of the string passed to NewStr, but is baed on the actual length of the string. Errors: If not enough memory is available, an ’out of memory’ error will occur. See also: DisposeStr (320) Listing: objectex/ex40.pp Program ex40 ; { Program t o demonstrate t h e NewStr f u n c t i o n } Uses O b j e c t s ; Var S : S t r i n g ; P : PString ; begin S: = ’Some r e a l l y c u t e s t r i n g ’ ; W r i t e l n ( ’ Memavail : ’ , Memavail ) ; P: = NewStr ( S ) ; I f P^S then W r i t e l n ( ’Oh−oh . . . Something i s wrong ! ! ’ ) ; W r i t e l n ( ’ A l l o c a t e d s t r i n g . Memavail : ’ , Memavail ) ; DisposeStr ( P ) ; W r i t e l n ( ’ D e a l l o c a t e d s t r i n g . Memavail : ’ , Memavail ) ; end .

319

CHAPTER 17. THE OBJECTS UNIT.

DisposeStr Declaration: Procedure DisposeStr (P: PString); Description: DisposeStr removes a dynamically allocated string from the heap. Errors: None. See also: NewStr (319) For an example, see NewStr (319).

Abstract Declaration: Procedure Abstract; Description: When implementing abstract methods, do not declare them as abstract. Instead, define them simply as virtual. In the implementation of such abstract methods, call the Abstract procedure. This allows explicit control of what happens when an abstract method is called. The current implementation of Abstract terminates the program with a run-time error 211. Errors: None. See also: Most abstract types.

RegisterObjects Declaration: Procedure RegisterObjects; Description: RegisterObjects registers the following objects for streaming: 1.TCollection, see section 17.10, page 347. 2.TStringCollection, see section 17.12, page 366. 3.TStrCollection, see section 17.13, page 368. Errors: None. See also: RegisterType (320)

RegisterType Declaration: Procedure RegisterType (Var S: TStreamRec); Description: RegisterType registers a new type for streaming. An object cannot be streamed unless it has been registered first. The stream record S needs to have the following fields set: ObjType: Sw_WordThis should be a unique identifier. Each possible type should have it’s own identifier. VmtLink: pointerThis should contain a pointer to the VMT (Virtual Method Table) of the object you try to register. You can get it with the following expression: VmtLink: Ofs(TypeOf(MyType)^); Load : Pointeris a pointer to a method that initializes an instance of that object, and reads the initial values from a stream. This method should accept as it’s sole argument a PStream type variable. 320

CHAPTER 17. THE OBJECTS UNIT.

Store: Pointeris a pointer to a method that stores an instance of the object to a stream. This method should accept as it’s sole argument a PStream type variable. Errors: In case of error (if a object with the same ObjType) is already registered), run-time error 212 occurs. Listing: objectex/myobject.pp Unit MyObject ;

Interface Uses O b j e c t s ; Type PMyObject = ^ TMyObject ; TMyObject = Object ( TObject ) Field : Longint ; Constructor I n i t ; Constructor Load ( Var Stream : TStream ) ; Destructor Done ; Procedure S t o r e ( Var Stream : TStream ) ; Function G e t F i e l d : L o n g i n t ; Procedure S e t F i e l d ( Value : L o n g i n t ) ; end ; Implementation Constructor TMyobject . I n i t ; begin Inherited I n i t ; F i e l d := −1; end ; Constructor TMyobject . Load ( Var Stream : TStream ) ; begin Stream . Read ( F i e l d , Sizeof ( F i e l d ) ) ; end ; Destructor TMyObject . Done ; begin end ; Function TMyObject . G e t F i e l d : L o n g i n t ; begin GetField := Field ; end ; Procedure TMyObject . S e t F i e l d ( Value : L o n g i n t ) ; begin F i e l d : = Value ; end ;

321

CHAPTER 17. THE OBJECTS UNIT.

Procedure TMyObject . S t o r e ( Var Stream : TStream ) ; begin Stream . Write ( F i e l d , SizeOf ( F i e l d ) ) ; end ; Const MyObjectRec : TStreamRec = ( Objtype : 6 6 6 ; v m t l i n k : Ofs ( TypeOf ( TMyObject ) ^ ) ; Load : @TMyObject . Load ; S t o r e : @TMyObject . S t o r e ; ); begin RegisterObjects ; RegisterType ( MyObjectRec ) ; end .

LongMul Declaration: Function LongMul (X, Y: Integer):

LongInt;

Description: LongMul multiplies X with Y. The result is of type Longint. This avoids possible overflow errors you would normally get when multiplying X and Y that are too big. Errors: None. See also: LongDiv (322)

LongDiv Declaration: Function LongDiv (X: Longint; Y: Integer):

Integer;

Description: LongDiv divides X by Y. The result is of type Integer instead of type Longint, as you would get normally. Errors: If Y is zero, a run-time error will be generated. See also: LongMul (322)

17.4

TRect

The TRect object is declared as follows: TRect = OBJECT A, B: TPoint; FUNCTION Empty: Boolean; FUNCTION Equals (R: TRect): Boolean; FUNCTION Contains (P: TPoint): Boolean; PROCEDURE Copy (R: TRect); PROCEDURE Union (R: TRect); PROCEDURE Intersect (R: TRect); PROCEDURE Move (ADX, ADY: Sw_Integer); PROCEDURE Grow (ADX, ADY: Sw_Integer); 322

CHAPTER 17. THE OBJECTS UNIT.

PROCEDURE Assign (XA, YA, XB, YB: Sw_Integer); END;

TRect.Empty Declaration: Function TRect.Empty:

Boolean;

Description: Empty returns True if the rectangle defined by the corner points A, B has zero or negative surface. Errors: None. See also: TRect.Equals (324), TRect.Contains (324) Listing: objectex/ex1.pp Program ex1 ; { Program t o demonstrate TRect . Empty } Uses o b j e c t s ;

Var ARect , BRect : TRect ; P : TPoint ; begin With ARect . A do begin X: = 1 0 ; Y: = 1 0 ; end ; With ARect . B do begin X: = 2 0 ; Y: = 2 0 ; end ; { O f f s e t B by ( 5 , 5 ) } With BRect . A do begin X: = 1 5 ; Y: = 1 5 ; end ; With BRect . B do begin X: = 2 5 ; Y: = 2 5 ; end ; { Point } With P do begin X: = 1 5 ; Y: = 1 5 ; end ; W r i t e l n ( ’A empty : ’ , ARect . Empty ) ; W r i t e l n ( ’B empty : ’ , BRect . Empty ) ; W r i t e l n ( ’A Equals B : ’ , ARect . Equals ( BRect ) ) ; W r i t e l n ( ’A Contains ( 1 5 , 1 5 ) : ’ , ARect . Contains (P ) ) ; end .

323

CHAPTER 17. THE OBJECTS UNIT.

TRect.Equals Declaration: Function TRect.Equals (R: TRect):

Boolean;

Description: Equals returns True if the rectangle has the same corner points A,B as the rectangle R, and False otherwise. Errors: None. See also: Empty (323), Contains (324) For an example, see TRect.Empty (323)

TRect.Contains Declaration: Function TRect.Contains (P: TPoint):

Boolean;

Description: Contains returns True if the point P is contained in the rectangle (including borders), False otherwise. Errors: None. See also: Intersect (325), Equals (324)

TRect.Copy Declaration: Procedure TRect.Copy (R: TRect); Description: Assigns the rectangle R to the object. After the call to Copy, the rectangle R has been copied to the object that invoked Copy. Errors: None. See also: Assign (327) Listing: objectex/ex2.pp Program ex2 ; { Program t o demonstrate TRect . Copy } Uses o b j e c t s ; Var ARect , BRect , CRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; CRect . Copy ( ARect ) ; I f ARect . Equals ( CRect ) Then W r i t e l n ( ’ ARect equals CRect ’ ) Else W r i t e l n ( ’ ARect does n o t equal CRect ! ’ ) ; end .

324

CHAPTER 17. THE OBJECTS UNIT.

TRect.Union Declaration: Procedure TRect.Union (R: TRect); Description: Union enlarges the current rectangle so that it becomes the union of the current rectangle with the rectangle R. Errors: None. See also: Intersect (325) Listing: objectex/ex3.pp Program ex3 ; { Program t o demonstrate TRect . Union } Uses o b j e c t s ;

Var ARect , BRect , CRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; { CRect i s union o f ARect and BRect } CRect . Assign ( 1 0 , 1 0 , 2 5 , 2 5 ) ; { Calculate i t e x p l i c i t l y } ARect . Union ( BRect ) ; I f ARect . Equals ( CRect ) Then W r i t e l n ( ’ ARect equals CRect ’ ) Else W r i t e l n ( ’ ARect does n o t equal CRect ! ’ ) ; end .

TRect.Intersect Declaration: Procedure TRect.Intersect (R: TRect); Description: Intersect makes the intersection of the current rectangle with R. If the intersection is empty, then the rectangle is set to the empty rectangle at coordinate (0,0). Errors: None. See also: Union (325) Listing: objectex/ex4.pp Program ex4 ; { Program t o demonstrate TRect . I n t e r s e c t } Uses o b j e c t s ;

Var ARect , BRect , CRect : TRect ; begin

325

CHAPTER 17. THE OBJECTS UNIT.

ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; { CRect i s i n t e r s e c t i o n o f ARect and BRect } CRect . Assign ( 1 5 , 1 5 , 2 0 , 2 0 ) ; { Calculate i t e x p l i c i t l y } ARect . I n t e r s e c t ( BRect ) ; I f ARect . Equals ( CRect ) Then W r i t e l n ( ’ ARect equals CRect ’ ) Else W r i t e l n ( ’ ARect does n o t equal CRect ! ’ ) ; BRect . Assign ( 2 5 , 2 5 , 3 0 , 3 0 ) ; A r e c t . I n t e r s e c t ( BRect ) ; I f ARect . Empty Then W r i t e l n ( ’ ARect i s empty ’ ) ; end .

TRect.Move Declaration: Procedure TRect.Move (ADX, ADY: Sw_Integer); Description: Move moves the current rectangle along a vector with components (ADX,ADY). It adds ADX to the X-coordinate of both corner points, and ADY to both end points. Errors: None. See also: Grow (326) Listing: objectex/ex5.pp Program ex5 ; { Program t o demonstrate TRect . Move } Uses o b j e c t s ;

Var ARect , BRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; ARect . Move ( 5 , 5 ) ; / / B r e c t should be where new ARect i s . BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; I f ARect . Equals ( BRect ) Then W r i t e l n ( ’ ARect equals BRect ’ ) Else W r i t e l n ( ’ ARect does n o t equal BRect ! ’ ) ; end .

TRect.Grow Declaration: Procedure TRect.Grow (ADX, ADY: Sw_Integer); Description: Grow expands the rectangle with an amount ADX in the X direction (both on the left and right side of the rectangle, thus adding a length 2*ADX to the width of the rectangle), and an amount ADY in

326

CHAPTER 17. THE OBJECTS UNIT.

the Y direction (both on the top and the bottom side of the rectangle, adding a length 2*ADY to the height of the rectangle. ADX and ADY can be negative. If the resulting rectangle is empty, it is set to the empty rectangle at (0,0). Errors: None. See also: Move (326). Listing: objectex/ex6.pp Program ex6 ; { Program t o demonstrate TRect . Grow } Uses o b j e c t s ;

Var ARect , BRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; ARect . Grow ( 5 , 5 ) ; / / B r e c t should be where new ARect i s . BRect . Assign ( 5 , 5 , 2 5 , 2 5 ) ; I f ARect . Equals ( BRect ) Then W r i t e l n ( ’ ARect equals BRect ’ ) Else W r i t e l n ( ’ ARect does n o t equal BRect ! ’ ) ; end .

TRect.Assign Declaration: Procedure Trect.Assign (XA, YA, XB, YB: Sw_Integer); Description: Assign sets the corner points of the rectangle to (XA,YA) and (Xb,Yb). Errors: None. See also: Copy (324) For an example, see TRect.Copy (324).

17.5

TObject

The full declaration of the TObject type is: TYPE TObject = OBJECT CONSTRUCTOR Init; PROCEDURE Free; DESTRUCTOR Done;Virtual; END; PObject = ^TObject; 327

CHAPTER 17. THE OBJECTS UNIT.

TObject.Init Declaration: Constructor TObject.Init; Description: Instantiates a new object of type TObject. It fills the instance up with Zero bytes. Errors: None. See also: Free (328), Done (328) For an example, see Free (328)

TObject.Free Declaration: Procedure TObject.Free; Description: Free calls the destructor of the object, and releases the memory occupied by the instance of the object. Errors: No checking is performed to see whether self is nil and whether the object is indeed allocated on the heap. See also: Init (328), Done (328) Listing: objectex/ex7.pp program ex7 ; { Program t o demonstrate t h e TObject . Free c a l l } Uses O b j e c t s ; Var O : PObject ; begin W r i t e l n ( ’ Memavail : ’ , Memavail ) ; / / A l l o c a t e memory f o r o b j e c t . O: =New( PObject , I n i t ) ; W r i t e l n ( ’ Memavail : ’ , Memavail ) ; / / Free memory o f o b j e c t . O^ . f r e e ; W r i t e l n ( ’ Memavail : ’ , Memavail ) ; end .

TObject.Done Declaration: Destructor TObject.Done;Virtual; Description: Done, the destructor of TObject does nothing. It is mainly intended to be used in the TObject.Free (328) method. The destructore Done does not free the memory occupied by the object. Errors: None. See also: Free (328), Init (328) Listing: objectex/ex8.pp 328

CHAPTER 17. THE OBJECTS UNIT.

program ex8 ; { Program t o demonstrate t h e TObject . Done c a l l } Uses O b j e c t s ; Var O : PObject ; begin W r i t e l n ( ’ Memavail / / A l l o c a t e memory O: =New( PObject , I n i t W r i t e l n ( ’ Memavail O^ . Done ; W r i t e l n ( ’ Memavail end .

17.6

: ’ , Memavail ) ; for object . ); : ’ , Memavail ) ; :

’ , Memavail ) ;

TStream

The TStream object is the ancestor for all streaming objects, i.e. objects that have the capability to store and retrieve data. It defines a number of methods that are common to all objects that implement streaming, many of them are virtual, and are only implemented in the descendrnt types. Programs should not instantiate objects of type TStream directly, but instead instantiate a descendant type, such as TDosStream, TMemoryStream. This is the full declaration of the TStream object: TYPE TStream = OBJECT (TObject) Status : Integer; { Stream status } ErrorInfo : Integer; { Stream error info } StreamSize: LongInt; { Stream current size } Position : LongInt; { Current position } FUNCTION Get: PObject; FUNCTION StrRead: PChar; FUNCTION GetPos: Longint; Virtual; FUNCTION GetSize: Longint; Virtual; FUNCTION ReadStr: PString; PROCEDURE Open (OpenMode: Word); Virtual; PROCEDURE Close; Virtual; PROCEDURE Reset; PROCEDURE Flush; Virtual; PROCEDURE Truncate; Virtual; PROCEDURE Put (P: PObject); PROCEDURE StrWrite (P: PChar); PROCEDURE WriteStr (P: PString); PROCEDURE Seek (Pos: LongInt); Virtual; PROCEDURE Error (Code, Info: Integer); Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; PROCEDURE CopyFrom (Var S: TStream; Count: Longint);

329

CHAPTER 17. THE OBJECTS UNIT.

END; PStream = ^TStream;

TStream.Get Declaration: Function TStream.Get :

PObject;

Description: Get reads an object definition from a stream, and returns a pointer to an instance of this object. Errors: On error, TStream.Status is set, and NIL is returned. See also: Put (334) Listing: objectex/ex9.pp Program ex9 ; { Program t o demonstrate TStream . Get and TStream . Put } Uses Objects , MyObject ;

{ D e f i n i t i o n and r e g i s t r a t i o n o f TMyObject }

Var Obj : PMyObject ; S : PStream ; begin Obj : =New( PMyObject , I n i t ) ; Obj ^ . S e t F i e l d ( $1111 ) ; W r i t e l n ( ’ F i e l d v a l u e : ’ , Obj ^ . G e t F i e l d ) ; { Since Stream i s an a b s t r a c t type , we i n s t a n t i a t e a TMemoryStream } S: =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S ^ . Put ( Obj ) ; Writeln ( ’ Disposing o b j e c t ’ ) ; S ^ . Seek ( 0 ) ; Dispose ( Obj , Done ) ; W r i t e l n ( ’ Reading o b j e c t ’ ) ; Obj : = PMyObject ( S ^ . Get ) ; W r i t e l n ( ’ F i e l d Value : ’ , Obj ^ . G e t F i e l d ) ; Dispose ( Obj , Done ) ; end .

TStream.StrRead Declaration: Function TStream.StrRead:

PChar;

Description: StrRead reads a string from the stream, allocates memory for it, and returns a pointer to a nullterminated copy of the string on the heap. Errors: On error, Nil is returned. See also: StrWrite (334), ReadStr (332) Listing: objectex/ex10.pp Program ex10 ; { Program t o demonstrate t h e TStream . StrRead TStream . S t r W r i t e f u n c t i o n s

330

CHAPTER 17. THE OBJECTS UNIT.

} Uses o b j e c t s ; Var P : PChar ; S : PStream ; begin P: = ’ Constant Pchar s t r i n g ’ ; W r i t e l n ( ’ W r i t i n g t o stream : " ’ ,P , ’ " ’ ) ; S: =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S^ . S t r W r i t e (P ) ; S ^ . Seek ( 0 ) ; P: = N i l ; P: =S ^ . StrRead ; DisPose ( S , Done ) ; W r i t e l n ( ’ Read from stream : " ’ ,P , ’ " ’ ) ; Freemem ( P , S t r l e n ( P ) + 1 ) ; end .

TStream.GetPos Declaration: TSTream.GetPos :

Longint; Virtual;

Description: If the stream’s status is stOk, GetPos returns the current position in the stream. Otherwise it returns -1 Errors: -1 is returned if the status is an error condition. See also: Seek (335), GetSize (331) Listing: objectex/ex11.pp Program ex11 ; { Program t o demonstrate t h e TStream . GetPos f u n c t i o n } Uses o b j e c t s ; Var L : S t r i n g ; S : PStream ; begin L : = ’Some k i n d o f s t r i n g ’ ; S: =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; W r i t e l n ( ’ Stream p o s i t i o n b e f o r e w r i t e : ’ ,S ^ . GetPos ) ; S ^ . W r i t e S t r (@L) ; W r i t e l n ( ’ Stream p o s i t i o n a f t e r w r i t e : ’ ,S ^ . GetPos ) ; Dispose ( S , Done ) ; end .

TStream.GetSize Declaration: Function TStream.GetSize:

Longint; Virtual;

Description: If the stream’s status is stOk then GetSize returns the size of the stream, otherwise it returns -1. 331

CHAPTER 17. THE OBJECTS UNIT.

Errors: -1 is returned if the status is an error condition. See also: Seek (335), GetPos (331) Listing: objectex/ex12.pp Program ex12 ; { Program t o demonstrate t h e TStream . GetSize f u n c t i o n } Uses o b j e c t s ; Var L : S t r i n g ; S : PStream ; begin L : = ’Some k i n d o f s t r i n g ’ ; S: =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; W r i t e l n ( ’ Stream s i z e b e f o r e w r i t e : ’ ,S ^ . GetSize ) ; S ^ . W r i t e S t r (@L) ; W r i t e l n ( ’ Stream s i z e a f t e r w r i t e : ’ ,S ^ . GetSize ) ; Dispose ( S , Done ) ; end .

TStream.ReadStr Declaration: Function TStream.ReadStr:

PString;

Description: ReadStr reads a string from the stream, copies it to the heap and returns a pointer to this copy. The string is saved as a pascal string, and hence is NOT null terminated. Errors: On error (e.g. not enough memory), Nil is returned. See also: StrRead (330) Listing: objectex/ex13.pp Program ex13 ; { Program t o demonstrate t h e TStream . ReadStr TStream . W r i t e S t r f u n c t i o n s } Uses o b j e c t s ; Var P : P S t r i n g ; L : String ; S : PStream ; begin L : = ’ Constant s t r i n g l i n e ’ ; W r i t e l n ( ’ W r i t i n g t o stream : " ’ , L , ’ " ’ ) ; S: =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S ^ . W r i t e S t r (@L) ; S ^ . Seek ( 0 ) ; P: =S ^ . ReadStr ; L : =P ^ ; DisposeStr ( P ) ;

332

CHAPTER 17. THE OBJECTS UNIT.

DisPose ( S , Done ) ; W r i t e l n ( ’ Read from stream : " ’ , L , ’ " ’ ) ; end .

TStream.Open Declaration: Procedure TStream.Open (OpenMode:

Word); Virtual;

Description: Open is an abstract method, that should be overridden by descendent objects. Since opening a stream depends on the stream’s type this is not surprising. Errors: None. See also: Close (333), Reset (333) For an example, see TDosStream.Open (340).

TStream.Close Declaration: Procedure TStream.Close; Virtual; Description: Close is an abstract method, that should be overridden by descendent objects. Since Closing a stream depends on the stream’s type this is not surprising. Errors: None. See also: Open (333), Reset (333) for an example, see TDosStream.Open (340).

TStream.Reset Declaration: PROCEDURE TStream.Reset; Description: Reset sets the stream’s status to 0, as well as the ErrorInfo Errors: None. See also: Open (333), Close (333)

TStream.Flush Declaration: Procedure TStream.Flush; Virtual; Description: Flush is an abstract method that should be overridden by descendent objects. It serves to enable the programmer to tell streams that implement a buffer to clear the buffer. Errors: None. See also: Truncate (334) for an example, see TBufStream.Flush (342).

333

CHAPTER 17. THE OBJECTS UNIT.

TStream.Truncate Declaration: Procedure TStream.Truncate; Virtual; Description: Truncate is an abstract procedure that should be overridden by descendent objects. It serves to enable the programmer to truncate the size of the stream to the current file position. Errors: None. See also: Seek (335) For an example, see TDosStream.Truncate (338).

TStream.Put Declaration: Procedure TStream.Put (P: PObject); Description: Put writes the object pointed to by P. P should be non-nil. The object type must have been registered with RegisterType (320). After the object has been written, it can be read again with Get (330). Errors: No check is done whether P is Nil or not. Passing Nil will cause a run-time error 216 to be generated. If the object has not been registered, the status of the stream will be set to stPutError. See also: Get (330) For an example, see TStream.Get (330);

TStream.StrWrite Declaration: Procedure TStream.StrWrite (P: PChar); Description: StrWrite writes the null-terminated string P to the stream. P can only be 65355 bytes long. Errors: None. See also: WriteStr (334), StrRead (330), ReadStr (332) For an example, see TStream.StrRead (330).

TStream.WriteStr Declaration: Procedure TStream.WriteStr (P: PString); Description: StrWrite writes the pascal string pointed to by P to the stream. Errors: None. See also: StrWrite (334), StrRead (330), ReadStr (332) For an example, see TStream.ReadStr (332).

334

CHAPTER 17. THE OBJECTS UNIT.

TStream.Seek Declaration: PROCEDURE TStream.Seek (Pos:

LongInt); Virtual;

Description: Seek sets the position to Pos. This position is counted from the beginning, and is zero based. (i.e. seeek(0) sets the position pointer on the first byte of the stream) Errors: If Pos is larger than the stream size, Status is set to StSeekError. See also: GetPos (331), GetSize (331) For an example, see TDosStream.Seek (339).

TStream.Error Declaration: Procedure TStream.Error (Code, Info:

Integer); Virtual;

Description: Error sets the stream’s status to Code and ErrorInfo to Info. If the StreamError procedural variable is set, Error executes it, passing Self as an argument. This method should not be called directly from a program. It is intended to be used in descendent objects. Errors: None. See also:

TStream.Read Declaration: Procedure TStream.Read (Var Buf; Count:

Sw_Word); Virtual;

Description: Read is an abstract method that should be overridden by descendent objects. Read reads Count bytes from the stream into Buf. It updates the position pointer, increasing it’s value with Count. Buf must be large enough to contain Count bytes. Errors: No checking is done to see if Buf is large enough to contain Count bytes. See also: Write (336), ReadStr (332), StrRead (330) Listing: objectex/ex18.pp program ex18 ; { Program t o demonstrate t h e TStream . Read method } Uses O b j e c t s ; Var Buf1 , Buf2 : Array [ 1 . . 1 0 0 0 ] of Byte ; I : longint ; S : PMemorySTream ; begin For I : = 1 to 1 0 0 0 do Buf1 [ I ] : = Random( 1 0 0 0 ) ; Buf2 : = Buf1 ; S: =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S ^ . Write ( Buf1 , SizeOf ( Buf1 ) ) ; S ^ . Seek ( 0 ) ;

335

CHAPTER 17. THE OBJECTS UNIT.

For I : = 1 to 1 0 0 0 do Buf1 [ I ] : = 0 ; S ^ . Read ( Buf1 , SizeOf ( Buf1 ) ) ; For I : = 1 to 1 0 0 0 do I f Buf1 [ I ] < > buf2 [ i ] then Writeln ( ’ B u f f e r d i f f e r s at p o s i t i o n Dispose ( S , Done ) ; end .

’ , I );

TStream.Write Declaration: Procedure TStream.Write (Var Buf; Count:

Sw_Word); Virtual;

Description: Write is an abstract method that should be overridden by descendent objects. Write writes Count bytes to the stream from Buf. It updates the position pointer, increasing it’s value with Count. Errors: No checking is done to see if Buf actually contains Count bytes. See also: Read (335), WriteStr (334), StrWrite (334) For an example, see TStream.Read (335).

TStream.CopyFrom Declaration: Procedure TStream.CopyFrom (Var S: TStream; Count:

Longint);

Description: CopyFrom reads Count bytes from stream S and stores them in the current stream. It uses the Read (335) method to read the data, and the Write (336) method to write in the current stream. Errors: None. See also: Read (335), Write (336) Listing: objectex/ex19.pp Program ex19 ; { Program t o demonstrate t h e TStream . CopyFrom f u n c t i o n } Uses o b j e c t s ; Var P : P S t r i n g ; L : String ; S1 , S2 : PStream ; begin L : = ’ Constant s t r i n g l i n e ’ ; W r i t e l n ( ’ W r i t i n g t o stream 1 : " ’ , L , ’ " ’ ) ; S1 : =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S2 : =New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S1 ^ . W r i t e S t r (@L) ; S1 ^ . Seek ( 0 ) ; W r i t e l n ( ’ Copying c o n t e n t s o f stream 1 t o stream 2 ’ ) ; S2 ^ . Copyfrom ( S1 ^ , S1 ^ . GetSize ) ; S2 ^ . Seek ( 0 ) ;

336

CHAPTER 17. THE OBJECTS UNIT.

P: = S2 ^ . ReadStr ; L : =P ^ ; DisposeStr ( P ) ; Dispose ( S1 , Done ) ; Dispose ( S2 , Done ) ; W r i t e l n ( ’ Read from stream 2 : " ’ , L , ’ " ’ ) ; end .

17.7

TDosStream

TDosStream is a stream that stores it’s contents in a file. it overrides a couple of methods of TSteam for this. In addition to the fields inherited from TStream (see section 17.6, page 329), there are some extra fields, that describe the file. (mainly the name and the OS file handle) No buffering in memory is done when using TDosStream. All data are written directly to the file. For a stream that buffers in memory, see section 17.8, page 341. Here is the full declaration of the TDosStream object: TYPE TDosStream = OBJECT (TStream) Handle: THandle; { DOS file handle } FName : AsciiZ; { AsciiZ filename } CONSTRUCTOR Init (FileName: FNameStr; Mode: Word); DESTRUCTOR Done; Virtual; PROCEDURE Close; Virtual; PROCEDURE Truncate; Virtual; PROCEDURE Seek (Pos: LongInt); Virtual; PROCEDURE Open (OpenMode: Word); Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; END; PDosStream = ^TDosStream;

TDosStream.Init Declaration: Constructor Init (FileName:

FNameStr; Mode:

Word);

Description: Init instantiates an instance of TDosStream. The name of the file that contains (or will contain) the data of the stream is given in FileName. The Mode parameter determines whether a new file should be created and what access rights you have on the file. It can be one of the following constants: stCreateCreates a new file. stOpenReadRead access only. stOpenWriteWrite access only. stOpenRead and write access. Errors: On error, Status is set to stInitError, and ErrorInfo is set to the DOS error code. See also: Done (338) For an example, see TDosStream.Truncate (338). 337

CHAPTER 17. THE OBJECTS UNIT.

TDosStream.Done Declaration: Destructor TDosStream.Done; Virtual; Description: Done closes the file if it was open and cleans up the instance of TDosStream. Errors: None. See also: Init (337), Close (338) for an example, see e.g. TDosStream.Truncate (338).

TDosStream.Close Declaration: Pocedure TDosStream.Close; Virtual; Description: Close closes the file if it was open, and sets Handle to -1. Contrary to Done (338) it does not clean up the instance of TDosStream Errors: None. See also: TStream.Close (333), Init (337), Done (338) For an example, see TDosStream.Open (340).

TDosStream.Truncate Declaration: Procedure TDosStream.Truncate; Virtual; Description: If the status of the stream is stOK, then Truncate tries to truncate the stream size to the current file position. Errors: If an error occurs, the stream’s status is set to stError and ErrorInfo is set to the OS error code. See also: TStream.Truncate (334), GetSize (331) Listing: objectex/ex16.pp Program ex16 ; { Program t o demonstrate t h e TStream . Truncate method } Uses O b j e c t s ; Var L : S t r i n g ; P : PString ; S : PDosStream ; { Only one w i t h Truncate implemented . } begin L : = ’Some c o n s t a n t s t r i n g ’ ; { Buffer size of 100 } S: =New( PDosStream , I n i t ( ’ t e s t . d a t ’ , s t c r e a t e ) ) ; W r i t e l n ( ’ W r i t i n g " ’ , L , ’ " t o stream w i t h handle ’ ,S ^ . Handle ) ; S ^ . W r i t e S t r (@L) ; S ^ . W r i t e S t r (@L) ; { Close c a l l s f l u s h f i r s t } S ^ . Close ;

338

CHAPTER 17. THE OBJECTS UNIT.

S ^ . Open ( stOpen ) ; W r i t e l n ( ’ Size o f stream i s : ’ ,S ^ . GetSize ) ; P: =S ^ . ReadStr ; L : =P ^ ; DisposeStr ( P ) ; W r i t e l n ( ’ Read " ’ , L , ’ " from stream w i t h handle ’ ,S ^ . Handle ) ; S ^ . Truncate ; W r i t e l n ( ’ Truncated stream . Size i s : ’ ,S ^ . GetSize ) ; S ^ . Close ; Dispose ( S , Done ) ; end .

TDosStream.Seek Declaration: Procedure TDosStream.Seek (Pos:

LongInt); Virtual;

Description: If the stream’s status is stOK, then Seek sets the file position to Pos. Pos is a zero-based offset, counted from the beginning of the file. Errors: In case an error occurs, the stream’s status is set to stSeekError, and the OS error code is stored in ErrorInfo. See also: TStream.Seek (335), GetPos (331) Listing: objectex/ex17.pp Program ex17 ; { Program t o demonstrate t h e TStream . Seek method } Uses O b j e c t s ; Var L : S t r i n g ; Marker : Word ; P : PString ; S : PDosStream ; begin L : = ’Some c o n s t a n t s t r i n g ’ ; { Buffer size of 100 } S: =New( PDosStream , I n i t ( ’ t e s t . d a t ’ , s t c r e a t e ) ) ; W r i t e l n ( ’ W r i t i n g " ’ , L , ’ " t o stream . ’ ) ; S ^ . W r i t e S t r (@L) ; Marker : =S ^ . GetPos ; W r i t e l n ( ’ Set marker a t ’ , Marker ) ; L : = ’Some o t h e r c o n s t a n t S t r i n g ’ ; W r i t e l n ( ’ W r i t i n g " ’ , L , ’ " t o stream . ’ ) ; S ^ . W r i t e S t r (@L) ; S ^ . Close ; S ^ . Open ( stOpenRead ) ; W r i t e l n ( ’ Size o f stream i s : ’ ,S ^ . GetSize ) ; W r i t e l n ( ’ Seeking t o marker ’ ) ; S ^ . Seek ( Marker ) ; P: =S ^ . ReadStr ; L : =P ^ ; DisposeStr ( P ) ; W r i t e l n ( ’ Read " ’ , L , ’ " from stream . ’ ) ;

339

CHAPTER 17. THE OBJECTS UNIT.

S ^ . Close ; Dispose ( S , Done ) ; end .

TDosStream.Open Declaration: Procedure TDosStream.Open (OpenMode:

Word); Virtual;

Description: If the stream’s status is stOK, and the stream is closed then Open re-opens the file stream with mode OpenMode. This call can be used after a Close (338) call. Errors: If an error occurs when re-opening the file, then Status is set to stOpenError, and the OS error code is stored in ErrorInfo See also: TStream.Open (333), Close (338) Listing: objectex/ex14.pp Program ex14 ; { Program t o demonstrate t h e TStream . Close method } Uses O b j e c t s ; Var L : S t r i n g ; P : PString ; S : PDosStream ; { Only one w i t h Close implemented . } begin L : = ’Some c o n s t a n t s t r i n g ’ ; S: =New( PDosStream , I n i t ( ’ t e s t . d a t ’ , s t c r e a t e ) ) ; W r i t e l n ( ’ W r i t i n g " ’ , L , ’ " t o stream w i t h handle ’ ,S ^ . Handle ) ; S ^ . W r i t e S t r (@L) ; S ^ . Close ; W r i t e l n ( ’ Closed stream . F i l e handle i s ’ ,S ^ . Handle ) ; S ^ . Open ( stOpenRead ) ; P: =S ^ . ReadStr ; L : =P ^ ; DisposeStr ( P ) ; W r i t e l n ( ’ Read " ’ , L , ’ " from stream w i t h handle ’ ,S ^ . Handle ) ; S ^ . Close ; Dispose ( S , Done ) ; end .

TDosStream.Read Declaration: Procedure TDosStream.Read (Var Buf; Count:

Sw_Word); Virtual;

Description: If the Stream is open and the stream status is stOK then Read will read Count bytes from the stream and place them in Buf. Errors: In case of an error, Status is set to StReadError, and ErrorInfo gets the OS specific error, or 0 when an attempt was made to read beyond the end of the stream. See also: TStream.Read (335), Write (341) For an example, see TStream.Read (335). 340

CHAPTER 17. THE OBJECTS UNIT.

TDosStream.Write Declaration: Procedure TDosStream.Write (Var Buf; Count:

Sw_Word); Virtual;

Description: If the Stream is open and the stream status is stOK then Write will write Count bytes from Buf and place them in the stream. Errors: In case of an error, Status is set to StWriteError, and ErrorInfo gets the OS specific error. See also: TStream.Write (336), Read (340) For an example, see TStream.Read (335).

17.8

TBufStream

Bufstream implements a buffered file stream. That is, all data written to the stream is written to memory first. Only when the buffer is full, or on explicit request, the data is written to disk. Also, when reading from the stream, first the buffer is checked if there is any unread data in it. If so, this is read first. If not the buffer is filled again, and then the data is read from the buffer. The size of the buffer is fixed and is set when constructing the file. This is useful if you need heavy throughput for your stream, because it speeds up operations. TYPE TBufStream = OBJECT (TDosStream) LastMode: Byte; { Last buffer mode } BufSize : Sw_Word; { Buffer size } BufPtr : Sw_Word; { Buffer start } BufEnd : Sw_Word; { Buffer end } Buffer : PByteArray; { Buffer allocated } CONSTRUCTOR Init (FileName: FNameStr; Mode, Size: Word); DESTRUCTOR Done; Virtual; PROCEDURE Close; Virtual; PROCEDURE Flush; Virtual; PROCEDURE Truncate; Virtual; PROCEDURE Seek (Pos: LongInt); Virtual; PROCEDURE Open (OpenMode: Word); Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; END; PBufStream = ^TBufStream;

TBufStream.Init Declaration: Constructor Init (FileName:

FNameStr; Mode,Size:

Word);

Description: Init instantiates an instance of TBufStream. The name of the file that contains (or will contain) the data of the stream is given in FileName. The Mode parameter determines whether a new file should be created and what access rights you have on the file. It can be one of the following constants: stCreateCreates a new file. stOpenReadRead access only. stOpenWriteWrite access only. 341

CHAPTER 17. THE OBJECTS UNIT.

stOpenRead and write access. The Size parameter determines the size of the buffer that will be created. It should be different from zero. Errors: On error, Status is set to stInitError, and ErrorInfo is set to the DOS error code. See also: TDosStream.Init (337), Done (342) For an example see TBufStream.Flush (342).

TBufStream.Done Declaration: Destructor TBufStream.Done; Virtual; Description: Done flushes and closes the file if it was open and cleans up the instance of TBufStream. Errors: None. See also: TDosStream.Done (338), Init (341), Close (342) For an example see TBufStream.Flush (342).

TBufStream.Close Declaration: Pocedure TBufStream.Close; Virtual; Description: Close flushes and closes the file if it was open, and sets Handle to -1. Contrary to Done (342) it does not clean up the instance of TBufStream Errors: None. See also: TStream.Close (333), Init (341), Done (342) For an example see TBufStream.Flush (342).

TBufStream.Flush Declaration: Pocedure TBufStream.Flush; Virtual; Description: When the stream is in write mode, the contents of the buffer are written to disk, and the buffer position is set to zero. When the stream is in read mode, the buffer position is set to zero. Errors: Write errors may occur if the file was in write mode. see Write (344) for more info on the errors. See also: TStream.Close (333), Init (341), Done (342) Listing: objectex/ex15.pp Program ex15 ; { Program t o demonstrate t h e TStream . Flush method } Uses O b j e c t s ; Var L : S t r i n g ;

342

CHAPTER 17. THE OBJECTS UNIT.

P : PString ; S : PBufStream ; { Only one w i t h Flush implemented . } begin L : = ’Some c o n s t a n t s t r i n g ’ ; { Buffer size of 100 } S: =New( PBufStream , I n i t ( ’ t e s t . d a t ’ , s t c r e a t e , 1 0 0 ) ) ; W r i t e l n ( ’ W r i t i n g " ’ , L , ’ " t o stream w i t h handle ’ ,S ^ . Handle ) ; S ^ . W r i t e S t r (@L) ; { At t h i s moment , t h e r e i s no data on d i s k y e t . } S ^ . Flush ; { Now t h e r e i s . } S ^ . W r i t e S t r (@L) ; { Close c a l l s f l u s h f i r s t } S ^ . Close ; W r i t e l n ( ’ Closed stream . F i l e handle i s ’ ,S ^ . Handle ) ; S ^ . Open ( stOpenRead ) ; P: =S ^ . ReadStr ; L : =P ^ ; DisposeStr ( P ) ; W r i t e l n ( ’ Read " ’ , L , ’ " from stream w i t h handle ’ ,S ^ . Handle ) ; S ^ . Close ; Dispose ( S , Done ) ; end .

TBufStream.Truncate Declaration: Procedure TBufStream.Truncate; Virtual; Description: If the status of the stream is stOK, then Truncate tries to flush the buffer, and then truncates the stream size to the current file position. Errors: Errors can be those of Flush (342) or TDosStream.Truncate (338). See also: TStream.Truncate (334), TDosStream.Truncate (338), GetSize (331) For an example, see TDosStream.Truncate (338).

TBufStream.Seek Declaration: Procedure TBufStream.Seek (Pos:

LongInt); Virtual;

Description: If the stream’s status is stOK, then Seek sets the file position to Pos. Pos is a zero-based offset, counted from the beginning of the file. Errors: In case an error occurs, the stream’s status is set to stSeekError, and the OS error code is stored in ErrorInfo. See also: TStream.Seek (335), GetPos (331) For an example, see TStream.Seek (335);

TBufStream.Open Declaration: Procedure TBufStream.Open (OpenMode: 343

Word); Virtual;

CHAPTER 17. THE OBJECTS UNIT.

Description: If the stream’s status is stOK, and the stream is closed then Open re-opens the file stream with mode OpenMode. This call can be used after a Close (342) call. Errors: If an error occurs when re-opening the file, then Status is set to stOpenError, and the OS error code is stored in ErrorInfo See also: TStream.Open (333), Close (342) For an example, see TDosStream.Open (340).

TBufStream.Read Declaration: Procedure TBufStream.Read (Var Buf; Count:

Sw_Word); Virtual;

Description: If the Stream is open and the stream status is stOK then Read will read Count bytes from the stream and place them in Buf. Read will first try to read the data from the stream’s internal buffer. If insufficient data is available, the buffer will be filled before contiunuing to read. This process is repeated until all needed data has been read. Errors: In case of an error, Status is set to StReadError, and ErrorInfo gets the OS specific error, or 0 when an attempt was made to read beyond the end of the stream. See also: TStream.Read (335), Write (344) For an example, see TStream.Read (335).

TBufStream.Write Declaration: Procedure TBufStream.Write (Var Buf; Count:

Sw_Word); Virtual;

Description: If the Stream is open and the stream status is stOK then Write will write Count bytes from Buf and place them in the stream. Write will first try to write the data to the stream’s internal buffer. When the internal buffer is full, then the contents will be written to disk. This process is repeated until all data has been written. Errors: In case of an error, Status is set to StWriteError, and ErrorInfo gets the OS specific error. See also: TStream.Write (336), Read (344) For an example, see TStream.Read (335).

17.9

TMemoryStream

The TMemoryStream object implements a stream that stores it’s data in memory. The data is stored on the heap, with the possibility to specify the maximum amout of data, and the the size of the memory blocks being used. TYPE TMemoryStream = BlkCount: BlkSize : MemSize :

OBJECT (TStream) Sw_Word; { Number of segments } Word; { Memory block size } LongInt; { Memory alloc size } 344

CHAPTER 17. THE OBJECTS UNIT.

BlkList : PPointerArray; { Memory block list } CONSTRUCTOR Init (ALimit: Longint; ABlockSize: Word); DESTRUCTOR Done; PROCEDURE Truncate; PROCEDURE Read (Var Buf; Count: Sw_Word); PROCEDURE Write (Var Buf; Count: Sw_Word); END; PMemoryStream = ^TMemoryStream;

Virtual; Virtual; Virtual; Virtual;

TMemoryStream.Init Declaration: Constructor TMemoryStream.Init (ALimit:

Longint; ABlockSize:

Word);

Description: Init instantiates a new TMemoryStream object. The memorystreamobject will initially allocate at least ALimit bytes memory, divided into memory blocks of size ABlockSize. The number of blocks needed to get to ALimit bytes is rounded up. By default, the number of blocks is 1, and the size of a block is 8192. This is selected if you specify 0 as the blocksize. Errors: If the stream cannot allocate the initial memory needed for the memory blocks, then the stream’s status is set to stInitError. See also: Done (345) For an example, see e.g TStream.CopyFrom (336).

TMemoryStream.Done Declaration: Destructor TMemoryStream.Done; Virtual; Description: Done releases the memory blocks used by the stream, and then cleans up the memory used by the stream object itself. Errors: None. See also: Init (345) For an example, see e.g TStream.CopyFrom (336).

TMemoryStream.Truncate Declaration: Procedure TMemoryStream.Truncate; Virtual; Description: Truncate sets the size of the memory stream equal to the current position. It de-allocates any memory-blocks that are no longer needed, so that the new size of the stream is the current position in the stream, rounded up to the first multiple of the stream blocksize. Errors: If an error occurs during memory de-allocation, the stream’s status is set to stError See also: TStream.Truncate (334) Listing: objectex/ex20.pp

345

CHAPTER 17. THE OBJECTS UNIT.

Program ex20 ; { Program t o demonstrate t h e TMemoryStream . Truncate method } Uses O b j e c t s ; Var L : S t r i n g ; P : PString ; S : PMemoryStream ; I , InitMem : L o n g i n t ; begin initMem : = Memavail ; L : = ’Some c o n s t a n t s t r i n g ’ ; { Buffer size of 100 } S: =New( PMemoryStream , I n i t ( 1 0 0 0 , 1 0 0 ) ) ; W r i t e l n ( ’ Free memory : ’ , Memavail ) ; W r i t e l n ( ’ W r i t i n g 1 0 0 t i m e s " ’ , L , ’ " t o stream . ’ ) ; For I : = 1 to 1 0 0 do S ^ . W r i t e S t r (@L) ; W r i t e l n ( ’ F i n i s h e d . Free memory : ’ , Memavail ) ; S ^ . Seek ( 1 0 0 ) ; S ^ . Truncate ; W r i t e l n ( ’ Truncated a t b y t e 1 0 0 . Free memory : ’ , Memavail ) ; Dispose ( S , Done ) ; W r i t e l n ( ’ F i n i s h e d . L o s t ’ , InitMem−Memavail , ’ Bytes . ’ ) ; end .

TMemoryStream.Read Declaration: Procedure Read (Var Buf; Count:

Sw_Word); Virtual;

Description: Read reads Count bytes from the stream to Buf. It updates the position of the stream. Errors: If there is not enough data available, no data is read, and the stream’s status is set to stReadError. See also: TStream.Read, Write (346) For an example, see TStream.Read (335).

TMemoryStream.Write Declaration: Procedure Write (Var Buf; Count:

Sw_Word); Virtual;

Description: Write copies Count bytes from Buf to the stream. It updates the position of the stream. If not enough memory is available to hold the extra Count bytes, then the stream will try to expand, by allocating as much blocks with size BlkSize (as specified in the constuctor call Init (345)) as needed. Errors: If the stream cannot allocate more memory, then the status is set to stWriteError See also: TStream.Write (336), Read (346) For an example, see TStream.Read (335).

346

CHAPTER 17. THE OBJECTS UNIT.

17.10

TCollection

The TCollection object manages a collection of pointers or objects. It also provides a series of methods to manipulate these pointers or objects. Whether or not objects are used depends on the kind of calls you use. ALl kinds come in 2 flavors, one for objects, one for pointers. This is the full declaration of the TCollection object: TYPE TItemList = Array [0..MaxCollectionSize - 1] Of Pointer; PItemList = ^TItemList; TCollection = OBJECT (TObject) Items: PItemList; { Item list pointer } Count: Sw_Integer; { Item count } Limit: Sw_Integer; { Item limit count } Delta: Sw_Integer; { Inc delta size } Constructor Init (ALimit, ADelta: Sw_Integer); Constructor Load (Var S: TStream); Destructor Done; Virtual; Function At (Index: Sw_Integer): Pointer; Function IndexOf (Item: Pointer): Sw_Integer; Virtual; Function GetItem (Var S: TStream): Pointer; Virtual; Function LastThat (Test: Pointer): Pointer; Function FirstThat (Test: Pointer): Pointer; Procedure Pack; Procedure FreeAll; Procedure DeleteAll; Procedure Free (Item: Pointer); Procedure Insert (Item: Pointer); Virtual; Procedure Delete (Item: Pointer); Procedure AtFree (Index: Sw_Integer); Procedure FreeItem (Item: Pointer); Virtual; Procedure AtDelete (Index: Sw_Integer); Procedure ForEach (Action: Pointer); Procedure SetLimit (ALimit: Sw_Integer); Virtual; Procedure Error (Code, Info: Integer); Virtual; Procedure AtPut (Index: Sw_Integer; Item: Pointer); Procedure AtInsert (Index: Sw_Integer; Item: Pointer); Procedure Store (Var S: TStream); Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PCollection = ^TCollection;

TCollection.Init Declaration: Constructor TCollection.Init (ALimit, ADelta:

Sw_Integer);

Description: Init initializes a new instance of a collection. It sets the (initial) maximum number of items in the collection to ALimit. ADelta is the increase size : The number of memory places that will be allocatiod in case ALimit is reached, and another element is added to the collection. Errors: None. 347

CHAPTER 17. THE OBJECTS UNIT.

See also: Load (348), Done (348) For an example, see TCollection.ForEach (358).

TCollection.Load Declaration: Constructor TCollection.Load (Var S: TStream); Description: Load initializes a new instance of a collection. It reads from stream S the item count, the item limit count, and the increase size. After that, it reads the specified number of items from the stream. Errors: Errors returned can be those of GetItem (350). See also: Init (347), GetItem (350), Done (348). Listing: objectex/ex22.pp Program ex22 ; { Program t o demonstrate t h e T C o l l e c t i o n . Load method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C M I S

: : : :

PCollection ; PMyObject ; Longint ; PMemoryStream ;

begin C: =New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d (100− I ) ; C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ I n s e r t e d ’ ,C^ . Count , ’ o b j e c t s ’ ) ; S: =New( PMemorySTream , I n i t ( 1 0 0 0 , 1 0 ) ) ; C^ . S t o r e ( S ^ ) ; C^ . F r e e A l l ; Dispose (C, Done ) ; S ^ . Seek ( 0 ) ; C^ . Load ( S ^ ) ; W r i t e l n ( ’ Read ’ ,C^ . Count , ’ o b j e c t s from stream . ’ ) ; Dispose ( S , Done ) ; Dispose (C, Done ) ; end .

TCollection.Done Declaration: Destructor TCollection.Done; Virtual; Description: Done frees all objects in the collection, and then releases all memory occupied by the instance. Errors: None. See also: Init (347), FreeAll (353) For an example, see TCollection.ForEach (358). 348

CHAPTER 17. THE OBJECTS UNIT.

TCollection.At Declaration: Function TCollection.At (Index:

Sw_Integer):

Pointer;

Description: At returns the item at position Index. Errors: If Index is less than zero or larger than the number of items in the collection, seeplErrorTCollection.Error is called with coIndexError and Index as arguments, resulting in a run-time error. See also: Insert (355) Listing: objectex/ex23.pp Program ex23 ; { Program t o demonstrate t h e T C o l l e c t i o n . At method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; begin C: =New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d (100− I ) ; C^ . I n s e r t (M) ; end ; For I : = 0 to C^ . Count −1 do begin M: =C^ . At ( I ) ; W r i t e l n ( ’ O b j e c t ’ , i , ’ has f i e l d : end ; C^ . F r e e A l l ; Dispose (C, Done ) ; end .

’ ,M^ . G e t F i e l d ) ;

TCollection.IndexOf Declaration: Function TCollection.IndexOf (Item:

Pointer):

Sw_Integer; Virtual;

Description: IndexOf returns the index of Item in the collection. If Item isn’t present in the collection, -1 is returned. Errors: See also: Listing: objectex/ex24.pp Program ex24 ; { Program t o demonstrate t h e T C o l l e c t i o n . IndexOf method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n }

349

CHAPTER 17. THE OBJECTS UNIT.

Var C : P C o l l e c t i o n ; M, Keep : PMyObject ; I : Longint ; begin Randomize ; C: =New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; Keep : = N i l ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); I f Random< 0 . 1 then Keep : =M; C^ . I n s e r t (M) ; end ; I f Keep= N i l then begin W r i t e l n ( ’ Please run again . No o b j e c t s e l e c t e d ’ ) ; Halt ( 1 ) ; end ; W r i t e l n ( ’ S e l e c t e d o b j e c t has f i e l d : ’ , Keep ^ . G e t F i e l d ) ; Write ( ’ S e l e c t e d o b j e c t has i n d e x : ’ ,C^ . IndexOf ( Keep ) ) ; W r i t e l n ( ’ should match i t ’ ’ s f i e l d . ’ ) ; C^ . F r e e A l l ; Dispose (C, Done ) ; end .

TCollection.GetItem Declaration: Function TCollection.GetItem (Var S: TStream):

Pointer; Virtual;

Description: GetItem reads a single item off the stream S, and returns a pointer to this item. This method is used internally by the Load method, and should not be used directly. Errors: Possible errors are the ones from TStream.Get (330). See also: TStream.Get (330), seeplStoreTCollection.Store

TCollection.LastThat Declaration: Function TCollection.LastThat (Test:

Pointer):

Pointer;

Description: This function returns the last item in the collection for which Test returns a non-nil result. Test is a function that accepts 1 argument: a pointer to an object, and that returns a pointer as a result. Errors: None. See also: FirstThat (351) Listing: objectex/ex25.pp Program ex21 ; { Program t o demonstrate t h e T C o l l e c t i o n . Foreach method }

350

CHAPTER 17. THE OBJECTS UNIT.

Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Function CheckField ( Dummy : P o i n t e r ; P : PMyObject ) : L o n g i n t ; begin I f P ^ . G e t F i e l d 56 has i n d e x ( should be 5 6 ) : ’ , C^ . IndexOf (C^ . F i r s t T h a t ( @CheckField ) ) ) ; C^ . F r e e A l l ; Dispose (C, Done ) ; end .

TCollection.Pack Declaration: Procedure TCollection.Pack; Description: Pack removes all Nil pointers from the collection, and adjusts Count to reflect this change. No memory is freed as a result of this call. In order to free any memory, you can call SetLimit with an argument of Count after a call to Pack. Errors: None. See also: SetLimit (359) Listing: objectex/ex26.pp Program ex21 ; { Program t o demonstrate t h e T C o l l e c t i o n . F i r s t T h a t method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Function CheckField ( Dummy : P o i n t e r ; P : PMyObject ) : L o n g i n t ; begin I f P ^ . G e t F i e l d >56 then C h e c k f i e l d :=1 else CheckField : = 0 ; end ; begin C: =New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I : = 1 to 1 0 0 do begin

352

CHAPTER 17. THE OBJECTS UNIT.

M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I ) ; C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ I n s e r t e d ’ ,C^ . Count , ’ o b j e c t s ’ ) ; W r i t e l n ( ’ f i r s t one f o r which F i e l d >56 has i n d e x ( should be 5 6 ) : ’ , C^ . IndexOf (C^ . F i r s t T h a t ( @CheckField ) ) ) ; C^ . F r e e A l l ; Dispose (C, Done ) ; end .

TCollection.FreeAll Declaration: Procedure TCollection.FreeAll; Description: FreeAll calls the destructor of each object in the collection. It doesn’t release any memory occumpied by the collection itself, but it does set Count to zero. Errors: See also: DeleteAll (354), FreeItem (357) Listing: objectex/ex28.pp Program ex28 ; { Program t o demonstrate t h e T C o l l e c t i o n . F r e e A l l method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : L o n g i n t ; begin Randomize ; C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem : = Memavail ; W r i t e l n ( ’ I n i t i a l memory : ’ , InitMem ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ Added 1 0 0 Items . Memory a v a i l a b l e : ’ , Memavail ) ; Write ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Write ( ’ ( Should be 100∗ ’ , SizeOF ( TMyObject ) ) ; W r i t e l n ( ’ = ’ ,100∗ SizeOf ( TMyObject ) , ’ ) ’ ) ; C^ . F r e e A l l ; W r i t e l n ( ’ Freed a l l o b j e c t s . Memory a v a i l a b l e : ’ , Memavail ) ; W r i t e l n ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Dispose (C, Done ) ; end .

353

CHAPTER 17. THE OBJECTS UNIT.

TCollection.DeleteAll Declaration: Procedure TCollection.DeleteAll; Description: DeleteAll deletes all elements from the collection. It just sets the Count variable to zero. Contrary to FreeAll (353), DeletAll doesn’t call the destructor of the objects. Errors: None. See also: FreeAll (353), Delete (355) Listing: objectex/ex29.pp Program ex29 ; { Program t o demonstrate t h e T C o l l e c t i o n . D e l e t e A l l method Compare w i t h example 2 8 , where F r e e A l l i s used . } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : L o n g i n t ; begin Randomize ; C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem : = Memavail ; W r i t e l n ( ’ I n i t i a l memory : ’ , InitMem ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ Added 1 0 0 Items . Memory a v a i l a b l e : ’ , Memavail ) ; Write ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Write ( ’ ( Should be 100∗ ’ , SizeOF ( TMyObject ) ) ; W r i t e l n ( ’ = ’ ,100∗ SizeOf ( TMyObject ) , ’ ) ’ ) ; C^ . D e l e t e A l l ; W r i t e l n ( ’ Deleted a l l o b j e c t s . Memory a v a i l a b l e : ’ , Memavail ) ; W r i t e l n ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Dispose (C, Done ) ; end .

TCollection.Free Declaration: Procedure TCollection.Free (Item:

Pointer);

Description: Free Deletes Item from the collection, and calls the destructor Done of the object. Errors: If the Item is not in the collection, Error will be called with coIndexError. See also: FreeItem (357), Listing: objectex/ex30.pp 354

CHAPTER 17. THE OBJECTS UNIT.

Program ex30 ; { Program t o demonstrate t h e T C o l l e c t i o n . Free method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : L o n g i n t ; begin Randomize ; C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem : = Memavail ; W r i t e l n ( ’ I n i t i a l memory : ’ , InitMem ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ Added 1 0 0 Items . Memory a v a i l a b l e : ’ , Memavail ) ; Write ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Write ( ’ ( Should be 100∗ ’ , SizeOF ( TMyObject ) ) ; W r i t e l n ( ’ = ’ ,100∗ SizeOf ( TMyObject ) , ’ ) ’ ) ; With C^ do While Count >0 do Free ( At ( Count − 1 ) ) ; W r i t e l n ( ’ Freed a l l o b j e c t s . Memory a v a i l a b l e : ’ , Memavail ) ; W r i t e l n ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Dispose (C, Done ) ; end .

TCollection.Insert Declaration: Procedure TCollection.Insert (Item:

Pointer); Virtual;

Description: Insert inserts Item in the collection. TCollection inserts this item at the end, but descendent objects may insert it at another place. Errors: None. See also: AtInsert (359), AtPut (359),

TCollection.Delete Declaration: Procedure TCollection.Delete (Item:

Pointer);

Description: Delete deletes Item from the collection. It doesn’t call the item’s destructor, though. For this the Free (354) call is provided. Errors: If the Item is not in the collection, Error will be called with coIndexError. See also: AtDelete (357),Free (354) Listing: objectex/ex31.pp

355

CHAPTER 17. THE OBJECTS UNIT.

Program ex31 ; { Program t o demonstrate t h e T C o l l e c t i o n . D e l e t e method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : L o n g i n t ; begin Randomize ; C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem : = Memavail ; W r i t e l n ( ’ I n i t i a l memory : ’ , InitMem ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ Added 1 0 0 Items . Memory a v a i l a b l e : ’ , Memavail ) ; Write ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Write ( ’ ( Should be 100∗ ’ , SizeOF ( TMyObject ) ) ; W r i t e l n ( ’ = ’ ,100∗ SizeOf ( TMyObject ) , ’ ) ’ ) ; With C^ do While Count >0 do Delete ( At ( Count − 1 ) ) ; W r i t e l n ( ’ Freed a l l o b j e c t s . Memory a v a i l a b l e : ’ , Memavail ) ; W r i t e l n ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Dispose (C, Done ) ; end .

TCollection.AtFree Declaration: Procedure TCollection.AtFree (Index:

Sw_Integer);

Description: AtFree deletes the item at position Index in the collection, and calls the item’s destructor if it is not Nil. Errors: If Index isn’t valid then Error (359) is called with CoIndexError. See also: Free (354), AtDelete (357) Listing: objectex/ex32.pp Program ex32 ; { Program t o demonstrate t h e T C o l l e c t i o n . AtFree method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : L o n g i n t ; begin Randomize ;

356

CHAPTER 17. THE OBJECTS UNIT.

C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem : = Memavail ; W r i t e l n ( ’ I n i t i a l memory : ’ , InitMem ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ Added 1 0 0 Items . Memory a v a i l a b l e : ’ , Memavail ) ; Write ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Write ( ’ ( Should be 100∗ ’ , SizeOF ( TMyObject ) ) ; W r i t e l n ( ’ = ’ ,100∗ SizeOf ( TMyObject ) , ’ ) ’ ) ; With C^ do While Count >0 do AtFree ( Count −1); W r i t e l n ( ’ Freed a l l o b j e c t s . Memory a v a i l a b l e : ’ , Memavail ) ; W r i t e l n ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Dispose (C, Done ) ; end .

TCollection.FreeItem Declaration: Procedure TCollection.FreeItem (Item:

Pointer); Virtual;

Description: FreeItem calls the destructor of Item if it is not nil. This function is used internally by the TCollection object, and should not be called directly. Errors: None. See also: Free (356), seeplAtFreeTCollection.AtFree

TCollection.AtDelete Declaration: Procedure TCollection.AtDelete (Index:

Sw_Integer);

Description: AtDelete deletes the pointer at position Index in the collection. It doesn’t call the object’s destructor. Errors: If Index isn’t valid then Error (359) is called with CoIndexError. See also: Delete (355) Listing: objectex/ex33.pp Program ex33 ; { Program t o demonstrate t h e T C o l l e c t i o n . A t D e l e t e method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : L o n g i n t ; begin Randomize ;

357

CHAPTER 17. THE OBJECTS UNIT.

C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem : = Memavail ; W r i t e l n ( ’ I n i t i a l memory : ’ , InitMem ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); C^ . I n s e r t (M) ; end ; W r i t e l n ( ’ Added 1 0 0 Items . Memory a v a i l a b l e : ’ , Memavail ) ; Write ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Write ( ’ ( Should be 100∗ ’ , SizeOF ( TMyObject ) ) ; W r i t e l n ( ’ = ’ ,100∗ SizeOf ( TMyObject ) , ’ ) ’ ) ; With C^ do While Count >0 do A t D e l e t e ( Count −1); W r i t e l n ( ’ Freed a l l o b j e c t s . Memory a v a i l a b l e : ’ , Memavail ) ; W r i t e l n ( ’ L o s t : ’ , Initmem−Memavail , ’ b y t e s . ’ ) ; Dispose (C, Done ) ; end .

TCollection.ForEach Declaration: Procedure TCollection.ForEach (Action:

Pointer);

Description: ForEach calls Action for each element in the collection, and passes the element as an argument to Action. Action is a procedural type variable that accepts a pointer as an argument. Errors: None. See also: FirstThat (351), LastThat (350) Listing: objectex/ex21.pp Program ex21 ; { Program t o demonstrate t h e T C o l l e c t i o n . Foreach method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy : P o i n t e r ; P : PMyObject ) ; begin Writeln ( ’ F i e l d : end ;

’ ,P ^ . G e t F i e l d ) ;

begin C: =New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d (100− I ) ; C^ . I n s e r t (M) ;

358

CHAPTER 17. THE OBJECTS UNIT.

end ; W r i t e l n ( ’ I n s e r t e d ’ ,C^ . Count , ’ o b j e c t s ’ ) ; C^ . ForEach ( @ P r i n t F i e l d ) ; C^ . F r e e A l l ; Dispose (C, Done ) ; end .

TCollection.SetLimit Declaration: Procedure TCollection.SetLimit (ALimit:

Sw_Integer); Virtual;

Description: SetLimit sets the maximum number of elements in the collection. ALimit must not be less than Count, and should not be larger than MaxCollectionSize Errors: None. See also: Init (347) For an example, see Pack (352).

TCollection.Error Declaration: Procedure TCollection.Error (Code, Info:

Integer); Virtual;

Description: Error is called by the various TCollection methods in case of an error condition. The default behaviour is to make a call to RunError with an error of 212-Code. This method can be overridden by descendent objects to implement a different error-handling. Errors: See also: Abstract (320)

TCollection.AtPut Declaration: Procedure TCollection.AtPut (Index:

Sw_Integer; Item:

Pointer);

Description: AtPut sets the element at position Index in the collection to Item. Any previous value is overwritten. Errors: If Index isn’t valid then Error (359) is called with CoIndexError. See also: For an example, see Pack (352).

TCollection.AtInsert Declaration: Procedure TCollection.AtInsert (Index:

Sw_Integer; Item:

Pointer);

Description: AtInsert inserts Item in the collection at position Index, shifting all elements by one position. In case the current limit is reached, the collection will try to expand with a call to SetLimit Errors: If Index isn’t valid then Error (359) is called with CoIndexError. If the collection fails to expand, then coOverFlow is passd to Error.

359

CHAPTER 17. THE OBJECTS UNIT.

See also: Insert (355) Listing: objectex/ex34.pp Program ex34 ; { Program t o demonstrate t h e T C o l l e c t i o n . A t I n s e r t method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy : P o i n t e r ; P : PMyObject ) ; begin Writeln ( ’ F i e l d : end ;

’ ,P ^ . G e t F i e l d ) ;

begin Randomize ; C: =New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; W r i t e l n ( ’ I n s e r t i n g 1 0 0 r e c o r d s a t random p l a c e s . ’ ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d ( I −1); I f I =1 then C^ . I n s e r t (M) else With C^ do A t I n s e r t (Random( Count ) ,M) ; end ; W r i t e l n ( ’ Values : ’ ) ; C^ . Foreach ( @ P r i n t F i e l d ) ; Dispose (C, Done ) ; end .

TCollection.Store Declaration: Procedure TCollection.Store (Var S: TStream); Description: Store writes the collection to the stream S. It does this by writeing the current Count, Limit and Delta to the stream, and then writing each item to the stream. The contents of the stream are then suitable for instantiating another collection with Load (348). Errors: Errors returned are those by TStream.Put (334). See also: Load (348), PutItem (361) For an example, see seeplLoadTCollection.Load.

360

CHAPTER 17. THE OBJECTS UNIT.

TCollection.PutItem Declaration: Procedure TCollection.PutItem (Var S: TStream; Item:

Pointer); Virtual;

Description: PutItem writes Item to stream S. This method is used internaly by the TCollection object, and should not be called directly. Errors: Errors are those returned by TStream.Put (334). See also: Store (360), GetItem (350).

17.11

TSortedCollection

TSortedCollection is an abstract class, implementing a sorted collection. You should never use an instance of TSortedCollection directly, instead you should declare a descendent type, and override the Compare (363) method. Because the collection is ordered, TSortedCollection overrides some TCollection methods, to provide faster routines for lookup. The Compare (363) method decides how elements in the collection should be ordered. Since TCollection has no way of knowing how to order pointers, you must override the compare method. Additionally, TCollection provides a means to filter out duplicates. if you set Duplicates to False (the default) then duplicates will not be allowed. Here is the complete declaration of TSortedCollection TYPE TSortedCollection = OBJECT (TCollection) Duplicates: Boolean; { Duplicates flag } Constructor Init (ALimit, ADelta: Sw_Integer); Constructor Load (Var S: TStream); Function KeyOf (Item: Pointer): Pointer; Virtual; Function IndexOf (Item: Pointer): Sw_Integer; Virtual; Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual; Function Search (Key: Pointer; Var Index: Sw_Integer): Boolean;Virtual; Procedure Insert (Item: Pointer); Virtual; Procedure Store (Var S: TStream); END; PSortedCollection = ^TSortedCollection; In the subsequent examples, the following descendent of TSortedCollection is used: Listing: objectex/mysortc.pp Unit MySortC ; Interface Uses O b j e c t s ; Type PMySortedCollection = ^ TMySortedCollection ; T M y S o r t e d C o l l e c t i o n = Object ( T S o r t e d C o l l e c t i o n ) Function Compare ( Key1 , Key2 : P o i n t e r ) : Sw_integer ; v i r t u a l ; end ;

361

CHAPTER 17. THE OBJECTS UNIT.

Implementation Uses MyObject ; Function T M y S o r t e d C o l l e c t i o n . Compare ( Key1 , Key2 : P o i n t e r ) : s w _ i n t e g e r ; begin Compare : = PMyobject ( Key1 ) ^ . G e t F i e l d − PMyObject ( Key2 ) ^ . G e t F i e l d ; end ; end .

TSortedCollection.Init Declaration: Constructor TSortedCollection.Init (ALimit, ADelta:

Sw_Integer);

Description: Init calls the inherited constuctor (see TCollection.Init (347)) and sets the Duplicates flag to false. You should not call this method directly, since TSortedCollection is a abstract class. Instead, the descendent classes should call it via the inherited keyword. Errors: None. See also: Load (362), Done (348) For an example, see

TSortedCollection.Load Declaration: Constructor Load (Var S: TStream); Description: Load calls the inherited constuctor (see TCollection.Load (348)) and reads the Duplicates flag from the stream.. You should not call this method directly, since TSortedCollection is a abstract class. Instead, the descendent classes should call it via the inherited keyword. Errors: None. See also: Init (362), Done (348) For an example, see TCollection.Load (348).

TSortedCollection.KeyOf Declaration: Function TSortedCollection.KeyOf (Item:

Pointer):

Pointer; Virtual;

Description: KeyOf returns the key associated with Item. TSortedCollection returns the item itself as the key, descendent objects can override this method to calculate a (unique) key based on the item passed (such as hash values). Keys are used to sort the objects, they are used to search and sort the items in the collection. If descendent types override this method then it allows possibly for faster search/sort methods based on keys rather than on the objects themselves.

362

CHAPTER 17. THE OBJECTS UNIT.

Errors: None. See also: IndexOf (363), Compare (363).

TSortedCollection.IndexOf Declaration: Function TSortedCollection.IndexOf (Item:

Pointer):

Sw_Integer; Virtual;

Description: IndexOf returns the index of Item in the collection. It searches for the object based on it’s key. If duplicates are allowed, then it returns the index of last object that matches Item. In case Item is not found in the collection, -1 is returned. Errors: None. See also: Search (364), Compare (363). For an example, see TCollection.IndexOf (349)

TSortedCollection.Compare Declaration: Function TSortedCollection.Compare (Key1, Key2: Virtual;

Pointer):

Sw_Integer;

Description: Compare is an abstract method that should be overridden by descendent objects in order to compare two items in the collection. This method is used in the Search (364) method and in the Insert (365) method to determine the ordering of the objects. The function should compare the two keys of items and return the following function results: Result < 0If Key1 is logically before Key2 (Key1 0If Key1 is logically after Key2 (Key1>Key2) Errors: An ’abstract run-time error’ will be generated if you call TSortedCollection.Compare directly. See also: IndexOf (363), Search (364) Listing: objectex/mysortc.pp Unit MySortC ; Interface Uses O b j e c t s ; Type PMySortedCollection = ^ TMySortedCollection ; T M y S o r t e d C o l l e c t i o n = Object ( T S o r t e d C o l l e c t i o n ) Function Compare ( Key1 , Key2 : P o i n t e r ) : Sw_integer ; v i r t u a l ; end ; Implementation Uses MyObject ; Function T M y S o r t e d C o l l e c t i o n . Compare ( Key1 , Key2 : P o i n t e r ) : s w _ i n t e g e r ;

363

CHAPTER 17. THE OBJECTS UNIT.

begin Compare : = PMyobject ( Key1 ) ^ . G e t F i e l d − PMyObject ( Key2 ) ^ . G e t F i e l d ; end ; end .

TSortedCollection.Search Declaration: Function TSortedCollection.Search (Key: Boolean;Virtual;

Pointer; Var Index:

Sw_Integer):

Description: Search looks for the item with key Key and returns the position of the item (if present) in the collection in Index. Instead of a linear search as TCollection does, TSortedCollection uses a binary search based on the keys of the objects. It uses the Compare (363) function to implement this search. If the item is found, Search returns True, otherwise False is returned. Errors: None. See also: IndexOf (349). Listing: objectex/ex36.pp Program ex36 ; { Program t o demonstrate t h e T S o r t e d C o l l e c t i o n . I n s e r t method } Uses Objects , MyObject , MySortC ; { For TMyObject , T M y S o r t e d C o l l e c t i o n d e f i n i t i o n and r e g i s t r a t i o n } Var C : P S o r t e d C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy : P o i n t e r ; P : PMyObject ) ; begin Writeln ( ’ F i e l d : end ;

’ ,P ^ . G e t F i e l d ) ;

begin Randomize ; C: =New( PMySortedCollection , I n i t ( 1 2 0 , 1 0 ) ) ; C^ . D u p l i c a t e s : = True ; W r i t e l n ( ’ I n s e r t i n g 1 0 0 r e c o r d s a t random p l a c e s . ’ ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ; M^ . S e t F i e l d (Random ( 1 0 0 ) ) ; C^ . I n s e r t (M) end ; M: =New( PMyObject , I n i t ) ; Repeat ; Write ( ’ Value t o search f o r ( − 1 s t o p s ) : ’ ) ;

364

CHAPTER 17. THE OBJECTS UNIT.

read ( I ) ; I f I −1 then begin M^ . S e t F i e l d ( i ) ; I f Not C^ . Search ( M, I ) then W r i t e l n ( ’ No such v a l u e found ’ ) else begin Write ( ’ Value ’ , PMyObject (C^ . At ( I ) ) ^ . G e t F i e l d ) ; Writeln ( ’ present at p o s i t i o n ’ , I ) ; end ; end ; U n t i l I =−1; Dispose (M, Done ) ; Dispose (C, Done ) ; end .

TSortedCollection.Insert Declaration: Procedure TSortedCollection.Insert (Item:

Pointer); Virtual;

Description: Insert inserts an item in the collection at the correct position, such that the collection is ordered at all times. You should never use Atinsert (359), since then the collection ordering is not guaranteed. If Item is already present in the collection, and Duplicates is False, the item will not be inserted. Errors: None. See also: AtInsert (359) Listing: objectex/ex35.pp Program ex35 ; { Program t o demonstrate t h e T S o r t e d C o l l e c t i o n . I n s e r t method } Uses Objects , MyObject , MySortC ; { For TMyObject , T M y S o r t e d C o l l e c t i o n d e f i n i t i o n and r e g i s t r a t i o n } Var C : P S o r t e d C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy : P o i n t e r ; P : PMyObject ) ; begin Writeln ( ’ F i e l d : end ;

’ ,P ^ . G e t F i e l d ) ;

begin Randomize ; C: =New( PMySortedCollection , I n i t ( 1 2 0 , 1 0 ) ) ; W r i t e l n ( ’ I n s e r t i n g 1 0 0 r e c o r d s a t random p l a c e s . ’ ) ; For I : = 1 to 1 0 0 do begin M: =New( PMyObject , I n i t ) ;

365

CHAPTER 17. THE OBJECTS UNIT.

M^ . S e t F i e l d (Random ( 1 0 0 ) ) ; C^ . I n s e r t (M) end ; W r i t e l n ( ’ Values : ’ ) ; C^ . Foreach ( @ P r i n t F i e l d ) ; Dispose (C, Done ) ; end .

TSortedCollection.Store Declaration: Procedure TSortedCollection.Store (Var S: TStream); Description: Store writes the collection to the stream S. It does this by calling the inherited TCollection.Store (360), and then writing the Duplicates flag to the stream. After a Store, the collection can be loaded from the stream with the constructor Load (362) Errors: Errors can be those of TStream.Put (334). See also: Load (362) For an example, see TCollection.Load (348).

17.12

TStringCollection

The TStringCollection object manages a sorted collection of pascal strings. To this end, it overrides the Compare (363) method of TSortedCollection, and it introduces methods to read/write strings from a stream. Here is the full declaration of the TStringCollection object: TYPE TStringCollection = OBJECT (TSortedCollection) Function GetItem (Var S: TStream): Pointer; Virtual; Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual; Procedure FreeItem (Item: Pointer); Virtual; Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PStringCollection = ^TStringCollection;

TStringCollection.GetItem Declaration: Function TStringCollection.GetItem (Var S: TStream):

Pointer; Virtual;

Description: GetItem reads a string from the stream S and returns a pointer to it. It doesn’t insert the string in the collection. This method is primarily introduced to be able to load and store the collection from and to a stream. Errors: The errors returned are those of TStream.ReadStr (332). See also: PutItem (368)

366

CHAPTER 17. THE OBJECTS UNIT.

TStringCollection.Compare Declaration: Function TStringCollection.Compare (Key1, Key2: Virtual;

Pointer):

Sw_Integer;

Description: TStringCollection overrides the Compare function so it compares the two keys as if they were pointers to strings. The compare is done case sensitive. It returns the following results: -1if the first string is alphabetically earlier than the second string. 0if the two strings are equal. 1if the first string is alphabetically later than the second string. Errors: None. See also: TSortedCollection.Compare (363) Listing: objectex/ex37.pp Program ex37 ; { Program t o demonstrate t h e T S t r i n g C o l l e c t i o n . Compare method } Uses O b j e c t s ; Var C : P S t r i n g C o l l e c t i o n ; S : String ; I : longint ; begin Randomize ; C: =New( P S t r i n g C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; C^ . D u p l i c a t e s : = True ; { D u p l i c a t e s a l l o w e d } W r i t e l n ( ’ I n s e r t i n g 1 0 0 r e c o r d s a t random p l a c e s . ’ ) ; For I : = 1 to 1 0 0 do begin S t r (Random( 1 0 0 ) ,S ) ; S: = ’ S t r i n g w i t h v a l u e ’ +S ; C^ . I n s e r t ( NewStr ( S ) ) ; end ; For I : = 0 to 9 8 do With C^ do I f Compare ( At ( i ) , At ( I + 1 ) ) = 0 then W r i t e l n ( ’ D u p l i c a t e s t r i n g found a t p o s i t i o n ’ , i ) ; Dispose (C, Done ) ; end .

TStringCollection.FreeItem Declaration: Procedure TStringCollection.FreeItem (Item:

Pointer); Virtual;

Description: TStringCollection overrides FreeItem so that the string pointed to by Item is disposed from memory. Errors: None. See also: TCollection.FreeItem (357)

367

CHAPTER 17. THE OBJECTS UNIT.

TStringCollection.PutItem Declaration: Procedure TStringCollection.PutItem (Var S: TStream; Item: Virtual;

Pointer);

Description: PutItem writes the string pointed to by Item to the stream S. This method is primarily used in the Load and Store methods, and should not be used directly. Errors: Errors are those of TStream.WriteStr (334). See also: GetItem (366)

17.13

TStrCollection

The TStrCollection object manages a sorted collection of null-terminated strings (pchar strings). To this end, it overrides the Compare (363) method of TSortedCollection, and it introduces methods to read/write strings from a stream. Here is the full declaration of the TStrCollection object: TYPE TStrCollection = OBJECT (TSortedCollection) Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual; Function GetItem (Var S: TStream): Pointer; Virtual; Procedure FreeItem (Item: Pointer); Virtual; Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PStrCollection = ^TStrCollection;

TStrCollection.GetItem Declaration: Function TStrCollection.GetItem (Var S: TStream):

Pointer; Virtual;

Description: GetItem reads a null-terminated string from the stream S and returns a pointer to it. It doesn’t insert the string in the collection. This method is primarily introduced to be able to load and store the collection from and to a stream. Errors: The errors returned are those of TStream.StrRead (330). See also: PutItem (369)

TStrCollection.Compare Declaration: Function TStrCollection.Compare (Key1, Key2: Virtual;

Pointer):

Sw_Integer;

Description: TStrCollection overrides the Compare function so it compares the two keys as if they were pointers to strings. The compare is done case sensitive. It returns -1if the first string is alphabetically earlier than the second string. 0if the two strings are equal. 1if the first string is alphabetically later than the second string. Errors: None. 368

CHAPTER 17. THE OBJECTS UNIT.

See also: TSortedCollection.Compare (363) Listing: objectex/ex38.pp Program ex38 ; { Program t o demonstrate t h e T S t r C o l l e c t i o n . Compare method } Uses Objects , S t r i n g s ; Var C S I P

: : : :

PStrCollection ; String ; longint ; Pchar ;

begin Randomize ; C: =New( P S t r C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; C^ . D u p l i c a t e s : = True ; { D u p l i c a t e s a l l o w e d } W r i t e l n ( ’ I n s e r t i n g 1 0 0 r e c o r d s a t random p l a c e s . ’ ) ; For I : = 1 to 1 0 0 do begin S t r (Random( 1 0 0 ) ,S ) ; S: = ’ S t r i n g w i t h v a l u e ’ +S ; P: = S t r A l l o c ( Length ( S ) + 1 ) ; C^ . I n s e r t ( StrPCopy ( P , S ) ) ; end ; For I : = 0 to 9 8 do With C^ do I f Compare ( At ( I ) , At ( I + 1 ) ) = 0 then W r i t e l n ( ’ D u p l i c a t e s t r i n g found a t p o s i t i o n ’ , I ) ; Dispose (C, Done ) ; end .

TStrCollection.FreeItem Declaration: Procedure TStrCollection.FreeItem (Item:

Pointer); Virtual;

Description: TStrCollection overrides FreeItem so that the string pointed to by Item is disposed from memory. Errors: None. See also: TCollection.FreeItem (357)

TStrCollection.PutItem Declaration: Procedure TStrCollection.PutItem (Var S: TStream; Item:

Pointer); Virtual;

Description: PutItem writes the string pointed to by Item to the stream S. This method is primarily used in the Load and Store methods, and should not be used directly. Errors: Errors are those of TStream.StrWrite (334). See also: GetItem (368)

369

CHAPTER 17. THE OBJECTS UNIT.

17.14

TUnSortedStrCollection

The TUnSortedStrCollection object manages an unsorted list of strings. To this end, it overrides the TStringCollection.Insert (??) method to add strings at the end of the collection, rather than in the alphabetically correct position. Take care, the Search (364) and IndexOf (349) methods will not work on an unsorted string collection. Here is the full declaration of the TUnsortedStrCollection object: TYPE TUnSortedStrCollection = OBJECT (TStringCollection) Procedure Insert (Item: Pointer); Virtual; END; PUnSortedStrCollection = ^TUnSortedStrCollection;

TUnSortedStrCollection.Insert Declaration: Procedure TUnSortedStrCollection.Insert (Item:

Pointer); Virtual;

Description: Insert inserts a string at the end of the collection, instead of on it’s alphabetical place, resulting in an unsorted collection of strings. Errors: See also: Listing: objectex/ex39.pp Program ex39 ; { Program t o demonstrate t h e T U n s o r t e d S t r C o l l e c t i o n . I n s e r t method } Uses Objects , S t r i n g s ; Var C S I P

: : : :

PUnsortedStrCollection ; String ; longint ; Pchar ;

begin Randomize ; C: =New( P U n s o r t e d S t r C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; W r i t e l n ( ’ I n s e r t i n g 1 0 0 r e c o r d s a t random p l a c e s . ’ ) ; For I : = 1 to 1 0 0 do begin S t r (Random( 1 0 0 ) ,S ) ; S: = ’ S t r i n g w i t h v a l u e ’ +S ; C^ . I n s e r t ( NewStr ( S ) ) ; end ; For I : = 0 to 9 9 do W r i t e l n ( I : 2 , ’ : ’ , P S t r i n g (C^ . At ( i ) ) ^ ) ; Dispose (C, Done ) ; end .

370

CHAPTER 17. THE OBJECTS UNIT.

17.15

TResourceCollection

A TResourceCollection manages a collection of resource names. It stores the position and the size of a resource, as well as the name of the resource. It stores these items in records that look like this: TYPE TResourceItem = packed RECORD Posn: LongInt; Size: LongInt; Key : String; End; PResourceItem = ^TResourceItem; It overrides some methods of TStringCollection in order to accomplish this. Remark that the TResourceCollection manages the names of the resources and their assiciated positions and sizes, it doesn’t manage the resources themselves. Here is the full declaration of the TResourceCollection object: TYPE TResourceCollection = OBJECT (TStringCollection) Function KeyOf (Item: Pointer): Pointer; Virtual; Function GetItem (Var S: TStream): Pointer; Virtual; Procedure FreeItem (Item: Pointer); Virtual; Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PResourceCollection = ^TResourceCollection;

TResourceCollection.KeyOf Declaration: Function TResourceCollection.KeyOf (Item:

Pointer):

Pointer; Virtual;

Description: KeyOf returns the key of an item in the collection. For resources, the key is a pointer to the string with the resource name. Errors: None. See also: TStringCollection.Compare (367)

TResourceCollection.GetItem Declaration: Function TResourceCollection.GetItem (Var S: TStream):

Pointer; Virtual;

Description: GetItem reads a resource item from the stream S. It reads the position, size and name from the stream, in that order. It DOES NOT read the resource itself from the stream. The resulting item is not inserted in the collection. This call is manly for internal use by the TCollection.Load (348) method. Errors: Errors returned are those by TStream.Read (335) See also: TCollection.Load (348), TStream.Read (335)

371

CHAPTER 17. THE OBJECTS UNIT.

TResourceCollection.FreeItem Declaration: Procedure TResourceCollection.FreeItem (Item:

Pointer); Virtual;

Description: FreeItem releases the memory occupied by Item. It de-allocates the name, and then the resourceitem record. It does NOT remove the item from the collection. Errors: None. See also: TCollection.FreeItem (357)

TResourceCollection.PutItem Declaration: Procedure TResourceCollection.PutItem (Var S: TStream; Item: Virtual;

Pointer);

Description: PutItem writes Item to the stream S. It does this by writing the position and size and name of the resource item to the stream. This method is used primarily by the Store (360) method. Errors: Errors returned are those by TStream.Write (336). See also: Store (360)

17.16

TResourceFile

TYPE TResourceFile = OBJECT (TObject) Stream : PStream; { File as a stream } Modified: Boolean; { Modified flag } Constructor Init (AStream: PStream); Destructor Done; Virtual; Function Count: Sw_Integer; Function KeyAt (I: Sw_Integer): String; Function Get (Key: String): PObject; Function SwitchTo (AStream: PStream; Pack: Boolean): PStream; Procedure Flush; Procedure Delete (Key: String); Procedure Put (Item: PObject; Key: String); END; PResourceFile = ^TResourceFile;

TResourceFile Fields TResourceFile has the following fields: Stream contains the (file) stream that has the executable image and the resources. It can be initialized by the Init (373) constructor call. Modified is set to True if one of the resources has been changed. It is set by the SwitchTo (373), Delete (374) and Put (374) methods. Calling Flush (374) will clear the Modified flag.

372

CHAPTER 17. THE OBJECTS UNIT.

TResourceFile.Init Declaration: Constructor TResourceFile.Init (AStream:

PStream);

Description: Init instantiates a new instance of a TResourceFile object. If AStream is not nil then it is considered as a stream describing an executable image on disk. Init will try to position the stream on the start of the resources section, and read all resources from the stream. Errors: None. See also: Done (373)

TResourceFile.Done Declaration: Destructor TResourceFile.Done; Virtual; Description: Done cleans up the instance of the TResourceFile Object. If Stream was specified at initialization, then Stream is disposed of too. Errors: None. See also: Init (373)

TResourceFile.Count Declaration: Function TResourceFile.Count:

Sw_Integer;

Description: Count returns the number of resources. If no resources were read, zero is returned. Errors: None. See also: Init (373)

TResourceFile.KeyAt Declaration: Function TResourceFile.KeyAt (I: Sw_Integer):

String;

Description: KeyAt returns the key (the name) of the I-th resource. Errors: In case I is invalid, TCollection.Error will be executed. See also: Get (373)

TResourceFile.Get Declaration: Function TResourceFile.Get (Key:

String):

PObject;

Description: Get returns a pointer to a instance of a resource identified by Key. If Key cannot be found in the list of resources, then Nil is returned. Errors: Errors returned may be those by TStream.Get See also:

373

CHAPTER 17. THE OBJECTS UNIT.

TResourceFile.SwitchTo Declaration: Function TResourceFile.SwitchTo (AStream: PStream;

PStream; Pack:

Boolean):

Description: SwitchTo switches to a new stream to hold the resources in. AStream will be the new stream after the call to SwitchTo. If Pack is true, then all the known resources will be copied from the current stream to the new stream (AStream). If Pack is False, then only the current resource is copied. The return value is the value of the original stream: Stream. The Modified flag is set as a consequence of this call. Errors: Errors returned can be those of TStream.Read (335) and TStream.Write (336). See also: Flush (374)

TResourceFile.Flush Declaration: Procedure TResourceFile.Flush; Description: If the Modified flag is set to True, then Flush writes the resources to the stream Stream. It sets the Modified flag to true after that. Errors: Errors can be those by TStream.Seek (335) and TStream.Write (336). See also: SwitchTo (374)

TResourceFile.Delete Declaration: Procedure TResourceFile.Delete (Key:

String);

Description: Delete deletes the resource identified by Key from the collection. It sets the Modified flag to true. Errors: None. See also: Flush (374)

TResourceFile.Put Declaration: Procedure TResourceFile.Put (Item:

PObject; Key:

String);

Description: Put sets the resource identified by Key to Item. If no such resource exists, a new one is created. The item is written to the stream. Errors: Errors returned may be those by TStream.Put (334) and TStream.Seek See also: Get (373)

17.17

TStringList

A TStringList object can be used to read a collection of strings stored in a stream. If you register this object with the RegisterType (320) function, you cannot register the TStrListMaker object. This is the public declaration of the TStringList object: 374

CHAPTER 17. THE OBJECTS UNIT.

TYPE TStrIndexRec = Packed RECORD Key, Count, Offset: Word; END; TStrIndex = Array [0..9999] Of TStrIndexRec; PStrIndex = ^TStrIndex; TStringList = OBJECT (TObject) Constructor Load (Var S: TStream); Destructor Done; Virtual; Function Get (Key: Sw_Word): String; END; PStringList = ^TStringList;

TStringList.Load Declaration: Constructor TstringList.Load (Var S: TStream); Description: The Load constructor reads the TStringList object from the stream S. It also reads the descriptions of the strings from the stream. The string descriptions are stored as an array of TstrIndexrec records, where each record describes a string on the stream. These records are kept in memory. Errors: If an error occurs, a stream error is triggered. See also: Done (375)

TStringList.Done Declaration: Destructor TstringList.Done; Virtual; Description: The Done destructor frees the memory occupied by the string descriptions, and destroys the object. Errors: None. See also: Load (375), TObject.Done (328)

TStringList.Get Declaration: Function TStringList.Get (Key:

Sw_Word):

String;

Description: Get reads the string with key Key from the list of strings on the stream, and returns this string. If there is no string with such a key, an empty string is returned. Errors: If no string with key Key is found, an empty string is returned. A stream error may result if the stream doesn’t contain the needed strings. See also: TStrListMaker.Put (376)

17.18

TStrListMaker

The TStrListMaker object can be used to generate a stream with strings, which can be read with the TStringList object. If you register this object with the RegisterType (320) function, you cannot register the TStringList object. This is the public declaration of the TStrListMaker object: 375

CHAPTER 17. THE OBJECTS UNIT.

TYPE TStrListMaker = OBJECT (TObject) Constructor Init (AStrSize, AIndexSize: Sw_Word); Destructor Done; Virtual; Procedure Put (Key: SwWord; S: String); Procedure Store (Var S: TStream); END; PStrListMaker = ^TStrListMaker;

TStrListMaker.Init Declaration: Constructor TStrListMaker.Init (AStrSize, AIndexSize:

SwWord);

Description: The Init constructor creates a new instance of the TstrListMaker object. It allocates AStrSize bytes on the heap to hold all the strings you wish to store. It also allocates enough room for AIndexSize key description entries (of the type TStrIndexrec). AStrSize must be large enough to contain all the strings you wish to store. If not enough memory is allocated, other memory will be overwritten. The same is true for AIndexSize : maximally AIndexSize strings can be written to the stream. Errors: None. See also: TObject.Init (328), Done (376)

TStrListMaker.Done Declaration: Destructor TStrListMaker.Done; Virtual; Description: The Done destructor de-allocates the memory for the index description records and the string data, and then destroys the object. Errors: None. See also: TObject.Done (328), Init (376)

TStrListMaker.Put Declaration: Procedure TStrListMaker.Put (Key:

Sw_Word; S: String);

Description: Put adds they string S with key Key to the collection of strings. This action doesn’t write the string to a stream. To write the strings to the stream, see the Store (376) method. Errors: None. See also: Store (376).

TStrListMaker.Store Declaration: Procedure TStrListMaker.Store (Var S: TStream); Description: Store writes the collection of strings to the stream S. The collection can then be read with the TStringList object. Errors: A stream error may occur when writing the strings to the stream. See also: TStringList.Load (375), Put (376).

376

Chapter 18

The PORTS unit 18.1

Introduction

The ports unit implements the port constructs found in Turbo Pascal. It uses classes and default array properties to do this. The unit exists on LINUX, OS /2 and DOS. It is implemented only for compatibility with Turbo Pascal. It’s usage is discouraged, because using ports is not portable programming, and the operating system may not even allow it (for instance W INDOWS). Under LINUX, your program must be run as root, or the IOPerm call must be set in order to set appropriate permissions on the port access.

18.2

Types,constants and variables

Types The following types are defined to implement the port access. tport = class protected procedure writeport(p : longint;data : byte); function readport(p : longint) : byte; public property pp[w : longint] : byte read readport write writeport;default; end; tportw = class protected procedure writeport(p : longint;data : word); function readport(p : longint) : word; public property pp[w : longint] : word read readport write writeport;default; end; tportl = class Protected procedure writeport(p : longint;data : longint); function readport(p : longint) : longint; 377

CHAPTER 18. THE PORTS UNIT

Public property pp[w : Longint] : longint read readport write writeport;default; end; Each of these types allows access to the ports using respectively, a byte, a word or a longint sized argument. Since there is a default property for each of this types, a sentence as port[221]:=12; Will result in the byte 12 being written to port 221, if port is defined as a variable of type tport

variables The following variables are defined: port, portb : tport; portw : tportw; portl : tportl; They allow access to the ports in a Turbo Pascal compatible way.

378

Chapter 19

The PRINTER unit. This chapter describes the PRINTER unit for Free Pascal. It was written for DOS by Florian Klämpfl, and it was written for LINUX by Michaël Van Canneyt, and has been ported to W INDOWS and OS /2 as well. Its basic functionality is the same for al supported systems, although there are minor differences on LINUX. The chapter is divided in 2 sections: • The first section lists types, constants and variables from the interface part of the unit. • The second section describes the functions defined in the unit.

19.1

Types, Constants and variables :

var lst : text; Lst is the standard printing device. On LINUX, Lst is set up using AssignLst(’/tmp/PID.lst’). You can change this behaviour at compile time, setting the DefFile constant.

19.2

Procedures and functions

AssignLst Declaration: Procedure AssignLst ( Var F : text; ToFile :

string[255]);

Description: LINUX only. Assigns to F a printing device. ToFile is a string with the following form: • ’|filename options’ : This sets up a pipe with the program filename, with the given options, such as in the popen() call. • ’filename’ : Prints to file filename. Filename can contain the string ’PID’ (No Quotes), which will be replaced by the PID of your program. When closing lst, the file will be sent to lpr and deleted. (lpr should be in PATH) •’filename|’ Idem as previous, only the file is NOT sent to lpr, nor is it deleted. (useful for opening /dev/printer or for later printing)

379

CHAPTER 19. THE PRINTER UNIT.

Errors: Errors are reported in Linuxerror. See also: lpr (1) Listing: printex/printex.pp program t e s t p r n ; uses p r i n t e r ; var i : i n t e g e r ; f : text ; begin w r i t e l n ( ’ Test o f p r i n t e r u n i t ’ ) ; writeln ( ’ Writing to l s t . . . ’ ) ; f o r i : = 1 to 8 0 do w r i t e l n ( l s t , ’ T h i s i s l i n e ’ , i , ’ . ’ # 1 3 ) ; close ( l s t ) ; w r i t e l n ( ’ Done . ’ ) ; { $ i f d e f Unix } writeln ( ’ W r i t i n g to pipe . . . ’ ) ; a s s i g n l s t ( f , ’ | / u s r / b i n / l p r −m ’ ) ; rewrite ( f ) ; f o r i : = 1 to 8 0 do w r i t e l n ( f , ’ T h i s i s l i n e ’ , i , ’ . ’ # 1 3 ) ; close ( f ) ; w r i t e l n ( ’ Done . ’ ) { $endif } end .

380

Chapter 20

The SOCKETS unit. This chapter describes the SOCKETS unit for Free Pascal. it was written for LINUX by Michaël Van Canneyt, and ported to W INDOWS by Florian Klämpfl. The chapter is divided in 2 sections: • The first section lists types, constants and variables from the interface part of the unit. • The second section describes the functions defined in the unit.

20.1

Types, Constants and variables :

The following constants identify the different socket types, as needed in the Socket (391) call. SOCK_STREAM SOCK_DGRAM SOCK_RAW SOCK_RDM SOCK_SEQPACKET SOCK_PACKET

= 1; = 2; = 3; = 4; = 5; =10;

{ { { { {

stream (connection) socket datagram (conn.less) socket raw socket reliably-delivered message sequential packet socket

} } } } }

The following constants determine the socket domain, they are used in the Socket (391) call. AF_UNSPEC AF_UNIX AF_INET AF_AX25 AF_IPX AF_APPLETALK AF_NETROM AF_BRIDGE AF_AAL5 AF_X25 AF_INET6 AF_MAX

= = = = = = = = = = = =

0; 1; { Unix domain sockets 2; { Internet IP Protocol 3; { Amateur Radio AX.25 4; { Novell IPX 5; { Appletalk DDP 6; { Amateur radio NetROM 7; { Multiprotocol bridge 8; { Reserved for Werner’s ATM 9; { Reserved for X.25 project 10; { IP version 6 12;

} } } } } } } } } }

The following constants determine the protocol family, they are used in the Socket (391) call. PF_UNSPEC PF_UNIX

= AF_UNSPEC; = AF_UNIX; 381

CHAPTER 20. THE SOCKETS UNIT.

PF_INET PF_AX25 PF_IPX PF_APPLETALK PF_NETROM PF_BRIDGE PF_AAL5 PF_X25 PF_INET6 PF_MAX

= = = = = = = = = =

AF_INET; AF_AX25; AF_IPX; AF_APPLETALK; AF_NETROM; AF_BRIDGE; AF_AAL5; AF_X25; AF_INET6; AF_MAX;

The following types are used to store different kinds of eddresses for the Bind (384), Recv (389) and Send (389) calls. TSockAddr = packed Record family:word; data :array [0..13] of char; end; TUnixSockAddr = packed Record family:word; path:array[0..108] of char; end; TInetSockAddr = packed Record family:Word; port :Word; addr :Cardinal; pad :array [1..8] of byte; end; The following type is returned by the SocketPair (391) call. TSockArray = Array[1..2] of Longint;

20.2

Functions and Procedures

Accept Declaration: Function Accept (Sock:Longint;Var Addr;Var Addrlen:Longint) :

Longint;

Description: Accept accepts a connection from a socket Sock, which was listening for a connection. If a connection is accepted, a file descriptor is returned. On error -1 is returned. The returned socket may NOT be used to accept more connections. The original socket remains open. The Accept call fills the address of the connecting entity in Addr, and sets its length in Addrlen. Addr should be pointing to enough space, and Addrlen should be set to the amount of space available, prior to the call. Errors: On error, -1 is returned, and errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EOPNOTSUPPThe socket type doesn’t support the Listen operation. SYS_EFAULTAddr points outside your address space.

382

CHAPTER 20. THE SOCKETS UNIT.

SYS_EWOULDBLOCKThe requested operation would block the process. See also: Listen (388), Connect (385) Listing: sockex/socksvr.pp Program s e r v e r ; { Program t o t e s t Sockets u n i t by Michael van Canneyt and P e t e r Vreman Server Version , F i r s t Run sock_svr t o l e t i t c r e a t e a s o c k e t and then s o c k _ c l i t o connect t o t h a t s o c k e t } uses BaseUnix , Sockets ; const SPath= ’ ServerSoc ’ ; Var FromName Buffer S Sin , Sout

: : : :

string ; string [ 2 5 5 ] ; Longint ; Text ;

procedure p e r r o r ( const S : s t r i n g ) ; begin writeln ( S, SocketError ) ; halt (100); end ;

begin S: = Socket ( AF_UNIX ,SOCK_STREAM, 0 ) ; i f S o c k e t E r r o r < >0 then P e r r o r ( ’ Server : Socket : ’ ) ; fpUnLink ( SPath ) ; i f not Bind ( S , SPath ) then P E r r o r ( ’ Server : Bind : ’ ) ; i f not L i s t e n ( S , 1 ) then P E r r o r ( ’ Server : L i s t e n : ’ ) ; W r i t e l n ( ’ W a i t i n g f o r Connect from C l i e n t , run now s o c k _ c l i i n an o t h e r t t y ’ ) ; i f not Accept ( S , FromName , Sin , Sout ) then P E r r o r ( ’ Server : Accept : ’ +fromname ) ; Reset ( Sin ) ; ReWrite ( Sout ) ; W r i t e l n ( Sout , ’ Message From Server ’ ) ; Flush ( SOut ) ; while not eof ( sin ) do begin Readln ( Sin , B u f f e r ) ; W r i t e l n ( ’ Server : read : ’ , b u f f e r ) ; end ; FPUnlink ( SPath ) ; end .

383

CHAPTER 20. THE SOCKETS UNIT.

Accept Declaration: Function Accept (Sock:longint;var addr:string;var SockIn,SockOut:text) : Boolean; Description: This is an alternate form of the Accept (382) command. It is equivalent to subsequently calling the regular Accept (382) function and the Sock2Text (391) function. The function returns True if successfull, False otherwise. Errors: The errors are those of Accept (382). See also: Accept (382)

Accept Declaration: Function Accept (Sock:longint;var addr:string;var SockIn,SockOut:File) : Boolean; Description: This is an alternate form of the Accept (382) command. It is equivalent to subsequently calling the regular Accept (382) function and the Sock2File (390) function. The Addr parameter contains the name of the unix socket file to be opened. The function returns True if successfull, False otherwise. Errors: The errors are those of Accept (382). See also: Accept (382)

Accept Declaration: Function Accept (Sock:longint;var addr:TInetSockAddr;var SockIn,SockOut:File) : Boolean; Description: This is an alternate form of the Accept (382) command. It is equivalent to subsequently calling the regular Accept (382) function and the Sock2File (390) function. The Addr parameter contains the parameters of the internet socket that should be opened. The function returns True if successfull, False otherwise. Errors: The errors are those of Accept (382). See also: Accept (382)

Bind Declaration: Function Bind (Sock:Longint;Var Addr;AddrLen:Longint) :

Boolean;

Description: Bind binds the socket Sock to address Addr. Addr has length Addrlen. The function returns True if the call was succesful, False if not. Errors: Errors are returned in SocketError and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_EINVALThe socket is already bound to an address, SYS_EACCESSAddress is protected and you don’t have permission to open it. More arrors can be found in the Unix man pages. See also: Socket (391) 384

CHAPTER 20. THE SOCKETS UNIT.

Bind Declaration: Function Bind (Sock:longint;const addr:string) :

boolean;

Description: This is an alternate form of the Bind command. This form of the Bind command is equivalent to subsequently calling Str2UnixSockAddr (391) and the regular Bind (384) function. The function returns True if successfull, False otherwise. Errors: Errors are those of the regular Bind (384) command. See also: Bind (384)

Connect Declaration: Function Connect (Sock:Longint;Var Addr;Addrlen:Longint) :

Longint;

Description: Connect opens a connection to a peer, whose address is described by Addr. AddrLen contains the length of the address. The type of Addr depends on the kind of connection you’re trying to make, but is generally one of TSockAddr or TUnixSockAddr. The Connect function returns a file descriptor if the call was successfull, -1 in case of error. Errors: On error, -1 is returned and errors are reported in SocketError. See also: Listen (388), Bind (384),Accept (382) Listing: sockex/sockcli.pp Program C l i e n t ; { Program t o t e s t Sockets u n i t by Michael van Canneyt and P e t e r Vreman C l i e n t Version , F i r s t Run sock_svr t o l e t i t c r e a t e a s o c k e t and then s o c k _ c l i t o connect t o t h a t s o c k e t } uses Sockets , L i n u x ; procedure P E r r o r ( const S : s t r i n g ) ; begin writeln (S, SocketError ) ; halt (100); end ;

Var Saddr : String [ 2 5 ] ; Buffer : string [ 2 5 5 ] ; S : Longint ; Sin , Sout : Text ; i : integer ; begin S: = Socket ( AF_UNIX ,SOCK_STREAM, 0 ) ; i f S o c k e t E r r o r < >0 then P e r r o r ( ’ C l i e n t : Socket : ’ ) ; Saddr : = ’ ServerSoc ’ ; i f not Connect ( S , SAddr , Sin , Sout ) then P E r r o r ( ’ C l i e n t : Connect : ’ ) ; Reset ( Sin ) ;

385

CHAPTER 20. THE SOCKETS UNIT.

ReWrite ( Sout ) ; B u f f e r : = ’ T h i s i s a t e x t s t r i n g s e n t by t h e C l i e n t . ’ ; f o r i : = 1 to 1 0 do W r i t e l n ( Sout , B u f f e r ) ; Flush ( Sout ) ; Readln ( SIn , B u f f e r ) ; WriteLn ( B u f f e r ) ; Close ( s o u t ) ; end .

Connect Declaration: Function Connect (Sock:longint;const addr:string;var SockIn,SockOut:text) : Boolean; Description: This is an alternate form of the Connect (385) command. It is equivalent to subsequently calling the regular Connect (385) function and the Sock2Text (391) function. The function returns True if successfull, False otherwise. Errors: The errors are those of Connect (385). See also: Connect (385)

Connect Declaration: Function Connect (Sock:longint;const addr:string;var SockIn,SockOut:file) : Boolean; Description: This is an alternate form of the Connect (385) command. The parameter addr contains the name of the unix socket file to be opened. It is equivalent to subsequently calling the regular Connect (385) function and the Sock2File (390) function. The function returns True if successfull, False otherwise. Errors: The errors are those of Connect (385). See also: Connect (385)

Connect Declaration: Function Connect (Sock:longint;const addr: : Boolean;

TInetSockAddr;var SockIn,SockOut:file)

Description: This is another alternate form of the Connect (385) command. It is equivalent to subsequently calling the regular Connect (385) function and the Sock2File (390) function. The Addr parameter contains the parameters of the internet socket to connect to. The function returns True if successfull, False otherwise. Errors: The errors are those of Connect (385). See also: Connect (385) Listing: sockex/pfinger.pp

386

CHAPTER 20. THE SOCKETS UNIT.

program p f i n g e r ; uses sockets , e r r o r s ; Var Addr : TInetSockAddr ; S : Longint ; Sin , Sout : Text ; Line : string ; begin Addr . f a m i l y : = AF_INET ; { p o r t 7 9 i n network o r d e r } Addr . p o r t : = 7 9 shl 8 ; { l o c a l h o s t : 1 2 7 . 0 . 0 . 1 i n network o r d e r } Addr . addr : = ( ( 1 shl 2 4 ) or 1 2 7 ) ; S: = Socket ( AF_INET ,SOCK_STREAM, 0 ) ; I f Not Connect ( S ,ADDR, SIN ,SOUT ) Then begin W r i t e l n ( ’ Couldn ’ ’ t connect t o l o c a l h o s t ’ ) ; W r i t e l n ( ’ Socket e r r o r : ’ , s t r e r r o r ( S o c k e t E r r o r ) ) ; halt ( 1 ) ; end ; rewrite ( sout ) ; r e s e t ( sin ) ; w r i t e l n ( sout , paramstr ( 1 ) ) ; flush ( sout ) ; while not eof ( sin ) do begin readln ( Sin , l i n e ) ; writeln ( l i n e ) ; end ; Shutdown ( s , 2 ) ; c l o s e ( sin ) ; close ( sout ) ; end .

GetPeerName Declaration: Function GetPeerName (Sock:Longint;Var Addr;Var Addrlen:Longint) : Description: GetPeerName returns the name of the entity connected to the specified socket Sock. The Socket must be connected for this call to work. Addr should point to enough space to store the name, the amount of space pointed to should be set in Addrlen. When the function returns succesfully, Addr will be filled with the name, and Addrlen will be set to the length of Addr. Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOBUFSThe system doesn’t have enough buffers to perform the operation. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EFAULTAddr points outside your address space. SYS_ENOTCONNThe socket isn’t connected. See also: Connect (385), Socket (391), connect (2)

387

Longint;

CHAPTER 20. THE SOCKETS UNIT.

GetSocketName Declaration: Function GetSocketName (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint; Description: GetSockName returns the current name of the specified socket Sock. Addr should point to enough space to store the name, the amount of space pointed to should be set in Addrlen. When the function returns succesfully, Addr will be filled with the name, and Addrlen will be set to the length of Addr. Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOBUFSThe system doesn’t have enough buffers to perform the operation. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EFAULTAddr points outside your address space. See also: Bind (384)

GetSocketOptions Declaration: Function GetSocketOptions (Sock,Level,OptName:Longint;Var OptVal;optlen:longint) : Longint; Description: GetSocketOptions gets the connection options for socket Sock. The socket may be obtained from different levels, indicated by Level, which can be one of the following: SOL_SOCKETFrom the socket itself. XXXset Level to XXX, the protocol number of the protocol which should interprete the option. For more information on this call, refer to the unix manual page getsockopt (2) . Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EFAULTOptVal points outside your address space. See also: GetSocketOptions (388)

Listen Declaration: Function Listen (Sock,MaxConnect:Longint) :

Boolean;

Description: Listen listens for up to MaxConnect connections from socket Sock. The socket Sock must be of type SOCK_STREAM or Sock_SEQPACKET. The function returns True if a connection was accepted, False if an error occurred. Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EOPNOTSUPPThe socket type doesn’t support the Listen operation. See also: Socket (391), Bind (384), Connect (385)

388

CHAPTER 20. THE SOCKETS UNIT.

Recv Declaration: Function Recv (Sock:Longint;Var Addr;AddrLen,Flags:Longint) :

Longint;

Description: Recv reads at most Addrlen bytes from socket Sock into address Addr. The socket must be in a connected state. Flags can be one of the following: 1: Process out-of band data. 4: Bypass routing, use a direct interface. ??: Wait for full request or report an error. The functions returns the number of bytes actually read from the socket, or -1 if a detectable error occurred. Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTCONNThe socket isn’t connected. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EFAULTThe address is outside your address space. SYS_EMSGSIZEThe message cannot be sent atomically. SYS_EWOULDBLOCKThe requested operation would block the process. SYS_ENOBUFSThe system doesn’t have enough free buffers available. See also: Send (389)

Send Declaration: Function Send (Sock:Longint;Var Addr;AddrLen,Flags:Longint) :

Longint;

Description: Send sends AddrLen bytes starting from address Addr to socket Sock. Sock must be in a connected state. The function returns the number of bytes sent, or -1 if a detectable error occurred. Flags can be one of the following: 1: Process out-of band data. 4: Bypass routing, use a direct interface. Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EFAULTThe address is outside your address space. SYS_EMSGSIZEThe message cannot be sent atomically. SYS_EWOULDBLOCKThe requested operation would block the process. SYS_ENOBUFSThe system doesn’t have enough free buffers available. See also: Recv (389), send (2)

389

CHAPTER 20. THE SOCKETS UNIT.

SetSocketOptions Declaration: Function SetSocketOptions (Sock,Level,OptName:Longint;Var OptVal;optlen:longint) : Longint; Description: SetSocketOptions sets the connection options for socket Sock. The socket may be manipulated at different levels, indicated by Level, which can be one of the following: SOL_SOCKETTo manipulate the socket itself. XXXset Level to XXX, the protocol number of the protocol which should interprete the option. For more information on this call, refer to the unix manual page setsockopt (2) . Errors: Errors are reported in SocketError, and include the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTSOCKThe descriptor is not a socket. SYS_EFAULTOptVal points outside your address space. See also: GetSocketOptions (388)

Shutdown Declaration: Function Shutdown (Sock:Longint;How:Longint) :

Longint;

Description: ShutDown closes one end of a full duplex socket connection, described by Sock. How determines how the connection will be shut down, and can be one of the following: 0: Further receives are disallowed. 1: Further sends are disallowed. 2: Sending nor receiving are allowed. On succes, the function returns 0, on error -1 is returned. Errors: SocketError is used to report errors, and includes the following: SYS_EBADFThe socket descriptor is invalid. SYS_ENOTCONNThe socket isn’t connected. SYS_ENOTSOCKThe descriptor is not a socket. See also: Socket (391), Connect (385)

Sock2File Declaration: Procedure Sock2File (Sock:Longint;Var SockIn,SockOut:File); Description: Sock2File transforms a socket Sock into 2 Pascal file descriptors of type File, one for reading from the socket (SockIn), one for writing to the socket (SockOut). Errors: None. See also: Socket (391), Sock2Text (391)

390

CHAPTER 20. THE SOCKETS UNIT.

Sock2Text Declaration: Procedure Sock2Text (Sock:Longint;Var SockIn,SockOut:

Text);

Description: Sock2Text transforms a socket Sock into 2 Pascal file descriptors of type Text, one for reading from the socket (SockIn), one for writing to the socket (SockOut). Errors: None. See also: Socket (391), Sock2File (390)

Socket Declaration: Function Socket (Domain,SocketType,Protocol:Longint) :

Longint;

Description: Socket creates a new socket in domain Domain, from type SocketType using protocol Protocol. The Domain, Socket type and Protocol can be specified using predefined constants (see the section on constants for available constants) If succesfull, the function returns a socket descriptor, which can be passed to a subsequent Bind (384) call. If unsuccesfull, the function returns -1. Errors: Errors are returned in SocketError, and include the follwing: SYS_EPROTONOSUPPORTThe protocol type or the specified protocol is not supported within this domain. SYS_EMFILEThe per-process descriptor table is full. SYS_ENFILEThe system file table is full. SYS_EACCESSPermission to create a socket of the specified type and/or protocol is denied. SYS_ENOBUFSInsufficient buffer space is available. The socket cannot be created until sufficient resources are freed. See also: SocketPair (391), socket (2) for an example, see Accept (382).

SocketPair Declaration: Function SocketPair (Domain,SocketType,Protocol:Longint;var Pair:TSockArray) : Longint; Description: SocketPair creates 2 sockets in domain Domain, from type SocketType and using protocol Protocol. The pair is returned in Pair, and they are indistinguishable. The function returns -1 upon error and 0 upon success. Errors: Errors are reported in SocketError, and are the same as in Socket (391) See also: Str2UnixSockAddr (391)

Str2UnixSockAddr Declaration: Procedure Str2UnixSockAddr(const addr:string;var t:TUnixSockAddr;var len:longint) Description: Str2UnixSockAddr transforms a Unix socket address in a string to a TUnixSockAddr structure which can be passed to the Bind (384) call. Errors: None. See also: Socket (391), Bind (384)

391

Chapter 21

The STRINGS unit. This chapter describes the STRINGS unit for Free Pascal. This unit is system independent, and therefore works on all supported platforms. Since the unit only provides some procedures and functions, there is only one section, which gives the declarations of these functions, together with an explanation.

21.1

Functions and procedures.

StrAlloc Declaration: Function StrAlloc (Len :

Longint) :

PChar;

Description: StrAlloc reserves memory on the heap for a string with length Len, terminating #0 included, and returns a pointer to it. Errors: If there is not enough memory, a run-time error occurs. See also: StrNew (399), StrPCopy (400).

StrCat Declaration: Function StrCat (Dest,Source :

PChar) :

Description: Attaches Source to Dest and returns Dest. Errors: No length checking is performed. See also: Concat () Listing: stringex/ex11.pp Program Example11 ; Uses s t r i n g s ; { Program t o demonstrate t h e S t r C a t f u n c t i o n . } Const P1 : PChar = ’ T h i s i s a PChar S t r i n g . ’ ; Var P2 : PChar ;

392

PChar;

CHAPTER 21. THE STRINGS UNIT.

begin P2 : = S t r A l l o c ( StrLen ( P1 ) ∗ 2 + 1 ) ; StrMove ( P2 , P1 , StrLen ( P1 ) + 1 ) ; { P2=P1 } StrCat ( P2 , P1 ) ; { Append P2 once more } W r i t e l n ( ’ P2 : ’ , P2 ) ; end .

StrComp Declaration: Function StrComp (S1,S2 :

PChar) :

Longint;

Description: Compares the null-terminated strings S1 and S2. The result is •A negative Longint when S1S2. Errors: None. See also: StrLComp (396), StrIComp (395), StrLIComp (398) For an example, see StrLComp (396).

StrCopy Declaration: Function StrCopy (Dest,Source :

PChar) :

PChar;

Description: Copy the null terminated string in Source to Dest, and returns a pointer to Dest. Dest needs enough room to contain Source, i.e. StrLen(Source)+1 bytes. Errors: No length checking is performed. See also: StrPCopy (400), StrLCopy (397), StrECopy (394) Listing: stringex/ex4.pp Program Example4 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrCopy f u n c t i o n . } Const P : PCHar = ’ T h i s i s a PCHAR s t r i n g . ’ ; var PP : PChar ; begin PP: = S t r A l l o c ( S t r l e n ( P ) + 1 ) ; STrCopy ( PP, P ) ; I f StrComp ( PP, P) < >0 then W r i t e l n ( ’Oh−oh problems . . . ’ ) else W r i t e l n ( ’ A l l i s w e l l : PP= ’ ,PP ) ; end .

393

CHAPTER 21. THE STRINGS UNIT.

StrDispose Declaration: Procedure StrDispose (P : PChar); Description: Removes the string in P from the heap and releases the memory. Errors: None. See also: Dispose () , StrNew (399) Listing: stringex/ex17.pp Program Example17 ; Uses s t r i n g s ; { Program t o demonstrate t h e S t r D is p o s e f u n c t i o n . } Const P1 : PChar = ’ T h i s i s a PChar s t r i n g ’ ; var P2 : PChar ; begin W r i t e l n ( ’ Before StnNew : Memory a v a i l a b l e : ’ , MemAvail ) ; P2 : = StrNew ( P1 ) ; W r i t e l n ( ’ A f t e r StrNew : Memory a v a i l a b l e : ’ , MemAvail ) ; W r i t e l n ( ’ P2 : ’ , P2 ) ; StrDispose ( P2 ) ; W r i t e l n ( ’ A f t e r S t r D i s p o s e : Memory a v a i l a b l e : ’ , MemAvail ) ; end .

StrECopy Declaration: Function StrECopy (Dest,Source :

PChar) :

PChar;

Description: Copies the Null-terminated string in Source to Dest, and returns a pointer to the end (i.e. the terminating Null-character) of the copied string. Errors: No length checking is performed. See also: StrLCopy (397), StrCopy (393) Listing: stringex/ex6.pp Program Example6 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrECopy f u n c t i o n . } Const P : PChar = ’ T h i s i s a PCHAR s t r i n g . ’ ; Var PP : PChar ; begin PP: = S t r A l l o c ( StrLen ( P ) + 1 ) ; I f L o n g i n t ( StrECopy ( PP, P)) − L o n g i n t (PP) StrLen (P ) then W r i t e l n ( ’ Something i s wrong here ! ’ )

394

CHAPTER 21. THE STRINGS UNIT.

else W r i t e l n ( ’PP= ’ ,PP ) ; end .

StrEnd Declaration: Function StrEnd (P : PChar) :

PChar;

Description: Returns a pointer to the end of P. (i.e. to the terminating null-character. Errors: None. See also: StrLen (397) Listing: stringex/ex7.pp Program Example6 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrEnd f u n c t i o n . } Const P : PChar = ’ T h i s i s a PCHAR s t r i n g . ’ ; begin I f L o n g i n t ( StrEnd ( P)) − L o n g i n t (P) StrLen (P ) then W r i t e l n ( ’ Something i s wrong here ! ’ ) else Writeln ( ’ A l l i s w e l l . . ’ ) ; end .

StrIComp Declaration: Function StrIComp (S1,S2 :

PChar) :

Longint;

Description: Compares the null-terminated strings S1 and S2, ignoring case. The result is •A negative Longint when S1S2. Errors: None. See also: StrLComp (396), StrComp (393), StrLIComp (398) Listing: stringex/ex8.pp Program Example8 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrLComp f u n c t i o n . } Const P1 : PChar = ’ T h i s i s t h e f i r s t s t r i n g . ’ ; P2 : PCHar = ’ T h i s i s t h e second s t r i n g . ’ ;

395

CHAPTER 21. THE STRINGS UNIT.

Var L : L o n g i n t ; begin Write ( ’ P1 and P2 are ’ ) ; I f StrComp ( P1 , P2) < >0 then w r i t e ( ’NOT ’ ) ; w r i t e ( ’ equal . The f i r s t ’ ) ; L:=1; While StrLComp ( P1 , P2 , L ) = 0 do inc ( L ) ; dec ( l ) ; W r i t e l n ( l , ’ c h a r a c t e r s are t h e same . ’ ) ; end .

StrLCat Declaration: Function StrLCat (Dest,Source :

PChar; MaxLen :

Longint) :

PChar;

Description: Adds MaxLen characters from Source to Dest, and adds a terminating null-character. Returns Dest. Errors: None. See also: StrCat (392) Listing: stringex/ex12.pp Program Example12 ; Uses s t r i n g s ; { Program t o demonstrate t h e S t r L C a t f u n c t i o n . } Const P1 : PChar = ’ 1234567890 ’ ; Var P2 : PChar ; begin P2 : = S t r A l l o c ( StrLen ( P1 ) ∗ 2 + 1 ) ; P2 ^ : = # 0 ; { Zero l e n g t h } StrCat ( P2 , P1 ) ; StrLCat ( P2 , P1 , 5 ) ; W r i t e l n ( ’ P2 = ’ , P2 ) ; end .

StrLComp Declaration: Function StrLComp (S1,S2 :

PChar; L : Longint) :

Longint;

Description: Compares maximum L characters of the null-terminated strings S1 and S2. The result is •A negative Longint when S1S2. Errors: None. See also: StrComp (393), StrIComp (395), StrLIComp (398) 396

CHAPTER 21. THE STRINGS UNIT.

Listing: stringex/ex8.pp Program Example8 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrLComp f u n c t i o n . } Const P1 : PChar = ’ T h i s i s t h e f i r s t s t r i n g . ’ ; P2 : PCHar = ’ T h i s i s t h e second s t r i n g . ’ ; Var L : L o n g i n t ; begin Write ( ’ P1 and P2 are ’ ) ; I f StrComp ( P1 , P2) < >0 then w r i t e ( ’NOT ’ ) ; w r i t e ( ’ equal . The f i r s t ’ ) ; L:=1; While StrLComp ( P1 , P2 , L ) = 0 do inc ( L ) ; dec ( l ) ; W r i t e l n ( l , ’ c h a r a c t e r s are t h e same . ’ ) ; end .

StrLCopy Declaration: Function StrLCopy (Dest,Source :

PChar; MaxLen :

Longint) :

PChar;

Description: Copies MaxLen characters from Source to Dest, and makes Dest a null terminated string. Errors: No length checking is performed. See also: StrCopy (393), StrECopy (394) Listing: stringex/ex5.pp Program Example5 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrLCopy f u n c t i o n . } Const P : PCHar = ’ 123456789ABCDEF ’ ; var PP : PCHar ; begin PP: = S t r A l l o c ( 1 1 ) ; Writeln ( ’ F i r s t 1 0 characters of P : end .

’ , StrLCopy ( PP, P , 1 0 ) ) ;

StrLen Declaration: Function StrLen (p :

PChar) :

Longint;

Description: Returns the length of the null-terminated string P. Errors: None. 397

CHAPTER 21. THE STRINGS UNIT.

See also: Length () Listing: stringex/ex1.pp Program Example1 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrLen f u n c t i o n . } Const P : PChar = ’ T h i s i s a c o n s t a n t pchar s t r i n g ’ ; begin W r i t e l n ( ’P : ’ ,p ) ; W r i t e l n ( ’ l e n g t h ( P ) : ’ , StrLen (P ) ) ; end .

StrLIComp Declaration: Function StrLIComp (S1,S2 :

PChar; L : Longint) :

Longint;

Description: Compares maximum L characters of the null-terminated strings S1 and S2, ignoring case. The result is •A negative Longint when S1S2. Errors: None. See also: StrLComp (396), StrComp (393), StrIComp (395) For an example, see StrIComp (395)

StrLower Declaration: Function StrLower (P : PChar) :

PChar;

Description: Converts P to an all-lowercase string. Returns P. Errors: None. See also: Upcase () , StrUpper (402) Listing: stringex/ex14.pp Program Example14 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrLower and StrUpper f u n c t i o n s . } Const P1 : PChar = ’ THIS IS AN UPPERCASE PCHAR STRING ’ ; P2 : PChar = ’ t h i s i s a lowercase s t r i n g ’ ;

398

CHAPTER 21. THE STRINGS UNIT.

begin W r i t e l n ( ’ Uppercase : StrLower ( P1 ) ; W r i t e l n ( ’ Lowercase : end .

’ , StrUpper ( P2 ) ) ; ’ , P1 ) ;

StrMove Declaration: Function StrMove (Dest,Source :

PChar; MaxLen :

Longint) :

PChar;

Description: Copies MaxLen characters from Source to Dest. No terminating null-character is copied. Returns Dest. Errors: None. See also: StrLCopy (397), StrCopy (393) Listing: stringex/ex10.pp Program Example10 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrMove f u n c t i o n . } Const P1 : PCHAR = ’ T h i s i s a pchar s t r i n g . ’ ;

Var P2 : Pchar ; begin P2 : = S t r A l l o c ( StrLen ( P1 ) + 1 ) ; StrMove ( P2 , P1 , StrLen ( P1 ) + 1 ) ; { P2 : = P1 } W r i t e l n ( ’ P2 = ’ , P2 ) ; end .

StrNew Declaration: Function StrNew (P : PChar) :

PChar;

Description: Copies P to the Heap, and returns a pointer to the copy. Errors: Returns Nil if no memory was available for the copy. See also: New () , StrCopy (393), StrDispose (394) Listing: stringex/ex16.pp Program Example16 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrNew f u n c t i o n . } Const P1 : PChar = ’ T h i s i s a PChar s t r i n g ’ ;

399

CHAPTER 21. THE STRINGS UNIT.

var P2 : PChar ; begin P2 : = StrNew ( P1 ) ; I f P1=P2 then w r i t e l n ( ’ T h i s can ’ ’ t be happening . . . ’ ) else w r i t e l n ( ’ P2 : ’ , P2 ) ; end .

StrPas Declaration: Function StrPas (P : PChar) :

String;

Description: Converts a null terminated string in P to a Pascal string, and returns this string. The string is truncated at 255 characters. Errors: None. See also: StrPCopy (400) Listing: stringex/ex3.pp Program Example3 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrPas f u n c t i o n . } Const P : PChar = ’ T h i s i s a PCHAR s t r i n g ’ ; var S : s t r i n g ; begin S: = StrPas ( P ) ; W r i t e l n ( ’S : ’ ,S ) ; end .

StrPCopy Declaration: Function StrPCopy (Dest :

PChar; Const Source :

String) :

PChar;

Description: Converts the Pascal string in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the string Source, i.e. Length(Source)+1 bytes. Errors: No length checking is performed. See also: StrPas (400) Listing: stringex/ex2.pp Program Example2 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrPCopy f u n c t i o n . }

400

CHAPTER 21. THE STRINGS UNIT.

Const S = ’ T h i s i s a normal s t r i n g . ’ ; Var P : Pchar ; begin p : = S t r A l l o c ( length ( S ) + 1 ) ; i f StrPCopy ( P , S) < >P then Writeln ( ’ This i s impossible ! ! ’ ) else writeln ( P ) ; end .

StrPos Declaration: Function StrPos (S1,S2 :

PChar) :

PChar;

Description: Returns a pointer to the first occurrence of S2 in S1. If S2 does not occur in S1, returns Nil. Errors: None. See also: Pos () , StrScan (401), StrRScan (401) Listing: stringex/ex15.pp Program Example15 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrPos f u n c t i o n . } Const P : PChar = ’ T h i s i s a PChar s t r i n g . ’ ; S : Pchar = ’ i s ’ ; begin W r i t e l n ( ’ P o s i t i o n o f ’ ’ i s ’ ’ i n P : ’ , l o n g i n t ( StrPos ( P , S)) − L o n g i n t (P ) ) ; end .

StrRScan Declaration: Function StrRScan (P : PChar; C : Char) :

PChar;

Description: Returns a pointer to the last occurrence of the character C in the null-terminated string P. If C does not occur, returns Nil. Errors: None. See also: Pos () , StrScan (401), StrPos (401) For an example, see StrScan (401).

StrScan Declaration: Function StrScan (P : PChar; C : Char) :

PChar;

Description: Returns a pointer to the first occurrence of the character C in the null-terminated string P. If C does not occur, returns Nil. 401

CHAPTER 21. THE STRINGS UNIT.

Errors: None. See also: Pos () , StrRScan (401), StrPos (401) Listing: stringex/ex13.pp Program Example13 ; Uses s t r i n g s ; { Program t o demonstrate t h e StrScan and StrRScan f u n c t i o n s . } Const P : PChar = ’ T h i s i s a PCHAR s t r i n g . ’ ; S : Char = ’ s ’ ; begin W r i t e l n ( ’ P , s t a r t i n g from f i r s t ’ ’ s ’ ’ : ’ , StrScan ( P , s ) ) ; W r i t e l n ( ’ P , s t a r t i n g from l a s t ’ ’ s ’ ’ : ’ , StrRScan ( P , s ) ) ; end .

StrUpper Declaration: Function StrUpper (P : PChar) :

PChar;

Description: Converts P to an all-uppercase string. Returns P. Errors: None. See also: Upcase () , StrLower (398) For an example, see StrLower (398)

402

Chapter 22

The SYSUTILS unit. This chapter describes the sysutils unit. The sysutils unit was largely written by Gertjan Schouten, and completed by Michaël Van Canneyt. It aims to be compatible to the Delphi sysutils unit, but in contrast with the latter, it is designed to work on multiple platforms. It is implemented on all supported platforms. This chapter starts out with a definition of all types and constants that are defined, followed by an overview of functions grouped by functionality, and lastly the complete explanation of each function.

22.1

Constants and types

The following general-purpose types are defined: tfilename = string; tsyscharset = set of char; tintegerset = set of 0..sizeof(integer)*8-1; longrec = packed record lo,hi : word; end; wordrec = packed record lo,hi : byte; end; TMethod = packed record Code, Data: Pointer; end; The use and meaning of these types should be clear, so no extra information will be provided here. The following general-purpose constants are defined: const SecsPerDay = 24 * 60 * 60; // Seconds and milliseconds per day MSecsPerDay = SecsPerDay * 1000; DateDelta = 693594; // Days between 1/1/0001 and 12/31/1899 Eoln = #10; 403

CHAPTER 22. THE SYSUTILS UNIT.

The following types are used frequently in date and time functions. They are the same on all platforms. type TSystemTime = record Year, Month, Day: word; Hour, Minute, Second, MilliSecond: word; end ; TDateTime = double; TTimeStamp = record Time: integer; { Number of milliseconds since midnight } Date: integer; { One plus number of days since 1/1/0001 } end ; The following type is used in the FindFirst (440),FindNext (441) and FindClose (440) functions. The win32 version differs from the other versions. If code is to be portable, that part shouldn’t be used. Type THandle = Longint; TSearchRec = Record Time,Size, Attr : Longint; Name : TFileName; ExcludeAttr : Longint; FindHandle : THandle; {$ifdef Win32} FindData : TWin32FindData; {$endif} end; The following constants are file-attributes that need to be matched in the findfirst call. Const faReadOnly faHidden faSysFile faVolumeId faDirectory faArchive faAnyFile

= = = = = = =

$00000001; $00000002; $00000004; $00000008; $00000010; $00000020; $0000003f;

The following constants can be used in the FileOpen (437) call. Const fmOpenRead fmOpenWrite fmOpenReadWrite

= $0000; = $0001; = $0002;

The following constants can be used in the FileSeek (438) call. Const fsFromBeginning = 0; 404

CHAPTER 22. THE SYSUTILS UNIT.

fsFromCurrent fsFromEnd

= 1; = 2;

The following variables are used in the case translation routines. type TCaseTranslationTable = array[0..255] of char; var UpperCaseTable: TCaseTranslationTable; LowerCaseTable: TCaseTranslationTable; The initialization code of the sysutils unit fills these tables with the appropriate values. For the win32 and go32v2 versions, this information is obtained from the operating system. The following constants control the formatting of dates. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit. Const DateSeparator: char = ’-’; ShortDateFormat: string = ’d/m/y’; LongDateFormat: string = ’dd" "mmmm" "yyyy’; ShortMonthNames: array[1..12] of string[128] = (’Jan’,’Feb’,’Mar’,’Apr’,’May’,’Jun’, ’Jul’,’Aug’,’Sep’,’Oct’,’Nov’,’Dec’); LongMonthNames: array[1..12] of string[128] = (’January’,’February’,’March’,’April’, ’May’,’June’,’July’,’August’, ’September’,’October’,’November’,’December’); ShortDayNames: array[1..7] of string[128] = (’Sun’,’Mon’,’Tue’,’Wed’,’Thu’,’Fri’,’Sat’); LongDayNames: array[1..7] of string[128] = (’Sunday’,’Monday’,’Tuesday’,’Wednesday’, ’Thursday’,’Friday’,’Saturday’); The following constants control the formatting of times. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit. Const ShortTimeFormat: string = ’hh:nn’; LongTimeFormat: string = ’hh:nn:ss’; TimeSeparator: char = ’:’; TimeAMString: string[7] = ’AM’; TimePMString: string[7] = ’PM’; The following constants control the formatting of currencies and numbers. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit. Const DecimalSeparator : Char = ’.’; ThousandSeparator : Char = ’,’; CurrencyDecimals : Byte = 2; 405

CHAPTER 22. THE SYSUTILS UNIT.

CurrencyString : String[7] = ’$’; { Format to use when formatting currency : 0 = $1 1 = 1$ 2 = $ 1 3 = 1 $ 4 = Currency string replaces decimal indicator. e.g. 1$50 } CurrencyFormat : Byte = 1; { Same as above, only for negative currencies: 0 = ($1) 1 = -$1 2 = $-1 3 = $14 = (1$) 5 = -1$ 6 = 1-$ 7 = 1$8 = -1 $ 9 = -$ 1 10 = $ 1} NegCurrFormat : Byte = 5; The following types are used in various string functions. type PString = ^String; TFloatFormat = (ffGeneral, ffExponent, ffFixed, ffNumber, ffCurrency); The following constants are used in the file name handling routines. Do not use a slash of backslash character directly as a path separator; instead use the OsDirSeparator character. Const DirSeparators : set of char = [’/’,’\’]; {$ifdef unix} OSDirSeparator = ’/’; {$else} OsDirSeparator = ’\’; {$endif}

22.2

Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where you can find the function.

String functions Functions for handling strings. Name

Description

Page

AnsiCompareStr

Compare two strings

446

AnsiCompareText

Compare two strings, case insensitive

447

406

CHAPTER 22. THE SYSUTILS UNIT.

AnsiExtractQuotedStr Removes quotes from string

448

AnsiLastChar

Get last character of string

448

AnsiLowerCase

Convert string to all-lowercase

449

AnsiQuotedStr

Qoutes a string

449

AnsiStrComp

Compare strings case-sensitive

449

AnsiStrIComp

Compare strings case-insensitive

450

AnsiStrLComp

Compare L characters of strings case sensitive

452

AnsiStrLIComp

Compare L characters of strings case insensitive

452

AnsiStrLastChar

Get last character of string

451

AnsiStrLower

Convert string to all-lowercase

453

AnsiStrUpper

Convert string to all-uppercase

454

AnsiUpperCase

Convert string to all-uppercase

455

AppendStr

Append 2 strings

455

AssignStr

Assign value of strings on heap

456

CompareStr

Compare two strings case sensitive

457

CompareText

Compare two strings case insensitive

458

DisposeStr

Remove string from heap

459

IsValidIdent

Is string a valid pascal identifier

471

LastDelimiter

Last occurance of character in a string

471

LeftStr

Get first N characters of a string

472

LoadStr

Load string from resources

472

LowerCase

Convert string to all-lowercase

472

NewStr

Allocate new string on heap

473

RightStr

Get last N characters of a string

473

StrAlloc

Allocate memory for string

444

StrBufSize

Reserve memory for a string

444

StrDispose

Remove string from heap

444

StrPas

Convert PChar to pascal string

445

StrPCopy

Copy pascal string

445

StrPLCopy

Copy N bytes of pascal string

445

UpperCase

Convert string to all-uppercase

480

Formatting strings Functions for formatting strings. Name

Description

Page

AdjustLineBreaks

Convert line breaks to line breaks for system

445

FormatBuf

Format a buffer

468

Format

Format arguments in string

462

FmtStr

Format buffer

462

407

CHAPTER 22. THE SYSUTILS UNIT.

QuotedStr

Quote a string

473

StrFmt

Format arguments in a string

474

StrLFmt

Format maximum L characters in a string

474

TrimLeft

Remove whitespace at the left of a string

479

TrimRight

Remove whitespace at the right of a string

479

Trim

Remove whitespace at both ends of a string

478

File input/output routines Functions for reading/writing to file. Name

Description

Page

FileCreate

Create a file and return handle

434

FileOpen

Open file end return handle

437

FileRead

Read from file

437

FileSeek

Set file position

438

FileTruncate

Truncate file length

439

FileWrite

Write to file

440

FileClose

Close file handle

434

File handling routines Functions for file manipulation. Name

Description

Page

AddDisk

Add sisk to list of disk drives

425

ChangeFileExt

Change extension of file name

428

CreateDir

Create a directory

426

DeleteFile

Delete a file

429

DiskFree

Free space on disk

426

DiskSize

Total size of disk

427

ExpandFileName

Create full file name

430

ExpandUNCFileName Create full UNC file name

430

ExtractFileDir

Extract directory part of filename

431

ExtractFileDrive

Extract drive part of filename

431

ExtractFileExt

Extract extension part of filename

432

ExtractFileName

Extract name part of filename

432

ExtractFilePath

Extrct path part of filename

432

ExtractRelativePath

Construct relative path between two files

432

FileAge

Return file age

433

FileDateToDateTime

Convert file date to system date

418

FileExists

Determine whether a file exists on disk

435

408

CHAPTER 22. THE SYSUTILS UNIT.

FileGetAttr

Get attributes of file

435

FileGetDate

Get date of last file modification

436

FileSearch

Search for file in path

438

FileSetAttr

Get file attributes

439

FileSetDate

Get file dates

439

FindFirst

Start finding a file

440

FindNext

Find next file

441

GetCurrentDir

Return current working directory

427

RemoveDir

Remove a directory from disk

428

RenameFile

Rename a file on disk

442

SetCurrentDir

Set current working directory

428

SetDirSeparators

Set directory separator characters

442

FindClose

Stop searching a file

440

DoDirSeparators

Replace directory separator characters

429

Date/time routines Functions for date and time handling. Name

Description

Page

DateTimeToFileDate

Convert DateTime type to file date

412

DateTimeToStr

Construct string representation of DateTime

412

DateTimeToString

Construct string representation of DateTime

413

DateTimeToSystemTime Convert DateTime to system time

414

DateTimeToTimeStamp Convert DateTime to timestamp

414

DateToStr

Construct string representation of date

415

Date

Get current date

411

DayOfWeek

Get day of week

415

DecodeDate

Decode DateTime to year month and day

416

DecodeTime

Decode DateTime to hours, minutes and seconds

416

EncodeDate

Encode year, day and month to DateTime

417

EncodeTime

Encode hours, minutes and seconds to DateTime

417

FormatDateTime

Return string representation of DateTime

418

IncMonth

Add 1 to month

419

IsLeapYear

Determine if year is leap year

419

MSecsToTimeStamp

Convert nr of milliseconds to timestamp

420

Now

Get current date and time

421

StrToDateTime

Convert string to DateTime

422

StrToDate

Convert string to date

421

StrToTime

Convert string to time

422

SystemTimeToDateTime Convert system time to datetime

409

423

CHAPTER 22. THE SYSUTILS UNIT.

TimeStampToDateTime Convert time stamp to DateTime

424

TimeStampToMSecs

Convert Timestamp to number of millicseconds

424

TimeToStr

return string representation of Time

425

Time

Get current tyme

423

22.3

Miscellaneous conversion routines

Functions for various conversions. Name

Description

Page

BCDToInt

Convert BCD number to integer

456

CompareMem

Compare two memory regions

457

FloatToStrF

Convert float to formatted string

460

FloatToStr

Convert float to string

459

FloatToText

Convert float to string

461

FormatFloat

Format a floating point value

468

GetDirs

Split string in list of directories

441

IntToHex

return hexadecimal representation of integer

469

IntToStr

return decumal representation of integer

470

StrToIntDef

Convert string to integer with default value

476

StrToInt

Convert string to integer

476

StrToFloat

Convert string to float

475

TextToFloat

Convert null-terminated string to float

477

22.4

Date and time functions

Date and time formatting characters Various date and time formatting routines accept a format string. to format the date and or time. The following characters can be used to control the date and time formatting: c : shortdateformat + ’ ’ + shorttimeformat d : day of month dd : day of month (leading zero) ddd : day of week (abbreviation) dddd : day of week (full) ddddd : shortdateformat dddddd : longdateformat m : month mm : month (leading zero)

410

CHAPTER 22. THE SYSUTILS UNIT.

mmm : month (abbreviation) mmmm : month (full) y : year (four digits) yy : year (two digits) yyyy : year (with century) h : hour hh : hour (leading zero) n : minute nn : minute (leading zero) s : second ss : second (leading zero) t : shorttimeformat tt : longtimeformat am/pm : use 12 hour clock and display am and pm accordingly a/p : use 12 hour clock and display a and p accordingly / : insert date seperator : : insert time seperator "xx" : literal text ’xx’ : literal text

TDateTime Declaration: TDateTime = Double; Description: Many functions return or require a TDateTime type, which contains a date and time in encoded form. The date and time are converted to a double as follows: •The date part is stored in the integer part of the double as the number of days passed since January 1, 1900. •The time part is stored in the fractional part of the double, as the number of milliseconds passed since midnight (00:00), divided by the total number of milliseconds in a day.

Date Declaration: Function Date:

TDateTime;

Description: Date returns the current date in TDateTime format. For more information about the TDateTime type, see TDateTime (411). Errors: None. See also: Time (423),Now (421), TDateTime (411). 411

CHAPTER 22. THE SYSUTILS UNIT.

Listing: sysutex/ex1.pp Program Example1 ; { T h i s program demonstrates t h e Date f u n c t i o n } uses s y s u t i l s ; Var YY,MM,DD : Word ; Begin W r i t e l n ( ’ Date : ’ , Date ) ; DeCodeDate ( Date , YY,MM,DD ) ; W r i t e l n ( format ( ’ Date i s ( DD/MM/ YY) : % d/%d/%d ’ , [ dd ,mm, yy ] ) ) ; End .

DateTimeToFileDate Declaration: Function DateTimeToFileDate(DateTime :

TDateTime) :

Longint;

Description: DateTimeToFileDate function converts a date/time indication in TDateTime format to a filedate function, such as returned for instance by the FileAge (433) function. Errors: None. See also: Time (423), Date (411), FileDateToDateTime (418), DateTimeToSystemTime (414), DateTimeToTimeStamp (414) Listing: sysutex/ex2.pp Program Example2 ; { T h i s program demonstrates t h e DateTimeToFileDate f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( ’ F i l e T i m e o f now would be : ’ , DateTimeToFileDate ( Now ) ) ; End .

DateTimeToStr Declaration: Function DateTimeToStr(DateTime:

TDateTime):

string;

Description: DateTimeToStr returns a string representation of DateTime using the formatting specified in ShortDateTimeFormat. It corresponds to a call to FormatDateTime(’c’,DateTime) (see section 22.4, page 410). Errors: None. See also: FormatDateTime (418), TDateTime (411). Listing: sysutex/ex3.pp

412

CHAPTER 22. THE SYSUTILS UNIT.

Program Example3 ; { T h i s program demonstrates t h e DateTimeToStr f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( ’ Today i s : W r i t e l n ( ’ Today i s : End .

’ , DateTimeToStr (Now ) ) ; ’ , FormatDateTime ( ’ c ’ ,Now ) ) ;

DateTimeToString Declaration: Procedure DateTimeToString(var Result: const DateTime: TDateTime);

string; const FormatStr:

string;

Description: DateTimeToString returns in Result a string representation of DateTime using the formatting specified in FormatStr. for a list of characters that can be used in the FormatStr formatting string, see section 22.4, page 410. Errors: In case a wrong formatting character is found, an EConvertError is raised. See also: FormatDateTime (418), section 22.4, page 410. Listing: sysutex/ex4.pp Program Example4 ; { T h i s program demonstrates t h e DateTimeToString f u n c t i o n } Uses s y s u t i l s ;

Procedure today ( Fmt : s t r i n g ) ; Var S : A n s i S t r i n g ; begin DateTimeToString ( S , Fmt , Date ) ; Writeln ( S ) ; end ; Procedure Now ( Fmt : s t r i n g ) ; Var S : A n s i S t r i n g ; begin DateTimeToString ( S , Fmt , Time ) ; Writeln ( S ) ; end ; Begin Today ( ’ " Today i s " dddd dd mmmm y ’ ) ; Today ( ’ " Today i s " d mmm yy ’ ) ; Today ( ’ " Today i s " d /mmm/ yy ’ ) ;

413

CHAPTER 22. THE SYSUTILS UNIT.

Now ( ’ ’ ’ The t i m e i s Now ( ’ ’ ’ The t i m e i s Now ( ’ ’ ’ The t i m e i s End .

’ ’am/ pmh : n : s ’ ) ; ’ ’ hh : nn : ssam /pm ’ ) ; ’ ’ tt ’ );

DateTimeToSystemTime Declaration: Procedure DateTimeToSystemTime(DateTime: TSystemTime);

TDateTime; var SystemTime:

Description: DateTimeToSystemTime converts a date/time pair in DateTime, with TDateTime format to a system time SystemTime. Errors: None. See also: DateTimeToFileDate (412), SystemTimeToDateTime (423), DateTimeToTimeStamp (414) Listing: sysutex/ex5.pp Program Example5 ; { T h i s program demonstrates t h e DateTimeToSystemTime f u n c t i o n } Uses s y s u t i l s ; Var ST : TSystemTime ; Begin DateTimeToSystemTime (Now, ST ) ; With St do begin W r i t e l n ( ’ Today i s ’ , year , ’ / ’ , month , ’ / ’ , Day ) ; W r i t e l n ( ’ The t i m e i s ’ , Hour , ’ : ’ , minute , ’ : ’ , Second , ’ . ’ , M i l l i S e c o n d ) ; end ; End .

DateTimeToTimeStamp Declaration: Function DateTimeToTimeStamp(DateTime:

TDateTime):

TTimeStamp;

Description: DateTimeToSystemTime converts a date/time pair in DateTime, with TDateTime format to a TTimeStamp format. Errors: None. See also: DateTimeToFileDate (412), SystemTimeToDateTime (423), DateTimeToSystemTime (414) Listing: sysutex/ex6.pp Program Example6 ; { T h i s program demonstrates t h e DateTimeToTimeStamp f u n c t i o n } Uses s y s u t i l s ; Var TS : TTimeStamp ;

414

CHAPTER 22. THE SYSUTILS UNIT.

Begin TS: = DateTimeToTimeStamp ( Now ) ; With TS do begin W r i t e l n ( ’Now i s ’ , time , ’ m i l l i s e c o n d p a s t m i d n i g h t ’ ) ; W r i t e l n ( ’ Today i s ’ , Date , ’ days p a s t 1 / 1 / 0 0 0 1 ’ ) ; end ; End .

DateToStr Declaration: Function DateToStr(Date:

TDateTime):

string;

Description: DateToStr converts Date to a string representation. It uses ShortDateFormat as it’s formatting string. It is hence completely equivalent to a FormatDateTime(’ddddd’, Date). Errors: None. See also: TimeToStr (425), DateTimeToStr (412), FormatDateTime (418), StrToDate (421) Listing: sysutex/ex7.pp Program Example7 ; { T h i s program demonstrates t h e DateToStr f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( Format ( ’ Today i s : % s ’ , [ DateToStr ( Date ) ] ) ) ; End .

DayOfWeek Declaration: Function DayOfWeek(DateTime:

TDateTime):

integer;

Description: DayOfWeek returns the day of the week from DateTime. Sunday is counted as day 1, Saturday is counted as day 7. The result of DayOfWeek can serve as an index to the LongDayNames constant array, to retrieve the name of the day. Errors: None. See also: Date (411), DateToStr (415) Listing: sysutex/ex8.pp Program Example8 ; { T h i s program demonstrates t h e DayOfWeek f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( ’ Today ’ ’ s day i s End .

’ , LongDayNames [ DayOfWeek ( Date ) ] ) ;

415

CHAPTER 22. THE SYSUTILS UNIT.

DecodeDate Declaration: Procedure DecodeDate(Date:

TDateTime; var Year, Month, Day:

word);

Description: DecodeDate decodes the Year, Month and Day stored in Date, and returns them in the Year, Month and Day variables. Errors: None. See also: EncodeDate (417), DecodeTime (416). Listing: sysutex/ex9.pp Program Example9 ; { T h i s program demonstrates t h e DecodeDate f u n c t i o n } Uses s y s u t i l s ; Var YY,MM,DD : Word ; Begin DecodeDate ( Date , YY,MM,DD ) ; W r i t e l n ( Format ( ’ Today i s %d/%d/%d ’ , [ dd ,mm, yy ] ) ) ; End .

DecodeTime Declaration: Procedure DecodeTime(Time: word);

TDateTime; var Hour, Minute, Second, MilliSecond:

Description: DecodeDate decodes the hours, minutes, second and milliseconds stored in Time, and returns them in the Hour, Minute and Second and MilliSecond variables. Errors: None. See also: EncodeTime (417), DecodeDate (416). Listing: sysutex/ex10.pp Program Example10 ; { T h i s program demonstrates t h e DecodeTime f u n c t i o n } Uses s y s u t i l s ; Var HH,MM, SS,MS : Word ; Begin DecodeTime ( Time , HH,MM, SS,MS) ; W r i t e l n ( format ( ’ The t i m e i s %d:%d:%d.%d ’ , [ hh ,mm, ss , ms ] ) ) ; End .

416

CHAPTER 22. THE SYSUTILS UNIT.

EncodeDate Declaration: Function EncodeDate(Year, Month, Day :word):

TDateTime;

Description: EncodeDate encodes the Year, Month and Day variables to a date in TDateTime format. It does the opposite of the DecodeDate (416) procedure. The parameters must lie withing valid ranges (boundaries included): Yearmust be between 1 and 9999. Monthmust be within the range 1-12. Daymsut be between 1 and 31. Errors: In case one of the parameters is out of it’s valid range, 0 is returned. See also: EncodeTime (417), DecodeDate (416). Listing: sysutex/ex11.pp Program Example11 ; { T h i s program demonstrates t h e EncodeDate f u n c t i o n } Uses s y s u t i l s ; Var YY,MM,DD : Word ; Begin DecodeDate ( Date , YY,MM,DD ) ; WriteLn ( ’ Today i s : ’ , FormatDateTime ( ’ dd mmmm yyyy ’ , EnCodeDate (YY,Mm, Dd ) ) ) ; End .

EncodeTime Declaration: Function EncodeTime(Hour, Minute, Second, MilliSecond:word):

TDateTime;

Description: EncodeTime encodes the Hour, Minute, Second, MilliSecond variables to a TDateTime format result. It does the opposite of the DecodeTime (416) procedure. The parameters must have a valid range (boundaries included): Hourmust be between 0 and 23. Minute,secondmust both be between 0 and 59. Millisecondmust be between 0 and 999. Errors: In case one of the parameters is outside of it’s valid range, 0 is returned. See also: EncodeDate (417), DecodeTime (416). Listing: sysutex/ex12.pp Program Example12 ; { T h i s program demonstrates t h e EncodeTime f u n c t i o n } Uses s y s u t i l s ; Var Hh ,MM, SS,MS : Word ;

417

CHAPTER 22. THE SYSUTILS UNIT.

Begin DeCodeTime ( Time , Hh ,MM, SS,MS) ; W r i t e l n ( ’ Present Time i s : ’ , FormatDateTime ( ’ hh :mm: ss ’ ,EnCodeTime ( HH,MM, SS,MS ) ) ) ; End .

FileDateToDateTime Declaration: Function FileDateToDateTime(Filedate :

Longint) :

TDateTime;

Description: FileDateToDateTime converts the date/time encoded in filedate to a TDateTime encoded form. It can be used to convert date/time values returned by the FileAge (433) or FindFirst (440)/FindNext (441) functions to TDateTime form. Errors: None. See also: DateTimeToFileDate (412) Listing: sysutex/ex13.pp Program Example13 ; { T h i s program demonstrates t h e FileDateToDateTime f u n c t i o n } Uses s y s u t i l s ; Var ThisAge : L o n g i n t ; Begin Write ( ’ ex13 . pp c r e a t e d on : ’ ) ; ThisAge : = FileAge ( ’ ex13 . pp ’ ) ; W r i t e l n ( DateTimeToStr ( FileDateToDateTime ( ThisAge ) ) ) ; End .

FormatDateTime Declaration: Function FormatDateTime(FormatStr:

string; DateTime:

TDateTime):string;

Description: FormatDateTime formats the date and time encoded in DateTime according to the formatting given in FormatStr. The complete list of formatting characters can be found in section 22.4, page 410. Errors: On error (such as an invalid character in the formatting string), and EConvertError exception is raised. See also: DateTimeToStr (412), DateToStr (415), TimeToStr (425), StrToDateTime (422) Listing: sysutex/ex14.pp Program Example14 ; { T h i s program demonstrates t h e FormatDateTime f u n c t i o n } Uses s y s u t i l s ;

418

CHAPTER 22. THE SYSUTILS UNIT.

Var ThisMoment : TDateTime ; Begin ThisMoment : =Now; W r i t e l n ( ’Now : ’ , FormatDateTime ( ’ hh : nn ’ , ThisMoment ) ) ; W r i t e l n ( ’Now : ’ , FormatDateTime ( ’DD MM YYYY ’ , ThisMoment ) ) ; W r i t e l n ( ’Now : ’ , FormatDateTime ( ’ c ’ , ThisMoment ) ) ; End .

IncMonth Declaration: Function IncMonth(const DateTime: TDateTime;

TDateTime; NumberOfMonths:

integer):

Description: IncMonth increases the month number in DateTime with NumberOfMonths. It wraps the result as to get a month between 1 and 12, and updates the year accordingly. NumberOfMonths can be negative, and can be larger than 12 (in absolute value). Errors: None. See also: Date (411), Time (423), Now (421) Listing: sysutex/ex15.pp Program Example15 ; { T h i s program demonstrates t h e IncMonth f u n c t i o n } Uses s y s u t i l s ; Var ThisDay : TDateTime ; Begin ThisDay : = Date ; W r i t e l n ( ’ ThisDay : ’ , DateToStr ( ThisDay ) ) ; W r i t e l n ( ’ 6 months ago : ’ , DateToStr ( IncMonth ( ThisDay , − 6 ) ) ) ; W r i t e l n ( ’ 6 months from now : ’ , DateToStr ( IncMonth ( ThisDay , 6 ) ) ) ; W r i t e l n ( ’ 1 2 months ago : ’ , DateToStr ( IncMonth ( ThisDay , − 1 2 ) ) ) ; W r i t e l n ( ’ 1 2 months from now : ’ , DateToStr ( IncMonth ( ThisDay , 1 2 ) ) ) ; W r i t e l n ( ’ 1 8 months ago : ’ , DateToStr ( IncMonth ( ThisDay , − 1 8 ) ) ) ; W r i t e l n ( ’ 1 8 months from now : ’ , DateToStr ( IncMonth ( ThisDay , 1 8 ) ) ) ; End .

IsLeapYear Declaration: Function IsLeapYear(Year:

Word):

boolean;

Description: IsLeapYear returns True if Year is a leap year, False otherwise. Errors: None. See also: IncMonth (419), Date (411) Listing: sysutex/ex16.pp

419

CHAPTER 22. THE SYSUTILS UNIT.

Program Example16 ; { T h i s program demonstrates t h e IsLeapYear f u n c t i o n } Uses s y s u t i l s ; Var YY,MM, dd : Word ; Procedure TestYear ( Y : Word ) ; begin W r i t e l n ( Y , ’ i s l e a p year : end ;

’ , IsLeapYear (Y ) ) ;

Begin DeCodeDate ( Date , YY,mm, dd ) ; TestYear ( yy ) ; TestYear ( 2 0 0 0 ) ; TestYear ( 1 9 0 0 ) ; TestYear ( 1 6 0 0 ) ; TestYear ( 1 9 9 2 ) ; TestYear ( 1 9 9 5 ) ; End .

MSecsToTimeStamp Declaration: Function MSecsToTimeStamp(MSecs:

Comp):

TTimeStamp;

Description: MSecsTiTimeStamp converts the given number of milliseconds to a TTimeStamp date/time notation. Use TTimeStamp variables if you need to keep very precise track of time. Errors: None. See also: TimeStampToMSecs (424), DateTimeToTimeStamp (414), Listing: sysutex/ex17.pp Program Example17 ; { T h i s program demonstrates t h e MSecsToTimeStamp f u n c t i o n } Uses s y s u t i l s ; Var MS : Comp ; TS : TTimeStamp ; DT : TDateTime ; Begin TS: = DateTimeToTimeStamp (Now ) ; W r i t e l n ( ’Now i n days s i n c e 1 / 1 / 0 0 0 1 : ’ ,TS . Date ) ; W r i t e l n ( ’Now i n m i l l i s e c s s i n c e m i d n i g h t : ’ ,TS . Time ) ; MS: = TimeStampToMSecs ( TS ) ; W r i t e l n ( ’Now i n m i l l i s e c s s i n c e 1 / 1 / 0 0 0 1 : ’ ,MS) ; MS: =MS−1000∗3600∗2; TS: = MSecsToTimeStamp (MS) ; DT: = TimeStampToDateTime ( TS ) ;

420

CHAPTER 22. THE SYSUTILS UNIT.

W r i t e l n ( ’Now minus 1 day : End .

’ , DateTimeToStr (DT ) ) ;

Now Declaration: Function Now:

TDateTime;

Description: Now returns the current date and time. It is equivalent to Date+Time. Errors: None. See also: Date (411), Time (423) Listing: sysutex/ex18.pp Program Example18 ; { T h i s program demonstrates t h e Now f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( ’Now : End .

’ , DateTimeToStr (Now ) ) ;

StrToDate Declaration: Function StrToDate(const S: string):

TDateTime;

Description: StrToDate converts the string S to a TDateTime date value. The Date must consist of 1 to three digits, separated by the DateSeparator character. If two numbers are given, they are supposed to form the day and month of the current year. If only one number is given, it is supposed to represent the day of the current month. (This is not supported in Delphi) The order of the digits (y/m/d, m/d/y, d/m/y) is determined from the ShortDateFormat variable. Errors: On error (e.g. an invalid date or invalid character), an EConvertError exception is raised. See also: StrToTime (422), DateToStr (415)n TimeToStr (425). Listing: sysutex/ex19.pp Program Example19 ; { T h i s program demonstrates t h e StrToDate f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t S t r ( S : S t r i n g ) ; begin Writeln ( S, ’ : end ;

’ , DateToStr ( StrToDate (S ) ) ) ;

Begin W r i t e l n ( ’ ShortDateFormat ’ , ShortDateFormat ) ;

421

CHAPTER 22. THE SYSUTILS UNIT.

T e s t S t r ( DateTimeToStr ( Date ) ) ; T e s t S t r ( ’ 05/05/1999 ’ ) ; TestStr ( ’ 5/5 ’ ) ; TestStr ( ’5 ’ ) ; End .

StrToDateTime Declaration: Function StrToDateTime(const S: string):

TDateTime;

Description: StrToDateTime converts the string S to a TDateTime date and time value. The Date must consist of 1 to three digits, separated by the DateSeparator character. If two numbers are given, they are supposed to form the day and month of the current year. If only one number is given, it is supposed to represent the day of the current month. (This is not supported in Delphi) The order of the digits (y/m/d, m/d/y, d/m/y) is determined from the ShortDateFormat variable. Errors: On error (e.g. an invalid date or invalid character), an EConvertError exception is raised. See also: StrToDate (421), StrToTime (422), DateTimeToStr (412) Listing: sysutex/ex20.pp Program Example20 ; { T h i s program demonstrates t h e StrToDateTime f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t S t r ( S : S t r i n g ) ; begin Writeln ( S, ’ : end ;

’ , DateTimeToStr ( StrToDateTime (S ) ) ) ;

Begin W r i t e l n ( ’ ShortDateFormat ’ , ShortDateFormat ) ; T e s t S t r ( DateTimeToStr (Now ) ) ; T e s t S t r ( ’ 05−05−1999 15:50 ’ ) ; T e s t S t r ( ’ 5 −5 13:30 ’ ) ; T e s t S t r ( ’ 5 1 : 3 0PM ’ ) ; End .

StrToTime Declaration: Function StrToTime(const S: string):

TDateTime;

Description: StrToTime converts the string S to a TDateTime time value. The time must consist of 1 to 4 digits, separated by the TimeSeparator character. If two numbers are given, they are supposed to form the hour and minutes. Errors: On error (e.g. an invalid date or invalid character), an EConvertError exception is raised. See also: StrToDate (421), StrToDateTime (422), TimeToStr (425)

422

CHAPTER 22. THE SYSUTILS UNIT.

Listing: sysutex/ex21.pp Program Example21 ; { T h i s program demonstrates t h e StrToTime f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t S t r ( S : S t r i n g ) ; begin Writeln ( S, ’ : end ; Begin teststr teststr teststr teststr End .

’ , TimeToStr ( StrToTime (S ) ) ) ;

( TimeToStr ( Time ) ) ; ( ’ 12:00 ’ ) ; ( ’ 15:30 ’ ) ; ( ’ 3:30PM ’ ) ;

SystemTimeToDateTime Declaration: Function SystemTimeToDateTime(const SystemTime:

TSystemTime):

TDateTime;

Description: SystemTimeToDateTime converts a TSystemTime record to a TDateTime style date/time indication. Errors: None. See also: DateTimeToSystemTime (414) Listing: sysutex/ex22.pp Program Example22 ; { T h i s program demonstrates t h e SystemTimeToDateTime f u n c t i o n } Uses s y s u t i l s ; Var ST : TSystemTime ; Begin DateTimeToSystemTime (Now, ST ) ; With St do begin W r i t e l n ( ’ Today i s ’ , year , ’ / ’ , month , ’ / ’ , Day ) ; W r i t e l n ( ’ The t i m e i s ’ , Hour , ’ : ’ , minute , ’ : ’ , Second , ’ . ’ , M i l l i S e c o n d ) ; end ; W r i t e l n ( ’ Converted : ’ , DateTimeToStr ( SystemTimeToDateTime ( ST ) ) ) ; End .

Time Declaration: Function Time:

TDateTime;

423

CHAPTER 22. THE SYSUTILS UNIT.

Description: Time returns the current time in TDateTime format. The date part of the TDateTimeValue is set to zero. Errors: None. See also: Now (421), Date (411) Listing: sysutex/ex23.pp Program Example23 ; { T h i s program demonstrates t h e Time f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( ’ The t i m e i s : End .

’ , TimeToStr ( Time ) ) ;

TimeStampToDateTime Declaration: Function TimeStampToDateTime(const TimeStamp:

TTimeStamp):

TDateTime;

Description: TimeStampToDateTime converts TimeStamp to a TDateTime format variable. It is the inverse operation of DateTimeToTimeStamp (414). Errors: None. See also: DateTimeToTimeStamp (414), TimeStampToMSecs (424) Listing: sysutex/ex24.pp Program Example24 ; { T h i s program demonstrates t h e TimeStampToDateTime f u n c t i o n } Uses s y s u t i l s ; Var TS : TTimeStamp ; DT : TDateTime ; Begin TS: = DateTimeToTimeStamp ( Now ) ; With TS do begin W r i t e l n ( ’Now i s ’ , time , ’ m i l l i s e c o n d p a s t m i d n i g h t ’ ) ; W r i t e l n ( ’ Today i s ’ , Date , ’ days p a s t 1 / 1 / 0 0 0 1 ’ ) ; end ; DT: = TimeStampToDateTime ( TS ) ; W r i t e l n ( ’ Together t h i s i s : ’ , DateTimeToStr (DT ) ) ; End .

TimeStampToMSecs Declaration: Function TimeStampToMSecs(const TimeStamp:

424

TTimeStamp):

comp;

CHAPTER 22. THE SYSUTILS UNIT.

Description: TimeStampToMSecs converts TimeStamp to the number of seconds since 1/1/0001. Use TTimeStamp variables if you need to keep very precise track of time. Errors: None. See also: MSecsToTimeStamp (420), TimeStampToDateTime (424) For an example, see MSecsToTimeStamp (420).

TimeToStr Declaration: Function TimeToStr(Time:

TDateTime):

string;

Description: TimeToStr converts the time in Time to a string. It uses the ShortTimeFormat variable to see what formatting needs to be applied. It is therefor entirely equivalent to a FormatDateTime(’t’,Time) call. Errors: None. See also: Listing: sysutex/ex25.pp Program Example25 ; { T h i s program demonstrates t h e TimeToStr f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( ’ The c u r r e n t t i m e i s : End .

22.5

’ , TimeToStr ( Time ) ) ;

Disk functions

AddDisk (Linux only) Declaration: Function AddDisk (Const PAth :

String) :

Longint;

Description: On Linux both the DiskFree (45) and DiskSize (46) functions need a file on the specified drive, since is required for the statfs system call. These filenames are set in drivestr[0..26], and the first 4 have been preset to : Disk 0’.’ default drive - hence current directory is used. Disk 1’/fd0/.’ floppy drive 1. Disk 2’/fd1/.’ floppy drive 2. Disk 3’/’ C: equivalent of DOS is the root partition. Drives 4..26 can be set by your own applications with the AddDisk call. The AddDisk call adds Path to the names of drive files, and returns the number of the disk that corresponds to this drive. If you add more than 21 drives, the count is wrapped to 4. Errors: None. See also: DiskFree (426), DiskSize (427) 425

CHAPTER 22. THE SYSUTILS UNIT.

CreateDir Declaration: Function CreateDir(Const NewDir :

String) :

Boolean;

Description: CreateDir creates a new directory with name NewDir. If the directory doesn’t contain an absolute path, then the directory is created below the current working directory. The function returns True if the directory was successfully created, False otherwise. Errors: In case of an error, the function returns False. See also: RemoveDir (428) Listing: sysutex/ex26.pp Program Example26 ; { T h i s program demonstrates t h e C r e a t e D i r and RemoveDir f u n c t i o n s } { Run t h i s program t w i c e i n t h e same d i r e c t o r y } Uses s y s u t i l s ; Begin I f Not D i r e c t o r y E x i s t s ( ’ NewDir ’ ) then I f Not C r e a t e D i r ( ’ NewDir ’ ) Then Writeln ( ’ Failed to create d i r e c t o r y else W r i t e l n ( ’ Created " NewDir " d i r e c t o r y Else I f Not RemoveDir ( ’ NewDir ’ ) Then W r i t e l n ( ’ F a i l e d t o remove d i r e c t o r y else W r i t e l n ( ’ Removed " NewDir " d i r e c t o r y End .

! ’) ’)

! ’) ’ );

DiskFree Declaration: Function DiskFree(Drive :

Byte) :

Int64;

Description: DiskFree returns the free space (in bytes) on disk Drive. Drive is the number of the disk drive: 0for the current drive. 1for the first floppy drive. 2for the second floppy drive. 3for the first hard-disk parttion. 4-26for all other drives and partitions. Remark Under LINUX, and Unix in general, the concept of disk is different than the DOS one, since the filesystem is seen as one big directory tree. For this reason, the DiskFree and DiskSize (46) functions must be mimicked using filenames that reside on the partitions. For more information, see AddDisk (425) Errors: On error, -1 is returned. See also: DiskSize (427), AddDisk (425) Listing: sysutex/ex27.pp 426

CHAPTER 22. THE SYSUTILS UNIT.

Program Example27 ; { T h i s program demonstrates t h e DiskFree f u n c t i o n } Uses s y s u t i l s ; Begin Write ( Writeln Write ( Writeln End .

’ Size o f c u r r e n t d i s k : ( ’ ( = ’ , DiskSize ( 0 ) div 1 0 2 4 , ’ Free space o f c u r r e n t d i s k : ( ’ ( = ’ , Diskfree ( 0 ) div 1 0 2 4 ,

’ , DiskSize ( 0 ) ) ; ’k) ’ ); ’ , Diskfree ( 0 ) ) ; ’k) ’ );

DiskSize Declaration: Function DiskSize(Drive :

Byte) :

Int64;

Description: DiskSize returns the size (in bytes) of disk Drive. Drive is the number of the disk drive: 0for the current drive. 1for the first floppy drive. 2for the second floppy drive. 3for the first hard-disk parttion. 4-26for all other drives and partitions. Remark Under LINUX, and Unix in general, the concept of disk is different than the DOS one, since the filesystem is seen as one big directory tree. For this reason, the DiskFree (45) and DiskSize functions must be mimicked using filenames that reside on the partitions. For more information, see AddDisk (425) Errors: On error, -1 is returned. See also: DiskFree (426), AddDisk (425) For an example, see DiskFree (426).

GetCurrentDir Declaration: Function GetCurrentDir :

String;

Description: GetCurrentDir returns the current working directory. Errors: None. See also: SetCurrentDir (428), DiskFree (45), DiskSize (46) Listing: sysutex/ex28.pp Program Example28 ; { T h i s program demonstrates t h e G e t C u r r e n t D i r f u n c t i o n } Uses s y s u t i l s ;

427

CHAPTER 22. THE SYSUTILS UNIT.

Begin Writeln ( ’ Current D i r e c t o r y i s : End .

’ , GetCurrentDir ) ;

RemoveDir Declaration: Function RemoveDir(Const Dir :

String) :

Boolean;

Description: RemoveDir removes directory Dir from the disk. If the directory is not absolue, it is appended to the current working directory. Errors: In case of error (e.g. the directory isn’t empty) the function returns False. If successful, True is returned. See also: For an example, see CreateDir (426).

SetCurrentDir Declaration: Function SetCurrentDir(Const NewDir :

String) :

Boolean;

Description: SetCurrentDir sets the current working directory of your program to NewDir. It returns True if the function was successfull, False otherwise. Errors: In case of error, False is returned. See also: GetCurrentDir (427) Listing: sysutex/ex29.pp Program Example29 ; { T h i s program demonstrates t h e S e t C u r r e n t D i r f u n c t i o n } Uses s y s u t i l s ; Begin I f S e t C u r r e n t D i r ( ’ . . ’ ) Then W r i t e l n ( ’Now i n d i r e c t o r y ’ , G e t C u r r e n t D i r ) else W r i t e l n ( ’ Change d i r e c t o r y t o . . f a i l e d . ’ ) ; End .

22.6

File handling functions

ChangeFileExt Declaration: Function ChangeFileExt(const FileName, Extension:

string):

string;

Description: ChangeFileExt changes the file extension in FileName to Extension. The extension Extension includes the starting . (dot). The previous extension of FileName are all characters after the last ., the . character included. If FileName doesn’t have an extension, Extension is just appended. 428

CHAPTER 22. THE SYSUTILS UNIT.

Errors: None. See also: ExtractFileName (432), ExtractFilePath (432), ExpandFileName (430)

DeleteFile Declaration: Function DeleteFile(Const FileName :

String) :

Boolean;

Description: DeleteFile deletes file FileName from disk. The function returns True if the file was successfully removed, False otherwise. Errors: On error, False is returned. See also: FileCreate (434), FileExists (435) Listing: sysutex/ex31.pp Program Example31 ; { T h i s program demonstrates t h e D e l e t e F i l e f u n c t i o n } Uses s y s u t i l s ; Var Line : String ; F , I : Longint ; Begin F:= FileCreate ( ’ t e s t . t x t ’ ) ; L i n e : = ’Some s t r i n g l i n e . ’ #10; For I : = 1 to 1 0 do F i l e W r i t e ( F , L i n e [ 1 ] , Length ( L i n e ) ) ; FileClose ( F ) ; DeleteFile ( ’ t e s t . t x t ’ ) ; End .

DoDirSeparators Declaration: Procedure DoDirSeparators(Var FileName :

String);

Description: This function replaces all directory separators ’ ’ and ’/’ to the directory separator character for the current system. Errors: None. See also: ExtractFileName (432), ExtractFilePath (432) Listing: sysutex/ex32.pp Program Example32 ; { T h i s program demonstrates t h e DoDirSeparators f u n c t i o n } { $H+ } Uses s y s u t i l s ; Procedure T e s t i t ( F : S t r i n g ) ;

429

CHAPTER 22. THE SYSUTILS UNIT.

begin W r i t e l n ( ’ Before : ’ , F ) ; DoDirSeparators ( F ) ; Writeln ( ’ A f t e r : ’ ,F ) ; end ; Begin Testit Testit Testit Testit End .

( ( ( (

GetCurrentDir ) ; ’ c : \ pp \ b i n \ win32 ’ ) ; ’ / usr / l i b / fpc ’ ) ; ’ \ usr \ l i b \ fpc ’ ) ;

ExpandFileName Declaration: Function ExpandFileName(Const FileName :

string):

String;

Description: ExpandFileName expands the filename to an absolute filename. It changes all directory separator characters to the one appropriate for the system first. Errors: None. See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), ExtractRelativePath (432) Listing: sysutex/ex33.pp Program Example33 ; { T h i s program demonstrates t h e ExpandFileName f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( F : S t r i n g ) ; begin W r i t e l n ( F , ’ expands t o : end ;

’ , ExpandFileName ( F ) ) ;

Begin T e s t i t ( ’ ex33 . pp ’ ) ; T e s t i t ( ParamStr ( 0 ) ) ; T e s t i t ( ’ / pp / b i n / win32 / ppc386 ’ ) ; T e s t i t ( ’ \ pp \ b i n \ win32 \ ppc386 ’ ) ; Testit ( ’ . ’ ); End .

ExpandUNCFileName Declaration: Function ExpandUNCFileName(Const FileName :

string):

String;

Description: ExpandUNCFileName runs ExpandFileName (430) on FileName and then attempts to replace the driveletter by the name of a shared disk. Errors: None. 430

CHAPTER 22. THE SYSUTILS UNIT.

See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), ExtractRelativePath (432)

ExtractFileDir Declaration: Function ExtractFileDir(Const FileName :

string):

string;

Description: ExtractFileDir returns only the directory part of FileName, not including a driveletter. The directory name has NO ending directory separator, in difference with ExtractFilePath (432). Errors: None. See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), ExtractRelativePath (432) Listing: sysutex/ex34.pp Program Example34 ; { T h i s program demonstrates t h e Ex t ra ct F il e Na m e f u n c t i o n } { $H+ } Uses s y s u t i l s ; Procedure T e s t i t ( F : S t r i n g ) ; begin Writeln Writeln Writeln Writeln Writeln Writeln end ;

( ( ( ( ( (

Begin Testit Testit Testit Testit End .

( Paramstr ( 0 ) ) ; ( ’ / u s r / l o c a l / b i n / mysqld ’ ) ; ( ’ c : \ pp \ b i n \ win32 \ ppc386 . exe ’ ) ; ( ’ / pp / b i n / win32 / ppc386 . exe ’ ) ;

’ FileName ’ Has Name ’ Has Path ’ Has E x t e n s i o n ’ Has D i r e c t o r y ’ Has D r i v e

: : : : : :

’ ’ ’ ’ ’ ’

,F ) ; , ExtractFileName ( F ) ) ; , ExtractFilePath (F ) ) ; , ExtractFileExt (F ) ) ; , ExtractFileDir (F ) ) ; , ExtractFileDrive (F ) ) ;

ExtractFileDrive Declaration: Function ExtractFileDrive(const FileName:

string):

string;

Description: Extract Errors: See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), ExtractRelativePath (432) For an example, see ExtractFileDir (431).

431

CHAPTER 22. THE SYSUTILS UNIT.

ExtractFileExt Declaration: Function ExtractFileExt(const FileName:

string):

string;

Description: ExtractFileExt returns the extension (including the .(dot) character) of FileName. Errors: None. See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), ExtractRelativePath (432) For an example, see ExtractFileDir (431).

ExtractFileName Declaration: Function ExtractFileName(const FileName:

string):

string;

Description: ExtractFileName returns the filename part from FileName. The filename consists of all characters after the last directory separator character (’/’ or ’´) or drive letter. The full filename can always be reconstucted by concatenating the result of ExtractFilePath (432) and ExtractFileName. Errors: None. See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432),ExtractRelativePath (432) For an example, see ExtractFileDir (431).

ExtractFilePath Declaration: Function ExtractFilePath(const FileName:

string):

string;

Description: ExtractFilePath returns the path part (including driveletter) from FileName. The path consists of all characters before the last directory separator character (’/’ or ’´), including the directory separator itself. In case there is only a drive letter, that will be returned. The full filename can always be reconstucted by concatenating the result of ExtractFilePath and ExtractFileName (432). Errors: None. See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), ExtractRelativePath (432) For an example, see ExtractFileDir (431).

ExtractRelativePath Declaration: Function ExtractRelativePath(Const BaseName,DestNAme :

String):

String;

Description: ExtractRelativePath constructs a relative path to go from BaseName to DestName. If DestName is on another drive (Not on Linux) then the whole Destname is returned. Note: This function does not exist in the Delphi unit. Errors: None. 432

CHAPTER 22. THE SYSUTILS UNIT.

See also: ExtractFileName (432), ExtractFilePath (432), ExtractFileDir (431), ExtractFileDrive (431), ExtractFileExt (432), Listing: sysutex/ex35.pp Program Example35 ; { T h i s program demonstrates t h e E x t r a c t R e l a t i v e P a t h f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( FromDir , ToDir : S t r i n g ) ; begin Write ( ’ From " ’ , FromDir , ’ " t o " ’ , ToDir , ’ " v i a " ’ ) ; W r i t e l n ( E x t r a c t R e l a t i v e P a t h ( FromDir , ToDir ) , ’ " ’ ) ; end ; Begin Testit Testit Testit Testit End .

( ( ( (

’ / pp / s r c / c o m p i l e r ’ , ’ / pp / b i n / win32 / ppc386 ’ ) ; ’ / pp / b i n / win32 / ppc386 ’ , ’ / pp / s r c / c o m p i l e r ’ ) ; ’ e : / pp / b i n / win32 / ppc386 ’ , ’ d : / pp / s r c / c o m p i l e r ’ ) ; ’ e : \ pp \ b i n \ win32 \ ppc386 ’ , ’ d : \ pp \ s r c \ c o m p i l e r ’ ) ;

FileAge Declaration: Function FileAge(Const FileName :

String):

Longint;

Description: FileAge returns the last modification time of file FileName. The FileDate format can be transformed to TDateTime format with the FileDateToDateTime (418) function. Errors: In case of errors, -1 is returned. See also: FileDateToDateTime (418), FileExists (435), FileGetAttr (435) Listing: sysutex/ex36.pp Program Example36 ; { T h i s program demonstrates t h e F i l e A g e f u n c t i o n } Uses s y s u t i l s ; Var S : TDateTime ; fa : Longint ; Begin f a : = FileAge ( ’ ex36 . pp ’ ) ; I f Fa−1 then begin S: = FileDateTodateTime ( f a ) ; W r i t e l n ( ’ I ’ ’m from ’ , DateTimeToStr (S ) ) end ; End .

433

CHAPTER 22. THE SYSUTILS UNIT.

FileClose Declaration: Procedure FileClose(Handle :

Longint);

Description: FileClose closes the file handle Handle. After this call, attempting to read or write from the handle will result in an error. Errors: None. See also: FileCreate (434), FileWrite (440), FileOpen (437), FileRead (437), FileTruncate (439), FileSeek (438) For an example, see FileCreate (434)

FileCreate Declaration: Function FileCreate(Const FileName :

String) :

Longint;

Description: FileCreate creates a new file with name FileName on the disk and returns a file handle which can be used to read or write from the file with the FileRead (437) and FileWrite (440) functions. If a file with name FileName already existed on the disk, it is overwritten. Errors: If an error occurs (e.g. disk full or non-existent path), the function returns -1. See also: FileClose (434), FileWrite (440), FileOpen (437), FileRead (437), FileTruncate (439), FileSeek (438) Listing: sysutex/ex37.pp Program Example37 ; { T h i s program demonstrates t h e F i l e C r e a t e f u n c t i o n } Uses s y s u t i l s ; Var I , J , F : L o n g i n t ; Begin F:= FileCreate ( ’ t e s t . dat ’ ) ; I f F=−1 then Halt ( 1 ) ; For I : = 0 to 1 0 0 do F i l e W r i t e ( F , I , SizeOf ( i ) ) ; FileClose ( f ) ; F : = FileOpen ( ’ t e s t . d a t ’ , fmOpenRead ) ; For I : = 0 to 1 0 0 do begin FileRead ( F , J , SizeOF ( J ) ) ; I f J I then W r i t e l n ( ’ Mismatch a t f i l e p o s i t i o n ’ , I ) end ; FileSeek ( F , 0 , fsFromBeginning ) ; Randomize ; Repeat FileSeek ( F , Random( 1 0 0 ) ∗ 4 , fsFromBeginning ) ; FileRead ( F , J , SizeOf ( J ) ) ; W r i t e l n ( ’ Random read : ’ , j ) ; U n t i l J >80;

434

CHAPTER 22. THE SYSUTILS UNIT.

FileClose ( F ) ; F : = FileOpen ( ’ t e s t . d a t ’ , fmOpenWrite ) ; I :=50∗ SizeOf ( L o n g i n t ) ; I f F i l e T r u n c a t e ( F , I ) then Writeln ( ’ SuccessFully truncated f i l e to ’ , I , ’ bytes . ’ ) ; FileClose ( F ) ; End .

FileExists Declaration: Function FileExists(Const FileName :

String) :

Boolean;

Description: FileExists returns True if a file with name FileName exists on the disk, False otherwise. Errors: None. See also: FileAge (433), FileGetAttr (435), FileSetAttr (439) Listing: sysutex/ex38.pp Program Example38 ; { T h i s program demonstrates t h e F i l e E x i s t s f u n c t i o n } Uses s y s u t i l s ; Begin I f F i l e E x i s t s ( ParamStr ( 0 ) ) Then W r i t e l n ( ’ A l l i s w e l l , I seem t o e x i s t . ’ ) ; End .

FileGetAttr Declaration: Function FileGetAttr(Const FileName :

String) :

Longint;

Description: FileGetAttr returns the attribute settings of file FileName. The attribute is a OR-ed combination of the following constants: faReadOnlyThe file is read-only. faHiddenThe file is hidden. (On LINUX, this means that the filename starts with a dot) faSysFileThe file is a system file (On file).

LINUX ,

this means that the file is a character, block or FIFO

faVolumeIdVolume Label. Not possible under LINUX. faDirectoryFile is a directory. faArchivefile is an archive. Not possible on LINUX. Errors: In case of error, -1 is returned. See also: FileSetAttr (439), FileAge (433), FileGetDate (436). Listing: sysutex/ex40.pp

435

CHAPTER 22. THE SYSUTILS UNIT.

Program Example40 ; { T h i s program demonstrates t h e F i l e G e t A t t r f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( Name : S t r i n g ) ; Var F : L o n g i n t ; Begin F : = F i l e G e t A t t r (Name ) ; I f F−1 then begin W r i t e l n ( ’ T e s t i n g : ’ ,Name ) ; I f ( F and faReadOnly ) < >0 then W r i t e l n ( ’ F i l e i s ReadOnly ’ ) ; I f ( F and faHidden ) < >0 then W r i t e l n ( ’ F i l e i s hidden ’ ) ; I f ( F and f a S y s F i l e ) < >0 then W r i t e l n ( ’ F i l e i s a system f i l e ’ ) ; I f ( F and faVolumeID ) < >0 then Writeln ( ’ F i l e i s a disk l a b e l ’ ) ; I f ( F and f a A r c h i v e ) < >0 then Writeln ( ’ F i l e i s a r t c h i v e f i l e ’ ) ; I f ( F and f a D i r e c t o r y ) < >0 then Writeln ( ’ F i l e i s a d i r e c t o r y ’ ) ; end else W r i t e l n ( ’ E r r o r r e a d i n g a t t r i b i t e s o f ’ ,Name ) ; end ; begin testit testit testit testit End .

( ’ ex40 . pp ’ ) ; ( ParamStr ( 0 ) ) ; ( ’ . ’ ); ( ’ / ’ );

FileGetDate Declaration: Function FileGetDate(Handle :

Longint) :

Longint;

Description: FileGetdate returns the filetime of the opened file with filehandle Handle. It is the same as FileAge (433), with this difference that FileAge only needs the file name, while FilegetDate needs an open file handle. Errors: On error, -1 is returned. See also: FileAge (433) Listing: sysutex/ex39.pp Program Example39 ; { T h i s program demonstrates t h e F i l e G e t D a t e f u n c t i o n }

436

CHAPTER 22. THE SYSUTILS UNIT.

Uses s y s u t i l s ; Var F , D : L o n g i n t ; Begin F:= FileCreate ( ’ t e s t . dat ’ ) ; D: = FileGetDate ( F ) ; W r i t e l n ( ’ F i l e c r e a t e d on ’ , DateTimeToStr ( FileDateToDateTime (D ) ) ) ; FileClose ( F ) ; DeleteFile ( ’ t e s t . dat ’ ) ; End .

FileOpen Declaration: Function FileOpen(Const FileName :

string; Mode :

Integer) :

Longint;

Description: FileOpen opens a file with name FileName with mode Mode. Mode can be one of the following constants: fmOpenReadThe file is opened for reading. fmOpenWriteThe file is opened for writing. fmOpenReadWriteThe file is opened for reading and writing. If the file has been successfully opened, it can be read from or written to (depending on the Mode parameter) with the FileRead (437) and FileWrite functions. Remark that you cannot open a file if it doesn’t exist yet, i.e. it will not be created for you. If you want tp create a new file, or overwrite an old one, use the FileCreate (434) function. Errors: On Error, -1 is returned. See also: FileClose (434), FileWrite (440), FileCreate (434), FileRead (437), FileTruncate (439), FileSeek (438) For an example, see FileOpen (437)

FileRead Declaration: Function FileRead(Handle : Longint;

Longint; Var Buffer; Count :

longint) :

Description: FileRead reads Count bytes from file-handle Handle and stores them into Buffer. Buffer must be at least Count bytes long. No checking on this is performed, so be careful not to overwrite any memory. Handle must be the result of a FileOpen (437) call. Errors: On error, -1 is returned. See also: FileClose (434), FileWrite (440), FileCreate (434), FileOpen (437), FileTruncate (439), FileSeek (438) For an example, see FileCreate (434)

437

CHAPTER 22. THE SYSUTILS UNIT.

FileSearch Declaration: Function FileSearch(Const Name, DirList :

String) :

String;

Description: FileSearch looks for the file Name in DirList, where dirlist is a list of directories, separated by semicolons or colons. It returns the full filename of the first match found. Errors: On error, an empty string is returned. See also: ExpandFileName (430), FindFirst (440) Listing: sysutex/ex41.pp Program Example41 ; { Program t o demonstrate t h e F i l e S e a r c h f u n c t i o n . } Uses S y s u t i l s ; Const { $ i f d e f unix } FN = ’ f i n d ’ ; P = ’ . : / bin : / usr / bin ’ ; { $else } FN = ’ f i n d . exe ’ ; P = ’ c : \ dos ; c : \ windows ; c : \ windows \ system ; c : \ windows \ system32 ’ ; { $endif } begin Writeln ( ’ f i n d i s i n : end .

’ , FileSearch ( FN, P ) ) ;

FileSeek Declaration: Function FileSeek(Handle,Offset,Origin :

Longint) :

Longint;

Description: FileSeek sets the file pointer on position Offset, starting from Origin. Origin can be one of the following values: fsFromBeginningOffset is relative to the first byte of the file. This position is zero-based. i.e. the first byte is at offset 0. fsFromCurrentOffset is relative to the current position. fsFromEndOffset is relative to the end of the file. This means that Offset can only be zero or negative in this case. If successfull, the function returns the new file position, relative to the beginning of the file. Remark: The abovementioned constants do not exist in Delphi. Errors: On error, -1 is returned. See also: FileClose (434), FileWrite (440), FileCreate (434), FileOpen (437) FileRead (437), FileTruncate (439) Listing: sysutex/ex42.pp

438

CHAPTER 22. THE SYSUTILS UNIT.

Program Example42 ; { T h i s program demonstrates t h e F i l e S e t A t t r f u n c t i o n } Uses s y s u t i l s ; Begin I f F i l e S e t A t t r ( ’ ex40 . pp ’ , faReadOnly or faHidden ) = 0 then W r i t e l n ( ’ S u c c e s s f u l l y made f i l e hidden and read−o n l y . ’ ) else W r i t e l n ( ’ Coulnd ’ ’ t make f i l e hidden and read−o n l y . ’ ) ; End .

For an example, see FileCreate (434)

FileSetAttr (Not on Linux) Declaration: Function FileSetAttr(Const Filename :

String; Attr:

longint) :

Longint;

Description: FileSetAttr sets the attributes of FileName to Attr. If the function was successful, 0 is returned, -1 otherwise. Attr can be set to an OR-ed combination of the pre-defined faXXX constants. Errors: On error, -1 is returned (always on linux). See also: FileGetAttr (435), FileGetDate (436), FileSetDate (439).

FileSetDate (Not on Linux) Declaration: Function FileSetDate(Handle,Age :

Longint) :

Longint;

Description: FileSetDate sets the file date of the file with handle Handle to Age, where Age is a DOS date-and-time stamp value. The function returns zero of successfull. Errors: On Linux, -1 is always returned, since this is impossible to implement. On Windows and DOS, a negative error code is returned. See also:

FileTruncate Declaration: Function FileTruncate(Handle,Size:

Longint) :

boolean;

Description: FileTruncate truncates the file with handle Handle to Size bytes. The file must have been opened for writing prior to this call. The function returns True is successful, False otherwise. Errors: On error, the function returns False. See also: FileClose (434), FileWrite (440), FileCreate (434), FileOpen (437) FileRead (437), FileSeek (438) For an example, see FileCreate (434).

439

CHAPTER 22. THE SYSUTILS UNIT.

FileWrite Declaration: Function FileWrite(Handle : : Longint;

Longint; Var Buffer; Count :

Longint)

Description: FileWrite writes Count bytes from Buffer to the file with handle Handle. Prior to this call, the file must have been opened for writing. Buffer must be at least Count bytes large, or a memory access error may occur. The function returns the number of bytes written, or -1 in case of an error. Errors: In case of error, -1 is returned. See also: FileClose (434), FileCreate (434), FileOpen (437) FileRead (437), FileTruncate (439), FileSeek (438) For an example, see FileCreate (434).

FindClose Declaration: Procedure FindClose(Var F : TSearchrec); Description: FindClose ends a series of FindFirst (440)/FindNext (441) calls, and frees any memory used by these calls. It is absolutely necessary to do this call, or huge memory losses may occur. Errors: None. See also: FindFirst (440), FindNext (441). For an example, see FindFirst (440).

FindFirst Declaration: Function FindFirst(Const Path : TSearchRec) : Longint;

String; Attr :

Longint; Var Rslt :

Description: FindFirst looks for files that match the name (possibly with wildcards) in Path and attributes Attr. It then fills up the Rslt record with data gathered about the file. It returns 0 if a file matching the specified criteria is found, a nonzero value (-1 on linux) otherwise. The Rslt record can be fed to subsequent calls to FindNext, in order to find other files matching the specifications. remark: A FindFirst call must always be followed by a FindClose (440) call with the same Rslt record. Failure to do so will result in memory loss. Errors: On error the function returns -1 on linux, a nonzero error code on Windows. See also: FindClose (49)FindCloseSys, FindNext (441). Listing: sysutex/ex43.pp Program Example43 ; { T h i s program demonstrates t h e F i n d F i r s t f u n c t i o n } Uses S y s U t i l s ; Var I n f o : TSearchRec ;

440

CHAPTER 22. THE SYSUTILS UNIT.

Count : L o n g i n t ; Begin Count : = 0 ; I f F i n d F i r s t ( ’ / ∗ ’ , f a A n y F i l e and f a D i r e c t o r y , I n f o ) = 0 then begin Repeat Inc ( Count ) ; With I n f o do begin I f ( A t t r and f a D i r e c t o r y ) = f a D i r e c t o r y then Write ( ’ D i r : ’ ) ; W r i t e l n ( Name: 4 0 , Size : 1 5 ) ; end ; U n t i l FindNext ( i n f o ) < >0; end ; FindClose ( I n f o ) ; W r i t e l n ( ’ F i n i s h e d search . Found ’ , Count , ’ matches ’ ) ; End .

FindNext Declaration: Function FindNext(Var Rslt :

TSearchRec) :

Longint;

Description: FindNext finds a next occurrence of a search sequence initiated by FindFirst. If another record matching the criteria in Rslt is found, 0 is returned, a nonzero constant is returned otherwise. remark: The last FindNext call must always be followed by a FindClose call with the same Rslt record. Failure to do so will result in memory loss. Errors: On error (no more file is found), a nonzero constant is returned. See also: FindFirst (440), FindClose (49) For an example, see FindFirst (440)

GetDirs Declaration: Function GetDirs(Var DirName : : Longint;

String; Var Dirs :

Array of pchar)

Description: GetDirs splits DirName in a null-byte separated list of directory names, Dirs is an array of PChars, pointing to these directory names. The function returns the number of directories found, or -1 if none were found. DirName must contain only OSDirSeparator as Directory separator chars. Errors: None. See also: ExtractRelativePath (432) Listing: sysutex/ex45.pp Program Example45 ; { T h i s program demonstrates t h e G e t D i r s f u n c t i o n } { $H+ }

441

CHAPTER 22. THE SYSUTILS UNIT.

Uses s y s u t i l s ; Var D i r s : Array [ 0 . . 1 2 7 ] of pchar ; I , Count : l o n g i n t ; D i r , NewDir : S t r i n g ; Begin Dir := GetCurrentDir ; Writeln ( ’ Dir : ’ , Dir ) ; NewDir : = ’ ’ ; count : = G e t D i r s ( D i r , D i r s ) ; For I : = 0 to Count −1 do begin NewDir : = NewDir+ ’ / ’ +StrPas ( D i r s [ I ] ) ; W r i t e l n ( NewDir ) ; end ; End .

RenameFile Declaration: Function RenameFile(Const OldName, NewName :

String) :

Boolean;

Description: RenameFile renames a file from OldName to NewName. The function returns True if successful, False otherwise. Remark: you cannot rename across disks or partitions. Errors: On Error, False is returned. See also: DeleteFile (429) Listing: sysutex/ex44.pp Program Example44 ; { T h i s program demonstrates t h e RenameFile f u n c t i o n } Uses s y s u t i l s ; Var F : L o n g i n t ; S : String ; Begin S: = ’Some s h o r t f i l e . ’ ; F : = F i l e C r e a t e ( ’ t e s t . dap ’ ) ; F i l e W r i t e ( F , S [ 1 ] , Length ( S ) ) ; FileClose ( F ) ; I f RenameFile ( ’ t e s t . dap ’ , ’ t e s t . d a t ’ ) then W r i t e l n ( ’ S u c c e s s f u l l y renamed f i l e s . ’ ) ; End .

SetDirSeparators Declaration: Function SetDirSeparators(Const FileName :

String) :

String;

Description: SetDirSeparators returns FileName with all possible DirSeparators replaced by OSDirSeparator.

442

CHAPTER 22. THE SYSUTILS UNIT.

Errors: None. See also: ExpandFileName (430), ExtractFilePath (432), ExtractFileDir (431) Listing: sysutex/ex47.pp Program Example47 ; { T h i s program demonstrates t h e S e t D i r S e p a r a t o r s f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( S e t D i r S e p a r a t o r s ( ’ / pp \ b i n / win32 \ ppc386 ’ ) ) ; End .

22.7

PChar functions

Introduction Most PChar functions are the same as their counterparts in the STRINGS unit. The following functions are the same : 1. StrCat (392) : Concatenates two PChar strings. 2. StrComp (393) : Compares two PChar strings. 3. StrCopy (393) : Copies a PChar string. 4. StrECopy (394) : Copies a PChar string and returns a pointer to the terminating null byte. 5. StrEnd (395) : Returns a pointer to the terminating null byte. 6. StrIComp (395) : Case insensitive compare of 2 PChar strings. 7. StrLCat (396) : Appends at most L characters from one PChar to another PChar. 8. StrLComp (396) : Case sensitive compare of at most L characters of 2 PChar strings. 9. StrLCopy (397) : Copies at most L characters from one PChar to another. 10. StrLen (397) : Returns the length (exclusive terminating null byte) of a PChar string. 11. StrLIComp (398) : Case insensitive compare of at most L characters of 2 PChar strings. 12. StrLower (398) : Converts a PChar to all lowercase letters. 13. StrMove (399) : Moves one PChar to another. 14. StrNew (399) : Makes a copy of a PChar on the heap, and returns a pointer to this copy. 15. StrPos (401) : Returns the position of one PChar string in another? 16. StrRScan (401) : returns a pointer to the last occurrence of on PChar string in another one. 17. StrScan (401) : returns a pointer to the first occurrence of on PChar string in another one. 18. StrUpper (402) : Converts a PChar to all uppercase letters. The subsequent functions are different from their counterparts in STRINGS, although the same examples can be used. 443

CHAPTER 22. THE SYSUTILS UNIT.

StrAlloc Declaration: Function StrAlloc(Size:

cardinal):

PChar;

Description: StrAlloc reserves memory on the heap for a string with length Len, terminating #0 included, and returns a pointer to it. Additionally, StrAlloc allocates 4 extra bytes to store the size of the allocated memory. Therefore this function is NOT compatible with the StrAlloc (392) function of the Strings unit. Errors: None. See also: StrBufSize (444), StrDispose (444), StrAlloc (392) For an example, see StrBufSize (444).

StrBufSize Declaration: Function StrBufSize(var Str:

PChar):

cardinal;

Description: StrBufSize returns the memory allocated for Str. This function ONLY gives the correct result if Str was allocated using StrAlloc (444). Errors: If no more memory is available, a runtime error occurs. See also: StrAlloc (444).StrDispose (444). Listing: sysutex/ex46.pp Program Example46 ; { T h i s program demonstrates t h e S t r B u f S i z e f u n c t i o n } { $H+ } Uses s y s u t i l s ; Const S

= ’Some n i c e s t r i n g ’ ;

Var P : Pchar ; Begin P: = S t r A l l o c ( Length ( S ) + 1 ) ; StrPCopy ( P , S ) ; Write ( P , ’ has l e n g t h ’ , length (S ) ) ; W r i t e l n ( ’ and b u f f e r s i z e ’ , S t r B u f S i z e (P ) ) ; StrDispose ( P ) ; End .

StrDispose Declaration: Procedure StrDispose(var Str:

PChar);

Description: StrDispose frees any memory allocated for Str. This function will only function correctly if Str has been allocated using StrAlloc (444) from the SYSUTILS unit. Errors: If an invalid pointer is passed, or a pointer not allocated with StrAlloc, an error may occur. See also: StrBufSize (444), StrAlloc (444), StrDispose (394) For an example, see StrBufSize (444). 444

CHAPTER 22. THE SYSUTILS UNIT.

StrPCopy Declaration: Function StrPCopy(Dest:

PChar; Source:

string):

PChar;

Description: StrPCopy Converts the Ansistring in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the string Source, i.e. Length(Source)+1 bytes. Errors: No checking is performed to see whether Dest points to enough memory to contain Source. See also: StrPLCopy (445), StrPCopy (400) For an example, see StrPCopy (400).

StrPLCopy Declaration: Function StrPLCopy(Dest: PChar;

PChar; Source:

string; MaxLen:

cardinal):

Description: StrPLCopy Converts maximally MaxLen characters of the Ansistring in Source to a Nullterminated string, and copies it to Dest. Dest needs enough room to contain the characters. Errors: No checking is performed to see whether Dest points to enough memory to contain L characters of Source. Errors: See also: StrPCopy (445).

StrPas Declaration: Function StrPas(Str:

PChar):

string;

Description: Converts a null terminated string in Str to an Ansitring, and returns this string. This string is NOT truncated at 255 characters as is the Errors: None. See also: StrPas (400). For an example, see StrPas (400).

22.8

String handling functions

AdjustLineBreaks Declaration: Function AdjustLineBreaks(const S: string):

string;

Description: AdjustLineBreaks will change all #13 characters with #13#10 on W INDOWS NT and DOS. On LINUX, all #13#10 character pairs are converted to #10 and single #13 characters also. Errors: None. See also: AnsiCompareStr (446), AnsiCompareText (447) Listing: sysutex/ex48.pp

445

CHAPTER 22. THE SYSUTILS UNIT.

Program Example48 ; { T h i s program demonstrates t h e A d j u s t L i n e B r e a k s f u n c t i o n } Uses s y s u t i l s ; Const S = ’ T h i s i s a s t r i n g ’ #13 ’ w i t h embedded ’ #10 ’ l i n e f e e d and ’ + #13 ’CR c h a r a c t e r s ’ ; Begin W r i t e l n ( A d j u s t L i n e B r e a k s (S ) ) ; End .

AnsiCompareStr Declaration: Function AnsiCompareStr(const S1, S2:

string):

integer;

Description: AnsiCompareStr compares two strings and returns the following result: S2. the comparision takes into account Ansi characters, i.e. it takes care of strange accented characters. Contrary to AnsiCompareText (447), the comparision is case sensitive. Errors: None. See also: AdjustLineBreaks (445), AnsiCompareText (447) Listing: sysutex/ex49.pp Program Example49 ; { T h i s program demonstrates t h e AnsiCompareStr f u n c t i o n } { $H+ } Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : S t r i n g ) ; Var R : L o n g i n t ; begin R: = AnsiCompareStr ( S1 , S2 ) ; Write ( ’ " ’ , S1 , ’ " i s ’ ) ; I f R ’ , s ) ; Fmt : = ’ [%10d ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; f m t : = ’ [%.4 d ] ’ ; S: = Format ( fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10.4d ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: d ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10d ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10.4 d ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:−10d ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: −10.4d ] ’ ; S: = Format ( fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗d ] ’ ; S: = Format ( fmt , [ 4 , 5 , 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ;

464

CHAPTER 22. THE SYSUTILS UNIT.

w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; Procedure TestHexaDecimal ; begin try Fmt : = ’ [%x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10.4 x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10 x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10.4 x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:−10x ] ’ ; S: = Format ( Fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: −10.4 x ] ’ ; S: = Format ( fmt , [ 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗x ] ’ ; S: = Format ( fmt , [ 4 , 5 , 1 0 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; Procedure T e s t P o i n t e r ; begin P: = P o i n t e r ( 1 2 3 4 5 6 7 ) ; try Fmt : = ’ [ 0 x%p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x%10p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x%10.4p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x%0:p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x%0:10p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x %0:10.4p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x%0:−10p ] ’ ; S: = Format ( Fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [ 0 x%0:−10.4p ] ’ ; S: = Format ( fmt , [ P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗p ] ’ ; S: = Format ( fmt , [ 4 , 5 , P ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; Procedure T e s t S t r i n g ; begin try Fmt : = ’ [%s ] ’ ; S: = Format ( fmt , [ ’ T h i s i s a s t r i n g ’ ] ) ; W r i t e l n ( f m t : 1 2 , ’ = > ’ , s ) ; f m t : = ’ [%0: s ] ’ ; s : = Format ( fmt , [ ’ T h i s i s a s t r i n g ’ ] ) ; W r i t e l n ( f m t : 1 2 , ’ = > ’ , s ) ; f m t : = ’ [%0:18 s ] ’ ; s : = Format ( fmt , [ ’ T h i s i s a s t r i n g ’ ] ) ; W r i t e l n ( f m t : 1 2 , ’ = > ’ , s ) ;

465

CHAPTER 22. THE SYSUTILS UNIT.

f m t : = ’ [%0:−18s ] ’ ; s : = Format ( fmt , [ ’ T h i s i s a s t r i n g ’ ] ) ; W r i t e l n ( f m t : 1 2 , ’ = > ’ , s ) ; f m t : = ’ [%0:18.12 s ] ’ ; s : = Format ( fmt , [ ’ T h i s i s a s t r i n g ’ ] ) ; W r i t e l n ( f m t : 1 2 , ’ = > ’ , s ) ; f m t : = ’ [%−∗.∗s ] ’ ; s : = Format ( fmt , [ 1 8 , 1 2 , ’ T h i s i s a s t r i n g ’ ] ) ; W r i t e l n ( f m t : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; Procedure T e s t E x p o n e n t i a l ; begin Try Fmt : = ’ [%e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10.4e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10.4 e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:−10e ] ’ ; S: = Format ( Fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: −10.4e ] ’ ; S: = Format ( fmt , [ 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗e ] ’ ; S: = Format ( fmt , [ 4 , 5 , 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; Procedure T e s t N e g a t i v e E x p o n e n t i a l ; begin Try Fmt : = ’ [%e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10.4e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10.4 e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:−10e ] ’ ; S: = Format ( Fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: −10.4e ] ’ ; S: = Format ( fmt , [ − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗e ] ’ ; S: = Format ( fmt , [ 4 , 5 , − 1 . 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ;

466

CHAPTER 22. THE SYSUTILS UNIT.

Procedure T e s t S m a l l E x p o n e n t i a l ; begin Try Fmt : = ’ [%e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10.4e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10.4 e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:−10e ] ’ ; S: = Format ( Fmt , [ 0 . 0 1 2 3 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: −10.4e ] ’ ; S: = Format ( fmt , [ 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗e ] ’ ; S: = Format ( fmt , [ 4 , 5 , 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; Procedure TestSmallNegExponential ; begin Try Fmt : = ’ [%e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%10.4e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:10.4 e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0:−10e ] ’ ; S: = Format ( Fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%0: −10.4e ] ’ ; S: = Format ( fmt , [ − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; Fmt : = ’ [%−∗.∗e ] ’ ; S: = Format ( fmt , [ 4 , 5 , − 0 . 0 1 2 3 4 ] ) ; w r i t e l n ( Fmt : 1 2 , ’ = > ’ , s ) ; except On E : E x c e p t i o n do begin W r i t e l n ( ’ E x c e p t i o n caught : ’ ,E . Message ) ; end ; end ; w r i t e l n ( ’ Press e n t e r ’ ) ; readln ; end ; begin TestInteger ; TestHexadecimal ; TestPointer ; TestExponential ; TestNegativeExponential ; TestSmallExponential ; TestSmallNegExponential ; teststring ; end .

467

CHAPTER 22. THE SYSUTILS UNIT.

FormatBuf Declaration: Function FormatBuf(Var Buffer; BufLen : Cardinal; Const Fmt; fmtLen : Cardinal; Const Args : Array of const) : Cardinal; Description: Format Errors: See also: Listing: sysutex/ex72.pp Program Example72 ; { T h i s program demonstrates t h e FormatBuf f u n c t i o n } Uses s y s u t i l s ; Var S : ShortString ; Const Fmt : S h o r t S t r i n g =

’ For some n i c e examples o f f o m a t t i n g see %s . ’ ;

Begin S: = ’ ’ ; SetLength ( S , FormatBuf ( S[ 1 ] , 2 5 5 , Fmt [ 1 ] , Length ( Fmt ) , [ ’ Format ’ ] ) ) ; Writeln ( S ) ; End .

FormatFloat Declaration: Function FormatFloat(Const format:

String; Value:

Extended):

String;

Description: FormatFloat formats the floating-point value given by Value using the format specifications in Format. The format specifier can give format specifications for positive, negative or zero values (separated by a semicolon). If the formatspecifier is empty or the value needs more than 18 digits to be correctly represented, the result is formatted with a call to FloatToStrF (460) with the ffGeneral format option. The following format specifiers are supported: 0is a digit place holder. If there is a corresponding digit in the value being formatted, then it replaces the 0. If not, the 0 is left as-is. #is also a digit place holder. If there is a corresponding digit in the value being formatted, then it replaces the #. If not, it is removed. by a space. .determines the location of the decimal point. Only the first ’.’ character is taken into account. If the value contains digits after the decimal point, then it is replaced by the value of the DecimalSeparator character. ,determines the use of the thousand separator character in the output string. If the format string contains one or more ’,’ charactes, then thousand separators will be used. The ThousandSeparator character is used. E+determines the use of scientific notation. If ’E+’ or ’E-’ (or their lowercase counterparts) are present then scientific notation is used. The number of digits in the output string is determined by the number of 0 characters after the ’E+’ 468

CHAPTER 22. THE SYSUTILS UNIT.

;This character separates sections for positive, negative, and zero numbers in the format string. Errors: If an error occurs, an exception is raised. See also: FloatToStr (459) Listing: sysutex/ex89.pp Program Example89 ; { T h i s program demonstrates t h e F o rm a t F l o at f u n c t i o n } Uses s y s u t i l s ; Const NrFormat =9; F o r m a t S t r i n g s : Array [ 1 . . NrFormat ] of s t r i n g = ( ’’, ’0 ’ , ’ 0.00 ’ , ’ #.## ’ , ’ # ,##0.00 ’ , ’ # ,##0.00;(# ,##0.00) ’ , ’ # , # # 0 . 0 0 ; ; Zero ’ , ’ 0.000E+00 ’ , ’ #.###E−0 ’ ) ; NrValue = 5 ; FormatValues : Array [ 1 . . NrValue ] of Double = (1234 , −1234 ,0.5 ,0 , −0.5); Width = 1 2 ; FWidth = 2 0 ; Var I , J : Integer ; S : String ; begin Write ( ’ Format ’ : FWidth ) ; For I : = 1 to NrValue do Write ( FormatValues [ i ] : Width : 2 ) ; Writeln ; For I : = 1 to NrFormat do begin Write ( F o r m a t S t r i n g s [ i ] : FWidth ) ; For J : = 1 to NrValue do begin S: = FormatFloat ( F o r m a t S t r i n g s [ I ] , FormatValues [ j ] ) ; Write ( S : Width ) ; end ; Writeln ; end ; End .

IntToHex Declaration: Function IntToHex(Value:

integer; Digits:

469

integer):

string;

CHAPTER 22. THE SYSUTILS UNIT.

Description: IntToHex converts Value to a hexadecimal string representation. The result will contain at least Digits characters. If Digits is less than the needed number of characters, the string will NOT be truncated. If Digits is larger than the needed number of characters, the result is padded with zeroes. Errors: None. See also: IntToStr (470), StrToInt Listing: sysutex/ex73.pp Program Example73 ; { T h i s program demonstrates t h e IntToHex f u n c t i o n } Uses s y s u t i l s ; Var I : l o n g i n t ; Begin For I : = 0 to 3 1 do begin W r i t e l n ( IntToHex ( 1 shl I , 8 ) ) ; W r i t e l n ( IntToHex ( 1 5 shl I , 8 ) ) end ; End .

IntToStr Declaration: Function IntToStr(Value:

integer):

string;

Description: IntToStr coverts Value to it’s string representation. The resulting string has only as much characters as needed to represent the value. If the value is negative a minus sign is prepended to the string. Errors: None. See also: IntToHex (469), StrToInt (476) Listing: sysutex/ex74.pp Program Example74 ; { T h i s program demonstrates t h e I n t T o S t r f u n c t i o n } Uses s y s u t i l s ; Var I : l o n g i n t ; Begin For I : = 0 to 3 1 do begin W r i t e l n ( I n t T o S t r ( 1 shl I ) ) ; W r i t e l n ( I n t T o S t r ( 1 5 shl I ) ) ; end ; End .

470

CHAPTER 22. THE SYSUTILS UNIT.

IsValidIdent Declaration: Function IsValidIdent(const Ident:

string):

boolean;

Description: IsValidIdent returns True if Ident can be used as a compoent name. It returns False otherwise. Ident must consist of a letter or underscore, followed by a combination of letters, numbers or underscores to be a valid identifier. Errors: None. See also: Listing: sysutex/ex75.pp Program Example75 ; { T h i s program demonstrates t h e I s V a l i d I d e n t f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( S : S t r i n g ) ; begin Write ( ’ " ’ ,S , ’ " i s ’ ) ; I f not I s V A l i d I d e n t ( S ) then Write ( ’NOT ’ ) ; Writeln ( ’ a v a l i d i d e n t i f i e r ’ ) ; end ; Begin Testit Testit Testit Testit Testit Testit End .

( ( ( ( ( (

’ _MyObj ’ ) ; ’ My__Obj1 ’ ) ; ’ My_1_Obj ’ ) ; ’ 1MyObject ’ ) ; ’ My@Object ’ ) ; ’ M123 ’ ) ;

LastDelimiter Declaration: Function LastDelimiter(const Delimiters, S: string):

Integer;

Description: LastDelimiter returns the last occurrence of any character in the set Delimiters in the string S. Errors: See also: Listing: sysutex/ex88.pp Program example88 ; { T h i s program demonstrates t h e L a s t D e l i m i t e r f u n c t i o n } uses S y s U t i l s ; begin Writeln ( L a s t D e l i m i t e r ( ’ \ . : ’ , ’ c : \ filename . ext ’ ) ) ; end .

471

CHAPTER 22. THE SYSUTILS UNIT.

LeftStr Declaration: Function LeftStr(const S: string; Count:

integer):

string;

Description: LeftStr returns the Count leftmost characters of S. It is equivalent to a call to Copy(S,1,Count). Errors: None. See also: RightStr (473), TrimLeft (479), TrimRight (479), Trim (478) Listing: sysutex/ex76.pp Program Example76 ; { T h i s program demonstrates t h e L e f t S t r f u n c t i o n } Uses s y s u t i l s ; Begin Writeln Writeln Writeln Writeln End .

( ( ( (

LeftStr ( LeftStr ( LeftStr ( LeftStr (

’ abcdefghijklmnopqrstuvwxyz ’ abcdefghijklmnopqrstuvwxyz ’ abcdefghijklmnopqrstuvwxyz ’ abcdefghijklmnopqrstuvwxyz

’ ’ ’ ’

,20)); ,15)); ,1)); ,200));

LoadStr Declaration: Function LoadStr(Ident:

integer):

string;

Description: This function is not yet implemented. resources are not yet supported. Errors: See also:

LowerCase Declaration: Function LowerCase(const s:

string):

string;

Description: LowerCase returns the lowercase equivalent of S. Ansi characters are not taken into account, only ASCII codes below 127 are converted. It is completely equivalent to the lowercase function of the system unit, and is provided for compatiibility only. Errors: None. See also: AnsiLowerCase (449), UpperCase (480), AnsiUpperCase (455) Listing: sysutex/ex77.pp Program Example77 ; { T h i s program demonstrates t h e LowerCase f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( LowerCase ( ’ THIS WILL COME o u t a l l LoWeRcAsE ! ’ ) ) ; End .

472

CHAPTER 22. THE SYSUTILS UNIT.

NewStr Declaration: Function NewStr(const S: string):

PString;

Description: NewStr assigns a new dynamic string on the heap, copies S into it, and returns a pointer to the newly assigned string. This function is obsolete, and shouldn’t be used any more. The AnsiString mechanism also allocates ansistrings on the heap, and should be preferred over this mechanism. Errors: If not enough memory is present, an EOutOfMemory exception will be raised. See also: AssignStr (456), DisposeStr (459) For an example, see AssignStr (456).

QuotedStr Declaration: Function QuotedStr(const S: string):

string;

Description: QuotedStr returns the string S, quoted with single quotes. This means that S is enclosed in single quotes, and every single quote in S is doubled. It is equivalent to a call to AnsiQuotedStr(s, ””). Errors: None. See also: AnsiQuotedStr (449), AnsiExtractQuotedStr (448). Listing: sysutex/ex78.pp Program Example78 ; { T h i s program demonstrates t h e QuotedStr f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin S: = ’ He s a i d ’ ’ H e l l o ’ ’ and walked on ’ ; Writeln ( S ) ; W r i t e l n ( ’ becomes ’ ) ; W r i t e l n ( QuotedStr ( S ) ) ; End .

RightStr Declaration: Function RightStr(const S: string; Count:

integer):

string;

Description: RightStr returns the Count rightmost characters of S. It is equivalent to a call to Copy(S,Length(S)+1-Count,Count) If Count is larger than the actual length of S only the real length will be used. Errors: None. See also: LeftStr (472),Trim (478), TrimLeft (479), TrimRight (479) Listing: sysutex/ex79.pp 473

CHAPTER 22. THE SYSUTILS UNIT.

Program Example79 ; { T h i s program demonstrates t h e R i g h t S t r f u n c t i o n } Uses s y s u t i l s ; Begin Writeln Writeln Writeln Writeln End .

( ( ( (

RightStr ( RightStr ( RightStr ( RightStr (

’ abcdefghijklmnopqrstuvwxyz ’ abcdefghijklmnopqrstuvwxyz ’ abcdefghijklmnopqrstuvwxyz ’ abcdefghijklmnopqrstuvwxyz

’ ’ ’ ’

,20)); ,15)); ,1)); ,200));

StrFmt Declaration: Function StrFmt(Buffer,Fmt : Pchar;

PChar; Const args:

Array of const) :

Description: StrFmt will format fmt with Args, as the Format (462) function does, and it will store the result in Buffer. The function returns Buffer. Buffer should point to enough space to contain the whole result. Errors: for a list of errors, see Format (462). See also: StrLFmt (474), FmtStr (462), Format (462), FormatBuf (468) Listing: sysutex/ex80.pp Program Example80 ; { T h i s program demonstrates t h e StrFmt f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin SetLEngth ( S , 8 0 ) ; W r i t e l n ( StrFmt (@S[ 1 ] , ’ For some n i c e examples o f f o m a t t i n g see %s . ’ , [ ’ Format ’ ] ) ) ; End .

StrLFmt Declaration: Function StrLFmt(Buffer : PCHar; Maxlen : args: Array of const) : Pchar;

Cardinal;Fmt :

PChar; Const

Description: StrLFmt will format fmt with Args, as the Format (462) function does, and it will store maximally Maxlen characters of the result in Buffer. The function returns Buffer. Buffer should point to enough space to contain MaxLen characters. Errors: for a list of errors, see Format (462). See also: StrFmt (474), FmtStr (462), Format (462), FormatBuf (468) Listing: sysutex/ex81.pp 474

CHAPTER 22. THE SYSUTILS UNIT.

Program Example80 ; { T h i s program demonstrates t h e StrFmt f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin SetLEngth ( S , 8 0 ) ; W r i t e l n ( StrLFmt (@S[ 1 ] , 8 0 , ’ For some n i c e examples o f f o m a t t i n g see %s . ’ , [ ’ Format ’ ] ) ) ; End .

StrToFloat Declaration: Function StrToFloat(Const S : String) :

Extended;

Description: StrToFloat converts the string S to a floating point value. S should contain a valid stroing representation of a floating point value (either in decimal or scientific notation). If the string contains a decimal value, then the decimal separator character can either be a ’.’ or the value of the DecimalSeparator variable. Errors: If the string S doesn’t contain a valid floating point string, then an exception will be raised. See also: TextToFloat (477),FloatToStr (459),FormatFloat (468),StrToInt (476) Listing: sysutex/ex90.pp Program Example90 ; { T h i s program demonstrates t h e S t r T o F l o a t f u n c t i o n } { $mode o b j f p c } { $h + } Uses S y s U t i l s ; Const NrValues = 5 ; T e s t S t r : Array [ 1 . . NrValues ] of s t r i n g = ( ’ 1 ,1 ’ , ’ −0,2 ’ , ’ 1 ,2E−4 ’ , ’ 0 ’ , ’ 1E4 ’ ) ; Procedure T e s t i t ; Var I : Integer ; E : Extended ; begin W r i t e l n ( ’ Using DecimalSeparator : ’ , DecimalSeparator ) ; For I : = 1 to NrValues do begin Writeln ( ’ Converting : ’ , TestStr [ i ] ) ; Try E: = StrToFloat ( T e s t S t r [ i ] ) ; W r i t e l n ( ’ Converted v a l u e : ’ ,E ) ; except

475

CHAPTER 22. THE SYSUTILS UNIT.

On E : E x c e p t i o n do W r i t e l n ( ’ E x c e p t i o n when c o n v e r t i n g : end ; end ;

’ ,E . Message ) ;

end ; Begin DecimalSeparator : = ’ , ’ ; Testit ; DecimalSeparator : = ’ . ’ ; Testit ; End .

StrToInt Declaration: Function StrToInt(const s:

string):

integer;

Description: StrToInt will convert the string Sto an integer. If the string contains invalid characters or has an invalid format, then an EConvertError is raised. To be successfully converted, a string can contain a combination of numerical characters, possibly preceded by a minus sign (-). Spaces are not allowed. Errors: In case of error, an EConvertError is raised. See also: IntToStr (470), StrToIntDef (476) Listing: sysutex/ex82.pp Program Example82 ; { $mode o b j f p c } { T h i s program demonstrates t h e S t r T o I n t f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( S t r T o I n t ( ’ 1234 ’ ) ) ; W r i t e l n ( S t r T o I n t ( ’ −1234 ’ ) ) ; Writeln ( StrToInt ( ’ 0 ’ ) ) ; Try W r i t e l n ( S t r T o I n t ( ’ 12345678901234567890 ’ ) ) ; except On E : E C o n v e r t E r r o r do W r i t e l n ( ’ I n v a l i d number encountered ’ ) ; end ; End .

StrToIntDef Declaration: Function StrToIntDef(const S: string; Default:

integer):

integer;

Description: StrToIntDef will convert a string to an integer. If the string contains invalid characters or has an invalid format, then Default is returned. To be successfully converted, a string can contain a combination of numerical characters, possibly preceded by a minus sign (-). Spaces are not allowed. 476

CHAPTER 22. THE SYSUTILS UNIT.

Errors: None. See also: IntToStr (470), StrToInt (476) Listing: sysutex/ex83.pp Program Example82 ; { $mode o b j f p c } { T h i s program demonstrates t h e S t r T o I n t f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( StrToIntDef ( ’ 1234 ’ , 0 ) ) ; W r i t e l n ( StrToIntDef ( ’ −1234 ’ , 0 ) ) ; W r i t e l n ( StrToIntDef ( ’ 0 ’ , 0 ) ) ; Try W r i t e l n ( StrToIntDef ( ’ 12345678901234567890 ’ , 0 ) ) ; except On E : E C o n v e r t E r r o r do W r i t e l n ( ’ I n v a l i d number encountered ’ ) ; end ; End .

TextToFloat Declaration: Function TextToFloat(Buffer:

PChar; Var Value:

Extended):

Boolean;

Description: TextToFloat converts the string in Buffer to a floating point value. Buffer should contain a valid stroing representation of a floating point value (either in decimal or scientific notation). If the buffer contains a decimal value, then the decimal separator character can either be a ’.’ or the value of the DecimalSeparator variable. The function returns True if the conversion was successful. Errors: If there is an invalid character in the buffer, then the function returns False See also: StrToFloat (475),FloatToStr (459), FormatFloat (468) Listing: sysutex/ex91.pp Program Example91 ; { T h i s program demonstrates t h e T e x t T o F l o a t f u n c t i o n } { $mode o b j f p c } { $h + } Uses S y s U t i l s ; Const NrValues = 5 ; T e s t S t r : Array [ 1 . . NrValues ] of pchar = ( ’ 1 ,1 ’ , ’ −0,2 ’ , ’ 1 ,2E−4 ’ , ’ 0 ’ , ’ 1E4 ’ ) ; Procedure T e s t i t ;

477

CHAPTER 22. THE SYSUTILS UNIT.

Var I : Integer ; E : Extended ; begin W r i t e l n ( ’ Using DecimalSeparator : ’ , DecimalSeparator ) ; For I : = 1 to NrValues do begin Writeln ( ’ Converting : ’ , TestStr [ i ] ) ; I f TextToFloat ( T e s t S t r [ i ] , E ) then W r i t e l n ( ’ Converted v a l u e : ’ ,E) else W r i t e l n ( ’ Unable t o c o n v e r t v a l u e . ’ ) ; end ; end ; Begin DecimalSeparator : = ’ , ’ ; Testit ; DecimalSeparator : = ’ . ’ ; Testit ; End .

Trim Declaration: Function Trim(const S: string):

string;

Description: Trim strips blank characters (spaces) at the beginning and end of S and returns the resulting string. Only #32 characters are stripped. If the string contains only spaces, an empty string is returned. Errors: None. See also: TrimLeft (479), TrimRight (479) Listing: sysutex/ex84.pp Program Example84 ; { T h i s program demonstrates t h e Trim f u n c t i o n } Uses s y s u t i l s ; { $H+ } Procedure T e s t i t ( S : S t r i n g ) ; begin W r i t e l n ( ’ " ’ , Trim ( S ) , ’ " ’ ) ; end ; Begin T e s t i t ( ’ ha ha what g e t s l o s t ? ’ ) ; T e s t i t (#10#13 ’ haha ’ ) ; Testit ( ’ ’ ); End .

478

CHAPTER 22. THE SYSUTILS UNIT.

TrimLeft Declaration: Function TrimLeft(const S: string):

string;

Description: TrimLeft strips blank characters (spaces) at the beginning of S and returns the resulting string. Only #32 characters are stripped. If the string contains only spaces, an empty string is returned. Errors: None. See also: Trim (478), TrimRight (479) Listing: sysutex/ex85.pp Program Example85 ; { T h i s program demonstrates t h e T r i m L e f t f u n c t i o n } Uses s y s u t i l s ; { $H+ } Procedure T e s t i t ( S : S t r i n g ) ; begin Writeln ( ’ " ’ , TrimLeft (S) , ’ " ’ ) ; end ; Begin T e s t i t ( ’ ha ha what g e t s l o s t ? ’ ) ; T e s t i t (#10#13 ’ haha ’ ) ; Testit ( ’ ’ ); End .

TrimRight Declaration: Function TrimRight(const S: string):

string;

Description: Trim strips blank characters (spaces) at the end of S and returns the resulting string. Only #32 characters are stripped. If the string contains only spaces, an empty string is returned. Errors: None. See also: Trim (478), TrimLeft (479) Listing: sysutex/ex86.pp Program Example86 ; { T h i s program demonstrates t h e T r i m R i g h t f u n c t i o n } Uses s y s u t i l s ; { $H+ } Procedure T e s t i t ( S : S t r i n g ) ; begin

479

CHAPTER 22. THE SYSUTILS UNIT.

Writeln ( ’ " ’ , TrimRight (S) , ’ " ’ ) ; end ; Begin T e s t i t ( ’ ha ha what g e t s l o s t ? ’ ) ; T e s t i t (#10#13 ’ haha ’ ) ; Testit ( ’ ’ ); End .

UpperCase Declaration: Function UpperCase(const s:

string):

string;

Description: UpperCase returns the uppercase equivalent of S. Ansi characters are not taken into account, only ASCII codes below 127 are converted. It is completely equivalent to the UpCase function of the system unit, and is provided for compatiibility only. Errors: None. See also: AnsiLowerCase (449), LowerCase (472), AnsiUpperCase (455) Errors: See also: Listing: sysutex/ex87.pp Program Example87 ; { T h i s program demonstrates t h e UpperCase f u n c t i o n } Uses s y s u t i l s ; Begin W r i t e l n ( UpperCase ( ’ t h i s w i l l come OUT ALL uPpErCaSe ! ’ ) ) ; End .

480

Chapter 23

The TYPINFO unit The TypeInfo unit contains many routines which can be used for the querying of the Run-Time Type Information (RTTI) which is generated by the compiler for classes that are compiled under the {$M+} switch. This information can be used to retrieve or set property values for published properties for totally unknown classes. In particular, it can be used to stream classes. The TPersistent class in the Classes unit is compiled in the {$M+} state and serves as the base class for all classes that need to be streamed. The unit should be compatible to the Delphi 5 unit with the same name. The only calls that are still missing are the Variant calls, since Free Pascal does not support the variant type yet. The examples in this chapter use a rttiobj file, which contains an object that has a published property of all supported types. It also contains some auxiliary routines and definitions.

23.1

Constants, Types and variables

Constants The following constants are used in the implementation section of the unit. BooleanIdents: array[Boolean] of String = (’False’, ’True’); DotSep: String = ’.’; The following constants determine the access method for the Stored identifier of a property as used in the PropProcs field of the TPropInfo record: ptField = 0; ptStatic = 1; ptVirtual = 2; ptConst = 3; The following typed constants are used for easy selection of property types. tkAny = [Low(TTypeKind)..High(TTypeKind)]; tkMethods = [tkMethod]; tkProperties = tkAny-tkMethods-[tkUnknown];

types The following pointer types are defined: 481

CHAPTER 23. THE TYPINFO UNIT

PShortString PByte PWord PLongint PBoolean PSingle PDouble PExtended PComp PFixed16 Variant

=^ShortString; =^Byte; =^Word; =^Longint; =^Boolean; =^Single; =^Double; =^Extended; =^Comp; =^Fixed16; = Pointer;

The TTypeKind determines the type of a property: TTypeKind = (tkUnknown,tkInteger,tkChar,tkEnumeration, tkFloat,tkSet,tkMethod,tkSString,tkLString,tkAString, tkWString,tkVariant,tkArray,tkRecord,tkInterface, tkClass,tkObject,tkWChar,tkBool,tkInt64,tkQWord, tkDynArray,tkInterfaceRaw); tkString = tkSString; tkString is an alias that is introduced for Delphi compatibility. If the property is and ordinal type, then TTOrdType determines the size and sign of the ordinal type: TTOrdType = (otSByte,otUByte,otSWord,otUWord,otSLong,otULong); The size of a float type is determined by TFloatType: TFloatType = (ftSingle,ftDouble,ftExtended,ftComp,ftCurr, ftFixed16,ftFixed32); A method property (e.g. an event) can have one of several types: TMethodKind = (mkProcedure,mkFunction,mkConstructor,mkDestructor, mkClassProcedure, mkClassFunction); The kind of parameter to a method is determined by TParamFlags: TParamFlags = set of (pfVar,pfConst,pfArray,pfAddress,pfReference,pfOut); Interfaces are described further with TntfFlags: TIntfFlags = set of (ifHasGuid,ifDispInterface,ifDispatch); The following defines a set of TTypeKind: TTypeKinds = set of TTypeKind; The TypeInfo function returns a pointer to a TTypeInfo record: TTypeInfo = record Kind : TTypeKind; Name : ShortString; end; PTypeInfo = ^TTypeInfo; PPTypeInfo = ^PTypeInfo; 482

CHAPTER 23. THE TYPINFO UNIT

Note that the Name is stored with as much bytes as needed to store the name, it is not padded to 255 characters. The type data immediatly follows the TTypeInfo record as a TTypeData record: PTypeData = ^TTypeData; TTypeData = packed record case TTypeKind of tkUnKnown,tkLString,tkWString,tkAString,tkVariant: (); tkInteger,tkChar,tkEnumeration,tkWChar: (OrdType : TTOrdType; case TTypeKind of tkInteger,tkChar,tkEnumeration,tkBool,tkWChar : ( MinValue,MaxValue : Longint; case TTypeKind of tkEnumeration: ( BaseType : PTypeInfo; NameList : ShortString ) ); tkSet: ( CompType : PTypeInfo ) ); tkFloat: ( FloatType : TFloatType ); tkSString: (MaxLength : Byte); tkClass: (ClassType : TClass; ParentInfo : PTypeInfo; PropCount : SmallInt; UnitName : ShortString ); tkMethod: (MethodKind : TMethodKind; ParamCount : Byte; ParamList : array[0..1023] of Char {in reality ParamList is a array[1..ParamCount] of: record Flags : TParamFlags; ParamName : ShortString; TypeName : ShortString; end; followed by ResultType : ShortString} ); tkInt64: (MinInt64Value, MaxInt64Value: Int64); tkQWord: (MinQWordValue, MaxQWordValue: QWord); tkInterface: (); end; 483

CHAPTER 23. THE TYPINFO UNIT

If the typeinfo kind is tkClass, then the property information follows the UnitName string, as an array of TPropInfo records. The TPropData record is not used, but is provided for completeness and compatibility with Delphi. TPropData = packed record PropCount : Word; PropList : record end; end; The TPropInfo record describes one published property of a class: PPropInfo = ^TPropInfo; TPropInfo = packed record PropType : PTypeInfo; GetProc : Pointer; SetProc : Pointer; StoredProc : Pointer; Index : Integer; Default : Longint; NameIndex : SmallInt; PropProcs : Byte; Name : ShortString; end; The Name field is stored not with 255 characters, but with just as many characters as required to store the name. TProcInfoProc = procedure(PropInfo : PPropInfo) of object; The following pointer and array types are used for typecasts: PPropList = ^TPropList; TPropList = array[0..65535] of PPropInfo;

23.2

Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where the function can be found.

Examining published property information Functions for retrieving or examining property information Name

Description

Page

FindPropInfo

Getting property type information, With error checking.

486

GetPropInfo

Getting property type information, No error checking.

494

GetPropInfos

Find property information of a certain kind

GetObjectPropClass

Return the declared class of an object property

493

GetPropList

Get a list of all published properties

496

484

??

CHAPTER 23. THE TYPINFO UNIT

IsPublishedProp

Is a property published

499

IsStoredProp

Is a property stored

500

PropIsType

Is a property of a certain kind

501

PropType

Return the type of a property

502

Getting or setting property values Functions to set or set a property’s value. Name

Description

Page

GetEnumProp

Return the value of an enumerated type property

487

GetFloatProp

Return the value of a float property

488

GetInt64Prop

Return the value of an Int64 property

489

GetMethodProp

Return the value of a procedural type property

490

GetObjectProp

Return the value of an object property

492

GetOrdProp

Return the value of an ordinal type property

493

GetPropValue

Return the value of a property as a variant

497

GetSetProp

Return the value of a set property

497

GetStrProp

Return the value of a string property

498

GetVariantProp

Return the value of a variant property

499

SetEnumProp

Set the value of an enumerated type property

??

SetFloatProp

Set the value of a float property

??

SetInt64Prop

Set the value of an Int64 property

??

SetMethodProp

Set the value of a procedural type property

??

SetObjectProp

Set the value of an object property

??

SetOrdProp

Set the value of an ordinal type property

??

SetPropValue

Set the value of a property trhough a variant

??

SetSetProp

Set the value of a set property

??

SetStrProp

Set the value of a string property

??

SetVariantProp

Set the value of a variant property

??

Auxiliary functions Name

Description

Page

GetEnumName

Get an enumerated type element name

487

GetEnumValue

Get ordinal number of an enumerated tye, based on the name.

488

GetTypeData

Skip type name and return a pointer to the type data

499

SetToString

Convert a set to its string representation

506

StringToSet

Convert a string representation of a set to a set

507

485

CHAPTER 23. THE TYPINFO UNIT

23.3

Functions and Procedures

FindPropInfo Declaration: Function FindPropInfo(AClass:TClass;const PropName: string): PPropInfo; Function FindPropInfo(Instance: TObject; const PropName: string): PPropInfo; Description: FindPropInfo examines the published property information of a class and returns a pointer to the property information for property PropName. The class to be examined can be specified in one of two ways: AClassa class pointer. Instancean instance of the class to be investigated. If the property does not exist, a EPropertyError exception will be raised. The GetPropInfo (494) function has the same function as the FindPropInfo function, but returns Nil if the property does not exist. Errors: Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetPropInfo (494), GetPropList (496), GetPropInfos (495) Listing: typinfex/ex14.pp Program example13 ; { T h i s program demonstrates t h e F i n d P r o p I n f o f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , typinfo , sysutils ;

Var O : TMyTestObject ; PT : PTypeData ; PI : PPropInfo ; I , J : Longint ; PP : P P r o p L i s t ; p r I : PPropInfo ; begin O: = TMyTestObject . Create ; PI : = F i n d P r o p I n f o (O, ’ B o o l e a n F i e l d ’ ) ; Writeln ( ’ FindPropInfo ( Instance , BooleanField ) PI : = F i n d P r o p I n f o (O. ClassType , ’ B y t e F i e l d ’ ) ; W r i t e l n ( ’ F i n d P r o p I n f o ( Class , B y t e F i e l d ) Write ( ’ F i n d P r o p I n f o ( Class , NonExistingProp ) Try PI : = F i n d P r o p I n f o (O, ’ NonExistingProp ’ ) ; except On E : E x c e p t i o n do W r i t e l n ( ’ Caught e x c e p t i o n " ’ ,E . ClassName , end ; O. Free ; end .

486

:

’ , PI ^ .Name ) ;

: ’ , PI ^ .Name ) ; : ’ );

’ " w i t h message :

’ ,E . Message ) ;

CHAPTER 23. THE TYPINFO UNIT

GetEnumName Declaration: Function GetEnumName(TypeInfo :

PTypeInfo;Value :

Integer) :

string;

Description: GetEnumName scans the type information for the enumeration type described by TypeInfo and returns the name of the enumeration constant for the element with ordinal value equal to Value. If Value is out of range, the first element of the enumeration type is returned. The result is lowercased, but this may change in the future. This can be used in combination with GetOrdProp to stream a property of an enumerated type. Errors: No check is done to determine whether TypeInfo really points to the type information for an enumerated type. See also: GetOrdProp (493), GetEnumValue (488) Listing: typinfex/ex9.pp program example9 ; { T h i s program demonstrates t h e GetEnumName , GetEnumValue f u n c t i o n s } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; T I : PTypeInfo ; begin O: = TMyTestObject . Create ; T I : = G e t P r o p I n f o (O, ’ MyEnumField ’ ) ^ . PropType ; W r i t e l n ( ’ GetEnumName : ’ ,GetEnumName ( TI , Ord (O. MyEnumField ) ) ) ; W r i t e l n ( ’ GetEnumValue ( m e f i r s t ) : ’ ,GetEnumName ( TI , GetEnumValue ( TI , ’ m e f i r s t ’ ) ) ) ; O. Free ; end .

GetEnumProp Declaration: Function GetEnumProp(Instance: TObject;const PropInfo: PPropInfo): string; Function GetEnumProp(Instance: TObject;const PropName: string): string; Description: GetEnumProp returns the value of an property of an enumerated type and returns the name of the enumerated value for the objetc Instance. The property whose value must be returned can be specified by its property info in PropInfo or by its name in PropName Errors: No check is done to determine whether PropInfo really points to the property information for an enumerated type. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetEnumProp (503) GetOrdProp (493), GetStrProp (498), GetInt64Prop (489),GetMethodProp (490), GetSetProp (497), GetObjectProp (492), GetEnumProp (487) Listing: typinfex/ex2.pp

487

CHAPTER 23. THE TYPINFO UNIT

program example2 ; { T h i s program demonstrates t h e GetEnumProp f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; T I : PTypeInfo ; begin O: = TMyTestObject . Create ; PI : = G et P r op I n f o (O, ’ MyEnumField ’ ) ; T I : = PI ^ . PropType ; W r i t e l n ( ’Enum p r o p e r t y : ’ ); W r i t e l n ( ’ Value : ’ W r i t e l n ( ’ Get ( name ) : ’ W r i t e l n ( ’ Get ( p r o p i n f o ) : ’ SetEnumProp (O, ’ MyEnumField ’ , ’ m e F i r s t W r i t e l n ( ’ Set ( name , m e F i r s t ) : ’ SetEnumProp (O, PI , ’ meSecond ’ ) ; W r i t e l n ( ’ Set ( p r o p i n f o , meSecond ) : ’ O. Free ; end .

,GetEnumName ( TI , Ord (O. MyEnumField ) ) ) ; , GetEnumProp (O, ’ MyEnumField ’ ) ) ; , GetEnumProp (O, PI ) ) ; ’ ); ,GetEnumName ( TI , Ord (O. MyEnumField ) ) ) ; ,GetEnumName ( TI , Ord (O. MyEnumField ) ) ) ;

GetEnumValue Declaration: Function GetEnumValue(TypeInfo : Integer;

PTypeInfo;const Name :

string) :

Description: GetEnumValue scans the type information for the enumeration type described by TypeInfor and returns the ordinal value for the element in the enumerated type that has identifier Name. The identifier is searched in a case-insensitive manner. This can be used to set the value of enumerated properties from a stream. Errors: If Name is not found in the list of enumerated values, then -1 is returned. No check is done whether TypeInfo points to the type information for an enumerated type. See also: GetEnumName (487), SetOrdProp (505) For an example, see GetEnumName (487).

GetFloatProp Declaration: Function GetFloatProp(Instance : TObject;PropInfo : PPropInfo) : Extended; Procedure SetFloatProp(Instance: TObject; const PropName: string; Value: Extended); Description: GetFloatProp returns the value of the float property described by PropInfo or with name Propname for the object Instance. All float types are converted to extended.

488

CHAPTER 23. THE TYPINFO UNIT

Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid float property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetFloatProp (503), GetOrdProp (493), GetStrProp (498), GetInt64Prop (489),GetMethodProp (490), GetSetProp (497), GetObjectProp (492), GetEnumProp (487) Listing: typinfex/ex4.pp program example4 ; { T h i s program demonstrates t h e GetFloatProp f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; begin O: = TMyTestObject . Create ; W r i t e l n ( ’ Real p r o p e r t y : ’ ) ; PI : = G e t P r o p I n f o (O, ’ R e a l F i e l d ’ ) ; W r i t e l n ( ’ Value : ’ ,O. R e a l F i e l d ) ; W r i t e l n ( ’ Get ( name ) : ’ , GetFloatProp (O, ’ R e a l F i e l d ’ ) ) ; W r i t e l n ( ’ Get ( p r o p i n f o ) : ’ , GetFloatProp (O, PI ) ) ; S e t F l o a t P r o p (O, ’ R e a l F i e l d ’ , system . Pi ) ; W r i t e l n ( ’ Set ( name , p i ) : ’ ,O. R e a l F i e l d ) ; S e t F l o a t P r o p (O, PI , exp ( 1 ) ) ; W r i t e l n ( ’ Set ( p r o p i n f o , e ) : ’ ,O. R e a l F i e l d ) ; W r i t e l n ( ’ Extended p r o p e r t y : ’ ) ; PI : = G e t P r o p I n f o (O, ’ E x t e n d e d F ie l d ’ ) ; W r i t e l n ( ’ Value : ’ ,O. Ex t en de d Fi el d ) ; W r i t e l n ( ’ Get ( name ) : ’ , GetFloatProp (O, ’ E xt e nd ed F ie ld ’ ) ) ; W r i t e l n ( ’ Get ( p r o p i n f o ) : ’ , GetFloatProp (O, PI ) ) ; S e t F l o a t P r o p (O, ’ E x t e n d e d F i e l d ’ , system . Pi ) ; W r i t e l n ( ’ Set ( name , p i ) : ’ ,O. Ex t en de d Fi el d ) ; S e t F l o a t P r o p (O, PI , exp ( 1 ) ) ; W r i t e l n ( ’ Set ( p r o p i n f o , e ) : ’ ,O. Ex t en de d Fi el d ) ; O. Free ; end .

GetInt64Prop Declaration: Function GetInt64Prop(Instance: TObject; PropInfo: PPropInfo): Int64; Function GetInt64Prop(Instance: TObject; const PropName: string): Int64; Description: Publishing of Int64 properties is not yet supported by Free Pascal. This function is provided for Delphi compatibility only at the moment. GetInt64Prop returns the value of the property of type Int64 that is described by PropInfo or with name Propname for the object Instance.

489

CHAPTER 23. THE TYPINFO UNIT

Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid Int64 property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception See also: SetInt64Prop (503), GetOrdProp (493), GetStrProp (498), GetFloatProp (488), GetMethodProp (490), GetSetProp (497), GetObjectProp (492), GetEnumProp (487) Listing: typinfex/ex15.pp program example15 ; { T h i s program demonstrates t h e GetInt64Prop f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; begin O: = TMyTestObject . Create ; Writeln ( ’ Int64 property : ’ ) ; PI : = G e t P r o p I n f o (O, ’ I n t 6 4 F i e l d ’ ) ; W r i t e l n ( ’ Value : ’ ,O. I n t 6 4 F i e l d ) ; W r i t e l n ( ’ Get ( name ) : ’ , GetInt64Prop (O, ’ I n t 6 4 F i e l d ’ ) ) ; W r i t e l n ( ’ Get ( p r o p i n f o ) : ’ , GetInt64Prop (O, PI ) ) ; S e t I n t 6 4 P r o p (O, ’ I n t 6 4 F i e l d ’ , 1 2 3 4 5 ) ; W r i t e l n ( ’ Set ( name, 1 2 3 4 5 ) : ’ ,O. I n t 6 4 F i e l d ) ; S e t I n t 6 4 P r o p (O, PI , 5 4 3 2 1 ) ; W r i t e l n ( ’ Set ( p r o p i n f o , 5 4 3 2 1 ) : ’ ,O. I n t 6 4 F i e l d ) ; O. Free ; end .

GetMethodProp Declaration: Function GetMethodProp(Instance : TObject;PropInfo : PPropInfo) : TMethod; Function GetMethodProp(Instance: TObject; const PropName: string): TMethod; Description: GetMethodProp returns the method the property described by PropInfo or with name Propname for object Instance. The return type TMethod is defined in the SysUtils unit as: TMethod = packed record Code, Data: Pointer; end; Data points to the instance of the class with the method Code. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid method property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception See also: SetMethodProp (504), GetOrdProp (493), GetStrProp (498), GetFloatProp (488), GetInt64Prop (489), GetSetProp (497), GetObjectProp (492), GetEnumProp (487) 490

CHAPTER 23. THE TYPINFO UNIT

Listing: typinfex/ex6.pp program example6 ; { T h i s program demonstrates t h e GetMethodProp f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o , s y s u t i l s ; Type T N o t i f y O b j e c t = Class ( TObject ) Procedure N o t i f i c a t i o n 1 ( Sender : TObject ) ; Procedure N o t i f i c a t i o n 2 ( Sender : TObject ) ; end ; Procedure T N o t i f y O b j e c t . N o t i f i c a t i o n 1 ( Sender : TObject ) ; begin Write ( ’ Received n o t i f i c a t i o n 1 o f o b j e c t w i t h c l a s s : ’ ) ; W r i t e l n ( Sender . ClassName ) ; end ; Procedure T N o t i f y O b j e c t . N o t i f i c a t i o n 2 ( Sender : TObject ) ; begin Write ( ’ Received n o t i f i c a t i o n 2 o f o b j e c t w i t h c l a s s : ’ ) ; W r i t e l n ( Sender . ClassName ) ; end ; Var O : PI NO M :

TMyTestObject ; : PPropInfo ; : TNotifyObject ; TMethod ;

Procedure P r i n t M e t h o d ( Const M : TMethod ) ; begin I f (M. Data= P o i n t e r (NO ) ) Then I f (M. Code= P o i n t e r ( @TNotifyObject . N o t i f i c a t i o n 1 ) ) then Writeln ( ’ N o t i f i c a t i o n 1 ’ ) else I f (M. Code= P o i n t e r ( @TNotifyObject . N o t i f i c a t i o n 2 ) ) then Writeln ( ’ N o t i f i c a t i o n 2 ’ ) else begin Write ( ’ Unknown method adress ( data : ’ ) ; Write ( h e x S t r ( L o n g i n t (M. data ) , 8 ) ) ; W r i t e l n ( ’ , code : ’ , h e x s t r ( L o n g i n t (M. Code ) , 8 ) , ’ ) ’ ) ; end ; end ;

begin O: = TMyTestObject . Create ; NO: = T N o t i f y O b j e c t . Create ; O. N o t i f y E v e n t : =@NO. N o t i f i c a t i o n 1 ; PI : = G e t P r o p I n f o (O, ’ N o t i f y E v e n t ’ ) ; W r i t e l n ( ’ Method p r o p e r t y : ’ ) ;

491

CHAPTER 23. THE TYPINFO UNIT

Write ( ’ N o t i f y i n g O. N o t i f y ; Write ( ’ Get ( name ) M: = GetMethodProp (O, ’ N o t i f y E v e n t ’ ) ; P r i n t M e t h o d (M) ; Write ( ’ N o t i f y i n g O. N o t i f y ; Write ( ’ Get ( p r o p i n f o ) M: = GetMethodProp (O, PI ) ; P r i n t M e t h o d (M) ; M. Data : =No ; M. Code : = P o i n t e r (@NO. N o t i f i c a t i o n 2 ) ; SetMethodProp (O, ’ N o t i f y E v e n t ’ ,M) ; Write ( ’ Set ( name , N o t i f i c a t i o n 2 ) M: = GetMethodProp (O, PI ) ; P r i n t M e t h o d (M) ; Write ( ’ N o t i f y i n g O. N o t i f y ; Write ( ’ Set ( p r o p i n f o , N o t i f i c a t i o n 1 ) M. Data : =No ; M. Code : = P o i n t e r (@NO. N o t i f i c a t i o n 1 ) ; SetMethodProp (O, PI ,M) ; M: = GetMethodProp (O, PI ) ; P r i n t M e t h o d (M) ; Write ( ’ N o t i f y i n g O. N o t i f y ; O. Free ; end .

: ’ ); : ’ );

: ’ ); : ’ );

: ’ );

: ’ ); :

’ );

: ’ );

GetObjectProp Declaration: Function GetObjectProp(Instance: TObject; const PropName: string): TObject; Function GetObjectProp(Instance: TObject; const PropName: string; MinClass:TClass): TObject; Function GetObjectProp(Instance: TObject; PropInfo: PPropInfo; MinClass: TClass): TObject; Description: GetObjectProp returns the object which the property descroibed by PropInfo with name Propname points to for object Instance. If MinClass is specified, then if the object is not descendent of class MinClass, then Nil is returned. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid method property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetMethodProp (504), GetOrdProp (493), GetStrProp (498), GetFloatProp (488), GetInt64Prop (489), GetSetProp (497), GetObjectProp (492), GetEnumProp (487) Listing: typinfex/ex5.pp program example5 ; { T h i s program demonstrates t h e GetObjectProp f u n c t i o n }

492

CHAPTER 23. THE TYPINFO UNIT

{ $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; NO1,NO2 : TNamedObject ; begin O: = TMyTestObject . Create ; NO1: = TNamedObject . Create ; NO1. ObjectName : = ’ F i r s t named o b j e c t ’ ; NO2: = TNamedObject . Create ; NO2. ObjectName : = ’ Second named o b j e c t ’ ; O. O b j F i e l d : =NO1; Writeln ( ’ Object property : ’ ) ; PI : = G e t P r o p I n f o (O, ’ O b j F i e l d ’ ) ; Write ( ’ P r o p e r t y c l a s s : ’ ); W r i t e l n ( GetObjectPropClass (O, ’ O b j F i e l d ’ ) . ClassName ) ; Write ( ’ Value : ’ ); W r i t e l n ( (O. O b j F i e l d as TNamedObject ) . ObjectName ) ; Write ( ’ Get ( name ) : ’ ); W r i t e l n ( ( GetObjectProp (O, ’ O b j F i e l d ’ ) As TNamedObject ) . ObjectName ) ; Write ( ’ Get ( p r o p i n f o ) : ’ ); W r i t e l n ( ( GetObjectProp (O, PI , TObject ) as TNamedObject ) . ObjectName ) ; SetObjectProp (O, ’ O b j F i e l d ’ ,NO2 ) ; Write ( ’ Set ( name ,NO2 ) : ’ ); W r i t e l n ( (O. O b j F i e l d as TNamedObject ) . ObjectName ) ; SetObjectProp (O, PI ,NO1 ) ; Write ( ’ Set ( p r o p i n f o ,NO1 ) : ’ ) ; W r i t e l n ( (O. O b j F i e l d as TNamedObject ) . ObjectName ) ; O. Free ; end .

GetObjectPropClass Declaration: Function GetObjectPropClass(Instance: TClass;

TObject; const PropName:

string):

Description: GetObjectPropClass returns the declared class of the property with name PropName. This may not be the actual class of the property value. Errors: No checking is done whether Instance is non-nil. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetMethodProp (504), GetOrdProp (493), GetStrProp (498), GetFloatProp (488), GetInt64Prop (489) For an example, see GetObjectProp (492).

GetOrdProp Declaration: Function GetOrdProp(Instance : TObject;PropInfo : PPropInfo) : Longint; Function GetOrdProp(Instance: TObject;const PropName: string): Longint; 493

CHAPTER 23. THE TYPINFO UNIT

Description: GetOrdProp returns the value of the ordinal property described by PropInfo or with name PropName for the object Instance. The value is returned as a longint, which should be typecasted to the needed type. Ordinal properties that can be retrieved include: Integers and subranges of integersThe value of the integer will be returned. Enumerated types and subranges of enumerated typesThe ordinal value of the enumerated type will be returned. SetsIf the base type of the set has less than 31 possible values. If a bit is set in the return value, then the corresponding element of the base ordinal class of the set type must be included in the set. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid ordinal property of Instance Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetOrdProp (505), GetStrProp (498), GetFloatProp (488), GetInt64Prop (489),GetMethodProp (490), GetSetProp (497), GetObjectProp (492), GetEnumProp (487) Listing: typinfex/ex1.pp program example1 ; { T h i s program demonstrates t h e GetOrdProp f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; begin O: = TMyTestObject . Create ; W r i t e l n ( ’ Boolean p r o p e r t y : ’ ); W r i t e l n ( ’ Value : ’ ,O. B o o l e a n F i e l d ) ; W r i t e l n ( ’ Ord ( Value ) : ’ , Ord (O. B o o l e a n F i e l d ) ) ; W r i t e l n ( ’ Get ( name ) : ’ , GetOrdProp (O, ’ B o o l e a n F i e l d ’ ) ) ; PI : = G e t P r o p I n f o (O, ’ B o o l e a n F i e l d ’ ) ; W r i t e l n ( ’ Get ( p r o p i n f o ) : ’ , GetOrdProp (O, PI ) ) ; SetOrdProp (O, ’ B o o l e a n F i e l d ’ , Ord ( False ) ) ; W r i t e l n ( ’ Set ( name , f a l s e ) : ’ ,O. B o o l e a n F i e l d ) ; SetOrdProp (O, PI , Ord ( True ) ) ; W r i t e l n ( ’ Set ( p r o p i n f o , t r u e ) : ’ ,O. B o o l e a n F i e l d ) ; O. Free ; end .

GetPropInfo Declaration: Function GetPropInfo(AClass: TClass; const PropName: string; AKinds: TTypeKinds) : PPropInfo; Function GetPropInfo(AClass: TClass; const PropName: string): PPropInfo; Function GetPropInfo(Instance: TObject; const PropName: string): PPropInfo; Function GetPropInfo(Instance: TObject; const PropName: string; AKinds: TTypeKinds) : PPropInfo; 494

CHAPTER 23. THE TYPINFO UNIT

Function GetPropInfo(TypeInfo: PPropInfo; Function GetPropInfo(TypeInfo: : TTypeKinds) : PPropInfo;

PTypeInfo;const PropName:

string) :

PTypeInfo;const PropName:

string; AKinds

Description: GetPropInfo returns a pointer to the TPropInfo record for a the PropName property of a class. The class to examine can be specified in one of three ways: InstanceAn instance of the class. AClassA class pointer to the class. TypeInfoA pointer to the type information of the class. In each of these three ways, if AKinds is specified, if the property has TypeKind which is not included in Akinds, Nil will be returned. Errors: If the property PropName does not exist, Nil is returned. See also: GetPropInfos (495),GetPropList (496) For an example, see most of the other functions.

GetPropInfos Declaration: Procedure GetPropInfos(TypeInfo:

PTypeInfo;PropList:

PPropList);

Description: GetPropInfos stores pointers to the property information of all published properties of a class with class info TypeInfo in the list pointed to by Proplist. The PropList pointer must point to a memory location that contains enough space to hold all properties of the class and its parent classes. Errors: No checks are done to see whether PropList points to a memory area that is big enough to hold all pointers. See also: GetPropInfo (494),GetPropList (496) Listing: typinfex/ex12.pp Program example12 ; { T h i s program demonstrates t h e Ge tP r op I nf o s f u n c t i o n } uses rttiobj , typinfo ;

Var O : TMyTestObject ; PT : PTypeData ; PI : PTypeInfo ; I , J : Longint ; PP : P P r o p L i s t ; p r I : PPropInfo ; begin O: = TMyTestObject . Create ; PI : =O. C l a s s I n f o ; PT: = GetTypeData ( PI ) ;

495

CHAPTER 23. THE TYPINFO UNIT

W r i t e l n ( ’ P r o p e r t y Count : ’ ,PT ^ . PropCount ) ; GetMem ( PP, PT ^ . PropCount ∗ SizeOf ( P o i n t e r ) ) ; G e t P r o p I n f o s ( PI , PP ) ; For I : = 0 to PT ^ . PropCount −1 do begin With PP ^ [ i ] ^ do begin Write ( ’ P r o p e r t y ’ , i + 1 : 3 , ’ : ’ ,name : 3 0 ) ; w r i t e l n ( ’ Type : ’ , TypeNames [ t y p i n f o . PropType (O,Name ) ] ) ; end ; end ; FreeMem (PP ) ; O. Free ; end .

GetPropList Declaration: Function GetPropList(TypeInfo : PTypeInfo; TypeKinds : PropList : PPropList) : Integer;

TTypeKinds;

Description: GetPropList stores pointers to property information of the class with class info TypeInfo for properties of kind TypeKinds in the list pointed to by Proplist. PropList must contain enough space to hold all properties. The function returns the number of pointers that matched the criteria and were stored in PropList. Errors: No checks are done to see whether PropList points to a memory area that is big enough to hold all pointers. See also: GetPropInfos (495), GetPropInfo (494) Listing: typinfex/ex13.pp Program example13 ; { T h i s program demonstrates t h e G e t P r o p L i s t f u n c t i o n } uses rttiobj , typinfo ;

Var O : TMyTestObject ; PT : PTypeData ; PI : PTypeInfo ; I , J : Longint ; PP : P P r o p L i s t ; p r I : PPropInfo ; begin O: = TMyTestObject . Create ; PI : =O. C l a s s I n f o ; PT: = GetTypeData ( PI ) ; W r i t e l n ( ’ T o t a l p r o p e r t y Count : ’ ,PT ^ . PropCount ) ; GetMem ( PP, PT ^ . PropCount ∗ SizeOf ( P o i n t e r ) ) ; J : = G e t P r o p L i s t ( PI , OrdinalTypes , PP ) ; W r i t e l n ( ’ O r d i n a l p r o p e r t y Count : ’ , J ) ; For I : = 0 to J −1 do

496

CHAPTER 23. THE TYPINFO UNIT

begin With PP ^ [ i ] ^ do begin Write ( ’ P r o p e r t y ’ , i + 1 : 3 , ’ : ’ ,name : 3 0 ) ; w r i t e l n ( ’ Type : ’ , TypeNames [ t y p i n f o . PropType (O,Name ) ] ) ; end ; end ; FreeMem (PP ) ; O. Free ; end .

GetPropValue Declaration: Function GetPropValue(Instance: TObject; const PropName: string): Variant; Function GetPropValue(Instance: TObject; const PropName: string; PreferStrings: Boolean): Variant; Description: Due to missing Variant support, GetPropValue is not yet implemented. The declaration is provided for compatibility with Delphi. Errors: See also:

GetSetProp Declaration: Function GetSetProp(Instance: TObject; const PropInfo: PPropInfo; Brackets: Boolean): string; Function GetSetProp(Instance: TObject; const PropName: string): string; Function GetSetProp(Instance: TObject; const PropName: string; Brackets: Boolean): string; Description: GetSetProp returns the contents of a set property as a string. The property to be returned can be specified by it’s name in PropName or by its property information in PropInfo. The returned set is a string representation of the elements in the set as returned by SetToString (506). The Brackets option can be used to enclose the string representation in square brackets. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid ordinal property of Instance Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetSetProp (505), GetStrProp (498), GetFloatProp (488), GetInt64Prop (489),GetMethodProp (490) Listing: typinfex/ex7.pp program example7 ; { T h i s program demonstrates t h e GetSetProp f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ;

497

CHAPTER 23. THE TYPINFO UNIT

Var O : TMyTestObject ; PI : PPropInfo ; Function S e t A s S t r i n g ( ASet : TMyEnums ) : S t r i n g ; Var i : TmyEnum ; begin r e s u l t := ’ ’ ; For i : = m e f i r s t to m e t h i r d do I f i i n ASet then begin I f ( Result ’ ’ ) then Result := Result+ ’ , ’ ; R e s u l t : = R e s u l t +MyEnumNames [ i ] ; end ; end ; Var S : TMyEnums ; begin O: = TMyTestObject . Create ; O. S e t F i e l d : = [ m e f i r s t , meSecond , meThird ] ; W r i t e l n ( ’ Set p r o p e r t y : ’ ); W r i t e l n ( ’ Value : W r i t e l n ( ’ Ord ( Value ) : W r i t e l n ( ’ Get ( name ) : PI : = G e t P r o p I n f o (O, ’ S e t F i e l d ’ ) ; W r i t e l n ( ’ Get ( p r o p i n f o ) : S : = [ meFirst , meThird ] ; SetOrdProp (O, ’ S e t F i e l d ’ , I n t e g e r (S ) ) ; Write ( ’ Set ( name , [ m e f i r s t , m e t h i r d ] ) : ’ W r i t e l n ( S e t A s S t r i n g (O. S e t F i e l d ) ) ; S : = [ meSecond ] ; SetOrdProp (O, PI , I n t e g e r ( S ) ) ; Write ( ’ Set ( p r o p i n f o , [ meSecond ] ) : ’ W r i t e l n ( S e t A s S t r i n g (O. S e t F i e l d ) ) ; O. Free ; end .

’ , S e t A s S t r i n g (O. S e t F i e l d ) ) ; ’ , L o n g i n t (O. S e t F i e l d ) ) ; ’ , GetSetProp (O, ’ S e t F i e l d ’ ) ) ; ’ , GetSetProp (O, PI , f a l s e ) ) ;

);

);

GetStrProp Declaration: Function GetStrProp(Instance : TObject; PropInfo : PPropInfo) : Ansistring; Function GetStrProp(Instance: TObject; const PropName: string): string; Description: GetStrProp returns the value of the string property described by PropInfo or with name PropName for object Instance. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid string property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: SetStrProp (506), GetOrdProp (493), GetFloatProp (488), GetInt64Prop (489),GetMethodProp (490) 498

CHAPTER 23. THE TYPINFO UNIT

Listing: typinfex/ex3.pp program example3 ; { T h i s program demonstrates t h e GetStrProp f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; begin O: = TMyTestObject . Create ; PI : = G e t P r o p I n f o (O, ’ A n s i S t r i n g F i e l d ’ ) ; Writeln ( ’ S t r i n g property : ’ ) ; W r i t e l n ( ’ Value : ’ ,O. A n s i S t r i n g F i e l d ) ; W r i t e l n ( ’ Get ( name ) : ’ , GetStrProp (O, ’ A n s i S t r i n g F i e l d ’ ) ) ; W r i t e l n ( ’ Get ( p r o p i n f o ) : ’ , GetStrProp (O, PI ) ) ; S e t S t r P r o p (O, ’ A n s i S t r i n g F i e l d ’ , ’ F i r s t ’ ) ; W r i t e l n ( ’ Set ( name , ’ ’ F i r s t ’ ’ ) : ’ ,O. A n s i S t r i n g F i e l d ) ; S e t S t r P r o p (O, PI , ’ Second ’ ) ; W r i t e l n ( ’ Set ( p r o p i n f o , ’ ’ Second ’ ’ ) : ’ ,O. A n s i S t r i n g F i e l d ) ; O. Free ; end .

GetTypeData Declaration: Function GetTypeData(TypeInfo :

PTypeInfo) :

PTypeData;

Description: GetTypeData returns a pointer to the TTypeData record that follows after the TTypeInfo record pointed to by TypeInfo. It essentially skips the Kind and Name fields in the TTypeInfo record. Errors: None. See also:

GetVariantProp Declaration: Function GetVariantProp(Instance : Variant;

TObject;PropInfo :

PPropInfo):

Description: Due to mising Variant support, the GetVariantProp function is not yet implemented. Provided for Delphi compatibility only. Errors: See also: SetVariantProp (507)

IsPublishedProp Declaration: Function IsPublishedProp(AClass: Boolean;

TClass; const PropName:

499

string):

CHAPTER 23. THE TYPINFO UNIT

Function IsPublishedProp(Instance: Boolean;

TObject; const PropName:

string):

Description: IsPublishedProp returns true if a class has a published property with name PropName. The class can be specfied in one of two ways: AClassA class pointer to the class. InstanceAn instance of the class. Errors: No checks are done to ensure Instance or AClass are valid pointers. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: IsStoredProp (500), PropIsType (501) Listing: typinfex/ex10.pp program example10 ; { T h i s program demonstrates t h e I s P u b l i s h e d P r o p f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; begin O: = TMyTestObject . Create ; Writeln ( ’ Property t e s t s : ’ ); Write ( ’ I s P u b l i s h e d P r o p (O, B o o l e a n F i e l d ) : ’ ); W r i t e l n ( I s P u b l i s h e d P r o p (O, ’ B o o l e a n F i e l d ’ ) ) ; Write ( ’ I s P u b l i s h e d P r o p ( Class , B o o l e a n F i e l d ) : ’ ) ; W r i t e l n ( I s P u b l i s h e d P r o p (O. ClassType , ’ B o o l e a n F i e l d ’ ) ) ; Write ( ’ I s P u b l i s h e d P r o p (O, SomeField ) : ’ ); W r i t e l n ( I s P u b l i s h e d P r o p (O, ’ SomeField ’ ) ) ; Write ( ’ I s P u b l i s h e d P r o p ( Class , SomeField ) : ’ ); W r i t e l n ( I s P u b l i s h e d P r o p (O. ClassType , ’ SomeField ’ ) ) ; O. Free ; end .

IsStoredProp Declaration: Function IsStoredProp(Instance : TObject;PropInfo : PPropInfo) : Boolean; Function IsStoredProp(Instance: TObject; const PropName: string): Boolean; Description: IsStoredProp returns True if the Stored modifier evaluates to True for the property described by PropInfo or with name PropName for object Instance. It returns False otherwise. If the function returns True, this indicates that the property should be written when streaming the object Instance. If there was no stored modifier in the declaration of the property, True will be returned. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. 500

CHAPTER 23. THE TYPINFO UNIT

See also: IsPublishedProp (499), PropIsType (501) Listing: typinfex/ex11.pp program example11 ; { T h i s program demonstrates t h e I s S t o r e d P r o p f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; begin O: = TMyTestObject . Create ; W r i t e l n ( ’ Stored t e s t s : ’ ); Write ( ’ I s S t o r e d P r o p (O, S t o r e d I n t e g e r C o n s t F a l s e ) : W r i t e l n ( I s S t o r e d P r o p (O, ’ S t o r e d I n t e g e r C o n s t F a l s e ’ ) ) ; Write ( ’ I s S t o r e d P r o p (O, S t o r e d I n t e g e r C o n s t T r u e ) : W r i t e l n ( I s S t o r e d P r o p (O, ’ S t o r e d I n t e g e r C o n s t T r u e ’ ) ) ; Write ( ’ I s S t o r e d P r o p (O, S t o r e d I nte ger Met hod ) : W r i t e l n ( I s S t o r e d P r o p (O, ’ S t o r edI nte ger Met hod ’ ) ) ; Write ( ’ I s S t o r e d P r o p (O, S t o r e d I n t e g e r V i r t u a l M e t h o d ) : W r i t e l n ( I s S t o r e d P r o p (O, ’ S t o r e d I n t e g e r V i r t u a l M e t h o d ’ O. Free ; end .

’ ); ’ ); ’ ); ’ ); ));

PropIsType Declaration: Function PropIsType(AClass: TClass; const PropName: string; TypeKind: TTypeKind): Boolean; Function PropIsType(Instance: TObject; const PropName: string; TypeKind: TTypeKind): Boolean; Description: PropIsType returns True if the property with name PropName has type TypeKind. It returns False otherwise. The class to be examined can be specified in one of two ways: AClassA class pointer. InstanceAn instance of the class. Errors: No checks are done to ensure Instance or AClass are valid pointers.Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: IsPublishedProp (499), IsStoredProp (500), PropType (502) Listing: typinfex/ex16.pp program example16 ; { T h i s program demonstrates t h e PropIsType f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ;

501

CHAPTER 23. THE TYPINFO UNIT

Var O : TMyTestObject ; begin O: = TMyTestObject . Create ; Writeln ( ’ Property t e s t s : ’ ); Write ( ’ PropIsType (O, BooleanField , t k B o o l ) : ’ ); W r i t e l n ( PropIsType (O, ’ B o o l e a n F i e l d ’ , t k B o o l ) ) ; Write ( ’ PropIsType ( Class , BooleanField , t k B o o l ) : ’ ) ; W r i t e l n ( PropIsType (O. ClassType , ’ B o o l e a n F i e l d ’ , t k B o o l ) ) ; Write ( ’ PropIsType (O, B y t e F i e l d , t k S t r i n g ) : ’ ); W r i t e l n ( PropisType (O, ’ B y t e F i e l d ’ , t k S t r i n g ) ) ; Write ( ’ PropIsType ( Class , B y t e F i e l d , t k S t r i n g ) : ’ ) ; W r i t e l n ( PropIsType (O. ClassType , ’ B y t e F i e l d ’ , t k S t r i n g ) ) ; O. Free ; end .

PropType Declaration: Function PropType(AClass: TClass; const PropName: string): TTypeKind; Function PropType(Instance: TObject; const PropName: string): TTypeKind; Description: Proptype returns the type of the property PropName for a class. The class to be examined can be specified in one of 2 ways: AClassA class pointer. InstanceAn instance of the class. Errors: No checks are done to ensure Instance or AClass are valid pointers. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: IsPublishedProp (499), IsStoredProp (500), PropIsType (501) Listing: typinfex/ex17.pp program example17 ; { T h i s program demonstrates t h e PropType f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; begin O: = TMyTestObject . Create ; Writeln ( ’ Property t e s t s : ’ ); Write ( ’ PropType (O, B o o l e a n F i e l d ) : ’ ); W r i t e l n ( TypeNames [ PropType (O, ’ B o o l e a n F i e l d ’ ) ] ) ; Write ( ’ PropType ( Class , B o o l e a n F i e l d ) : ’ ) ; W r i t e l n ( TypeNames [ PropType (O. ClassType , ’ B o o l e a n F i e l d ’ ) ] ) ; Write ( ’ PropType (O, B y t e F i e l d ) : ’ ); W r i t e l n ( TypeNames [ PropType (O, ’ B y t e F i e l d ’ ) ] ) ; Write ( ’ PropType ( Class , B y t e F i e l d ) : ’ );

502

CHAPTER 23. THE TYPINFO UNIT

W r i t e l n ( TypeNames [ PropType (O. ClassType , ’ B y t e F i e l d ’ ) ] ) ; O. Free ; end .

SetEnumProp Declaration: Procedure SetEnumProp(Instance: TObject; const PropInfo: PPropInfo; const Value: string); Procedure SetEnumProp(Instance: TObject; const PropName: string; const Value: string); Description: SetEnumProp sets the property described by PropInfo or with name PropName to Value. Value must be a string with the name of the enumerate value, i.e. it can be used as an argument to GetEnumValue (488). Errors: No checks are done to ensure Instance or PropInfo are valid pointers. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetEnumProp (487), SetStrProp (506), SetFloatProp (503), SetInt64Prop (503),SetMethodProp (504). For an example, see GetEnumProp (487).

SetFloatProp Declaration: Procedure SetFloatProp(Instance : TObject; PropInfo : PPropInfo; Value : Extended); Procedure SetFloatProp(Instance: TObject; const PropName: string; Value: Extended); Description: SetFloatProp assigns Value to the property described by PropInfo or with name Propname for the object Instance. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid float property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetFloatProp (488), SetOrdProp (505), SetStrProp (506), SetInt64Prop (503),SetMethodProp (504) For an example, see GetFloatProp (488).

SetInt64Prop Declaration: Procedure SetInt64Prop(Instance: TObject; PropInfo: PPropInfo; const Value: Int64); Procedure SetInt64Prop(Instance: TObject; const PropName: string; const Value: Int64); Description: SetInt64Prop assigns Value to the property of type Int64 that is described by PropInfo or with name Propname for the object Instance. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid Int64 property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. 503

CHAPTER 23. THE TYPINFO UNIT

See also: GetInt64Prop (489), GetMethodProp (490), SetOrdProp (505), SetStrProp (506), SetFloatProp (503) For an example, see GetInt64Prop (489).

SetMethodProp Declaration: Procedure SetMethodProp(Instance : TObject;PropInfo : PPropInfo; const Value : TMethod); Procedure SetMethodProp(Instance: TObject; const PropName: string; const Value: TMethod); Description: SetMethodProp assigns Value to the method the property described by PropInfo or with name Propname for object Instance. The type TMethod of the Value parameter is defined in the SysUtils unit as: TMethod = packed record Code, Data: Pointer; end; Data should point to the instance of the class with the method Code. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid method property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetMethodProp (490), SetOrdProp (505), SetStrProp (506), SetFloatProp (503), SetInt64Prop (503) For an example, see GetMethodProp (490).

SetObjectProp Declaration: Procedure SetObjectProp(Instance: TObject; PropInfo: PPropInfo; Value: TObject); Procedure SetObjectProp(Instance: TObject; const PropName: string; Value: TObject); Description: SetObjectProp assigns Value to the the object property described by PropInfo or with name Propname for the object Instance. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid method property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetObjectProp (492), SetOrdProp (505), SetStrProp (506), SetFloatProp (503), SetInt64Prop (503), SetMethodProp (504) For an example, see GetObjectProp (492).

504

CHAPTER 23. THE TYPINFO UNIT

SetOrdProp Declaration: Procedure SetOrdProp(Instance : TObject; PropInfo : PPropInfo; Value : Longint); Procedure SetOrdProp(Instance: TObject; const PropName: string; Value: Longint); Description: SetOrdProp assigns Value to the the ordinal property described by PropInfo or with name Propname for the object Instance. Ordinal properties that can be set include: Integers and subranges of integersThe actual value of the integer must be passed. Enumerated types and subranges of enumerated typesThe ordinal value of the enumerated type must be passed. Subrange typesof integers or enumerated types. Here the ordinal value must be passed. SetsIf the base type of the set has less than 31 possible values. For each possible value; the corresponding bit of Value must be set. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid ordinal property of Instance. No range checking is performed. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetOrdProp (493), SetStrProp (506), SetFloatProp (503), SetInt64Prop (503),SetMethodProp (504) For an example, see GetOrdProp (493).

SetPropValue Declaration: Procedure SetPropValue(Instance: const Value: Variant);

TObject; const PropName:

string;

Description: Due to missing Variant support, this function is not yet implemented; it is provided for Delphi compatibility only. Errors: See also:

SetSetProp Declaration: Procedure SetSetProp(Instance: TObject; const PropInfo: PPropInfo; const Value: string); Procedure SetSetProp(Instance: TObject; const PropName: string; const Value: string); Description: SetSetProp sets the property specified by PropInfo or PropName for object Instance to Value. Value is a string which contains a comma-separated list of values, each value being a string-representation of the enumerated value that should be included in the set. The value should be accepted by the StringToSet (507) function. The value can be formed using the SetToString (506) function. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid ordinal property of Instance. No range checking is performed. Specifying an invalid property name in PropName will result in an EPropertyError exception. 505

CHAPTER 23. THE TYPINFO UNIT

See also: GetSetProp (497), SetOrdProp (505), SetStrProp (506), SetFloatProp (503), SetInt64Prop (503),SetMethodProp (504), SetToString (506), StringToSet (507) For an example, see GetSetProp (497).

SetStrProp Declaration: procedure SetStrProp(Instance : TObject; PropInfo : PPropInfo; const Value : Ansistring); Procedure SetStrProp(Instance: TObject; const PropName: string; const Value: AnsiString); Description: SetStrProp assigns Value to the string property described by PropInfo or with name Propname for object Instance. Errors: No checking is done whether Instance is non-nil, or whether PropInfo describes a valid string property of Instance. Specifying an invalid property name in PropName will result in an EPropertyError exception. See also: GetStrProp (498), SetOrdProp (505), SetFloatProp (503), SetInt64Prop (503),SetMethodProp (504) For an example, see GetStrProp (498)

SetToString Declaration: function SetToString(PropInfo: PPropInfo; Value: Integer) : String; function SetToString(PropInfo: PPropInfo; Value: Integer; Brackets: Boolean) : String; Description: SetToString takes an integer representation of a set (as received e.g. by GetOrdProp) and turns it into a string representing the elements in the set, based on the type information found in the PropInfo property information. By default, the string representation is not surrounded by square brackets. Setting the Brackets parameter to True will surround the string representation with brackets. The function returns the string representation of the set. Errors: No checking is done to see whether PropInfo points to valid property information. See also: GetEnumName (487), GetEnumValue (488), StringToSet (507) Listing: typinfex/ex18.pp program example18 ; { T h i s program demonstrates t h e S e t T o S t r i n g f u n c t i o n } { $mode o b j f p c } uses r t t i o b j , t y p i n f o ; Var O : TMyTestObject ; PI : PPropInfo ; I : longint ;

506

CHAPTER 23. THE TYPINFO UNIT

begin O: = TMyTestObject . Create ; PI : = G e t P r o p I n f o (O, ’ S e t F i e l d ’ ) ; O. S e t F i e l d : = [ m e f i r s t , meSecond , meThird ] ; I : = GetOrdProp (O, PI ) ; W r i t e l n ( ’ Set p r o p e r t y t o s t r i n g : ’ ) ; W r i t e l n ( ’ Value : ’ , S e t T o S t r i n g ( PI , I , False ) ) ; O. S e t F i e l d : = [ m e f i r s t , meSecond ] ; I : = GetOrdProp (O, PI ) ; W r i t e l n ( ’ Value : ’ , S e t T o S t r i n g ( PI , I , True ) ) ; I : = S t r i n g T o S e t ( PI , ’ m e f i r s t ’ ) ; SetOrdProp (O, PI , I ) ; I : = GetOrdProp (O, PI ) ; W r i t e l n ( ’ Value : ’ , S e t T o S t r i n g ( PI , I , False ) ) ; I : = S t r i n g T o S e t ( PI , ’ [ mesecond , m e t h i r d ] ’ ) ; SetOrdProp (O, PI , I ) ; I : = GetOrdProp (O, PI ) ; W r i t e l n ( ’ Value : ’ , S e t T o S t r i n g ( PI , I , True ) ) ; O. Free ; end .

SetVariantProp Declaration: Procedure SetVariantProp(Instance : TObject; PropInfo : PPropInfo; Const Value: Variant); Procedure SetVariantProp(Instance: TObject; const PropName: string; const Value: Variant); Description: Due to missing Variant support, this function is not yet implemented. Provided for Delphi compatibility only. Errors: See also:

StringToSet Declaration: function StringToSet(PropInfo:

PPropInfo; const Value:

string):

Description: StringToSet converts the string representation of a set in Value to a integer representation of the set, using the property information found in PropInfo. This property information should point to the property information of a set property. The function returns the integer representation of the set. (i.e, the set value, typecast to an integer) The string representation can be surrounded with square brackets, and must consist of the names of the elements of the base type of the set. The base type of the set should be an enumerated type. The elements should be separated by commas, and may be surrounded by spaces. each of the names will be fed to the GetEnumValue (488) function. Errors: No checking is done to see whether PropInfo points to valid property information. If a wrong name is given for an enumerated value, then an EPropertyError will be raised. See also: GetEnumName (487), GetEnumValue (488), SetToString (506) For an example, see SetToString (506). 507

Integer;

Chapter 24

The VIDEO unit The Video unit implements a screen access layer which is system independent. It can be used to write on the screen in a system-independent way, which should be optimal on all platforms for which the unit is implemented. The working of the Video is simple: After calling InitVideo (518), the array VideoBuf contains a representation of the video screen of size ScreenWidth*ScreenHeight, going from left to right and top to bottom when walking the array elements: VideoBuf[0] contains the character and color code of the top-left character on the screen. VideoBuf[ScreenWidth] contains the data for the character in the first column of the second row on the screen, and so on. To write to the ’screen’, the text to be written should be written to the VideoBuf array. Calling UpdateScreen (522) will then cp the text to the screen in the most optimal way. (an example can be found further on). The color attribute is a combination of the foreground and background color, plus the blink bit. The bits describe the various color combinations: bits 0-3 The foreground color. Can be set using all color constants. bits 4-6 The background color. Can be set using a subset of the color constants. bit 7 The blinking bit. If this bit is set, the character will appear blinking. Each possible color has a constant associated with it, see page 509 for a list of constants. The contents of the VideoBuf array may be modified: This is ’writing’ to the screen. As soon as everything that needs to be written in the array is in the VideoBuf array, calling UpdateScreen will copy the contents of the array screen to the screen, in a manner that is as efficient as possible. The updating of the screen can be prohibited to optimize performance; To this end, the LockScreenUpdate (519) function can be used: This will increment an internal counter. As long as the counter differs from zero, calling UpdateScreen (522) will not do anything. The counter can be lowered with UnlockScreenUpdate (521). When it reaches zero, the next call to UpdateScreen (522) will actually update the screen. This is useful when having nested procedures that do a lot of screen writing. The video unit also presents an interface for custom screen drivers, thus it is possible to override the default screen driver with a custom screen driver, see the SetVideoDriver (520) call. The current video driver can be retrieved using the GetVideoDriver (516) call. Remark: The video unit should not be used together with the crt unit. Doing so will result in very strange behaviour, possibly program crashes.

508

CHAPTER 24. THE VIDEO UNIT

24.1

Constants, Type and variables

Constants The following constants describe colors that can be used as foreground and background colors. Black Blue Green Cyan Red Magenta Brown LightGray

= = = = = = = =

0; 1; 2; 3; 4; 5; 6; 7;

The following color constants can be used as foreground colors only: DarkGray LightBlue LightGreen LightCyan LightRed LightMagenta Yellow White

= = = = = = = =

8; 9; 10; 11; 12; 13; 14; 15;

The foreground and background color can be combined to a color attribute with the following code: Attr:=ForeGroundColor + (BackGroundColor shl 4); The color attribute can be logically or-ed with the blink attribute to produce a blinking character: Blink

= 128;

But not all drivers may support this. The following constants describe the capabilities of a certain video mode: cpUnderLine cpBlink cpColor cpChangeFont cpChangeMode cpChangeCursor

= = = = = =

$0001; $0002; $0004; $0008; $0010; $0020;

The following constants describe the various supported cursor modes: crHidden crUnderLine crBlock crHalfBlock

= = = =

0; 1; 2; 3;

When a video function needs to report an error condition, the following constants are used:

509

CHAPTER 24. THE VIDEO UNIT

vioOK errVioBase errVioInit errVioNotSupported errVioNoSuchMode

= = = = =

0; 1000; errVioBase + 1; { Initialization error} errVioBase + 2; { Unsupported function } errVioBase + 3; { No such video mode }

The following constants can be read to get some information about the current screen: ScreenWidth ScreenHeight LowAscii NoExtendedFrame FVMaxWidth

: : : : =

Word = 0; { Width of the screen, in characters } Word = 0; { Height of the screen, in characters } Boolean = true; Boolean = false; 132;

The error-handling code uses the following constants: errOk = 0; ErrorCode: Longint = ErrOK; ErrorInfo: Pointer = nil; ErrorHandler: TErrorHandler = DefaultErrorHandler; The ErrorHandler variable can be set to a custom-error handling function. It is set by default to the DefaultErrorHandler (513) function.

Types The TVideoMode record describes a videomode. Its fields are self-explaining: Col,Row describe the number of columns and rows on the screen for this mode. Color is True if this mode supports colors, or False if not. PVideoMode = ^TVideoMode; TVideoMode = record Col,Row : Word; Color : Boolean; end; TVideoCell describes one character on the screen. One of the bytes contains the color attribute with which the character is drawn on the screen, and the other byte contains the ASCII code of the character to be drawn. The exact position of the different bytes in the record is operating system specific. On most little-endian systems, the high byte represents the color attribute, while the lowbyte represents the ASCII code of the character to be drawn. TVideoCell = Word; PVideoCell = ^TVideoCell; The TVideoBuf and PVideoBuf are two types used to represent the screen. TVideoBuf = array[0..32759] of TVideoCell; PVideoBuf = ^TVideoBuf; The following type is used when reporting error conditions: TErrorHandlerReturnValue = (errRetry, errAbort, errContinue); 510

CHAPTER 24. THE VIDEO UNIT

Here, errRetry means retry the operation, errAbort abort and return error code and errContinue means abort without returning an errorcode. The TErrorHandler function is used to register an own error handling function. It should be used when installing a custom error handling function, and must return one of the above values. TErrorHandler = function (Code: Longint; Info: Pointer): TErrorHandlerReturnValue; Code should contain the error code for the error condition, and the Info parameter may contain any data type specific to the error code passed to the function. The TVideoDriver record can be used to install a custom video driver, with the SetVideoDriver (520) call: TVideoDriver = Record InitDriver : DoneDriver : UpdateScreen : ClearScreen : SetVideoMode : GetVideoModeCount : GetVideoModeData : SetCursorPos : GetCursorType : SetCursorType : GetCapabilities : end;

Procedure; Procedure; Procedure(Force : Boolean); Procedure; Function (Const Mode : TVideoMode) : Boolean; Function : Word; Function(Index : Word; Var Data : TVideoMode) : Boolean; procedure (NewCursorX, NewCursorY: Word); function : Word; procedure (NewType: Word); Function : Word;

Variables The following variables contain information about the current screen status: ScreenColor : Boolean; CursorX, CursorY : Word; ScreenColor indicates whether the current screen supports colors. CursorX,CursorY contain the current cursor position. The following variable forms the heart of the Video unit: The VideoBuf array represents the physical screen. Writing to this array and calling UpdateScreen (522) will write the actual characters to the screen. VideoBuf : PVideoBuf; OldVideoBuf : PVideoBuf; VideoBufSize : Longint; The OldVideoBuf contains the state of the video screen after the last screen update. The UpdateScreen (522) function uses this array to decide which characters on screen should be updated, and which not. Note that the OldVideoBuf array may be ignored by some drivers, so it should not be used. The Array is in the interface section of the video unit mainly so drivers that need it can make use of it.

511

CHAPTER 24. THE VIDEO UNIT

24.2

Functions and Procedures

The examples in this section make use of the unit vidutil, which contains the TextOut function. This function writes a text to the screen at a given location. It looks as follows: Listing: videoex/vidutil.pp unit v i d u t i l ; Interface uses video ; { $ i f n d e f cpu86 } { $ e r r o r T h i s example o n l y works on i n t e l 8 0 x86 machines } { $endif }

Procedure TextOut ( X , Y : Word ; Const S : S t r i n g ) ; Implementation Procedure TextOut ( X , Y : Word ; Const S : S t r i n g ) ; Var W, P , I ,M : Word ; begin P : = ( ( X−1)+(Y−1)∗ ScreenWidth ) ; M: = Length ( S ) ; I f P+M>ScreenWidth ∗ ScreenHeight then M: = ScreenWidth ∗ ScreenHeight−P ; For I : = 1 to M do VideoBuf ^ [ P+ I −1]:=Ord ( S [ i ] ) + ( $07 shl 8 ) ; end ; end .

ClearScreen Declaration: procedure ClearScreen; Description: ClearScreen clears the entire screen, and calls UpdateScreen (522) after that. This is done by writing spaces to all character cells of the video buffer in the default color (lightgray on black, color attribute $07). Errors: None. See also: InitVideo (518), UpdateScreen (522) Listing: videoex/ex3.pp program t e s t v i d e o ; uses video , keyboard , v i d u t i l ; { $ i f n d e f cpu86 }

512

CHAPTER 24. THE VIDEO UNIT

{ $ e r r o r T h i s example o n l y works on i n t e l 8 0 x86 machines } { $endif } Var i : longint ; k : TkeyEvent ; begin InitVideo ; InitKeyboard ; For I : = 1 to 1 0 do TextOut ( i , i , ’ Press any key t o c l e a r screen ’ ) ; UpdateScreen ( f a l s e ) ; K: = GetKeyEvent ; ClearScreen ; TextOut ( 1 , 1 , ’ Cleared screen . Press any key t o end ’ ) ; UpdateScreen ( t r u e ) ; K: = GetKeyEvent ; DoneKeyBoard ; DoneVideo ; end .

DefaultErrorHandler Declaration: function DefaultErrorHandler(AErrorCode: TErrorHandlerReturnValue;

Longint; AErrorInfo:

Pointer):

Description: DefaultErrorHandler is the default error handler used by the video driver. It simply sets the error code AErrorCode and AErrorInfo in the global variables ErrorCode and ErrorInfo and returns errContinue. Errors: None. See also:

DoneVideo Declaration: procedure DoneVideo; Description: DoneVideo disables the Video driver if the video driver is active. If the videodriver was already disabled or not yet initialized, it does nothing. Disabling the driver means it will clean up any allocated resources, possibly restore the screen in the state it was before InitVideo was called. Particularly, the VideoBuf and OldVideoBuf arrays are no longer valid after a call to DoneVideo. The DoneVideo should always be called if InitVideo was called. Failing to do so may leave the screen in an unusable state after the program exits. Errors: Normally none. If the driver reports an error, this is done through the ErrorCode variable. See also: InitVideo (518) For an example, see most other functions.

513

CHAPTER 24. THE VIDEO UNIT

GetCapabilities Declaration: function GetCapabilities:

Word;

Description: GetCapabilities returns the capabilities of the current driver. It is an or-ed combination of the following constants: cpUnderLineThe driver supports underlined characters. cpBlinkThe driver supports blinking characters. cpColorThe driver supports colors. cpChangeFontThe driver supports the setting of a screen font. Note, however, that a font setting API is not supported by the video unit. cpChangeModeThe driver supports the setting of screen modes. cpChangeCursorThe driver supports changing the cursor shape. Note that the video driver should not yet be initialized to use this function. It is a property of the driver. Errors: None. See also: GetCursorType (515), GetVideoDriver (516) Listing: videoex/ex4.pp Program Example4 ; { Program t o demonstrate t h e G e t C a p a b i l i t i e s f u n c t i o n . } Uses v i d e o ; Var W: Word ; Procedure TestCap ( Cap : Word ; Msg : S t r i n g ) ; begin Write ( Msg , ’ : ’ ) ; I f (W and Cap=Cap ) then W r i t e l n ( ’ Yes ’ ) else W r i t e l n ( ’ No ’ ) ; end ; begin W: = G e t C a p a b i l i t i e s ; W r i t e l n ( ’ Video d r i v e r s u p p o r t s f o l l o w i n g f u n c t i o n a l i t y ’ ) ; TestCap ( cpUnderLine , ’ U n d e r l i n e d c h a r a c t e r s ’ ) ; TestCap ( c p B l i n k , ’ B l i n k i n g c h a r a c t e r s ’ ) ; TestCap ( cpColor , ’ C o l o r c h a r a c t e r s ’ ) ; TestCap ( cpChangeFont , ’ Changing f o n t ’ ) ; TestCap ( cpChangeMode , ’ Changing v i d e o mode ’ ) ; TestCap ( cpChangeCursor , ’ Changing c u r s o r shape ’ ) ; end .

514

CHAPTER 24. THE VIDEO UNIT

GetCursorType Declaration: function GetCursorType:

Word;

Description: GetCursorType returns the current cursor type. It is one of the following values: crHiddenThe cursor is currently hidden. crUnderLineThe cursor is currently the underline character. crBlockThe cursor is currently the block character. crHalfBlockThe cursur is currently a block with height of half the character cell height. Note that not all drivers support all types of cursors. Errors: None. See also: SetCursorType (520), GetCapabilities (514) Listing: videoex/ex5.pp Program Example5 ; { Program t o demonstrate t h e GetCursorType f u n c t i o n . } Uses video , keyboard , v i d u t i l ; Const C u r s o r t y p e s : Array [ crHidden . . c r H a l f B l o c k ] of s t r i n g = ( ’ Hidden ’ , ’ UnderLine ’ , ’ Block ’ , ’ H a l f B l o c k ’ ) ; begin InitVideo ; InitKeyboard ; TextOut ( 1 , 1 , ’ Cursor t y p e : ’ +CursorTypes [ GetCursorType ] ) ; TextOut ( 1 , 2 , ’ Press any key t o e x i t . ’ ) ; UpdateScreen ( False ) ; GetKeyEvent ; DoneKeyboard ; DoneVideo ; end .

GetLockScreenCount Declaration: Function GetLockScreenCount :

integer;

Description: GetLockScreenCount returns the current lock level. When the lock level is zero, a call to UpdateScreen (522) will actually update the screen. Errors: None. See also: LockScreenUpdate (519), UnlockScreenUpdate (521), UpdateScreen (522) Listing: videoex/ex6.pp Program Example6 ; { Program t o demonstrate t h e GetLockScreenCount f u n c t i o n . } Uses video , keyboard , v i d u t i l ;

515

CHAPTER 24. THE VIDEO UNIT

Var I : Longint ; S : String ; begin InitVideo ; InitKeyboard ; TextOut ( 1 , 1 , ’ Press key t i l l new t e x t appears . ’ ) ; UpdateScreen ( False ) ; Randomize ; For I : = 0 to Random( 1 0 ) + 1 do LockScreenUpdate ; I :=0; While GetLockScreenCount < >0 do begin Inc ( I ) ; Str ( I ,S ) ; UnlockScreenUpdate ; GetKeyEvent ; TextOut ( 1 , 1 , ’ UnLockScreenUpdate had t o be c a l l e d ’ +S+ ’ t i m e s ’ ) ; UpdateScreen ( False ) ; end ; TextOut ( 1 , 2 , ’ Press any key t o end . ’ ) ; UpdateScreen ( False ) ; GetKeyEvent ; DoneKeyboard ; DoneVideo ; end .

GetVideoDriver Declaration: Procedure GetVideoDriver (Var Driver :

TVideoDriver);

Declaration: GetVideoDriver retrieves the current videodriver and returns it in Driver. This can be used to chain video drivers. Errors: None. See also: SetVideoDriver (520) For an example, see the section on writing a custom video driver.

GetVideoMode Declaration: procedure GetVideoMode(var Mode:

TVideoMode);

Description: GetVideoMode returns the settings of the currently active video mode. The row,col fields indicate the dimensions of the current video mode, and Color is true if the current video supports colors. Errors: None. See also: SetVideoMode (521), GetVideoModeData (518) Listing: videoex/ex7.pp 516

CHAPTER 24. THE VIDEO UNIT

Program Example7 ; { Program t o demonstrate t h e GetVideoMode f u n c t i o n . } Uses video , keyboard , v i d u t i l ; Var M : TVideoMode ; S : String ; begin InitVideo ; InitKeyboard ; GetVideoMode (M) ; i f M. C o l o r then TextOut ( 1 , 1 , ’ C u r r e n t else TextOut ( 1 , 1 , ’ C u r r e n t S t r (M. Row, S ) ; TextOut ( 1 , 2 , ’ Number o f S t r (M. Col , S ) ; TextOut ( 1 , 3 , ’ Number o f T e x t o u t ( 1 , 4 , ’ Press any UpdateScreen ( False ) ; GetKeyEvent ; DoneKeyboard ; DoneVideo ; end .

mode has c o l o r ’ ) mode does n o t have c o l o r ’ ) ; rows

: ’ +S ) ;

columns : ’ +S ) ; key t o e x i t . ’ ) ;

GetVideoModeCount Declaration: Function GetVideoModeCount :

Word;

Description: GetVideoModeCount returns the number of video modes that the current driver supports. If the driver does not support switching of modes, then 1 is returned. This function can be used in conjunction with the GetVideoModeData (518) function to retrieve data for the supported video modes. Errors: None. See also: GetVideoModeData (518), GetVideoMode (516) Listing: videoex/ex8.pp Program Example8 ; { Program t o demonstrate t h e GetVideoModeCount f u n c t i o n . } Uses video , keyboard , v i d u t i l ; Procedure DumpMode (M : TVideoMode ; Index : I n t e g e r ) ; Var S : String ; begin

517

CHAPTER 24. THE VIDEO UNIT

S t r ( Index : 2 , S ) ; inc ( Index ) ; TextOut ( 1 , Index , ’ Data f o r mode ’ +S+ ’ : ’ ) ; i f M. C o l o r then TextOut ( 1 9 , Index , ’ color , ’ ) else TextOut ( 1 9 , Index , ’ No c o l o r , ’ ) ; S t r (M. Row: 3 , S ) ; TextOut ( 2 8 , Index , S+ ’ rows ’ ) ; S t r (M. Col : 3 , S ) ; TextOut ( 3 6 , index , S+ ’ columns ’ ) ; end ; Var i , Count : I n t e g e r ; m : TVideoMode ; begin InitVideo ; InitKeyboard ; Count : = GetVideoModeCount ; For I : = 1 to Count do begin GetVideoModeData ( I −1,M) ; DumpMode(M, I −1); end ; TextOut ( 1 , Count +1 , ’ Press any key t o e x i t ’ ) ; UpdateScreen ( False ) ; GetKeyEvent ; DoneKeyboard ; DoneVideo ; end .

GetVideoModeData Declaration: Function GetVideoModeData(Index :

Word; Var Data:

TVideoMode) :

Description: GetVideoModeData returns the characteristics of the Index-th video mode in Data. Index is zero based, and has a maximum value of GetVideoModeCount-1. If the current driver does not support setting of modes (GetVideoModeCount=1) and Index is zero, the current mode is returned. The function returns True if the mode data was retrieved succesfully, False otherwise. Errors: In case Index has a wrong value, False is returned. See also: GetVideoModeCount (517), SetVideoMode (521), GetVideoMode (516) For an example, see GetVideoModeCount (517).

InitVideo Declaration: procedure InitVideo; Description: InitVideo Initializes the video subsystem. If the video system was already initialized, it does nothing. After the driver has been initialized, the VideoBuf and OldVideoBuf pointers are

518

Boolean;

CHAPTER 24. THE VIDEO UNIT

initialized, based on the ScreenWidth and ScreenHeight variables. When this is done, the screen is cleared. Errors: if the driver fails to initialize, the ErrorCode variable is set. See also: DoneVideo (513) For an example, see most other functions.

LockScreenUpdate Declaration: Procedure LockScreenUpdate; Description: LockScreenUpdate increments the screen update lock count with one. As long as the screen update lock count is not zero, UpdateScreen (522) will not actually update the screen. This function can be used to optimize screen updating: If a lot of writing on the screen needs to be done (by possibly unknown functions), calling LockScreenUpdate before the drawing, and UnlockScreenUpdate (521) after the drawing, followed by a UpdateScreen (522) call, all writing will be shown on screen at once. Errors: None. See also: UpdateScreen (522), UnlockScreenUpdate (521), GetLockScreenCount (515) For an example, see GetLockScreenCount (515).

SetCursorPos Declaration: procedure SetCursorPos(NewCursorX, NewCursorY: Word); Description: SetCursorPos positions the cursor on the given position: Column NewCursorX and row NewCursorY. The origin of the screen is the upper left corner, and has coordinates (0,0). The current position is stored in the CursorX and CursorY variables. Errors: None. See also: SetCursorType (520) Listing: videoex/ex2.pp program example2 ; uses video , keyboard ; { $ i f n d e f cpu86 } { $ e r r o r T h i s example o n l y works on i n t e l 8 0 x86 machines } { $endif } Var P , PP, D : I n t e g e r ; K : TKeyEvent ; Procedure PutSquare ( P : I N t e g e r ; C : Char ) ; begin VideoBuf ^ [ P ] : = Ord (C) + ( $07 shl 8 ) ;

519

CHAPTER 24. THE VIDEO UNIT

VideoBuf ^ [ P+ScreenWidth ] : = Ord ( c ) + ( $07 shl 8 ) ; VideoBuf ^ [ P+ 1 ] : = Ord ( c ) + ( $07 shl 8 ) ; VideoBuf ^ [ P+ScreenWidth + 1 ] : = Ord ( c ) + ( $07 shl 8 ) ; end ; begin InitVideo ; InitKeyBoard ; P: = 0 ; PP:= −1; Repeat I f PP−1 then PutSquare ( PP, ’ ’ ) ; PutSquare ( P , ’ # ’ ) ; SetCursorPos ( P Mod ScreenWidth , P div ScreenWidth ) ; UpdateScreen ( False ) ; PP: =P ; Repeat D: = 0 ; K: = TranslateKeyEvent ( GetKeyEvent ) ; Case GetKeyEventCode ( K ) of k b d L e f t : I f ( P Mod ScreenWidth ) < >0 then D:= −1; kbdUp : I f P>=ScreenWidth then D:=− ScreenWidth ; kbdRight : I f ( ( P+ 2 ) Mod ScreenWidth ) < >0 then D: = 1 ; kbdDown : i f ( P0) or ( GetKeyEventChar (K)= ’ q ’ ) ; P: =P+D ; u n t i l GetKeyEventChar ( K)= ’ q ’ ; DoneKeyBoard ; DoneVideo ; end .

SetCursorType Declaration: procedure SetCursorType(NewType:

Word);

Description: SetCursorType sets the cursor to the type specified in NewType. crHiddenthe cursor is not visible. crUnderLinethe cursor is a small underline character (usually denoting insert mode). crBlockthe cursor is a block the size of a screen cell (usually denoting overwrite mode). crHalfBlockthe cursor is a block half the size of a screen cell. Errors: None. See also: SetCursorPos (519)

SetVideoDriver Declaration: Function SetVideoDriver (Const Driver :

520

TVideoDriver) :

Boolean;

CHAPTER 24. THE VIDEO UNIT

Description: SetVideoDriver sets the videodriver to be used to Driver. If the current videodriver is initialized (after a call to InitVideo) then it does nothing and returns False. A new driver can only be installed if the previous driver was not yet activated (i.e. before a call to InitVideo (518)) or after it was deactivated (i.e after a call to DoneVideo). For more information about installing a videodriver, see section 24.3, page 522. Errors: If the current driver is initialized, then False is returned. See also: The example video driver in section 24.3, page 522 For an example, see the section on writing a custom video driver.

SetVideoMode Declaration: Function SetVideoMode(Mode:

TVideoMode) :

Boolean;

Description: SetVideoMode sets the video mode to the mode specified in Mode: TVideoMode = record Col,Row : Word; Color : Boolean; end; If the call was succesful, then the screen will have Col columns and Row rows, and will be displaying in color if Color is True. The function returns True if the mode was set succesfully, False otherwise. Note that the video mode may not always be set. E.g. a console on Linux or a telnet session cannot always set the mode. It is important to check the error value returned by this function if it was not succesful. The mode can be set when the video driver has not yet been initialized (i.e. before InitVideo (518) was called) In that case, the video mode will be stored, and after the driver was initialized, an attempt will be made to set the requested mode. Changing the video driver before the call to InitVideo will clear the stored video mode. To know which modes are valid, use the GetVideoModeCount (517) and GetVideoModeData (518) functions. To retrieve the current video mode, use the GetVideoMode (516) procedure. Errors: If the specified mode cannot be set, then errVioNoSuchMode may be set in ErrorCode See also: GetVideoModeCount (517) GetVideoModeData (518) GetVideoMode (516)

UnlockScreenUpdate Declaration: Procedure UnlockScreenUpdate; Description: UnlockScreenUpdate decrements the screen update lock count with one if it is larger than zero. When the lock count reaches zero, the UpdateScreen (522) will actually update the screen. No screen update will be performed as long as the screen update lock count is nonzero. This mechanism can be used to increase screen performance in case a lot of writing is done. It is important to make sure that each call to LockScreenUpdate (519) is matched by exactly one call to UnlockScreenUpdate Errors: None. See also: LockScreenUpdate (519), GetLockScreenCount (515), UpdateScreen (522) For an example, see GetLockScreenCount (515). 521

CHAPTER 24. THE VIDEO UNIT

UpdateScreen Declaration: procedure UpdateScreen(Force:

Boolean);

Description: UpdateScreen synchronizes the actual screen with the contents of the VideoBuf internal buffer. The parameter Force specifies whether the whole screen has to be redrawn (Force=True) or only parts that have changed since the last update of the screen. The Video unit keeps an internal copy of the screen as it last wrote it to the screen (in the OldVideoBuf array). The current contents of VideoBuf are examined to see what locations on the screen need to be updated. On slow terminals (e.g. a LINUX telnet session) this mechanism can speed up the screen redraw considerably. Errors: None. See also: ClearScreen (512) For an example, see most other functions.

24.3

Writing a custom video driver

Writing a custom video driver is not difficult, and generally means implementing a couple of functions, which whould be registered with the SetVideoDriver (520) function. The various functions that can be implemented are located in the TVideoDriver record: TVideoDriver = Record InitDriver : DoneDriver : UpdateScreen : ClearScreen : SetVideoMode : GetVideoModeCount : GetVideoModeData : SetCursorPos : GetCursorType : SetCursorType : GetCapabilities : end;

Procedure; Procedure; Procedure(Force : Boolean); Procedure; Function (Const Mode : TVideoMode) : Boolean; Function : Word; Function(Index : Word; Var Data : TVideoMode) : Boolean; procedure (NewCursorX, NewCursorY: Word); function : Word; procedure (NewType: Word); Function : Word;

Not all of these functions must be implemented. In fact, the only absolutely necessary function to write a functioning driver is the UpdateScreen function. The general calls in the Video unit will check which functionality is implemented by the driver. The functionality of these calls is the same as the functionality of the calls in the video unit, so the expected behaviour can be found in the previous section. Some of the calls, however, need some additional remarks. InitDriver Called by InitVideo, this function should initialize any data structures needed for the functionality of the driver, maybe do some screen initializations. The function is guaranteed to be called only once; It can only be called again after a call to DoneVideo. The variables ScreenWidth and ScreenHeight should be initialized correctly after a call to this function, as the InitVideo call will initialize the VideoBuf and OldVideoBuf arrays based on their values. DoneDriver This should clean up any structures that have been initialized in the InitDriver function. It should possibly also restore the screen as it was before the driver was initialized. 522

CHAPTER 24. THE VIDEO UNIT

The VideoBuf and OldVideoBuf arrays will be disposed of by the general DoneVideo call. UpdateScreen This is the only required function of the driver. It should update the screen based on the VideoBuf array’s contents. It can optimize this process by comparing the values with values in the OldVideoBuf array. After updating the screen, the UpdateScreen procedure should update the OldVideoBuf by itself. If the Force parameter is True, the whole screen should be updated, not just the changed values. ClearScreen If there is a faster way to clear the screen than to write spaces in all character cells, then it can be implemented here. If the driver does not implement this function, then the general routines will write spaces in all video cells, and will call UpdateScreen(True). SetVideoMode Should set the desired video mode, if available. It should return True if the mode was set, False if not. GetVideoModeCount Should return the number of supported video modes. If no modes are supported, this function should not be implemented; the general routines will return 1. (for the current mode) GetVideoModeData Should return the data for the Index-th mode; Index is zero based. The function should return true if the data was returned correctly, false if Index contains an invalid index. If this is not implemented, then the general routine will return the current video mode when Index equals 0. GetCapabilities If this function is not implemented, zero (i.e. no capabilities) will be returned by the general function. The following unit shows how to override a video driver, with a driver that writes debug information to a file. Listing: videoex/viddbg.pp u n i t viddbg ; Interface uses v i d e o ;

Procedure S t a r t V i d e o L o g g i n g ; Procedure StopVideoLogging ; Function I s V i d e o L o g g i n g : Boolean ; Procedure SetVideoLogFileName ( FileName : S t r i n g ) ; Const D e t a i l e d V i d e o L o g g i n g : Boolean = False ; Implementation uses s y s u t i l s , keyboard ; var NewVideoDriver , OldVideoDriver : TVideoDriver ; A c t i v e , Logging : Boolean ; LogFileName : S t r i n g ; VideoLog : Text ;

523

CHAPTER 24. THE VIDEO UNIT

Function TimeStamp : S t r i n g ; begin TimeStamp : = FormatDateTime ( ’ hh : nn : ss ’ , Time ( ) ) ; end ; Procedure S t a r t V i d e o L o g g i n g ; begin Logging : = True ; W r i t e l n ( VideoLog , ’ S t a r t l o g g i n g v i d e o o p e r a t i o n s a t : ’ , TimeStamp ) ; end ; Procedure StopVideoLogging ; begin W r i t e l n ( VideoLog , ’ Stop l o g g i n g v i d e o o p e r a t i o n s a t : ’ , TimeStamp ) ; Logging : = False ; end ; Function I s V i d e o L o g g i n g : Boolean ; begin I s V i de o L o g g i n g : = Logging ; end ; Var ColUpd , RowUpd : Array [ 0 . . 1 0 2 4 ] of I n t e g e r ; Procedure D u m p S c r e e n S t a t i s t i c s ( Force : Boolean ) ; Var I , Count : I n t e g e r ; begin I f Force then Write ( VideoLog , ’ f o r c e d ’ ) ; W r i t e l n ( VideoLog , ’ v i d e o update a t ’ , TimeStamp , ’ : ’ ) ; F i l l C h a r ( Colupd , SizeOf ( ColUpd ) , # 0 ) ; F i l l C h a r ( Rowupd , SizeOf ( RowUpd ) , # 0 ) ; Count : = 0 ; For I : = 0 to VideoBufSize div SizeOf ( T V i d e o C e l l ) do begin I f VideoBuf ^ [ i ] < > OldVideoBuf ^ [ i ] then begin Inc ( Count ) ; Inc ( ColUpd [ I mod ScreenWidth ] ) ; Inc ( RowUpd [ I div ScreenHeight ] ) ; end ; end ; Write ( VideoLog , Count , ’ v i d e o c e l l s d i f f e r e d d i v i d e d over ’ ) ; Count : = 0 ; For I : = 0 to ScreenWidth −1 do I f ColUpd [ I ] < >0 then Inc ( Count ) ; Write ( VideoLog , Count , ’ columns and ’ ) ; Count : = 0 ; For I : = 0 to ScreenHeight −1 do

524

CHAPTER 24. THE VIDEO UNIT

I f RowUpd [ I ] < >0 then Inc ( Count ) ; W r i t e l n ( VideoLog , Count , ’ rows . ’ ) ; I f D e t a i l e d V i d e o L o g g i n g Then begin For I : = 0 to ScreenWidth −1 do I f ( ColUpd [ I ] < > 0 ) then W r i t e l n ( VideoLog , ’ Col ’ , i , ’ : For I : = 0 to ScreenHeight −1 do I f ( RowUpd [ I ] < > 0 ) then W r i t e l n ( VideoLog , ’Row ’ , i , ’ : end ; end ;

’ , ColUpd [ I ] : 3 , ’ rows changed ’ ) ;

’ ,RowUpd [ I ] : 3 , ’ colums changed ’ ) ;

Procedure LogUpdateScreen ( Force : Boolean ) ; begin I f Logging then D u m p S c r e e n S t a t i s t i c s ( Force ) ; O l d V i d e o D r i v e r . UpdateScreen ( Force ) ; end ; Procedure L o g I n i t V i d e o ; begin OldVideoDriver . I n i t D r i v e r ( ) ; Assign ( VideoLog , logFileName ) ; Rewrite ( VideoLog ) ; A c t i v e : = True ; StartVideoLogging ; end ; Procedure LogDoneVideo ; begin StopVideoLogging ; Close ( VideoLog ) ; A c t i v e : = False ; O l d V i d e o D r i v e r . DoneDriver ( ) ; end ; Procedure SetVideoLogFileName ( FileName : S t r i n g ) ; begin I f Not A c t i v e then LogFileName : = FileName ; end ; Initialization GetVideoDriver ( OldVideoDriver ) ; NewVideoDriver : = O l d V i d e o D r i v e r ; NewVideoDriver . UpdateScreen : = @LogUpdateScreen ; NewVideoDriver . I n i t D r i v e r : = @LogInitVideo ; NewVideoDriver . DoneDriver : = @LogDoneVideo ; LogFileName : = ’ Video . l o g ’ ; Logging : = False ; S e t V i d e o D r i v e r ( NewVideoDriver ) ; end .

525

CHAPTER 24. THE VIDEO UNIT

The unit can be used in any of the demonstration programs, by simply including it in the uses clause. Setting DetailedVideoLogging to True will create a more detailed log (but will also slow down functioning)

526

Index Abstract, 320 Accept, 382, 384 Access, 192 AddDisk, 45 AddDisk (Linux only), 425 AdjustLineBreaks, 445 Alarm, 193 allocate_ldt_descriptors, 86 allocate_memory_block, 88 AnsiCompareStr, 446 AnsiCompareText, 447 AnsiExtractQuotedStr, 448 AnsiLastChar, 448 AnsiLowerCase, 449 AnsiQuotedStr, 449 AnsiStrComp, 449 AnsiStrIComp, 450 AnsiStrLastChar, 451 AnsiStrLComp, 452 AnsiStrLIComp, 452 AnsiStrLower, 453 AnsiStrUpper, 454 AnsiUpperCase, 455 AppendStr, 455 Arc, 120 arccos, 264 arcosh, 264 arcsin, 265 arctan2, 266 arsinh, 266 artanh, 267 AssignCrt, 30 AssignLst, 379 AssignPipe, 194 AssignStr, 456 AssignStream, 194

CFSetISpeed, 197 CFSetOSpeed, 197 ChangeFileExt, 428 Chmod, 198 Chown, 197 Circle, 121 ClearDevice, 121 ClearScreen, 512 ClearViewPort, 121 Clone, 199 CloseDir, 201 CloseGraph, 121 ClrEol, 30 ClrScr, 31 CompareMem, 457 CompareStr, 457 CompareText, 458 Connect, 385, 386 copyfromdos, 88 copytodos, 88 cosh, 268 cotan, 268 create_code_segment_alias_descriptor, 89 CreateDir, 426 CreateShellArgV, 201 CursorBig, 30 CursorOff, 31 CursorOn, 32 cycletorad, 268 Date, 411 DateTimeToFileDate, 412 DateTimeToStr, 412 DateTimeToString, 413 DateTimeToSystemTime, 414 DateTimeToTimeStamp, 414 DateToStr, 415 DayOfWeek, 415 DecodeDate, 416 DecodeTime, 416 DefaultErrorHandler, 513 degtograd, 269 degtorad, 269 Delay, 32 DeleteFile, 429

Bar, 120 Bar3D, 121 BaseName, 196 BCDToInt, 456 Bind, 384, 385 ceil, 267 CFMakeRaw, 196

527

INDEX

DelLine, 32 DetectGraph, 122 DetectMouse, 296 DirName, 202 disable, 89 DiskFree, 45, 426 DiskSize, 46, 427 DisposeStr, 320, 459 DoDirSeparators, 429 DoneKeyboard, 165 DoneMouse, 297 DoneVideo, 513 DosExitCode, 47 dosmemfillchar, 89 dosmemfillword, 90 dosmemget, 91 dosmemmove, 91 dosmemput, 91 DosVersion, 47 DrawPoly, 122 DumpHeap, 141 Dup, 203 Dup2, 203 dxe_load, 61 Ellipse, 122 Emms, 294 enable, 92 EncodeDate, 417 EncodeTime, 417 EnvCount, 48 EnvStr, 48 EpochToLocal, 204 Exec, 49 Execl, 205 Execle, 205 Execlp, 206 Execv, 207 Execve, 207 Execvp, 208 ExpandFileName, 430 ExpandUNCFileName, 430 ExtractFileDir, 431 ExtractFileDrive, 431 ExtractFileExt, 432 ExtractFileName, 432 ExtractFilePath, 432 ExtractRelativePath, 432 Fcntl, 218, 219 FD_Clr, 209 FD_IsSet, 210 FD_Set, 210 FD_ZERO, 209

fdClose, 210 fdFlush, 210 fdOpen, 211 fdRead, 212 fdSeek, 213 fdTruncate, 213 fdWrite, 213 FExpand, 49, 214 FileAge, 433 FileClose, 434 FileCreate, 434 FileDateToDateTime, 418 FileExists, 435 FileGetAttr, 435 FileGetDate, 436 FileOpen, 437 FileRead, 437 FileSearch, 438 FileSeek, 438 FileSetAttr (Not on Linux), 439 FileSetDate (Not on Linux), 439 FileTruncate, 439 FileWrite, 440 FillEllipse, 122 FillPoly, 122 FindClose, 49, 440 FindFirst, 50, 440 FindNext, 50, 441 FindPropInfo, 486 FloatToStr, 459 FloatToStrF, 460 FloatToText, 461 FLock, 214 FloodFill, 123 floor, 270 FmtStr, 462 FNMatch, 214 Fork, 219 Format, 462 FormatBuf, 468 FormatDateTime, 418 FormatFloat, 468 free_ldt_descriptor, 92 free_memory_block, 92 free_rm_callback, 92 FRename, 219 frexp, 270 FSearch, 51, 215 FSplit, 51, 215 FSStat, 216 FStat, 217 ftok, 149 FunctionKeyName, 165

528

INDEX

get_cs, 93 get_descriptor_access_rights, 93 get_ds, 93 get_linear_addr, 93 get_meminfo, 94 get_next_selector_increment_value, 95 get_page_size, 95 get_pm_interrupt, 95 get_rm_callback, 96 get_rm_interrupt, 98 get_run_mode, 99 get_segment_base_address, 99 get_segment_limit, 100 get_ss, 100 GetArcCoords, 123 GetAspectRatio, 123 GetBkColor, 123 GetCapabilities, 514 GetCBreak, 52 GetColor, 123 GetCurrentDir, 427 GetCursorType, 515 GetDate, 52, 220 GetDateTime, 220 GetDefaultPalette, 123 GetDirs, 441 GetDomainName, 221 GetDriverName, 124 GetEGid, 221 GetEnumName, 487 GetEnumProp, 487 GetEnumValue, 488 GetEnv, 53, 222 GetEpochTime, 223 GetEUid, 222 GetFAttr, 53 GetFillPattern, 124 GetFillSettings, 124 GetFloatProp, 488 GetFS, 223 GetFTime, 54 GetGid, 224 GetGraphMode, 124 GetHostName, 224 GetImage, 124 GetInt64Prop, 489 GetIntVec, 55 GetKeyboardDriver, 166 GetKeyEvent, 166 GetKeyEventChar, 167 GetKeyEventCode, 167 GetKeyEventFlags, 168 GetKeyEventShiftState, 168 GetKeyEventUniCode, 169

GetLastButtonPress, 306 GetLastButtonRelease, 307 GetLineSettings, 124 GetLocalTimezone, 224 GetLockScreenCount, 515 GetLongName, 55 GetLongOpts, 65 GetMaxColor, 125 GetMaxMode, 125 GetMaxX, 125 GetMaxY, 125 GetMethodProp, 490 GetModeName, 125 GetModeRange, 126 GetMouseButtons, 297 GetMouseDriver, 298 GetMouseEvent, 298 GetMouseState, 308 GetMouseX, 298 GetMouseY, 299 GetObjectProp, 492 GetObjectPropClass, 493 Getopt, 65 GetOrdProp, 493 GetPalette, 126 GetPaletteSize, 126 GetPeerName, 387 GetPid, 225 GetPixel, 126 GetPPid, 225 GetPriority, 225 GetPropInfo, 494 GetPropInfos, 495 GetPropList, 496 GetPropValue, 497 GetSetProp, 497 GetShortName, 55 GetSocketName, 388 GetSocketOptions, 388 GetStrProp, 498 GetTextSettings, 126 GetTime, 55, 226 GetTimeOfDay, 226, 227 GetTimezoneFile, 227 GetTypeData, 499 GetUid, 227 GetVariantProp, 499 GetVerify, 56 GetVideoDriver, 516 GetVideoMode, 516 GetVideoModeCount, 517 GetVideoModeData, 518 GetViewSettings, 127 GetX, 127 529

INDEX

GetY, 127 Glob, 228 global_dos_alloc, 100 global_dos_free, 102 GlobFree, 228 GotoXY, 33 Gpm_AnyDouble, 70 Gpm_AnySingle, 71 Gpm_AnyTriple, 71 Gpm_Close, 71 Gpm_FitValues, 71 Gpm_FitValuesM, 71 Gpm_GetEvent, 72 Gpm_GetLibVersion, 73 Gpm_GetServerVersion, 73 Gpm_GetSnapshot, 73 Gpm_LowerRoi, 74 Gpm_Open, 74 Gpm_PopRoi, 74 Gpm_PushRoi, 74 Gpm_RaiseRoi, 75 Gpm_Repeat, 75 Gpm_StrictDouble, 75 Gpm_StrictSingle, 75 Gpm_StrictTriple, 76 gradtodeg, 271 gradtorad, 271 GraphDefaults, 127 GraphErrorMsg, 127 GraphResult, 128 HideMouse, 299, 309 HighVideo, 33 hypot, 272 ImageSize, 128 IncMonth, 419 InitGraph, 128 InitKeyBoard, 169 InitMouse, 300, 309 InitVideo, 518 inportb, 102 inportl, 102 inportw, 102 InsLine, 34 InstallUserDriver, 129 InstallUserFont, 129 intpower, 272 Intr, 56 IntToHex, 469 IntToStr, 470 IOCtl, 228 IOperm, 229 IsATTY, 229

IsFunctionKey, 169 IsLeapYear, 419 IsPublishedProp, 499 IsStoredProp, 500 IsValidIdent, 471 Keep, 57 KeyEventToString, 170 KeyPressed, 34 Kill, 232 LastDelimiter, 471 ldexp, 273 LeftStr, 472 Line, 129 LineRel, 129 LineTo, 130 Link, 233 Listen, 388 lnxp1, 273 LoadStr, 472 LocalToEpoch, 234 lock_code, 103 lock_data, 103 lock_linear_region, 103 LockScreenUpdate, 519 log10, 274 log2, 274 logn, 275 LongDiv, 322 LongMul, 322 LowerCase, 472 LowVideo, 35 LPressed, 310 LStat, 232 MarkHeap, 141 max, 275 maxIntValue, 276 maxvalue, 276 mean, 277 meanandstddev, 278 min, 279 minIntValue, 279 minvalue, 280 MkFifo, 235 MMap, 235 momentskewkurtosis, 281 MoveRel, 130 MoveTo, 130 MPressed, 310 MSDos, 57 MSecsToTimeStamp, 420 msgctl, 150

530

INDEX

msgget, 149 msgrcv, 150 msgsnd, 149 MUnMap, 237 NanoSleep, 237 NewStr, 319, 473 Nice, 238 norm, 281 NormVideo, 35 NoSound, 35 Now, 421 npxsetup, 63 Octal, 238 OpenDir, 239 outportb, 104 outportl, 104 outportw, 104 OutText, 130 OutTextXY, 130 PackTime, 57 pause, 240 PClose, 240 PieSlice, 131 PollKeyEvent, 170 PollMouseEvent, 300 PollShiftStateEvent, 171 POpen, 240 popnstddev, 282 popnvariance, 283 power, 283 PropIsType, 501 PropType, 502 PutImage, 131 PutKeyEvent, 171 PutMouseEvent, 300 PutPixel, 131 QuotedStr, 473 radtocycle, 284 radtodeg, 284 radtograd, 285 randg, 285 ReadDir, 241 ReadKey, 36 ReadLink, 241 ReadPort, 243 ReadPortB, 243 ReadPortL, 243 ReadPortW, 244 ReadTimezoneFile, 244 realintr, 105

Rectangle, 131 Recv, 389 RegisterBGIDriver, 131 RegisterBGIFont, 132 RegisterObjects, 320 RegisterType, 320 RemoveDir, 428 RenameFile, 442 RestoreCRTMode, 132 RightStr, 473 RPressed, 310 S_ISBLK, 230 S_ISCHR, 230 S_ISDIR, 230 S_ISFIFO, 230 S_ISLNK, 231 S_ISREG, 231 S_ISSOCK, 231 Sector, 132 SeekDir, 244 seg_fillchar, 105 seg_fillword, 106 seg_move, 107 segment_to_descriptor, 106 Select, 244 SelectText, 245 semctl, 154 semget, 153 semop, 153 Send, 389 set_descriptor_access_rights, 107 set_pm_interrupt, 107 set_rm_interrupt, 108 set_segment_base_address, 109 set_segment_limit, 109 SetActivePage, 132 SetAllPallette, 132 SetAspectRatio, 133 SetBkColor, 133 SetCBreak, 58 SetColor, 133 SetCurrentDir, 428 SetCursorPos, 519 SetCursorType, 520 SetDate, 58 SetDirSeparators, 442 SetEnumProp, 503 SetExtraInfo, 142 SetFAttr, 58 SetFillPattern, 133 SetFillStyle, 133 SetFloatProp, 503 SetFTime, 59 531

INDEX

SetGraphBufSize, 134 SetGraphMode, 134 SetHeapTraceOutput, 143 SetInt64Prop, 503 SetIntVec, 59 SetKeyboardDriver, 172 SetLineStyle, 134 SetMethodProp, 504 SetMouseAscii, 310 SetMouseDriver, 301 SetMouseHideWindow, 311 SetMousePos, 312 SetMouseShape, 313 SetMouseSpeed, 314 SetMouseWindow, 315 SetMouseXRange, 315 SetMouseXY, 301 SetMouseYRange, 316 SetObjectProp, 504 SetOrdProp, 505 SetPalette, 135 SetPriority, 246 SetPropValue, 505 SetRGBPalette, 135 SetSetProp, 505 SetSocketOptions, 390 SetStrProp, 506 SetTextJustify, 135 SetTextStyle, 135 SetTime, 59 SetToString, 506 SetUserCharSize, 136 SetVariantProp, 507 SetVerify, 59 SetVideoDriver, 520 SetVideoMode, 521 SetViewPort, 136 SetVisualPage, 136 SetWriteMode, 137 Shell, 246 ShiftStateToString, 173 shmat, 159 shmctl, 159 shmdt, 159 shmget, 158 ShowMouse, 302, 316 Shutdown, 390 SigAction, 247 Signal, 249 SigPending, 248 SigProcMask, 248 SigRaise, 248 SigSuspend, 249 sincos, 286

sinh, 286 Sock2File, 390 Sock2Text, 391 Socket, 391 SocketPair, 391 Sound, 37 stddev, 287 Str2UnixSockAddr, 391 StrAlloc, 392, 444 StrBufSize, 444 StrCat, 392 StrComp, 393 StrCopy, 393 StrDispose, 394, 444 StrECopy, 394 StrEnd, 395 StrFmt, 474 StrIComp, 395 StringToPPchar, 250 StringToSet, 507 StrLCat, 396 StrLComp, 396 StrLCopy, 397 StrLen, 397 StrLFmt, 474 StrLIComp, 398 StrLower, 398 StrMove, 399 StrNew, 399 StrPas, 400, 445 StrPCopy, 400, 445 StrPLCopy, 445 StrPos, 401 StrRScan, 401 StrScan, 401 StrToDate, 421 StrToDateTime, 422 StrToFloat, 475 StrToInt, 476 StrToIntDef, 476 StrToTime, 422 StrUpper, 402 sum, 288 sumofsquares, 288 sumsandsquares, 289 SwapVectors, 60 SymLink, 251 SysInfo, 252 SystemTimeToDateTime, 423 tan, 290 tanh, 290 tb_size, 109 TBufStream.Close, 342 532

INDEX

TBufStream.Done, 342 TBufStream.Flush, 342 TBufStream.Init, 341 TBufStream.Open, 343 TBufStream.Read, 344 TBufStream.Seek, 343 TBufStream.Truncate, 343 TBufStream.Write, 344 TCDrain, 253 TCFlow, 253 TCFlush, 254 TCGetAttr, 254 TCGetPGrp, 255 TCollection.At, 349 TCollection.AtDelete, 357 TCollection.AtFree, 356 TCollection.AtInsert, 359 TCollection.AtPut, 359 TCollection.Delete, 355 TCollection.DeleteAll, 354 TCollection.Done, 348 TCollection.Error, 359 TCollection.FirstThat, 351 TCollection.ForEach, 358 TCollection.Free, 354 TCollection.FreeAll, 353 TCollection.FreeItem, 357 TCollection.GetItem, 350 TCollection.IndexOf, 349 TCollection.Init, 347 TCollection.Insert, 355 TCollection.LastThat, 350 TCollection.Load, 348 TCollection.Pack, 352 TCollection.PutItem, 361 TCollection.SetLimit, 359 TCollection.Store, 360 TCSendBreak, 255 TCSetAttr, 255 TCSetPGrp, 256 TDateTime, 411 TDosStream.Close, 338 TDosStream.Done, 338 TDosStream.Init, 337 TDosStream.Open, 340 TDosStream.Read, 340 TDosStream.Seek, 339 TDosStream.Truncate, 338 TDosStream.Write, 341 TellDir, 256 TextBackground, 37 TextColor, 37 TextHeight, 137 TextMode, 38

TextToFloat, 477 TextWidth, 137 Time, 423 TimeStampToDateTime, 424 TimeStampToMSecs, 424 TimeToStr, 425 TMemoryStream.Done, 345 TMemoryStream.Init, 345 TMemoryStream.Read, 346 TMemoryStream.Truncate, 345 TMemoryStream.Write, 346 TObject.Done, 328 TObject.Free, 328 TObject.Init, 328 totalvariance, 291 transfer_buffer, 110 TranslateKeyEvent, 173 TranslateKeyEventUniCode, 173 TRect.Assign, 327 TRect.Contains, 324 TRect.Copy, 324 TRect.Empty, 323 TRect.Equals, 324 TRect.Grow, 326 TRect.Intersect, 325 TRect.Move, 326 TRect.Union, 325 TResourceCollection.FreeItem, 372 TResourceCollection.GetItem, 371 TResourceCollection.KeyOf, 371 TResourceCollection.PutItem, 372 TResourceFile.Count, 373 TResourceFile.Delete, 374 TResourceFile.Done, 373 TResourceFile.Flush, 374 TResourceFile.Get, 373 TResourceFile.Init, 373 TResourceFile.KeyAt, 373 TResourceFile.Put, 374 TResourceFile.SwitchTo, 374 Trim, 478 TrimLeft, 479 TrimRight, 479 TSortedCollection.Compare, 363 TSortedCollection.IndexOf, 363 TSortedCollection.Init, 362 TSortedCollection.Insert, 365 TSortedCollection.KeyOf, 362 TSortedCollection.Load, 362 TSortedCollection.Search, 364 TSortedCollection.Store, 366 TStrCollection.Compare, 368 TStrCollection.FreeItem, 369 TStrCollection.GetItem, 368 533

INDEX

TStrCollection.PutItem, 369 TStream.Close, 333 TStream.CopyFrom, 336 TStream.Error, 335 TStream.Flush, 333 TStream.Get, 330 TStream.GetPos, 331 TStream.GetSize, 331 TStream.Open, 333 TStream.Put, 334 TStream.Read, 335 TStream.ReadStr, 332 TStream.Reset, 333 TStream.Seek, 335 TStream.StrRead, 330 TStream.StrWrite, 334 TStream.Truncate, 334 TStream.Write, 336 TStream.WriteStr, 334 TStringCollection.Compare, 367 TStringCollection.FreeItem, 367 TStringCollection.GetItem, 366 TStringCollection.PutItem, 368 TStringList.Done, 375 TStringList.Get, 375 TStringList.Load, 375 TStrListMaker.Done, 376 TStrListMaker.Init, 376 TStrListMaker.Put, 376 TStrListMaker.Store, 376 TTYName, 256 TUnSortedStrCollection.Insert, 370 Umask, 256 Uname, 257 UnLink, 257 unlock_code, 110 unlock_data, 110 unlock_linear_region, 110 UnlockScreenUpdate, 521 UnPackTime, 60 UpdateScreen, 522 UpperCase, 480 Utime, 257 variance, 291 WaitPid, 258 WhereX, 38 WhereY, 38 Window, 39 WritePort, 259 WritePortB, 259 WritePortL, 259 WritePortW, 260 534