Turbo Prolog Toolbox 1987 PDF
Turbo Prolog Toolbox 1987 PDF
Copyright 1987
All Rights Reserved
BORlAND INTERNATIONAL, INC.
4585 scans VALLEY DRIVE
scans VALLEY, CA 95066
USA
INTERNATIONAL
First Edition
Printed in USA
9 876 5 4 3 2
Table of Contents
Chapter 1 Introduction 1
Wha t These Tools Can Do for You ............................... 2
How to Use This Book ......................................... 3
Who's Who? .................................................. 3
The Distribution Disks ......................................... 3
Tool Domains and Predicates ................................... 4
Running the Sample Programs .................................. 5
Installing the Toolbox on a Hard Disk ......................... 5
Installing the Toolbox on Floppy Disks ........................ 6
A Helpful Hint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 7
Reserved Windows ............................................ 7
Part 1 User's Guide 9
Chapter 2 User Interface Tools 11
Status Lines ................................................. 11
A Sample Program Using a Status Line ............... . . . . . . .. 12
Some Basic Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 13
The menu Tool Predicate .................................... 14
Using menu in a Sample Program ............................ 15
The Tool Predicate menu_leave . .............................. 17
Using menu_leave in a Sample Program ....................... 17
The Tool Predicate menu_mult ............................... 17
Using menu_mult in a Sample Program ....................... 18
Using menu, menu_leave, and menu_mult in a Program .......... 20
longmenu, longmenu_leave, and longmenu_mult .................... 21
Using the longmenu Tool Predicates in a Program .............. 21
Box Menus .................................................. 23
Using boxmenu and boxmenu_mult in a Program ............... 24
A Line Menu ................................................ 25
Using linemenu in a Program ................................ 26
Pull-d.own Menus ............................................ 26
Using pulldown in a Program ... . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 29
Tree Menu Input ............................................. 31
Using treemenu in a Program .......................... . . . . .. 32
A Line Input Driver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 33
Using the Three lineinput Tool Predicates in a Program ......... 34
Reading a File Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 36
Using readfilename in a Program ............................. 36
Context-Sensitive Help ........................................ 37
Help Contexts in Tool Predicates ............................ 40
Resizing Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 41
Using resizewindow in a Program. . . . . . . . . . . . . . . . . . . . . . . . . . . .. 42
A Mixed Bag of BIOS Calls .................................... 43
Setting and Reading the Verify Switch . . . . . . . . . . . . . . . . . . . . . . .. 43
Changing the Color of the Screen Border. . . . . . . . . . . . . . . . . . . . .. 44
Reading File Names from the Directory. . . . . . . . . . . . . . . . . . . . . .. 44
Chapter 3 Screen-Layout Tools 47
Basic Screen-Layout Definition ................................. 48
Basic Use of the Screen Handler ................................ 51
Facilities in SCRDEF.PRO ..................................... 53
Define Screen Layout ...................................... 54
Save Screen Layout ........................................ 56
Load Screen Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 56
Edit Layout Definition File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 57
Associating Values with Fields ................................. 57
Associating Actions with Fields ................................ 61
No-Input Fields .............................................. 64
Computing Travel Time ............................... . . . .. 65
Three Sample Programs ........................... . . . . . . . . . . .. 70
Sorting for Common Interests ............................... 70
Using Screen Handlers in a Sample Program .................. 72
Recording Sales Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 76
A Label-Printing Program .................................. 80
More Advanced Uses of the Screen Handler ..................... 86
Specifying New Special Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 86
Associating Help Text With a Field ........................... 86
Adding Your Own Screen-Definition Types ................... 87
Using Several Screen Layouts Interchangeably , .. , ............ 89
Creating New Screen Definitions from Old. . . . . . . . . . . . . . . . . . .. 90
Printing Formatted Reports .................................... 90
Chapter 4 Graphics Tools 95
Coping with Different Coordinate Systems ...................... 95
iI
Virtual-Screen Coordinates ................................. 96
Low-level Tool Predicates and Virtual Coordinates ............. 96
The Predicate plot ......................................... 97
The Predicate box ......................................... 97
The Predicate ellipse ....................................... 98
The Predicate sector ....................................... 98
The Predicate lineShade .................................... 99
Using Low-level Tool Graphics Predicates in a Sample Program . 100
Defining Scales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 103
Drawing Axes on the Screen .................................. 106
Using Scales and Axes in a Sample Program. . . . . . . . . . . . . . . . .. 107
Other Tool Predicates for Handling Coordinates ................. 112
Setting a Scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 112
Conversion Between Virtual and Text Coordinates . . . . . . . . . . .. 112
Conversion Between Scaled and Text or Virtual Coordinates ... 113
Pie Charts .................................................. 114
Using a Pie Chart in a Sample Program . . . . . . . . . . . . . . . . . . . . .. 115
Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 119
Using bargraph and bargraph3d in a Sample Program . . . . . . . . . .. 120
Color Graphics with the EGA Card ............................ 122
Using the EGA Palettes in a Sample Program. . . . . . . . . . . . . . . .. 123
Loading .PIC Files .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 126
Using Zoadpic in a Sample Program . . .. . . . . . . . . .. .. . .. .. . . . .. 127
Using Zoadpic and savepic to Create an On-Screen Presentation .. 128
Chapter 5 Communication with Remote Serial Devices 131
The Communication Tool Predicates ........................... 131
Hardware Considerations .................................... 132
Pinouts for DTE-to-DTE Configuration ...................... 133
Pinouts for DTE-to-OCE Configuration . . . . . . . . . . . . . . . . . . . . .. 133
General Serial Communications ............................... 134
Opening a Serial Port ..................................... 134
Closing a Serial Port ...................................... 136
Obtaining Transmission Status Information ................ ;. 136
Transmit a Character from a Serial Port . . . . . . . . . . . . . . . . . . . . .. 138
Receiving a Character from a Serial Port ..................... 139
Obtaining Input and Output Queue Sizes ............... . . . .. 139
Deleting the Output Buffer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 140
Deleting the Input Buffer .................................. 140
Some Complete Sample Programs ............................. 140
III
A Printer Driver That Lets You Modify the File Being Printed ... 141
Terminal Emulation ........................................ 143
Polled Communication with Time Out ...................... 144
Transmission with a True Subset of the XMODEM Protocol .... 146
Modem Communication ..................................... 153
Sending a Break Signal to a Modem . . . . . . . . . . . . . . . . . . . . . . . .. 153
Setting the Modem Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 153
Sending a Command or Data to a Modem ................... 155
Receiving a Response from a Modem. . . . . . . . . . . . . . . . . . . . . . .. 155
A Menu-Driven Serial Communications Program. . . . . . . . . . . . . . .. 156
Chapter 6 Importing Data from Other Systems 165
Accessing a Reflex File ....................................... 166
Reading One Reflex Record at a Time ....................... 168
Accessing a dBASE III File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 170
Reading One dBASE III Record at a Time .................... 172
Accessing a Lotus 1-2-3 or Symphony File ...................... 174
Reading All Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 177
Reading a Specific Cell .................................... 177
Chapter 7 The Parser Generator 181
What Does a Parser Do? .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 181
The Different Types of Parsers . . . . . . . . . . . . . .. . . . . . . . . . . . . . .. 182
Lexical Analysis: The Scanner .............................. 183
Describing the Grammar .................................. 183
Backus Naur Form Grammar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 184
The Toolbox Parser Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 186
Specifying the Input to the Parser Generator ................. 187
Creating Your Own Grammar .............................. 190
Examples Demonstrating the Parser Generator .................. 193
The Toolbox Version of a Grammar ......................... 194
Example of the Parser Generator's Input Grammar. . . . . . . . . . .. 195
Example of a Parser Domains File Generated by the Parser. . . .. 196
Example of a Scanner for the Generated Parser ............... 197
Example of Generated Parser .............................. 198
Example of the Scanner and Generated Parser Used Together. .. 199
Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 201
Using the Whole System in a Working Sample . . . . . . . . . . . . . . .. 202
The Generated Domain Definitions ......................... 203
The Generated Parser ..................................... 204
The Scanner ............................................. 206
Iv
The Parser Generator System ................................. 212
The System Around the Generated Parser. . . . . . . . . . . . . . . . . . .. 212
Bootstrapping a Parser ....................................... 213
Part 2 Reference Guide 217
Chapter 8 Reference Guide 219
Introduction ............................................... 219
axisla1>els . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 224
bargraph ................................................... 225
batGraph3d ................................................ 227
border ..................................................... 229
box ........................................................ 230
boxmenu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 231
boxmenu_leave ............................................. 233
boxmenu_mult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 235
changestatus ................................................ 237
closeRS232 ................................................. 238
createwindow (used by scrhnd) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 239
defineScale ................................................. 240
delInBuf_RS232 ............................................. 241
delOt1tBuf_RS232 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 242
disks pace .................................................. 243
dosver ..................................................... 244
draw ...................................................... 245
ellipse ..................................................... 246
field_action (programmer defined) . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 247
field_value (programmer defined) ............................. 248
Findmatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 249
findScale ................................................... 250
getverify ................................................... 251
gwrite ..................................................... 252
help ....................................................... 253
init_dBase3 ................................................. 254
init_Reflex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 255
lineinput ................................................... 256
lineinput_leave ............................................. 258
lineinput_repeat ............................................. 259
lineMenu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 261
lineShade .................................................. 262
loadpic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 264
v
longmenu 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 265
0
menu_leave 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 276
0
menu_mult 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 278
0
modify'Axes 0 0 0 0 0 0 0 0 0 281
noinput (programmer defined) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 .. 0 0 0 0 0 282
0
openRS232 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 283
0
pieChart 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 o. 287
plot00000.00000000.000000000000000000.0000 0000.0000.00 0 0 0 289
0
rd_LotusFile 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 298
0
rxStr_Modem 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 308
0
scaleCursor 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 310
0
scaleLine 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 311
scalePlot .00000000000 0 0 00 0 000 0000000000000000 0 0 0 0 0 0 312
scalePolygon 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 313
scale_text 00000 0 .00.0 0 0 0 0 0 0000000000 00 0 0 000 0 00. 314
scale_virtual 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 315
0
vi
sector ...................................................... 318
sendBreak_RS232 ............................................ 319
setModemMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 320
setverify ................................................... 322
shiftScale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 323
status_RS232 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 324
temp_helpcontext ........................................... 326
tempstatus ................................................. 327
ticks ....................................................... 328
treemenu ................................................... 329
txCh_RS232 ................................................ 331
txStr_Modem ............................................... 332
virtual_text ................................................. 333
writescr (programmer defined) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 334
Appendix A Compiling a Project 335
Compiling Projects Provided in the Toolbox. . . . . . . . . . . . . . . . . . . .. 335
Creating Your Own Project File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 336
Glossary 337
Index 341
vii
c H A p T E R
1
Introduction
Introduction
don't need. (It's a good idea to edit a copy of the files, so that you have the
originals for later use.)
This manual assumes that you have a good working knowledge of Turbo
Prolog. If you don't, you should first work through the tutorials in the
Turbo Prolog Owner's Handbook.
Who'sWho?
In this manual, user always means the person who works with Turbo
Prolog programs and programmer refers to the person who creates the
Turbo Prolog code.
Introduction 3
The tool files on Disk 1 can be divided among four levels, each providing
tools or declarations and clauses from which higher-level tools are
constructed:
Level 1: Declaration files These files at the lowest level contain
declarations of domains used by the Toolbox predicates. For example,
TDOMS.PRO is a declaration file.
Level 2: Low-level tool files These contain several predicate definitions
that are used by the higher level tool predicates. For example,
TPREDS.PRO contains clauses for the predicates repeat, max, and min.
GRAPHICS.OBJ contains external tool predicates, provided in .OBJ-code
form because they have been implemented in C or assembler.
Level 3: Tool files These files are function specific in that each contains
either a major tool or a family of closely related tools. Thus, in order for
an application to use two tools at this level (for instance, a status line
and a menu), two tool files must be included in the application program
(in this case, STATUS.PRO and MENU. PRO). The tool files include
MENU.PRO, LONGMENU.PRO, BOXMENU.PRO, and SCRHND.PRO.
Level 4: Utility program files These include a program for defining texts
to be used when offering users context-sensitive help (HELPDEF.PRO),
a program for defining screen layouts (SCRDEF.HLP), and a parser
generator. (NOTE: The license agreement at the beginning of this
manual specifies that these program files are for your personal use
alone. You may not give away or sell them in any form.)
Introduction 5
PRO directory C:' TOOLBOX
OBI directory C:' TOOLBOX
EXE directory C:' TOOLBOX
TURBO directory C: 'PROLOG
That's it-you're set to begin programming with the Toolbox.
A Helpful Hint
Start with the simplest example in a chapter and add files to your work
disk as needed. When you've filled your development work disk, you can
select unnecessary files and delete them. That way, you can continue using
the same work disk.
As you progress, you may find it convenient to set up different
development work disks according to your areas of interest.
Reserved Windows
The Turbo Prolog tools use windows 80 to 85 inclusive. These windows can
not be used by any program that uses the tool predicates.
Introduction 7
8 Turbo Prolog Toolbox Owner's Handbook
p A R T
1
User's Guide
9
10 Turbo Prolog Toolbox Owner's Handbook
c H A p T E R
2
User Interface Tools
This chapter introduces the various tools that help you develop customized
user interfaces. It includes tools for status lines, different types of menus,
line inputs, context-sensitive Help, window resizing, and some BIOS (Basic
Input/Output System) calls. Sample programs follow each tool
description, to suggest how you can implement the tool in your program.
Status Lines
STATUS.PRO contains a set of tools that uses window number 83 (see
makewindow) to display a status line at the bottom of the screen, rather like
the Turbo Prolog editor status line, which reminds you of the action of
each function key. A status line is initially displayed via the makestatus tool
predicate, which takes the form
rnakestatus(ATTR,STRING)
ATTR is the window color attributes; STRING is the text status window.
The call
rnakestatus(112,"d=date t=time rn=rnore l=less ")
XSTATUS.PRO
90 &1
makewindow(2,7,0,"1,0,0,25,80),
makewindow(1,7,7,"1,0,0,24,80),
cursor (20, 0),
makestatus(7,"Press any key (first status line)"),
write ("A status line can be created easily with the makestatus
tool predicate."),
nl,nl,
readkey( ),
write(II*~***************************************************\n"),
write ("\nThe contents of the status line can later be changed by the") ,
write(lI\nchangestatus command"),
write(lI\n\nPress the space bar to see the effect of \n"),
write (lI\tchangestatus (\"A new status line: please press the spacebar\")\n\n"),
readkey( ),
changestatus ("A new status line: please press the spacebar"),
readkey( ),
changestatus ("A new status line"),
write(II*****************************************************\n"),
write(lI\nA status line can be removed by the rernovestatus predicate."),
write (lI\n\nPress the spacebar to see the effect of removestatus. When"),
write(lI\nyou are ready to continue, press the spacebar once again\n\n"),
readkeyU,
.Pi
pascal
lisp
ModulaZ
douin.
number list = integer*
FecI1cat
ask (numberlist, integer)
career (integer, string)
q(integer, string, stringlist)
9011
makewindow (1, 7,0, '"',0,0,25, SO),
ask([1,2,3,4],Total),career(Total,Job),
makewindow(1,7,7,"Career",20,10,5,50),
nl,write("You should be in",Job),readcharC).
ella
q(4,"If you were at a party and saw someone standing alone, would you:",
["organize lots of people to go over and talk to that person",
"go over and talk to him or her yourself",
"just smile at him or her sympathetically",
"take no notice"]).
q(3,"Which of the following activities do you most enjoy?",
[parties,"going out for a meal", sports, cinema, "flower arranging",
"reading a book"]).
q(2,"Which one of the following best describes you?",
[obstinate, determined, ambitious, considerate, thoughtful,
"couldn't care what turns up"]).
q(l,"Which one of the following best describes you?",
[wild,"very extroverted",extroverted,happy,"quiet and refined",
quiet, "very introverted", "extremely shy"]).
ask( [] ,0).
ask([X I Y],S) :-
ask(Y,T),q(X,Title,Choicelist),
menu (10, 7, 7, 7,Choicelist,Title,1,ChoiceNo),
S = T+ChoiceNo.
career (Total, advertising) :- Total<S.
career (Total, computing) :- Total>7,Total<20.
career(_,archaeology).
XLCAREER.PRO
ask( [l ,0).
ask([X I Yl,S) :- ask(Y,T),q(X,Title,Choicelist),
R = 4*(4-X), C = 7*(4-X), FATTR = 7t16*X
menu leave(R,C,7,FATTR,Choicelist,Title,1,ChoiceNo),
S = TtChoiceNo.
XIQ.PRO
90a1
makewindow(1,7,7,IIProfessor Blanketbrain's Intelligence Test",O,O,25,80),
write("\n\n\tMake any number of selections using the RETURN key. "),
write ("\n\tWhen all selections have been made, press FlO .11),
XMENU.PRO
test :-
changestatus("Use of menu mult "(F10:End CR:Select or delete
ESC:Abort")-;
menu mult (10, 10, 7,66, [first, second, third, fourth, fifth, "6", "7"],
- "test", [3,6] CHOICEL),
write("You chose: ",CHOICEL),nl,fall.
90al
makewindow (1,23, 0, "test", 0, 0, 24, 80),
makestatus(112,"Choose a number"),
test,
changestatus ("End of demo") ,n!.
FecI1cate.
test
for (INTEGER, INTEGER, INTEGER)
str (STRING)
c1au
for (X,X, ).
for(I,A,B) :- B)A,A1 = At1,for(I,A1,B).
str(first).
str( second) .
str(third).
str (S) :- for (I, 4, 50), str_int (S, I) .
test
changestatus(IILon9lllenu is used to select from more than
23 alternatives CR:Select ESC:Abort"),
fiDdal.l. (X, str (X), L),
lon9lllenu (10,10,5,7,7, L, "lon9lllenu", 0, CHOICE),
write(IILast time you chose: ",CHOICE),nl,fall.
test
changestatus (IIlon9lllenu with pre-selected starting point for the cursor
CR:Select ESC:Abort"),
fiAdall (X, str (X) , L) ,
lon9lllenu (10, 10, 5, 7,7, L, "lon9lllenu", 3, CHOICE) ,
write(IILast time you chose: ",CHOICE),nl,fall.
test
changestatus(IIUsing lon9lllenu to create an unframed menu
CR:Select ESC:Abort"),
fiAdall (X, str (X) , L) ,
lon9lllenu(10,10,5,112,0,L,"This message will not be visible",2,CHOICE),
write(IILast time you chose: ",CHOICE),nl,faU.
test
changestatus("Lon9lllenu leave: Make one selection from each menu
displayed CR:Select ESC:Abort"),
fiAdall (X, str (X) , L) ,
lon9lllenu leave(5,0,5, 7, 7,L,first,1,CHl),
lon9lllenu-leave (10,20, 5, 7,7, L, second,2,CH2),
lon9lllenu-leave (15,40, 5, 7,7, L, third,3,CH3),
removewindow, removewindow, removewindow,
write(IILast time you chose: ",CH1,", ",CH2,", ",CH3),nl,fall.
test
changestatus ("Use longmenu mult to allow any number of options
FlO : End CR: (Un) select ESC:Abort"),
pl
makewindow(1,7,O,"test",O,0,24,80),
write ("Use cursor keys to inspect the rest of the menu items\n\n"),
makestatus(112,"Choose a number"),
test,
write("End of demo").
Box Menus
With a box menu, users can select items from more than one column of
choices. The Turbo Prolog system, for example, displays a box menu
containing file names when the empty string is given as a response to the
Load option of Files. The boxmenu tool predicate is contained in the file
BOXMENU.PRO and takes theform
boxmenu (Row, Col, NoOfRows, NoOfCols, Wattr, Fattr, Stringlist, Header,
StChoice,Choicel
where
Row and Col determine the position of the window.
NoOfRows determines the number of rows in the window.
NoOfCols determines the number of columns in the window.
~ttr and Fattr determine respectively the attributes for the window
itself and for its frame-if Fattr is zero, there is no frame on the window.
Stringlist contains the list of possible selections.
, Header is the text in the top of the window.
StChoice determines where the bar should be placed when the menu is
first displayed.
Choice is bound to the selection made.
For example,
~oI/1,
boxmenu (5, 5,,\~, 7,5, [a,b,c, d,e, f,g,h, i, j,k, l,m,n], "letters", 3,CHOICE)
The only difference is that the parameter in whiC;h tbe sele.9tions made are
returned is npw a list of INTEGERs .. ~h& fh f' sJp r1/1;1(1. ' tt fNt5 a "e
r
hI,? 111/,];1 && a cuJt-ti, /It? To f/,(' I 1\ e 1 f?;-( l'Sf stLiS t Cho/c:::e I
XBOXMENU.PRO
test
changestatus ("Now choose three numbers, one from each menu"),
f1Dclal1 (X, str (X) , L) ,
boxmenu leave(0,0,10,50, 7, 7,L,
-IIThis is a demonstration of boxmenu leave",O,CHI),
boxmenu leave(4,20,10,50, 7, 7,L, -
-IIThis is a demonstration of boxmenu leave II ,0, CH2) ,
boxmenu leave(8,40,10,50, 7, 7,L, -
-IIThis is a demonstration of boxmenu leave",0,CH3),
removewindow, remove window , removewindow, -
write(IILast time you chose the numbers: ",CHI,", II,CH2,", ",CH3),
nl,f&l1.
test
changestatus ("Now choose several numbers
FIO:End CR:Select or remove"),
f1Ddall (X, str (X) , L) ,
boxmenu mult (0, 0, 18, 78, 7,7, L,
-IIThis is a demonstration of boxmenu mult",
[5,10,20],CHOICEL), -
write(IILast time you chose the numbers:",CHOICEL),nl,f&l1.
90&1
makewindow (1, 7,0,1111,0,0,25,80),
makewindow(1, 7,0, "test", 20, 0, 4, 80),
makestatus (112, "Choose a number"),
test,
write(IIEnd of demonstration"),nl,readkey(J.
A Line Menu
The tool predicate linemenu implements a menu on a single line and is
contained in the file LINEMENU.PRO. It takes the form
linemenu (Row, Attr, Attr, Stringlist, Integer)
produces a line menu rather like the top line of Turbo Prolog's pull-down
menu system.
XLiNEMNU.PRO
90 &1
makewindow(1, 7, O,"test", 0, 0,24,80),
cursor(5,O),
makestatus (112,"Choose a programming language 11),
linemenu(O, 7, 7, [IBasicl ,IFortran l ,IPascal l ,IApll,ILispl,IProlog"],CH1),
write ("Last time you chose item number ", CHl) I nI,
changestatus ("Now choose from an unframed menu") I
linemenu (0, 7, 0, [IBasicl,IFortran" I IPascall,IApll,"Lisplt ,"Prolog"], CHOICE),
changestatus (1111) I
write(ItThis time you chose item number "/CHOICE),nl,
write (ItEnd of demo lt ) ,nl, readkey(J.
Pull-down Menus
PULLDOWN.PRO contains pull-down menus that allow menu items to be
grouped into related families, as in the Turbo Prolog user interface. Once
you move the cursor to an item in the main menu line and then press
Return, another menu appears, pulled down vertically below the horizontal
. . . . . . . . . . . . . . . . . . . ._. . . . . I.
lun COIIpile
Print
rullCATIS Cop~
_ ( ..... COl.dtr.attr.stri..Li.t tri... iat lenaMe
_iaIUIOII.COL.A"I.Am.STIIIIGLIST.mlllG rile Hute
__ HSYIIIOL. 1011. mi. mlllGLIST .lOWiCOI.IIIT nodu Ie list
lleaaZ(llY. ml IIGLI ST. lOW. 1011. ROIl. SYltIOLl Zap file in editol'
I~ ~~
IIilkellla'OIoI(l. 7 .. 1.25.81). Operating s~"teoo
_ ..(5.1 7.7.I ..... ic.p.a:d.li. - . 1 ' 0 1 L - - - - - - - - - '
"'IIIic. i. !lOIlI' r.VID'ite lanluale?'.4.aIOICIJ.
CLAUSES
Me_( I0Il. COL. WAUl. rA"I. LIST .IIIAI". STAlTaIOICI. CHOICI) :-
__ iaiUIOII.COL.WAm.rml.LlST.IlIAID.IIOOrlOll.LlIU.
Sr1=st'AlrctIOICI-l.lMx( ST1.Sr2).IWC=lIOOnoY-l la(ST2.IWC.STAJrIOll).
Me_I( coat. STAII'fIOU .IM"I. LI sr .lIOOlIOII. LIII. CHOI CI).
1'_lIIIi. .OII.
where
Attribute is the color attribute to be used in all the windows (and their
frames) that are part of the pull-down menu system.
Menulist is a list constructed using the curtain functor (as described in
the following paragraphs), which contains the text for each of the menus
that can be pulled down.
On return from pulldown, Choice is bound to the code number for the
horizontal menu item on which the cursor was resting when a selection
was made.
In a pull-down menu system built using puZldown, the action taken when a
given menu item has been selected is determined by the pdwaction
predicate. This allows the program to perform commands with the pull-
down window remaining on the screen. If pdwaction fails, Choice and
SubChoice are bound to the relevant values; the entire menu system is
removed from the screen and pulldown succeeds. If, on the other hand,
pdwaction succeeds, then puZldown continues to loop and the last selected
menu item remains highlighted.
To use pulldown, you must include the database predicate pdwstate in your
program's database declarations as follows:
clataba
pdwstate (ROW, COL, SYMBOL, ROW, COL)
Menulist is specified by giving a list of values for the curtain functor. It takes
three parameters, as in
curtain (COL, STRING, STRINGLIST)
The first parameter specifies which column the horizontal menu item
should begin on, the second gives the name of that menu item, and the
third is the list of items that are to appear in the corresponding vertical
menu. Thus,
curtain (4, "Animals", ["Dog", "Cat", "Bullfinch"])
When the user makes a choice, any actions to be carried out must be
specified by a clause with the pdwaction predicate. This clause takes just two
integer parameters: The first gives the code of the horizontal (or main)
menu item, and the second specifies the corresponding vertical menu item
selected (which is zero if no vertical menu exists). Thus, if pulldown were
used with the above MENULIST and the Save option of the Files menu
were selected, then the corresponding action would be defined by
completing the right-hand side of the clause:
pdwaction(5,2) :- ........... ..
Besides pressing Return, the user can also select a given item from a pu1l-
down menu by pressing the highlighted letter of that item. pulldown
highlights the first capital letter of each menu item or, if no letters are
capitalized, the first lowercase letter.
which displays the message Please press the space bar at row 15, column 20.
The standard predicate exit then returns control to the Turbo Prolog
system.
After running this program as supplied on the Toolbox disk, you may find
it revealhlg to replace the above pdwaction clause with the following:
pdwaction(5,O) :- fa1l.
clau.e.
r Pulldown tries first to call pdwaction with the windows open.,
r If no pdwaction is found CHOICE and SUBCHOICE are returned and'
r the windows are removed.,
pdwaction(1,l) :- msg(3,10,"Input 1 selected").
pdwaction(1,2) :- msg(4,10,"Input 2 selected").
pdwaction (1,3) :- msg (5,10, "Input 3 selected").
pdwaction(2,0) :- msg(5,25,"List all").
pdwaction(3,1) :- msg(3,42,"Load something").
pdwaction(3,2) :- msg(4,42,"Save something").
pdwaction(3,3) :- msg(5,42,"Delete some garbage").
pdwaction(3,4) :- msg(6,42,"Change directory").
pdwaction(4,1) :- msg(3,45,"Actions with directories").
pdwaction(4,2) :- msg(4,45,"Change colors").
pdwaction(5,0) :- msg(15,10,"Please press the space bar."),exit.
msg(R,C,S) :-
makewindow (1, 7,7, "" ,R, C, 5, 30),
window str (S),
readkey( ),
removewindow.
r
1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
., INPUT LIST
makewindow (1, 7,0,1"1,0,0,25,80),
FILES SETUP QUIT
A SYMBOL can be up, down, left, or right to indicate which way the tree is to
be drawn when it is displayed. More details follow on the TREE definition.
The SELECTOR parameter returns a code for the menu item chosen.
In each case, the code to be returned when a certain tree item is selected is
included in the definition of that item via the tree functor. This functor takes
three arguments: The first is a S1RING giving the text for that menu item;
the second is the code to be returned if that menu item is selected; and the
third is a TREELIST specifying the rest of the tree. Thus, a TREE domain is
defined by
SELECTOR = INTEGER
TREE = tree (STRING, SELECTOR, TREELIST)
TREELIST = TREE*
XTREE.PRO
code=3000
clau
treeaction( ) :-
cursor (R, C),
menu (R, C, 7, 7, [continue, select) , test, 0, CHI ,
CH = 2.
preclicat
test
show (SYMBOL)
clau
show (DIRECTION)
treemenu(DIRECTION,tree ("start", 1,
[tree ("start problem", 2,
[tree("gasoline help", 3, [)),
tree("electrical system",4,
[tree ("battery flat", 5,
[tree ("another", 6, [) ),
tree ("recharge", 7,[)),
tree ("push start", 8, [)) J),
tree("wet weather", 9, [)))),
tree ("alternative", 10, [)))),
tree ("overheating", 11, [)),
tree ("smell", 12, [)),
tree ("vibration", 13, [)),
tree ("start last", 14,
[tree ("bad running", 15,
[tree("bad idling",16,[)),
tree ("lack_of_power", 17, [) ) ) ),
90al
repeat, test.
Prompt BeforeString
accepts input from a user and does nothing with it until he or she presses
Esc.
In order to use lineinput, lineinpuCleave, or lineinput_repeat, the following
database predicates must be declared in the containing program:
databa
insmode
lineinpstate (STRING, COL)
lineinpflag
clataba..
insmode
lineinpstate (STRING, COL)
lineinpflag
o1a
insmode.
~edicat
test
o1au
test
line input (10, 10, 45, 7,7, "Which computer do you have:", "IBM PC", TXT),
write("Resulting text input: ",TXT),nl,faU.
test
changestatus ("Modify each of the three texts, pressing CR after each"),
lineinput leave(7,10,40, 7, 7, "Text1: ","This is old text l",TXTl),
lineinput-leave(10,10,40,7,7,"Text2: ","This is old text 2",TXT2),
lineinput-Ieave(13,10,40,7,7,"Text3: ","This is old text 3",TXT3),
removewindow, removewindow, removewindow,
write("TEXTl = ",TXTl),nl,
write("TEXT2 = ",TXT2),nl,
write("TEXT3 = ",TXT3),nl,
fail.
test
write(lI\nPress the space bar for a demo of lineinputJepeat ll ) ,
readkey( ),
clearwindow,
changestatus (Illineinput repeat requests for new
lines until the ESC key is pressed."),
line input repeat (7,10,40, 7, 7,"Text: II,IIII,TXT),
shiftwindow (OLD) ,
shiftwindow(2) ,
write(ITEXT=",TXT),nl,
shiftwindow (OLD),
fail.
90al
makewindow (2, 7,0,1111,0,0,24,80),
makestatus (112, "Input some new text or modify the old text"),
test.
where
Row and Col determine the position of the input field on the screen.
l'V.zttr and Fattr are the window and frame attributes respectively.
Extension is the STRING that is to be added to the file name if no file
type is specified.
OldFileName is the file name to be displayed in the window when it is
first displayed. Users can edit this text and then press Return or FlO
once their preferred file name is in the window.
NewFileName becomes bound to the new file name with the Extension
added automatically to the user's input if no file type was specified.
A program that uses readfilename must include the file LINEINP.PRO-in
addition to TPREDS.PRO, TDOMS.PRO, and FILENAME.PRO-and
contain the following database declarations at an appropriate point:
clataba
insmode
lineinpstate (STRING, COL)
lineinpflag
XFILENAM.PRO
90al
makewindow (2, 7,7, "Instructions", 0, 0, 24, 35), disk (DIR),
nl, wri te (" 1. Set the directory\n to your TOOLS dir: \n" , DIR) , nl, nl,
makewindow(3,7,7,"Results",0,35,24,45) ,
setdir(5,5),disk(DIR),write("Directory=",DIR),nl,nl,
shiftwindow(2),
write (" Now try the following in turn: ") ,nl,
write (" ============================"), nl, nl,
write (" 2. Just press RETURN"),nl,
write (" 3. Give the file name \"test\"") ,nl,
write (" 4. Try the file name \"test.txt\""),nl,
write (" 5. Delete the old name and\n then press RETURN"),
nl, nl, nl, nl,
write (" - CTRL-BACKSPACE deletes the\n old file name"),
write("\n\n\n - Use CTRL-BREAK to stop"),
shiftwindow(3) ,
makestatus (112," Give some file names and inspect the result of
readfilename.") ,
repeat,
refreshstatus,
read filename (20, 41, 7,7, pro, "oldname. datil ,NEWNAME),
write (IFilename=",NEWNAME) ,nl,
fail.
Context-Sensitive Help
This section describes tools for the implementation of context-sensitive
Help facilities. The Help texts are placed in a single Help file by running
r-------Definition of helpfiles--------.
.--------,---I1Help text~--------,
databa
helptext (HELPCONTEXT ,ATTR, ATTR, STRING, ROW, COL, ROW, COL, FILEPOS)
helpcontext(HELPCONTEXT)
helpfile (STRING)
1Dclude "help.pro"
90al
....nl (helpfile ("xhelp.hlp")),
consult ("xhelp.def"),
push helpcontext(helpl),
help;
push helpcontext (help2),
help;
pop helpcontext,
help.
Resizing Windows
RESIZE. PRO contains the definition of the tool predicate resizewindow,
which doesn't take any parameters. The call
resizewindow
prompts the user to resize the current window. The arrow keys (and the
Control key for larger steps) are used for resizing, just as in the Turbo
Prolog system.
To move windows on most PCs, you can use the shift-arrow keys. On some
PCs, you must use number keys: press 4 to move left, 2 to move down, 6 to
move right, and 8 to move up.
XRESIZE.PRO
1Dclucle "tdoms.pro"
databa
windowsize(ROW,COL)
precl1cat
writescr
1Dclud. "tpreds. pro"
1Dclucle "status.pro"
1Dclucle "resize. pro"
clau
writescr :- keypressed,!.
writescr :-
write(IIThe resizing tool predicate allows a window to be resized\n"),
write(tlin the same way as with the Turbo Prolog system. \n\n"),
fail.
writescr :- keypressed,!.
writescr :-
attribute (112),
write (tiThe main advantage of the tool version is that
you can modify\n"),
write (tithe resize predicate to suit your own needs. \n\n"),
attribute (7)
goal
makewindow(1,7,O,"I,O,O,24,80),
makewindow(2,7,7,ltest",5,5,14,70),
resizewindow.
3
Screen-Layout Tools
The Turbo Prolog Toolbox provides tool predicates for designing and
implementing screen layouts easily. In this chapter, you'll learn how to
define a screen layout and how to edit, save, and load the definition. You'll
associate values and actions with fields-and specify no input fields. A few
sample programs follow, then more advanced techniques are discussed:
specifying new keys and screen-definition types, producing inter-
changeable screen layouts, and creating new screen definitions from old.
Finally, formatting and printing reports are explained.
If you follow through the examples and type in the instructions shown,
you'll find it easier to understand the various concepts behind screen-
layout definitions.
Many of these screen tools are not restricted to the row and column
dimensions of the PC screen; they allow you to work with a virtual screen.
So you can offer users any size of screen-though, of course, only one
monitor-sized screenful of a larger window can be viewed at a time.
Moreover, the screen-layout tools are designed so that you can work with a
PC-sized screen first, then move to virtual-screen capabilities only when it
becomes necessary: The real-screen tools and the virtual-screen tools are
entirely compatible.
Whether you're working with real screens or virtual screens, screen-layout
definitions are created by running the program in SCRDEF.PRO. These
layout definitions are then used by the screen-handling tool predicate
Screen-Layout Tools 47
scrhnd. The definition of scrhnd for real screens is contained in
SCRHND.PRO; for virtual screens, that definition is in VSCRHND.PRO.
These definitions are entirely compatible. In fact, you can use
VSCRHND.PRO even when working with real displays, although the total
program code size will be greater.
scrhnd enables you to associate actions and a value with each data field
specified in a layout definition. For example, having defined two fields in
which prices are entered, the action associated with each of these two fields
may be to pop up a menu from which items with specified prices can be
selected, and to add the price of the item chosen to a running total. This
running total can then be used to determine the value to be displayed in a
third field that is reserved for the total cost of the two items.
St~eet:
City:
State:
Zip Code: _
Supplementa~y Info~mation: _ _ __
Discount: Telephone: _ __
Screen-Layout Tools 49
position (7,22). Note that when you move the cursor from the data field just
defined, the relevant information at the top of the screen is deleted.
The remaining fields in Figure 3 are defined similarly; you should now
complete them. When you have defined all fields, press FlO. To save this
layout definition in a file, select the Save Screen Layout option from the
menu. When prompted for a file name, save this definition under the name
XMAIL.SCR.
The contents of XMAIL.SCR constitute a screen definition file. Such a file
contains clauses for three database predicates corresponding to the
following declarations:
elataba
field (FieldName, Type, Row, Column, Length)
text field (Row, Column, Length, FieldString)
windowsize(Height,Width)
The database predicate windowsize uses Height and Width to determine the
size of the window through which the user can view the real or virtual
screen. Clauses for textfield specify the text fields in the (virtual) screen
layout, with each text field specified by its position (Row,Column), the
Length of the field, and its contents (FieldString). Clauses for the database
predicate field specify the data fields: FieldName gives the name of a field,
Row and Column specify the starting position of that field within the
(virtual) screen window, Length names the length of that field, and Type
specifies which type of data this field can accept.
In this example, SCRDEF.PRO generates the following text-file description
of the screen layout (to see this description, select the Edit Screen Definition
File option of SCRDEF.PRO and enter the file XMAIL.SCR).
field (IFirstNames", str, 5, 36, 23)
field (IILastName ll , str, 7,33,26)
field ("Street", str, 9, 33, 26)
field ("City", str, 11, 33, 26)
field ("State", str, 13, 33,26)
field (IZipCode", str, 15, 33, B)
field(ISupplnfo",str,17,49,10)
field ("Discount", real, 19, 31, B)
field(ITel",str,19,50,14)
txtfield(2,22,19,"Mailing list entry:")
txtfield (3, 22,19,"*******************")
txtfield(5,22,14,"First Name(s):")
txtfield(7,22,11,"Last Name: ")
txtfield(9,22,7,IStreet:")
txtfield(1l,22,1l,"City: ")
txtfield(13,22,11,"State: ")
txtfield (15, 22, 9, "ZipCode: ")
Screen-Layout Tools 51
KeyUsedForReturn, the parameter in the third line of the example sequence,
is bound to the code for the key that terminates the screen handler. If
TopLineSwitch is bound to ON, a line is displayed at the top of the screen
giving the name of the field that currently contains the cursor. No such line
is displayed if TopLineSwitch is bound to OFF.
Suppose that the user makes the entries shown in Figure 3.3.
Street:
City:
State:
Zip Code: . .
:- . .. : ~. . t: :. ~. :1:
Discount:_._ Telephone:'
On return from scrhnd, entries are automatically made in the database for
the predicate value declared by
clataba
value (FieldName, String)
as follows:
value (IFirstNamesl,"Wilbur James")
value (ILastNamel,IThompson")
value (IStreet l ,"37 East 28th Street")
value (ICityl,"New York")
value (IStatel,"NY")
value ("Tel", "212-348-1234")
value ("ZipCode l ,"23456")
value ("Discount", "28")
XMAIL.PRO
90al
consult (lIxmail. scr"),
createwindow (on),
scrhnd (on, ),
clearwindow,
value(IFirstNames",FName),
value(ILastName",LName),
value(IStreet",Street),
value(ICity",City),
value(IState",State),
value ("Tel", Tel),
value(IZipCode",Zip),
value(IDiscount",Discount),nl,nl,TAB
write ("+---------------------------------------------- -----------------II),nl,
write (FName, II ", LName, "\n", Street, "\n", City, "\n", State, "\n") ,nl,
write(IIYour reference number will be your telephone number:",Tel),nl,
write(lIyou have been granted ",Discount,"% discount."),nl,
write("+-------------------------~-------------------------------------II~.
Facilities in SCRDEF.PRO
You can use the program SCRDEF.PRO to generate screen-layout defini-
tions along the lines of the earlier examples. When SCRDEF is executed, the
following menu appears.
Screen-Layout Tools 53
r--Scmn definition--
--Save SCl'een layout
Load meen I~out
Edit layout de inition file
You can then do one of the following: Define a screen layout, Save the
current screen-layout definition in a file, Load a previously saved screen-
layout definition, or Edit (or browse) through a file containing a screen-
layout definition. Pressing the first letter of each menu item (shown here in
boldface type) calls up that command. In the following sections, each of
these commands are described in more detail.
Screen-Layout Tools 55
Insert a line F8
To insert a blank line on the screen, press F8.
Resize the window Shift-FlO
To resize the screen-layout editor window, hold Shift down and press FlO.
A new Help line appears at the bottom of the screen that specifies which
keys may be used to resize the window (which, by default, is as large as it
can be).
Return to the main menu FlO, Esc
Press FlO or Esc.
First Number: _ _
Second Number: _
Total: _
Screen-Layout Tools 57
field (IFirstNo", real, 5,38, 9)
field (" SecondNo" , real, 7,38, 9)
field ("Total", real, 10, 38, 9)
txt field (5,23, 13, "First Number: ")
txt field (7,23,14, "Second Number: II)
txtfield (10, 30, 6, "Total: ")
windowsize(21,77)
When this screen-definition file is used in conjunction with scrhnd, the user
is presented with the specified screen layout and should type in strings
corresponding to valid real numbers for the FirstNo and SecondNo fields.
scrhnd records these values as strings in the database for the value predicate.
Thus, if the user types 23 and 76 respectively, the corresponding database
entries are
value (IFirstNo", "23")
value (ISecondNo", "76") .
. In order to associate a value with the Total field, which depends on the
FirstNo and SecondNo values entered by the user, use the tool predicate
field_value. It takes two parameters, the name of a field and the value to be
displayed in that field. Thus,
field value(ITotal",T) :-
-value(IFirstNo",N1),
str real(N1,Num1),
value (ISecondNo",N2),
str real(N2,Num2),!,
Tnum = Num1tNum2,
str_real (T, Tnum) .
defines the value to be displayed in the Total field as: the sum of FirstNo
and SecondNo, if both have been entered; the value of one, if that is all that
the user entered; or zero, if the user hasn't made any entries.
The final step is to update a copy of HNDBASIS.PRO by editing it to
include the above clauses for field_value. HNDBASIS.PRO provides the
basic framework for programs that use the screen-handling tools. It
contains all the necessary database predicate and domain definitions, and a
reminder that, in general, a program using scrhnd should define clauses for
the field_action, field_value, and noinput tool predicates.
1**********************************************************************
A minimal structure for a program that uses the screen handlers.
**********************************************************************1
1**********************************************************************
Domains
************************************************************************1
inclwle "tdoms. proll
dcuw
FNAME = SYMBOL
TYPE = int (): str (): real ()
1**********************************************************************
Database Predicates
**********************************************************************1
databa
r Database declarations used in SCRHND */
insmode r Global insertmode */
act field (FNAME) r Actual field */
screen (SYMBOL,DBASEDOM) r Saving different screens */
value (FNAME,STRING) r Value of a field */
field (FNAME, TYPE, ROW, COL, LEN) r Screen definition */
txtfield (ROW, COL, LEN, STRING)
windsize(ROW,COL).
notopline
r Database predicates used by VSCRHND */
windstart(ROW,COL)
mycursord (ROW, COL)
r Database declarations used in LlNEINP */
lineinpstate (STRING, COL)
lineinpflag
1**********************************************************************
Include tools
**********************************************************************1
inclwle "tpreds. pro II
inclwle "menu.pro"
inclwle "status.pro"
inclwle "lineinp.pro"
iDclwle II scrhnd. pro"
clau
Screen-Layout Tools 59
1***************************************************** *****************
field action
****************************************************** ****************1
1***************************************************** *****************
field value
****************************************************** ****************1
field_value (FNAME, VAL) : - value (FNAME, VAL), I
1***************************************************** *****************
noinput
****************************************************** ****************1
noinput U :- fall.
Note that the default value for a field is defined as the value the user types
by the clause
field_value (FNAME,VAL) :- value (FNAME,VAL),I.
Now, copy HNDBASIS.PRO into the editor and move your cursor to the
first line after the field_value comment line. Insert the clauses worked out a
few pages earlier for the Total field's value-all ten lines of code. Then, at
the very end of the program, type in these lines:
9'0a1
consult (" ADDERDEF . SCR") ,
createwindow(off),
scrhnd(off,_).
Fi~5t Numbe~: __
Second Numbel': _
Total: _
Screen-Layout Tools 61
Next, take MYADDER.PRO, which is actually HNDBASIS.PRO with the
following altered field_value clauses:
field value(ITotal",T) :-
-value (IFirstNo" ,Nl),
str real (Nl, Numl),
value (" SecondNo" , N2) ,
str real (N2,Num2), !,
Tnum = Numl+Num2,
str_real (T, Tnum) .
field value(ITotal",Nl)
-value(IFirstNo",Nl),!.
field_value(ITotall,IO").
field value(FNAME,VAL) :-
-value (FNAME, VAL) , ! .
Change the field action for Total from the default defined by
field_action U :- !, fail.
to
field action ("Total")
-l'etl'lct(value(IMemory", )) ,fail.
field action(ITotal") :-
-field value(ITotal",T),
....1'. (value ("Memory" , T) ) .
When Return is pressed in the Total field, therefore, the current value of
Total is asserted for Memory.
Now, change the goal so that XMADDER.SCR is consulted rather than
ADDERDEF.SCR, and you're done.
The following program, XMADDER.PRO, shows the completed code. Try
modifying it so that when Return is pressed in either FirstNo or SecondNo,
the current value of Memory becomes the value of that field (while the value
of Memory remains unaltered).
dou,in.
FNAME = SYMBOL
TYPE = int()i str()i real()
databa
r Database declarations used in SCRHND */
insmode r Global insertmode */
actfield (FNAME) r Actual field */
screen (SYMBOL, DBASEDOM) r Saving different screens */
value (FNAME,STRING) r Value of a field */
field (FNAME, TYPE, ROW, COL, LEN) r Screen definition */
txtfield(ROW,COL,LEN,STRING)
windowsize(ROW,COL).
notopline
qo.l
consult (lIxmadder.scr"),
createwindow (off) ,
makestatus (112, II Type some numbers"),
scrhnd(off,J.
cl.u
1**********************************************************************
field action
**********************************************************************1
field action("Total") :-
- r.tr.ct (value ("Memory", J), f.il.
field action(ITotal") :-
-field value("Total",T),
....rtI(value(IMemory",T)) .
Screen-Layout Tools 63
1**********************************************************************
field value
**********************************************************************1
field value("Total",T) :-
-value ("FirstNo", Nl) ,
str real (Nl, Numl) ,
value ("SecondNo" ,N2),
str real (N2,Num2),!,
Tnum = NumltNum2,
str_real(T,Tnum).
1**********************************************************************
noinput
**********************************************************************1
noinput U :- f.il.
No-Input Fields
You may have spotted one slight problem with the adding-machine-plus-
memory program: The user can type values into the Memory field.
Fortunately, any such user-initiated entry is overridden when the program
makes a proper entry in that field. Nevertheless, it's still an untidy feature.
And the same failing applies to the Total field, although the effect is less
noticeable.
Thanks to the noinput predicate, blocking users from entering text into
specific fields is easy to arrange. In this case, just specify the Memory and
Total fields as no-input fields by replacing the default defining clause for
noinput (near the end of the program) in HNDBASIS as follows:
noinput("Memory").
no input ("Total") .
Make these alterations, then verify that you can't enter information in the
Memory and Total fields.
.. .-
Figure 3.7: The XTRAVEL Screen Layout
Going from top to bottom, the useful data field names are arrivetime,
timenow, miles, and speed. There is also a field called flip, which displays a
speedometer dial (and demonstrates just how powerful the Toolbox
screen-handling facilities are).
Another useful feature is that the timenow field is continually updated, like
a real time clock. You accomplish this by defining the field value for
timenow as follows:
field value(tirnenow,TlME) :-
, -tirne(Ho,M,S,H),
T = St((HtSO) div 100),
str int(Seconds,T),std(Seconds,SecondsSt),
str-int(Minutes,M),std(Minutes,MinutesSt),
str=int(Hour,Ho),
Screen-Layout Tools 65
std(Hour,Hour5t),
concat (Hour5t, ": II ,51) ,concat (51, MinutesSt, 52) ,concat (S2, ": II ,S3),
concat(S3,SecondsSt,Time).
Here, the predicate std ensures that the time is always displayed in the
standard hh:mm:ss format. The standard predicate time accesses the system
clock.
The user can reset the clock whenever Return is pressed with the cursor in
the timenow field. Hence, a field action for timenow is defined as follows:
field action(timenow) :-
-makewindow(1, 7, 7,"5et new time",5,5,8,40),
write (IIHours: \t"), readint (H) ,nl,
write (IIMinutes: \t") ,readint (M) ,nl,
write (IISeconds: \t") ,readint (5),
time (H,M, 5, 0), fall.
field action(timenow) :-
-removewindow.
To determine the necessary speed and display it in the speed field, convert
the strings into numbers:
field value(speed,NecSpeed) :-
-field value (timenow, TimeStr),
value(arrivetime,ArriveStr),
timediff(ArriveStr,TimeStr,TimeSecs),
value(miles,Mile5tr),!,
str real (MileStr,NoOfMiles),
ReaISpeed = NoOfMiles/(TimeSecs/3600),
str_real(NecSpeed,ReaISpeed).
field value(Fn,X) :-
-value (Fn, X) , ! .
{/* Values from normal user input*/l
To complete the basic program, give it a goal and define the predicates
used to specify the field values and actions:
clcu1Da
!LIST = INTEGER*
90U
consult (lixtravel. scr"),
createwindow(off),
scrhnd(off,_).
c:1a",
str intgl(IIII,[)) :-!.
str-intgl (STR, [H I T)) :-
- fronttoken(STR,INTSTR,REST),
str int (INTSTR, H) , !,
str-intgl(REST,T).
str-intgl(STR,T) :-
fronttoken(STR, ,REST),
str_intgl(REST,T).
timesplit(TimeStr,H,M,S) :-
str intgl(Timestr,Intglist),
Intglist = [H,M,S).
timediff (TimeStrl, TimeStr2, DiffSecs)
timesplit(TimeStrl,Hl,Ml,Sl),
timesplit(TimeStr2,H2,M2,S2),
TotSecsl = Hl*3600.0tMl*60tSl,
TotSecs2 = H2*3600.0tM2*60tS2,
DiffSecs = TotSecsl-TotSecs2.
All that remains is to complete the speedometer. To do so, add the database
predicate declaration
flip (STRING)
to the existing ones. This defines a field value for the field flip as follows:
field value(flip,STR2) :- !,
-r.tract(flip(STR)),
frontchar (STR,CH,STR1),
str char(CHS,CH),
concat (STR1,CHS,STR2),
...RtI(flip(STR2)),! .
Screen-Layout Tools 67
XTRAVEL.PRO
databa
r Database declarations used in SCRHND */
insmodeT r Global insertmode */
actfield(FNAME) r Actual field */
screen (SYMBOL, DBASEDOM) r Saving different screens */
value (FNAME,STRING) r Value of a field */
field (FNAME, TYPE, ROW, COL, LEN) r Screen definition */
txt field (ROW, COL, LEN, STRING)
windowsize (ROW, COL)
notopline
flip (STRING)
p:r:.clicat
timesplit(STRING,INTEGER,INTEGER,INTEGER)
timediff (STRING, STRING, REAL)
std (STRING, STRING)
goo.l
consult("xtravel.scr"), createwindow(off), scrhnd(off,J.
clau
1**********************************************************************
field action
**********************************************************************1
field action(timenow) :-
- makewindow (1, 7,7, "Set new time II ,5,5,8,40),
write (IIHours: \t"), readint (H) ,nl,
write (IIMinutes: \t"), readint (M) ,nl,
field action(speed)
-makewindow(1, 7, 7, "ERROR Window",S,S,8,40),
write("\n\n This is not an input field"),
sound(100,300),
Readchar ( ),
removewindow.
/**********************************************************************
field value
**********************************************************************/
field value (timenow, TIME) : - !,
-time (Ho,M,S,H),
T = S+((H+SO) div 100),
str int(Seconds,T),std(Seconds,SecondsSt),
str-int (Minutes,M), std (Minutes,MinutesSt),
str-int (Hour,Ho),
std(Hour,HourSt),
concat (HourSt,":", Sl) ,concat (Sl,MinutesSt,S2), concat (S2,":", S3),
concat(S3,SecondsSt,Time).
field value(speed,NecSpeed) :- !,
-field value(timenow,TimeStr),
value(arrivetime,ArriveStr),
timediff(ArriveStr,TimeStr,TimeSecs),
value (miles,MileStr), !,
str real (MileStr,NoOfMiles),
ReaISpeed = NoOfMiles/(TimeSecs/3600),
str_real (NecSpeed, RealSpeed) .
/**********************************************************************
noinput
**********************************************************************/
no input (speed) .
noinput(timenow).
noinput (flip) .
/**********************************************************************
Intermediate predicates
**********************************************************************/
Screen-Layout Tools 69
cio.uiD.
ILIST = INTEGER*
predicate.
str_intgl (STRING, ILIST)
clau.e.
str intgl("",[ll :- !.
str-intgl(STR,[HIT]) :-
- fronttoken(STR,INTSTR,REST),
str int(INTSTR,H),!,
str-intgl(REST,T).
str-intgl(STR,T) :-
fronttoken (STR, , REST) ,
str_intgl(REST,T) .
timesplit(TimeStr,H,M,S) :-
str intgl(Timestr,Intglist),
Intglist = [H,M,S].
timediff (TimeStrl, TimeStr2,DiffSecs)
time split (TimeStrl,Hl,Ml,Sl),
timesplit(TimeStr2,H2,M2,S2),
TotSecsl = HI *3600. O+Ml *60+S1,
TotSecs2 = H2*3600+M2*60+S2,
DiffSecs = TotSecsl-TotSecs2.
std(H,HS) :- str_len(H,L),L<2, !,concat("O",H,HS).
std(H,H).
Screen-Layout Tools 71
Database of people and theil' intel'ests
***************************** ~**
Na: . . . . . . . . . . . . . .. .
Addl'ess: _ _ _ _ _ _ _ __
This program uses many of the tools introduced so far, particularly the
screen-handling facilities described in the section "Basic Use of the Screen
Handler."
XCLUB.PRO
dcu.in.
FNAME = SYMBOL
FNAMELIST = FNAME*
TYPE = intI); str(); real()
dcu.in.
r Domains for the demo */
Name, Address = STRING
Age = INTEGER
Sex = m or f
Interest = symbol
Interests = Interest*
FILE = textfile
databa
r Database declarations used in SCRHND */
insmode r Global insert mode */
act field (FNAME) r Actual field */
screen (SYMBOL, DBASEDOM) r Saving different screens */
value (FNAME, STRING) r Value of a field */
field (FNAME, TYPE,ROW, COL, LEN) r Screen definition */
txtfield(ROW,COL,LEN,STRING)
windowsize(ROW,COL).
notopline
r Database predicates used in VSCRHND */
windowstart (ROW, COL)
mycursord (ROW, COL)
r Database declarations used in L1NEINP */
lineinpstate(STRING,COL)
lineinpflag
r Local database */
person (Name,Address,Age, Sex, Interests)
iDclude "tpreds.pro"
include "menu. pro"
iDclude IIstatus.proll
include "lineinp.pro"
iDclude "filename.pro"
include II scrhnd. pro"
Screen-Layout Tools 73
predicat
r Predicates for the people demo *'
gsex (STRING, Sex)
ginterests(STRING,Interests)
gperson(Dbasedom)
wperson (Dbasedom)
listdba
wr(DBASEDOM)
process (INTEGER)
nondeterm member (INTEREST, INTERESTS)
go.l
makewindow(77,7,0,"",0,0,24,80),
makestatus (112, '"'),
consult ("xclub. scr"),
consult("xclub.dba"),
repeat,
changestatus (" Select an option."),
menu(10,25, 7, 7,
["Save new database",
"Input new person",
"Update an entry",
"Find people with your interests",
"List database" J ,
"CHOICE",
4,Ch) ,
process(CH),CH = O,!.
cl.utI
member (X, [X I J).
member (X, [_I LJ) : - member (X, L) .
process(O).
process (1) :-
changestatus ("Type in a name for the database."),
readfilename(10,10,7,7,dba,"xclub.dba",FILE),
openwrite (textfile,FILE),
writedevice(textfile),
listdba,
close file (textfile) .
process (2) :-
r.tract (value ( , )) ,f.11.
process (2) :- - -
createwindow (off) ,
changestatus ("Enter data on new person. Move cursor with arrows.
FlO :End"),
scrhnd (off,KEY) ,not (KEY=esc),
gperson(P) , RI (P) ,f.11.
process (2) :-
removewindow.
process (3) :-
r.tract (value ( , )), f.11.
process (3) :-
createwindow (off),
changestatus("To find an old record, give a name and press FlO."),
1**********************************************************************
Write and get data to and from the "value" predicate
**********************************************************************1
wperson( ) :- r.tract(value( , )),fa11.
wperson(person(Name,Address,Age,Sex,Interests))
Name = Sl, rtl(value(fl,Sl)),
Address = S2, rtl(value(f2,S2)),
str int (S3,Age) , ....rtl(value (f3,S3)),
gsex(S4,Sex),a rtl(value(f4,S4)),
ginterests (S5, Interests) ,a...rtl (value (f5, S5)) .
gperson(person(Name,Address,Age,Sex,Interests))
value(f1,Sl), Name = Sl,
value (f2, S2), Address = S2,
value(f3,S3), str int(S3,Age),
value (f4,S4), gsex (S4,Sex),
value(f5,S5), ginterests(S5,Interests),!.
1**********************************************************************
Conversions between a string and the corresponding domain
**********************************************************************1
gsex("m",m) .
gsex(IIfll,f).
Screen-Layout Tools 75
ginterests (5, [H ITJ) : - bound, (5) , !, fronttoken (S,H, 51) ,ginterests (51, T) .
ginterests (5, [HJ) : - bound. (H) , !, H = S.
ginterests (5, [H ITJ) :- bound. (H) ,
ginterests(SS,T),concat(H,",",SSS),
concat (SSS,SS,S) .
/**********************************************************************
List the database
**********************************************************************/
wr (X) : - write (X), nl.
listdba :-
person(A,B,C,D,E),
wr(person(A,B,C,D,E)),
fail.
listdba.
-
f'leans of paYlr~mt: _
aL I
ng screen ayou{
Customer Name:
Address'
Deliver:
-
Extra Warranty:
Telephone::
~ .~ike.an.d.~idie.l Price
-------
------- - Total:_
..
Amount from customer:_
.. 1-, 7. . I. m
Change:_
The program assumes that a customer can make three purchases at most;
pay by cash, check, or credit card; have the items delivered; and take out an
extra warranty agreement.
XSHOP.PRO
clOII&1D.
FNAME = SYMBOL
TYPE = int(); str(); real()
FILE = myprinter
clataba
r Database declarations used in SCRHND'
insmode r Global insertmode'
actfield(FNAME) r Actual field .,
screen (SYMBOL, DBASEDOM) r Saving different screens .,
value (FNAME, STRING) r Value of a field .,
field (FNAME, TYPE, ROW, COL, LEN) r Screen definition .,
txt field (ROW, COL, LEN, STRING)
Screen-Layout Tools 77
windowsize(ROW,COL).
notopline
r Database declarations used in VSCRHND */
windstart(ROW,COL)
mycursord (ROW, COL)
r Database declarations used in LlNEINP */
lineinpstate(STRING,COL)
lineinpflag
r SPECIFIC FOR THIS APPLICATION */
payment (STRING)
delivery
warranty
wu
payment(cash).
iDclucle "tpreds. pro"
iDclucle "menu.pro"
iDclud.e "lineinp.pro"
iDclucle II status. pro"
iDclucle II scrhnd. pro"
90 &1
consult (lIxshop. scr"),
makewindow(1,66,66,"Sal es Transaction Record",0,0,24,80),
makestatus(112,"Fill in the sales record and press FlO when finished",
0,0,25,80),
scrhnd(off,J.
~eclicat
index (INTEGER, STRINGLIST,STRING)
concatlist(STRINGLIST,STRING)
clau.
index (1, [HI ],H) :- !.
index(N,[_IT],X) :- N>l,Nl = N-l,index(Nl,T,X).
concatlist ([], 1111)
concatlist([HIT],S) :-
concatlist (T,Sl), concat (H,Sl,S)
~eclicat
nondeterm product (STRING, STRING, REAL)
claua
product ("1111", "Washing Machine",200.35).
product(12222","Dishwasher",239.67).
product("3333","Fridge and Freezer",456.78).
product("4444","Radio",456.78).
product (15555 1,ITelevision",456. 78).
clau
1***************************************************** *****************
Main routines
****************************************************** ****************1
1**********************************************************************
field action
**********************************************************************1
pr.dicate.
make (FNAME)
cl.u
field action(delivery) :- :retr.ct(delivery),!.
field-action (delivery) :- ....rtl(delivery).
field-action (warranty) :- :r.t:r.ct(warranty),!.
field-action (warranty) :- rtl(warranty).
field-action (payment) :- r.t:r.ct(payment( )),fa1l.
field-action (payment) :- -
-cursor (R, C),
LIST = [ICashl,ICheck","Credit card"],
menu(R,C,7,7,LIST,"Please select method of payment",l,PayNo),
index (Payno, LIST,STR),
rtl(payment(STR)).
field action(iteml) !,make(iteml).
field-action (item2) :- !,make(item2).
field=action(item3) :- !,make(item3).
1**********************************************************************
field value
**********************************************************************1
predicat
price (FNAME,REAL)
cl.ua
price (FNAME,PRICE)
value (FNAME, CODE), product (CODE, _, PRICE) , ! .
price C, 0) .
field value(date,DATE) :- !,
-date (D,M, Y),
str int (DS,D), str int (MS,M), str int (YS, Y),
concatlist ([DS, ": ",MS, ": ", YS] ,DATE) .
Screen-Layout Tools 79
field value (total, TotalS) I,.
-price (iteml, pl),
price (item2,P2),
price(item3,P3),
Total = PI+P2+P3,
str_real (TotalS, Total) .
field value(change,CS) :- !,
-value(money,MM),!,str real(MM,M),
price(iteml,PI), -
price{item2,P2),
price{item3,P3),
Total = M- (PI +P2+P3),
str_real{CS,Total) .
field value(iteml,CODE) !, value (iteml, CODE),
field-value (i tem2, CODE) !,value(item2,CODE),
field=value (item3,CODE) !,value(item3,CODE),
field value (makel, DESC) !, value (iteml,Code), product (Code, Desc, ),
field-value (make2, DESC) !,value(item2,Code),product(Code,Desc,-),
field=value(make3,DESC) I, value (item3,Code), product (Code,Desc, =),
field value(pricel,PRICEs) :- I,
-value(iteml,Code),product(Code,_,PRICE),I,str_real(PRICEs,PRICE).
field value{price2,PRICEs) :- I,
-value(item2,Code),product(Code, ,PRICE),!,str real(PRICEs,PRICE).
field value(price3,PRICEs) :- I, - -
-value(item3,Code),product(Code,_,PRICE),I,str_real(PRICEs,PRICE).
field_value (payment, P) : - payment (P) , !.
field value(delivery,yes) :- delivery, I.
field=value (delivery, no) : - !.
field value(warranty,yes) :- warranty, I.
field=value(warranty,no) :- I.
r Catch other values from the database *'
field_value (Fn, X) : - value (Fn, X) , I .
A Label-Printing Program
The final example in this section is a label-printing utility contained in
XLABEL.PRO. Its screen-definition file is XLABEL.SCR, which uses scrhnd
to produce the following screen.
rtve the cursor wi th the mow keyS and select by pressing RlnJRN
Figure 3.11: Label-Printing Utility Screen
Pressing Return in the Edit Label field calls the editmsg standard predicate,
so that the displayed label can be edited with the full Turbo Prolog editor.
Press FlO to terminate editing; then save the label in a disk file by pressing
Return with the cursor in the Save Label field. Retrieve a previously saved
label by pressing Return with the cursor in the Load Label field. The
Filename Label field displays the file name used for the last load or save
operation and is a no-input field. The Directory field allows a default
directory to be specified.
The Printer field specifies whether the printer is attached to PRN, COMl, or
COM2. Selecting that field produces a menu, from which one of these three
must be chosen. Once the number of labels to be printed has been set,
printing begins when the Print Labels field is selected.
However, before printing any labels, the fields on the right-hand side of the
screen must be adjusted to the desired printer characteristics. Thus, you
should do the following:
DoubleStrike (dbstrike) must be turned ON or OFF.
The number of lines to be printed per label and the desired level of
indentation must be set.
Screen-Layout Tools 81
A choice must be made between fast, medium, and letter-quality speeds
of printing and the fonts to be used at each speed (specified with printer
escape sequences) .
The appropriate Initializing and Doublestrike escape sequences must be
entered if they are different from the defaults.
(These settings work with an Epson or Epson-compatible printer.)
XLABEL.SCR
domain.
FNAME = SYMBOL
TYPE = intI); str(); real()
FILE = myprinter
databa.e
r Database declarations used in SCRHND */
insmode r Global insertmode */
act field (FNAME) r Actual field */
screen (SYMBOL, DBASEDOM) r Saving different screens */
value (FNAME, STRING) r Value of a field */
field (FNAME, TYPE, ROW, COL, LEN) r Screen definition *1
txtfield (ROW, COL, LEN, STRING)
windowsize(ROW,COL).
notopline
label (STRING)
dbstrike
font (INTEGER)
printer (STRING)
cl.u
change (value (X, )) :- r.tr.ct(value(X, )),f.i1.
change (label ( )) :- r.tr.ct(label( )),f.i1.
change(font( )) :- r.tr.ct(font( )),f.i1.
change (printer ( )) :- r.tr.ct(prInter( )),f.i1.
change(label(L8L)) :- !, rtl(label(L8L)),displbl.
change (X) :- artl(X).
displbl :-
label (L8L), !,
shiftwindow(5),
window str (L8L),
shift wIndow (1) .
filename (FILENAME) :-
value (file,FNAME),!,
cursor (ROW, COL), Rl = ROW+2,
readfilename (Rl,COL, 7, 7,lbl,FNAME,FILENAME),
change (value (file, FILENAME) )
printlabels :-
label (L8L) , str lines (L8L, LIST) ,
printer(PRINTER),
value (number,NN), str int (NN,NOOFLABELS),
openwrite(myprinter,PRINTER),
writedevice (myprinter),
setprintercodes,
Screen-Layout Tools 83
for (I, O,NOOFLABELS),
printlabel (LIST) ,
I> = NOOFLABELS-l,!,
close file (myprinter) .
printlabel(LIST) :-
value (indent, NN), str int (NN, N),
member (LINE,LIST), -
write n(N,' '),write(LlNE),nl,
fail.-
printlabel(LIST) :-
listlen (LIST, LEN),
value (labellines, TT), str int (TT, TOT) , !,
SKIP = TOT-LEN, -
write_n(SKIP,'\n').
setprintercodes :-
value (initcode, INIT),
printercode(INIT),fa11.
setprintercodes :-
dbstrike,
value (dbstrikecode,DBSTRIKE),
printercode(DBSTRIKE),fa11.
setprintercodes :-
font (N) ,str int (NO, N) ,
con cat ("font" , NO, FRONT) ,
value (FRONT,FRONTCODE),
printercode (FRONTCODE), fail.
setprintercodes.
printercode ("") : - !.
printercode(CODE) :-
frontchar(CODE,'\\',REST),
f ronttoken (RES T, NUM, RES TCODE) ,
str int (NUM, CHI) ,
char int(CH,CHI),
write (CH), !,
printercode (RESTCODE) .
printercode(CODE) :-
frontchar (CODE, CH,REST),
write (CH) ,
printercode(REST).
for(I,I, ).
for(I,A,S) :- B>A,Al = Atl,for(I,Al,B) .
write n(O, ) :- !.
write=n(N,CH) :- N>O,write(CH),Nl = N-l,write_n(Nl,CH).
str lines ('"', [J) :- !.
str-lines (STR, [H I TJ) :-
- search char (' \n' , STR, 0, N) ,
frontstr (N, STR, H, R) ,
90al
makewindow (5, 7,7, "LABEL", 15, 0, 9, 80),
Screen-Layout Tools 85
makewindow(1, 7, 7,IILabel Printing",0,0,15,BO),
makestatus (112, II Move the cursor with the arrow keys and select
by pressing RETURN"),
consult("xlabel.dba"),
displbl,
scrhnd(off,J.
scr (up) :- .
scr(esc) :- .
Defining a new special key simply involves adding values to these clauses.
For example, the + key could be given a special meaning as follows:
scr(char('+')) :- value(fl, Vall), value(f2, Va12),
str int(Vall, NumVall),
str-int(Val2, NumVal2),
NumSum = NumVall + NumVa12,
str int (Sum, NumSum),
rtl(value(total, Sum)).
When the cursor is in a field that has a .HLP file defined, pressing Fl results
in the contents of that file being displayed in the given window.
Alternatively, displayhelp can be used to make the Help messages context
sensitive (see "Context-Sensitive Help" in Chapter 2) by defining the form
ser ( fkey (1)) : -
aetfield (FieldName), displayhelp (FieldName) .
Screen-Layout Tools 87
predicate.
valid (FNAME, TYPE, STRING)
types (INTEGER, TYPE, STRING)
clau.e.
valid ( , str, ).
valid(-,int,STR) :- str int(STR, ).
valid C real,STR) :- str=real(STR,-_).
types(l,int,"integer").
types (2, real, "real") .
types(3,str,"string").
succeeds only if the EntryString that the user has inserted in FieldName has a
value of the correct FieldValueType. (You can specify more precise
validation-for example, file names entered could be checked in the
directory to confirm their existence.)
To verify entries of date type, add a clause like
valid( , date, EntryString) :-
fronttoken(EntryString, Month, Restl),
str int(Month, ),
fronttoken(RestI, ,Rest2),
fronttoken(Rest2,-Day, Rest3),
str int(Day, ),
fronttoken (Rest3, , Year)
str_int(Year, _I. -
Suppose you want to use two different screen layouts, referred to by the
SYMBOLic names screenl and screen2. The basic idea is to move from one
screen to the other by a call to shiftscreen of the form
shift screen (NewScreen)
If you have been using screenl and NewScreen is bound to screen2, scrhnd
will operate with screen2 after the call.
Screen-definition files contain facts for the database predicates textfield, field,
and windowsize. These facts are normally consulted before a call to scrhnd.
In order to use shiftscreen, store the facts for both screen definitions in a file
of facts for screen. If screenl were defined by
field("input1",str,9,27,17)
txtfield (7,27,17, "Input on screen 1")
windsize(20,77)
Screen-Layout Tools 89
The definition of shiftscreen shows how everything will work:
shiftscreen( ) :- zoRzoact(field( , , , , )),fail.
shiftscreen(-) :- zoRract(txtfield( ~ ~ ~ )),fa11.
shiftscreen n :- zoetzoact (windsize (-, -) ), lail.
shiftscreen (NAME) : - screen (NAME, TERM), a...rtl (TERM) , fail.
shiftscreen U .
As with all the Toolbox tools, you aren't limited by screen and shiftscreen.
The straightforward use of consult is a perfectly viable alternative.
clau
run :- zo.tzoact ( ), fail.
run :- consult("goods.scr"),regscreen(goods),f.il.
run :- consult (llorders. scr") ,regscreen (orders), f.il.
run :- consult (llcustomer. scr") , regscreen (customer), f.il.
run :- consult("inf.scr"),regscreen(inf),f.il.
run :- save("invoice.scr").
regscreen(NAME) :-
zo.tzoact (field (A,B,C,D,E)),
rtl (screen (NAME, field (A,B,C,D,E))), fail.
regscreen(NAME) :-
zo.tzoact(txtfield(A,B,C,D)),
artl (screen (NAME, txtfield(A,B,C,D))) ,fa11.
regscreen(NAME) :-
zo.tzo.ct(windowsize(A,B,C,D)),
a eRl (screen (NAME,windowsize (A,B,C,D))) ,f.il.
regscreen (J .
Screen-Layout Tools 91
XREPORT.PRO
cIou1D.
FNAME = SYMBOL
TYPE = int(); str(); real()
FIELD = field (STRING, COL)
FIELDLIST = FIELD*
databa.e
r Database declarations used in SCRHND ill
insmode r Global insertmode ill
act field (FNAME) r Actual field *'
screen (SYMBOL,DBASEDOM) r Saving different screens *'
value (FNAME, STRING) r Value of a field *'
field (FNAME, TYPE, ROW, COL, LEN)
txtfield (ROW, COL, LEN, STRING)
r Screen definition *'
windowsize (ROW, COL)
notopline
r Database declarations used in SCRHNO *'
windstart (ROW, COL)
rnycursord (ROW, COL)
r Database declarations used in LlNEINP *'
lineinpstate(STRING,COL)
r SPECIFIC FOR THIS APPLICATION *'
payment (STRING)
delivery
warranty
1Dclacle "tpreds. pro"
1Dclwie "report. pro"
90al
consult("xreport.scr"),
rnakewindow(1,31,O,"I,O,O,25,80),
write ("\t\tRemove the comment in the goal to send to the printer\n\n"),
r writedevice(printer). ill
report(20).
predicate.
nondeterrn product (STRING, STRING, REAL)
clau...
product(ll1l1l,"Washing Machine",200.35).
product(12222 1,IDishwasher",239.67).
product(13333 1,"Fridge and Freezer",456.78).
product(14444 1,"Radio",456.78).
product(15555 1,ITelevision",456.78).
1*******
field value
*****************
**** ************************************************ ****************1
preclicate.
price (FNAME,REAL)
claua
price (FNAME,PRICE)
value (FNAME, CODE), product (CODE, _, PRICE), ! .
price C' 0) .
field value (time, TIME) : - !,
-time (H,M,S, ),
str int(HS,H),str int(MS,M),str int(SS,S),
concatlist ([HS," :iI,MS,":" ,SS], TIME) .
field value(date,DATE) :- !,
-date (D,M, Y),
str int (DS, D) , str int (MS,M), str int (YS, Y) ,
concatlist ( [DS,": ii, MS, II: II, YS] , DATE) .
field value(total,TotalS) .,I
-price (iteml,Pl),
price (item2,P2),
price(item3,P3),
Total = PltP2tP3,
str_real(TotalS,Total).
field value(change,CS) :- !,
-value (money,MM), !, str real(MM,M),
price(iteml,Pl), -
price(item2,P2),
price(item3,P3),
Total = M-(PltP2tP3),
str_real(CS,Total).
field value(iteml,CODE) !,value(iteml,CODE),!.
field-value (item2, CODE) !,value(item2,CODE),! .
field=value (item3, CODE) !,value(item3,CODE),! .
field value(makel,DESC) - !,value(iteml,Code),product(Code,Desc, I,!.
field-value (make2, DESC) - !,value(item2,Code),product(Code,Desc,-),!.
field=value (make3, DESC) - !,value(item3,Code),product(Code,Desc,=),!.
Screen-Layout Tools 93
field value(pricel,PRICEs) :- I,
-value (iteml,Code), product (Code, _,PRICE), I, str_real (PRICEs, PRICE) .
field value(price2,PRICEs) :- I,
-value(item2,Code),product(Code, ,PRICE),I,str real(PRICEs,PRICE).
field value(price3,PRICEs) :- I, - -
-value(item3,Code),product(Code,_,PRICE),I,str_real(PRICEs,PRICE).
field_value (payment,P) :- payment(P),I.
field value(delivery,yes) :- delivery, I.
field=value(delivery,no) :- I.
field value (warranty, yes) : - warranty, I .
field=value (warranty, no) : - I.
r Catch other values from the database *'
field_value (Fn,X) :- value(Fn,X),I.
value(lname",IJ B Gruntfuttock") .
value(lstreet","3 Railway Terrace").
value(lIcityl,IISeattle").
value(lstatel,"Washington").
value ("tel", "222 333 4444").
value ("iteml", "1111") .
value(litem2 1,12222").
value (litem3", "3333") .
value(lmoney",llOOO.OO").
payment (IICheck") .
delivery.
4
Graphics Tools
Graphics Tools 95
Virtual-Screen Coordinates
Turbo Prolog's standard predicates for graphics use virtual-screen
coordinates. When the entire monitor screen is used, the virtual-screen
coordinate system refers to the upper left-hand comer as (0,0) and the
lower right-hand corner as (31999,31999). These coordinates are
automatically scaled down to the actual pixel (picture element) positions on
the monitor, whether the graphics card driving it provides 320 X 200, 640 X
200, or 640 X 350 pixels.
All the following standard predicates in Turbo Prolog take virtual-screen
coordinates as parameters:
line (Rowl, columnl, Row2, Column2, Color)
dot (Row, Column, Color)
penpos (Row, Column, Direction)
forward (Step)
back (Step)
If, for example, the Turbo Prolog standard predicate dot is called, as in
dot(16000,16000,1)
which uses the entire screen for graphics display, a colored dot appears at
the center of the screen.
When the graphics standard predicates are used in a window, virtual
coordinates within that window are relative to the upper left-hand corner
of the window. This corner is regarded as coordinate position (0,0). If, for
example, an unframed window is created with 12 rows and 80 columns, the
upper left-hand corner of the window is at (0,0) and the lower right-hand
corner is at [(32000X12/25)-1,31999]; that is, (15359,31999).
plots a pixel, a dot inside a box frame, a filled-in box, or the letter X at the
virtual point (Vrow,Vcol). It plots the element in the named Color, with the
given Shape according to the value to which Shape is bound:
o One pixel is drawn.
1 A dot is drawn inside a box.
2 A box is drawn and filled.
3 The letter X is drawn.
The range for Vrow, Vcol, and Vsize is 0 to 31999 in each case.
with Rowl, Row2, Coil, and Col2 in the range 0 to 31999, draws a box
according to the value to which Fill is bound:
o A box is drawn with color LineColor but not filled.
1 A box is drawn with color LineColor and filled with the
color FillColor.
Graphics Tools 97
The Predicate ellipse
draws an ellipse, provided that the following are true: Row, Column, and
VerticalRadius are in the range 0 to 31999; Ratio is a real number between 0
and 1 representing the ratio of the horizontal radius of the ellipse to its
vertical radius. If Fill is bound to 0, an ellipse is drawn but not filled in; if
Fill is 1, then an ellipse is drawn and filled.
Row and Column should be bound to values in the range 0 to 31999 and
Increment bound to an angle in the range 0 to 360 degrees. sector draws that
sector of a circle centered on (Row,Col) with radius Radius occupying the
angle between StartAng and EndAng-specified in degrees. A horizontal
radius from the center of the circle pointing toward the right-hand side of
the display screen denotes zero degrees. The sector is drawn in the given
Color and is filled if Fill is 1 and not filled if Fill is O. If it is filled, then
Increment specifies the size of the angle used to fill the sector. The specified
triangle is drawn in these increments.
draws a line between the points (Rowl,Col1) and (Row2,Col2), and shades
an area on one side of the line. The shading is toward the top of the screen,
toward the bottom, or toward the left or right side of the screen depending
on the value of the Direction parameter:
o Shadeup
1 Shadedown
2 Shadeleft
3 Shade right
The shading covers the area from the beginning line to the line indicated by
the EndLine parameter. When shading is toward the left or right of the
/ screen, Endline is the column number-from the Toolbox domain
VCOL-specifying a vertical line at which shading stops.
When shading up or down, Endline is represented by a VROW value.
Coercion between the domains VROW and VCOL is necessary (look at
lineShade's declaration). This is done by a code fragment of the form
. . . CoerceVariable = VROWvalue, lineshade( . . . . . . . . ,CoerceVariable, .. ),
Rowl, Row2, Coll, Col2, and EndLine must all be in the range 0 to 31999. The
coding for Direction is as follows:
o Shade up to the row specified by EndLine
1 Shade down to the row specified by EndLine
2 Shade left to the column specified by EndLine
3 Shade right to the column specified by EndLine
Graphics Tools 99
In all cases, coerce the value of Endline to a value in the VeOL domain.
XGEOMTR.PRO
project "xgeometr"
,.
iDclwle "tdoms.pro"
iDclude "gdoms. pro"
clataba
news line (string)
Fedicat
message (string, string, string, string, string)
wfs(char)
wait (integer)
pl
graphics(l,l,l),
makewindow(l, 6, 6, "Geometric shapes", 0, 0, 18, 40),
makewindow(3,7,0,"",18,0,6,40),
makewindow(4, 8, 0, "SPACE BAR MESSAGE" ,24,5,1,20),
claue.
newsline(IIPress the space bar to continue. ") .
message(S1,S2,S3,S4,S5) :-
shiftwindow(Old),shiftwindow(3),
clearwindow,
attribute (1), write (Sl, "\n"),
attribute(2),write(S2,I\n"),
attribute (3) ,write (S3, "\n"),
attribute (1) ,write (S4, "\n"),
attribute(2),write(S5,I\n"),
shiftwindow(Old).
wfs(C) :-
shiftwindow (4) ,
attribute (2),
newsline(S),field str(0,0,20,S),
keypressed,readchar(C),!,
field str(0,O,20," 1I),shiftwindow(3).
wfs(C) :- wait(2000),
:retract (newsline (String)), !,
frontstr (1, String, F, Rest),
concat (Rest, F, New) ,
a e:rtl(newsline(New)),
wfs(C).
The call
scalecursor (23, 51)
places the cursor (that is, starts the text) at the scaled coordinate position
(23,51).
scalePlot is a tool predicate contained in GGRAPH.PRO and plots points
when scaled graphics are used. Its declaration takes the form
scalePlot(X,Y,COLOR)
plots a point at position (100,200) according to the scale currently active and
in color 3.
Another tool predicate, scaleLine, plots lines in scaled graphics. Its
declaration takes the form
scaleLine (X, Y, x, Y, COLOR)
(Xl,Y1) is the starting point of the line, (X2,Y2) is the end point of the line,
and Color determines the color of the line.
A more complicated image in a scaled display can be represented as a list
of points belonging to the domain DRAWING, which is defined in
GOOMS.PRO as
dcu.iD.
DRAWING = POINT*
POINT = p (X, Y)
X,Y = REAL
The points specified by the DRAWING are plotted and connected to form a
polygon in the specified COLOR. For example,
scalePolygon (3, [p(3, 1), p (5, 3), p (3,5), p(1, 3)])
draws a diamond shape on the screen, scaled to fit the currently active
scale.
The tool predicate draw is used to draw a scaled polygon belonging to the
domain DRAWINGS. An object from the domain DRAWINGS is a list of
colored polygons in which the functor d binds a color to a DRAWING,
which is itself a polygon:
X,Y = REAL
POINT = p (X, Y)
DRAWING = POINT*
D = d(COLOR,DRAWING)
DRAWINGS = D*
For example,
draw([d(2,[p(70,100),p(90,195),p(100,230)]),
produces a triangle.
In the entry
axisPair(AxesPairNo,AxesWindowNo,GraphWindowNo,
Xmarkers, Ymarkers, Left, Bottom, Right, Top)
AxesPairNo is the number of the scaled coordinate system used when you
need to refer to these axes again, and they are drawn in window number
AxesWindowNo.
When axes are defined using makeAxes, the first step on execution of the
makeAxes call is drawing the axes in the currently active window. A new
window is then created inside that active window so that subsequent
images in the coordinate system are automatically clipped if the image
being drawn exceeds the ranges for the currently active scale. The number
of this window is returned in Graph WindowNo. Left, Right, Bottom, and Top
specify the number of character positions that are to be left between the
edges of this window and the border of the screen.
The markings on the axes are defined by two markers of the form
marker (Unit, Formatspecifier, FieldWidth)
This scale is subsequently referred to as scale number 1. Then the axes are
defined with AxisPairNo set to 1, and the corresponding internal window is
also given the window number 1:
shiftwindow (1) ,
makeAxes (1, _,Gwindow,marker (10, d, 2) ,marker (10, d, 3) ,2,3,2,1)
(It is only for convenience that the corresponding window, scale, and axis
pairs have the same reference number in this example.)
The demo also illustrates how to modify axes so they can reflect changes in
the scales. This facility is used in the program to implement zooming
capabilities and the like.
XGRAPH.PRO
code=3000
include "tdoms. pro"
include "gdoms. pro"
databa.e
Scale(ScaleNo,x,x,y,y)
activeScale(ScaleNo)
axes (integer, integer, integer, xmarker, ymarker, col, row, col, row)
newsline (string) r Used by this demo only */
include "gglobs.pro"
include "tpreds. pro"
include "gpreds. pro"
include "ggraph.pro"
predicate.
element (string, drawing)
process (char)
zoom(x,x,y,y)
message (string, string, string, string, string)
wfs(char)
wait (integer)
function (x)
message(IIThe first graph is used for coordinates, which",
lion the X axis run from to 100 and on the Y axis",
"run from -100 to +100. This is accomplished by",
"defining a 'scale'. In this way the graph is",
"automatically scaled to fit the actual window. ",
"\tdefineScale (l, 0, 100, -100, 100) "),
defineScale (l, 0, 100, -100, 100),
wfs( ),
message ("Now we can draw axes in the actual window",
"corresponding to that scale: II ,
1111 ,
"\tmakeAxes (l,Ano, Gno,marker (l0, d,2) ,marker (10,d, 3),1,1,1,1) ",
1111 ,
1111) ,
shiftwindow(l),
removewindow,
makewindow(l,ll,O,"Graph 1",0,36,lB,44),
shiftwindow(GWindow),
function (0) ,
wfs( ),
message (IINormal text can be written in the graph area. ",
.11.
lI\tshiftwindow(Gno), cursor (0, 0), write (\"F (X) = 100*cos (6. 2S*X/50) \"l, ",
1111 ,
1111),
shiftwindow(GWindow),
cursor (0, 0), write ("F (X) = 100*cos (6. 2S*X/50) "),
wfse),
cl.a
element (carbody ,
[p(70,100),p(90,195),p(190,205),p(240,300),
p(400,300),p(450,205),p(500,205),p(500,100),p(70,100))).
element (frontwindow,
[p(243,290),p(320,290),p(320,210),p(200,210),p(243,290I)).
element (frontdoor,
[p(200,205),p(200,105),p(320,105),p(320,205),p(200,205I)).
element (rearwindow,
[p(330,290),p(398,290),p(438,210),p(330,210),p(330,290Ill.
element (light, [p(85, 165), p(93, 165), p(98, 196))) .
process('+') :- zoom(O,-100,O,-60).
process('-') :- zoom(O,100,O,60).
r Big*'
r Sman,
process('l') :- zoom(50,50,O,O). r Left'
process('r') :- zoom(-50,-50,O,O). r Right*'
process('u') :- zoom(O,O,-50,-50). r Up'
process('d') :- zoom(O,O,50,50). r Down'
process('w') :- zoom(O,-50,O,O). r Wide'
process('t') :- zoom(O,O,O,-50). r TaU'
process('<')
activescale(N), !,
scale(N,X1,X2, , ),!,
L = X2-X1,H = X1=X2,
zoom(L,H,O,O).
process('>') :-
activescale(N),!,
scale(N, I ,Y1,Y2),!,
L = Y2-yI,H = Yl-Y2,
zoom(O,O,L,H) .
zoom(Dxl,Dxh,Dyl,Dyh) :-
acti vescale (N) , !,
scale (N,Xmin,Xmax, Ymin, Ymax) , !,
NewXl = Xmin+Dxl,
NewYl = Ymin+Dyl,
NewXh = Xmax+Dxh,
NewYh = Ymax+Dyh,
NewXl <>NewXh,
NewYl<>NewYh,!,
J:.tJ:lct(scale(N"" )),!,
J:tI(scale(N,NewXI,NewXh,NewYl,NewYh)).
message(S1,S2,S3,S4,S5):-
shiftwindow (Old) , shift window (3) ,
clearwindow,write(S1,"\n",S2,"\n",S3,"\n",S4,"\n",S5),shiftwindow(Old).
SeHing a Scale
The Toolbox predicate find Scale evaluates an image, then automatically
defines an appropriate scale so that the image fits into a given window. A
call takes the following form:
findScale (ScaleNo, Drawing, Xfactor, Yfactor)
Xfactor indicates the amount of stretch (if any) you desire in the X direction
when the images specified for this scale are represented on screen; Yfactor is
the amount of stretch in the Y direction. Hence, the following call defines a
scale that is twice as big on the X axis as the original DRAWING and is 1.3
times as big on the Y Axis. The identification number of the scale defined is
returned in the parameter ScaleNo:
setscale(ScaleNo, [p(l,1),p(9,1),p(9,9),p(1,9)), 2, 1.3)
gives the virtual coordinates for the character in the lower right-hand
comer of the entire screen; that is, (30720,31600). This enables the use of
virtual coordinates based upon text coordinates but with their origin still at
(0,0).
GPREDS.PRO also contains the tool predicate that is called in the form
gwrite(Row,Col,String,Color,Direction)
Pie Charts
This section requires the file GPIE.PRO. Pie charts graphically show the
percentages or parts that make up a whole "pie." The Toolbox provides the
tool predicate pieChart, which draws a pie chart corresponding to the given
input parameters, namely:
pieChart(vrow,vcol,vradius, pieSegmentList)
vrow and veol the coordinates for the center of the pie
vradius the radius of the pie
pieSegmentList[Sliee(PereentageValue,label,fill,frame),Sliee( .. .)]
a list of the "slices," each specified with:
percentage value: A negative percentage causes the slice
to stick out from the rest of the pie.
optional label: If the label ends with an = character, the
label is suffixed with the actual corresponding
percentage value.
pieChart draws using virtual coordinates, that is, the center (specified as
(Row,Column and the Radius are given in scaled coordinates. If the
percentages given do not add up to 100 percent, pieChart scales up the slices
specified so that they occupy the whole pie. This also allows the pie chart to
be drawn in windows of different sizes.
The definition of pieChart is in the file GPIE.PRO. It can be modified
and/ or expanded. For example, you can make the slice labels look
different. The pie slices are drawn by calling the external predicate sector,
which you met in an earlier section and which is implemented in C. Thus,
programs that use pie charts need to be compiled and linked as projects.
XPIE.PRO
project "xpie"
iDcl.ucle "tdoms. pro"
iDcl._ IIgdoms. pro"
databa.e
news line (string)
include "gglobs.pro"
iDcl.ucle "tpreds. pro"
incl_ "gpreds.pro"
iDcl._ "gpie. pro"
predicate.
message (string, string, string, string, string)
wfs(char)
wait (integer)
shiftwindow (1),
gwrite(O, 5, "SALES: THE FIRST SIX MONTHS IN 1987",3,0),
gwrite(5,0,IEVALUATION:",1,0),
gwrite (6, 0, "------------", 1, 0),
gwrite(8,0,"\219 = good",3,0),
gwrite(10,0,"\219 = average",2,0),
gwrite(12,0,"\219 = bad",I,O),
gwri te (14, 0, "------------" ,1, 0) ,
wfs( ),
message(IIIf certain slices need special",
"attention, they can be moved outward",
"and their labels suffixxed with",
"a percentage.",
1111),
shiftwindow(I),
clearwindow,
pieChart (11000, 19000, 6000,
[slice (10.6, IIJanuaryll, 1,2),
slice(-20.7,"February=",2,3),
slice (15 .1, "March", 3, 2),
slice(-23.5, "April=", 1,3),
slice(5,IJune",2,1),
slice (17, II July" ,3,2) 1),
gwrite (0, 5, "SALES: THE FIRST SIX MONTHS IN 1987",3,0),
gwrite (4, 0, "EVALUATION: ",3,0),
gwrite(6,0,"------------1,1,0),
gwrite(8, 0, "\219 = good",3,0),
gwrite(10,0,"\219 = average",2,0),
gwrite(12,0,"\219 = bad",I,O),
gwrite (14, 0, "------------",1,0),
wfs( ),
message ("Two small pie charts can be ",
"used for comparing different periods. ",
1111
,
shiftwindow (1) ,
gwrite(O,O,"SALES: JANUARY 1986 - MARCH 1987",1,0),
gwrite(3,0,"The two best months:",l,O),
gwrite(5,5,"JuI86 \219",7,0),
gwrite(7,5,"Oct86 \219",10,0),
cl.us
message (SI, S2,S3,S4, S5)
shiftwindow (Old), shiftwindow (3),
clearwindow,
attribute (1) ,write(Sl,"\n") ,
attribute (2) ,write (S2, "\n") ,
attribute (1) ,write (S3, "\n") ,
attribute (2), write (S4, "\n") ,
attribute (1), write (S5, "\n") ,
shiftwindow (Old) .
wfs(C) :-
shiftwindow (4), clearwindow,
attribute (1),
newsline(S),field str(0,0,20,S),
keypressed, readchar(C) , !, shiftwindow(3) .
EVALUATION:
= good
11111111 :::: "~Lq,pe:Ii!"',agE!'
= bad
Bar Charts
This section uses the file GBAR.PRO. Bar charts are another way of
representing sets of numerical data. You generate a bar chart by calling one
of these tool predicates:
bargraph (Left, Bottom, Right, Top, BarRatio, Barlist,Factor )
bargraph3d (Left, Bottom, Right, Top, BarRatio, Theta,Barlis t,Factor)
Either predicate can generate colored bar charts; the bargraph3d bar chart
resembles three-dimensional boxes. The position of the bar chart relative to
the borders of the currently active window is specified on a character basis
by the four parameters Left, Bottom, Right, and Top.
For a three-dimensional bar chart, the viewing angle is passed as an angle
measured in radians. The parameter BarRatio specifies the width of the
bars relative to the spacing between the bars. A spacing of 0.5 indicates that
the bars have the same width as the gaps between them.
The list of bars belongs to the domain
XBAR.PRO
project "xbar"
include "tdorns. pro"
include "gdorns. pro"
include "gglobs. pro"
include "tpreds.pro"
include "gpreds. pro"
include "gbar. pro"
goal
Theta = 0.3,
GraphlRatio = 0.5,
graphics (1, 1, 1),
gwrite(O,12,"3-D BAR CHART.",3,O),
gwrite(I,12,"--------------",2,O),
gwrite(2,1,"SALES IN BILLION $",1,1),
gwrite(24,O,"Resolution: 320x200 pixels in 4 colors",I,O),
BarGraph3D (3, 4, 4, 4, Theta, GraphlRatio,
[bar(2,"",1,2),
bar(3,"1984",1,3),
bar(5,"",1,2),
space,
bar (4, 1111,1,2),
bar(7,"1985",1,3),
bar (7,1111 ,1,2) ,
space,
bar (4, 1111,1,2),
bar(7,"1986",1,3),
3-D BAR-CHART.
S
A
L
E
S
I 7 7 77
N
B 5
I
L
L
I 2:
o
N
:$
The choices of Palette have meaning only in eGA graphics mode 1 (see the
Turbo Prolog Owner's Handbook).
The EGA adapter supports a palette with programmable colors. Two tool
predicates may be used to manipulate these:
setEGApalette (ColorList)
setEGAregister (Register, Color)
They are found in the file GEGA.PRO, and the following example
demonstrates how they work.
XEGA.PRO
douiDa
FILE = data file
databa
color (integer, integer)
actualcolor (integer)
pr.dicate.
test (integer)
choice (key)
changecolor (integer)
shiftcolor (color)
getColorList (integer list)
showfield (integer)
loop
ella
r Default settings of the EGA palette registers
color(O,O) .
*'
color(1,1) .
color(2,2).
color(3,3).
color (4,4) .
color(5,5) .
color(6,6)
color (7, 7)
color(8,56).
color(9,57).
color (10, 58) .
color (11, 59) .
color (12, 60)
color (13, 61) .
color(14,62) .
color (15, 63) .
color(16,0) .
test(17) :- !.
test (N) :-
str int (S,N) ,
concat(IIColor ",S,Sn),
FieldRow = Nt3,N = N,
gwrite(FieldRow,20,Sn,N ,0),
N1 = Nt 1, -
test(N1).
choice (up) :- !,
shiftcolor(-1).
choice (down) :- !,
shiftcolor (1) .
choice (left) :- !,
changecolor(-1) .
choice (right) :- !,
changecolor(1).
choice(char('s')) :-!,
getColorList(L),
openwrite(datafile,"color.def"),
writedevice(datafile),
write(L) ,
close file (datafile),
writedevice(screen).
choice ( ) :-
beep.
90al
graphics(S,l,l),
gwrite(O,lS,IfDEFINITION OF THE 17 EGA-PALETTE REGISTERSIf,l,O),
gwrite(2,20, If Register (0-16)",1,0),
gwrite(2,40,IfColor code (0-63)",1,0),
rtl(actualcolor(l)),
getcolorlist(L),
setEGApalette(L),
test (1),
gwrite (3,20, "Background",l, 0),
gwrite (19, 20, "Border lf ,1,0),
cursor;(21,2),
attribute (1) ,write (If Use "), attribute (lS), write ("\24"),
attribute (1), write (If or If), attribute (lS), write (1\2S"),
in which all the parameters are bound, loads a full screen graphics image
from the file determined by Filename. For the purpose of addressing various
portions of this image, it is regarded as occupying 200 rows, numbered 0
through 199, and 320 columns, numbered 0 through 319. StartRowPicFile
and StartColPicFile specify the top left-hand comer of the sub-image to be
selected from the full screen image. NoOfRows and NoOfCols complete the
specification of this sub-image. StartRowScreen and StartColScreen specify
XPICDEMO.PRO
project "xpicdemo"
include "tdoms.pro"
include "gglobs. pro"
include "tpreds.pro"
iDclude IImenu.pro"
predicate.
picture (STRING)
90a1
picture (X),
graphics (1, 1,2),
loadpic(X,0,0,0,0,199,319),readchar( ),
graphics (1, 1,3),
write("\nPIC 1: Whole screen"),readchar( ),
loadpic(X,O,O, 0,0,199,319),readchar( ),clearwindow,
write("\nPIC 2: Upper Left-Hand Corner 1I),readchar( ),
loadpic (X, 0, 0, 0, 0,100,160) , readchar ( ), clearwindow-;
write("\nPIC 3: Bottom Left-Hand Corner 1I),readchar( ),
loadpic(X,100,0, 100,0,100,160),readchar( ),clearwindow,
write("\nPIC 4: Bottom Right-Hand Corner "),readchar( ),
loadpic(X,100,160,100,160,100,160),readchar( ),clearwIndow,
write ("\nPIC 5: Upper Right-Hand Corner "), readchar ( ),
loadpic(X,0,160, 0,160,100,160),readchar( ),clearwindow,
write("\nPIC 6: Top Left Corner = ==> Bottom Right Corner 1I),readchar( ),
loadpic(X,0,0,100,160,100,160),readchar( ),clearwindow,
write("\nPIC 7: Middle ===> Upper Left-Hand Corner 1I),readchar( ),
loadpic(X,50,80, 0,0,100,160),readchar( ),clearwindow,fail. -
'clau.e. -
picture ("Welcome.pic") .
picture (IITest.pic fl )
stores the currently selected graphics screen image in the file specified by
Filename.
indicates that the top left-hand comer of the letter p begins at row 84,
column 94 of the full-screen image.
getnewpositions controls how letters you type are displayed on the screen.
findpicture helps to take special care of the Space bar and Return, both of
which affect the positioning of letters on the display screen but do not
produce images on a slide.
project "xslides"
90al
makewindow(11,7,0,"",0,0,25,80),
repeat, text,
menu(10,10,64,23, ["Make some slides","See the slide show","Exit"],
"Choose an option",1,Choice),
decide (Choice), text,
fail.
clau
decide(1)
graphics(1,1,2) ,
attribute (2),
mydisplay(O,O,O).
decide (2) :-
slide( ,B),graphics(1,1,2),
loadpic(B, 0, 0, 0,0,199,319),
readchar ( ),
clearwindow,
fail.
decide(3) :- exit.
mydisplay(Row,Col,Slideno)
readchar (X) ,X<>' \027' ,
findpicture(X,Row,Col,NewX,NewY,Slideno,NewSlideno),
mydisplay(NewX,NewY,NewSlideno) .
findpicture('\27',_,_,_,_,_,_) :- !,fail.
findpicture('t', , ,0,0,Slideno,NewSlideno) .,
I
5
Communication with Remote Serial
Devices
This chapter explains the communication tool predicates that the Toolbox
offers. The first section deals with general serial communications, followed
by several sample programs-including a subset of the popular XMODEM
file-transfer protocol. Next, modem communication is discussed, along
with the tools provided for this by the Toolbox. Finally, a complete menu-
driven serial communications program is shown.
Before going on, note that you should be familiar with serial
communications in general and the IBM-PC communication hardware in
particular, especially the Asynchronous Adapter. More details can be found
in the IBM-PC technical reference manual. Similarly, if you intend to use
the communication tool predicates to communicate via a modem, study the
owner's manual that comes with your modem.
Hardware Considerations
When connecting a PC to a remote device, you must determine whether
each device is configured as DTE (Data Terminal Equipment) or DCE (Data
Communications Equipment). Since the IBM PC (and most IBM PC-
compatibles) emulates DTE, it is only necessary to determine what signals
the remote device emulates. This information can usually be found in the
manual for that device. Once you've determined this, you can decide
which of the following pinouts is required.
The following list shows commonly used communications terms and their
meanings:
The following pinout can generally be used when connecting two Pcs
together directly (hard-wired). A cable with this configuration is known as
a null modem cable.
mMPC RS232 ADAPTER REMOTE DEVICE
TX Pin 2 > Pin 3 RX
RX Pin 3 > Pin 2 TX
DSR Pin 6 > Pin 20 DTR
Ground Pin 7 > Pin 7Ground
DTR Pin 20 > Pin 6 DSR
In addition, to implement the RTS/CTS (Request To Send/Clear To Send)
handshaking protocol, the following connections must be made:
RTS Pin 4 > Pin 5 CTS
CTS Pin 5 > Pin 4 RTS
all the parameters must be bound and the following values filled in.
initializes the COMI port for printing using an HP LaserJet printer with
input and output buffers of 256 bytes.
A call
closeRS232 (PortNo)
in which PortNo is bound to the code for an opened I/O port (PortNo=l
means COM1, PortNo=2 means COM2) binds Status to the bit mask value
representing the current transmission status as shown:
Thus, the predicate check_status is defined by the following and can be used
to display transmission status messages:
transmits the character CH to the output buffer for port number PortNo,
where PortNo=l means the COMl serial communication port and PortNo=2
means the COM2 serial communication port.
To monitor the transmission state after a character has been transmitted,
use the predicate send_ch, defined as follows:
send chICH) :- txCh RS232(1,CH),!.
send-ch ( ) :- write (IIError sending character II),
- status RS232(1,Status),
write("Status code=",Status).
binds CH to the next available character (if any) from the input buffer for
port number PortNo, where PortNo=l means the COMl communication
port and PortNo=2 means the COM2 communication port.
rxch_RS232 fails if the input buffer is empty or the specified port is not
open. If anything goes wrong, you can obtain more information about the
current transmission state by calling the status_RS232 tool predicate as
described earlier.
with PortNo bound to the code for a serial I/O port (PortNo=l means
COMl, PortNo=2 means COM2), SizeOfInputQueue and SizeOjOutputQueue
become bound, respectively, to the number of characters in the input and
output queues. queuesize_RS232 fails if the specified COM port is not open.
Thus, the clause tesCqueue defined by
test queue :- queuesize RS232(1,SizeI,SizeO),
- write(IINo of characters in input queue: ",SizeI),
write("No of characters in output queue: ",SizeO).
with PortNo bound to the code for an I/O port, deletes the contents of the
output buffer for that port.
with PortNo bound to the code for an I/O port, deletes the contents of the
input buffer for that port. The call
delInBuf_ RS232 (1)
with TimelnHu nd red ths OfSec bound to 50, for example, suspends the
current program for half a second.
project "xprinter"
domain.
FILE = sp
include "comglobs.pro"
predicate.
run
process until eof
openfile(file~string)
transmit (char)
trans ch delay (char, integer)
wait_untIl_ernpty_output_buffer(integer)
90a1
run.
clau
run :-
PortNo = 1, r COM1 */
InputBufSize = 1, r Size of input buffer */
OutputBufSize = 4000, r Size of output buffer */
BaudRate = 7, r 9600 bits per second */
Parity = 0, r No parity */
WordLength = 3, r Eight data bits */
StopBits = 0, r One stop bits */
Protocol = 2, r XON/XOFF can not be used */
openRS232(PortNo, InputBufSize, OutputBufSize, BaudRate,
Parity, WordLength, StopBits, Protocol),
openfile(sp,IDATA.TRS"),!,
process until eof, closefile (sp),
write(lI\nPrint succeeded"),
wait until empty output buffer (lOa),
closeRS232(1). - -
run : - closeRS232 (1) .
/**********************************************************************
Open a file for reading - if possible
**********************************************************************1
open file (Sp, FileName) :- openread(Sp,FileName),!, readdevice(Sp).
openfile(_,FileNarne) :- write(lI\nlmpossible to open ",FileName),fail.
1**********************************************************************
Read a character from the current readdevice,
convert it to uppercase and print it.
Continue this process until eef or a "Ume out" event.
**********************************************************************1
process until eof :-
eof(sp)~transrnit(/\OI2/),!. r Send Form Feed */
Terminal Emulation
In this section, you'll see how to construct a terminal-emulation program
using the tool predicates in the sample file XTERM.PRO. The program
allows your PC to act as a terminal when connected either to another PC
(via the COMl ports of each machine) or to a larger mini- or mainframe
computer.
Some of the serial communications tool predicates are used to define a
predicate terminal that allows interrupt-based transmission and reception.
Everything received from COMl is shown in the Receive window, and
characters typed at the keyboard are transmitted through COMl and
echoed to the Transmit window. This process continues until Escape (ASCII
code 27) is pressed, and the program terminates.
XTERM.PRO
project "xterm"
include "tdoms. pro"
include "comglobs.pro"
include "tpreds. pro"
Clod
run.
clau
run :-
makewindow(2, 42,36," Transmit window", 0,0,12,80),
makewindow(3, 63,5," Receive window", 12,0,12,80),
PortNo = 1, r COM1 */
InputBufSize = 1, r Size of input buffer */
OutputBufSize = 1, r Size of output buffer */
BaudRate = 7, r 9600 bits per second */
Parity = 0, r No parity */
WordLength = 3, r Eight data bits */
StopBits = 0, r One stop bits */
Protocol = 0, r Fully asynchronous */
openRS232 (PortNo, InputBufSize, OutputBufSize, BaudRate,
Parity, WordLength, StopBits, Protocol),
terminal, !, closeRS232 (1) .
run :- cioseRS232 (1) .
/**********************************************************************
TERMINAL MODE
Transmission without time out
**********************************************************************/
terminal chk_rdch, chk_wrch,terrninal.
chk rdch rdch_CRLF_RS232 (CH), !,gotowindow(3), write (CH) .
chk-rdch.
chk wrch :-
- gotowindow(2), cursor (R, C), cursor (R,C) ,not (keypressed), ! .
chk_wrch :- readchar(CH),CH<>'\027', wrch_CRLF(CH).
rdch_CRLF_RS232 (CH) :- rxch_RS232(1,CH), CH<>'\013'.
wrch CRLF('\013') :- !,nl, trans ch('\013'), trans_ch('\010').
wrch=CRLF(CH) :- write(CH), trans_ch(CH).
trans ch (CH) : - txCh RS232 (1, CH), !.
trans=ch(CH) :- trans_chICH).
XPOLLlNG.PRO
Project "xpolling"
1Dclude "tdoms. pro"
1Dclude "tpreds. pro"
include "menu. pro"
include "comglobs.pro"
predicate.
send str (STRING)
send-ch CRLF(CHAR,INTEGER)
send-ch(CHAR, INTEGER)
receIve str ()
receive- ch (CHAR, INTEGER)
wait ok(INTEGER,INTEGER,INTEGER)
wr status (INTEGER)
check_status (INTEGER, INTEGER, STRING)
90al
openRS232 (1,256,256,7,0,3,0,2),
send str(IIHello, all our readers\n"),
closeRS232(1).
clau.e.
r Transmit a string *'
send str("") :- !.
send-str(S) :- frontchar(S,CH,S2),
- write(CH), send ch CRLF(CH,50),
send_str(S2). - -
send ch CRLF('\lO' ,I) :- !,send ch('\13' ,I), send_ch('\lO' ,I).
send=ch=CRLF(CH,I) :- send_ch(CH,I).
send chICH, ) :- wrch RS232(1,CH),!.
send-chICH,!) :- status RS232(1,Status), !,
- wait_ok(Status,I,!2), send_ch(CH,I2).
r Time out*/
wait ok( ,1,12) :- I > 0,12 = 1-1,ticks(10),!.
wait=ok(Status,_,50) :- wr_status(Status).
r De-mask status value */
wr status(O) :- !.
wr-status(Status) :-
- shiftwindow (WD), shiftwindow (1) ,
check status(Status,1, "Input Characters have been lost"),
check-status (Status,2, "Parity Error"),
check-status (Status,4, "Overrun detected"),
check-status (Status, B, "Framing error detected"),
check-status (Status, 16, "Break signal detected"),
check-status(Status,32, "An XOFF has been received"),
check-status(Status,64, "An XON has been received"),
check-status (Status,12B,"An XOFF has been transmitted"),
check-status(Status,256,"An XON has been transmitted"),
check-status(Status,512,"Input buffer empty when attempt to read"),
check-status (Status, 1024, "Output buffer full when attempt to write"),
write(lI\nPress SPACE to continue or ESC to abort"), readchar (Ch),
shiftwindow(2), shiftwindow(3),
shiftwindow(WD),CH<>'\27' .
check status(Status,BitMask,Mess) :-
-bitand(Status,BitMask,V), V<>O, !, nl, write(Mess).
check_status(_,_,_).
XXMODEM.PRO
project "xxmodem"
domain.
FILE = sp;dp
databa.e
last char(Char)
retrans_coun (Integer)
iDcl.ude "tdoms. pro"
include "comglobs. pro"
iDcl.ucie "tpreds.pro"
include "menu. pro"
domain.
Package = package(char,char,dataL)
DataL = chart
predicate.
run
mkList(O, []) :- !.
mkList(I,['\026'IT]) :- 12 = 1-1, mkList(I2,T).
write list([]) :- !.
write=list([HIT]) :- write(H), write_list(T).
1**********************************************************************
Transmit a package
**********************************************************************1
send_Package (package (PNO,CPNO,DataLII :- headline(PNOI,
r Send SOH'
txCh RS232 (1,' \001'),
mess(IISend SOH",' '), ticks(201, delInbuf_RS232(11,
send_Package(package(PNO,CPNO,dataL
1**********************************************************************
Retransmission predicates used by send_Package
**********************************************************************1
reset retransmit counter :- DOt(retrans count II, I.
reset=retransmit=counter :- r.tract(retrans_coun(_, I.
Modem Communication
This section explains how to use the modem-related tools to send a break
signal, set the modem mode, send commands, and send and receive
information.
XCOMMU.PRO
1***********************************************************************
Complete serial communications package
***********************************************************************1
nobreak
project "xcommu"
domain.
FILE = sf; df
predicate.
decide (integer)
r Miscellaneous */
mess (string)
rdch keyb(char)
get_FileName (string, string)
goal
makewindow(l, 23,130," Message window ", 4,35,8,45),
makewindow(2, 42,36," Transmit window ", 3,0,10,80),
makewindow(3, 63,S," Receive window ",13,0,10,80),
makewindow(6, 10,7," Configuration ",0,0,3,80),
rtl(editbuf("")),
rt. (port (1, "COMMU")),
rt.(port(2,IMODEM")),
repeat,
port(ComPort,"COMMU"),
port (ModPort, "MODEM") ,
shiftwindow(6), clearwindow,
write(1I The communication port is COMI,ComPort,", The modem is COM",ModPort),
decide (1) :-
mess ("0pen RS232 failed").
r Terminal Mode */
decide (5) :-
shiftwindow(2), write(lI\nTerminal Mode, Press Esc to abort\n"),
interactive com.
r Quit*/
decide(17) :-
closeRS232(1),f.1l. r Close COM1 */
decide (17) :-
closeRS232 (2) ,fail. r Close COM2 */
decide (17) :- exit.
1**********************************************************************
Polled transmission with time out
**********************************************************************1
r Transmit a string */
send str ('11', ) : - !.
send-str(S,PortNo) :-
- frontchar(S,CH,S2),
write(CH), send ch CRLF(CH,50,PortNo),
send_str(S2,PortNo).
send ch CRLF('\10',I,PortNo) :-
- !-;-send ch('\13',I,PortNo), send ch('\lO',I,PortNo).
send_ch_CRLF1cH,I,PortNo) :- send_ch(CH,I,PortNo).
send chICH, ,PortNo) :- txCh RS232(PortNo,CH),!.
send-ch(CH,l,PortNo):- -
- status RS232(PortNo,Status), !,
wait_ok(Status,I,I2), send_ch(CH,I2,PortNo).
r Receive a string and copy it to a file */
receive str(PortNo) :-
receive ch (CH,50,PortNo), !, write (CH),
writedevice(FP), writedevice(df), write(CH), writedevice(FP),
/**********************************************************************
TERMINAL MODE
Interrupt-based transmission without time out
**********************************************************************/
r Terminal Mode */
interactive com chk_rdch, chk_wrch, interactive_com.
chk rdch' :-
port(PortNo,ICOMMU"),
/**********************************************************************
TERMINAL MODE - MODEM COMMUNICATION
Interrupt-based transmission without time out
**********************************************************************/
interactive_modem() :- chk_rdmodem, chk_wrmodem,interactive_modem.
chk wrmodem : - shiftwindow (2), cursor (R, C), cursor (R, C), not (keypressed) , ! .
chk=wrmodem :- readln(L), upper_lower(L,L2), chk_modem(L,L2).
1**********************************************************************
MODEM SUPPORT PREDICATES
**********************************************************************/
init modem line :-
- shiftwindow (OldWD), 1* Old window */
trans modem("Z ",2,1,10), r Reset the modem to initial state */
trans- modem("C1", 2, 1, 10), 1* Set carrier high */
shiftwindow(OldWd) .
1***************************************************** *****************
Miscellaneous
**********************************************************************}
mess (Str) :-
shiftwindow(WD), shiftwindow(1),
write("\n\n",Str),
write ("\nPress Space to continue"), readchar (J,
shiftwindow (2), shift window (3) ,
shift window (WD) .
r Read char from keyboard and transform CR to LF */
rdch keyb(CH) :- readchar(CH), CH<>'\013',!.
rdch=keyb('\010'). rCH ='\010',*/
6
Importing Data from Other Systems
Together, a record list from the domain REFLEXRECL and the list of field
names from the domain FLDNAMES form a complete data structure
describing a Reflex database.
The sample Reflex me, XREFLEX.RXD, is a personnel database constructed
so that Reflex displays its structure as shown in the following Reflex Field
& Sort Settings tool:
Name Text 2 a
with all parameters except the last being input parameters, obtained from
the call to Init_Reflex. The following example shows how to access the
The two last literals (makewindow and Zist_Recs) are not necessary, but they
display the contents of the Reflex file in a readable manner.
The following example shows you how to use Init_Reflex and Rd_ReflexRec
to read a Reflex file record by record:
OneByOne :-
openread(fp,IIXreflex.rxd"), readdevice(fp),
filemode (fp, 0),
r Build data structure */
Init Reflex(TotRecs,FldNames,TypeL,TextPools),
makewindow(85,72,33,11 Reflex(tm) Sequential Access ",
0,40,25,40),
XREFLEX.PRO
project "xreflex"
cIouiu
FILETAB = fp
global predicate.
real_ints (REAL, INTEGER, INTEGER, INTEGER, INTEGER) - (o,i,i,i,i) language c
iDclacle "readext. pro"
iDclu.cle "reflex.pro"
predicat
r List data records *'
list Recs (FldNames, ReflexRecL)
list-rec (FldNames, ReflexRec)
list-elem(ReflexElem)
PressAKey
doPrompt
el.a
list Recs( , []) :- !.
list-Recs(FldNames,[ReflexRecIReflexRecs))
- nl,nl,
list rec (FldNames, ReflexRec),
PressAKey,
list_Recs (FldNames, ReflexRecs) .
list rec ( [ ) , [)) : - !.
list-rec([FldNameIFldNames),[ElemIElems))
- writef("\n%-20: ",FldName),
list elem (Elem) ,
list=rec(FldNames,Elems) .
list elem(untyped) :- write ("Untyped") .
list=elem(text(Str)) :- write(Str).
Using the tool predicate Rd_dBase3File, the dBASE III data records can be
read and collected in a list belonging to the tool domain DBASE3RECL,
which has the following declaration:
DBASE3RECL = DBASE3REC* r The database is a list of records */
DBASE3REC = DBASE3ELEM* r Fields in each record */
DBASE3ELEM = char (STRING): r Characters */
real (REAL) : r 64-bit IEEE floating-point */
logical (BOOL) : r Logical */
memo (STRING) : r Memo text loaded from a .DBT file */
date (STRING) r Format YYYY MM DO */
BOOL = CHAR r Y y N n T t F f or Space */
The record list from the domain DBASE3RECL and the list of field names
from the domain FLDNAMEL make up a complete data structure
describing a dBASE III (vl.1) database file.
The Toolbox file XDBASE3.DBF is a dBASE III file containing personnel
data organized as follows:
Name Char/String 25
Birth....Date Date 8
Age Numeric 2
Memo Memo
The example below shows how to use this predicate to access the dBASE III
file XDBASE3.DBF and the memo file XDBASE3.DBT.
AccessAll(DbaseRecs) :-
openread (fp, "xdbase3. dbf"), filemode (fp, 0), readdevice (fp),
openread (mfp, "xdbase3 . dbt ") , filemode (mfp, 0) ,
r Build data structure */
Init_Dbase3(TotRecs,FldNameL,FldDescL),
r Read all data records */
rd_dBase3File(TotRecs,mfp,FldDescL,RecL),
r List all records */
makewindow(85,41,36," dBASE III(tm) All Data Records ",0,0,25,40),
list_recL(FldNameL,RecL), DoPrompt.
The two last literals (makewindow and lis CRees) are not necessary, but they
display the contents of the dBASE III file in a readable manner.
XDBASE3.PRO
project "xdbase3"
domain.
FILE = fp ; mfp
global predicat
real_ints(REAL,INTEGER,INTEGER,INTEGER,INTEGER) - (o,i,i,i,i) language c
include "readext. pro"
include "dbase3.pro"
predicate.
r Listing of the database *1
list reel (FldNameL, dBase3Reel)
list-rec(FldNameL,dBase3Rec)
list-elem(dBase3Elem)
NoofNL (Integer)
PressAKey
doPrompt
clau.e.
1*** ***** ************ ********* *** ********** *********************** ** ***
List Data from .DBF & .DBT
**** ***************** *** ** ** ** *** *** ******* *** ********** ** ************I
list recL( ,[]) :- !.
list-recL(FldNameL, [RecIRecL]) :-
- nl,nl,
list ree (FldNameL, Ree), PressAkey,
list=reeL(FldNarneL,ReeL) .
list ree ( [], []) : - !.
list-ree([FldNarneIFldNames], [ElemIElems])
- writef("\n%-12: ",FldName),
list elem (Elem) ,
list=ree(FldNames,Elems) .
list elem(ehar(Str)) :- write (Str) .
list=elem(real(Real)) :- write(Real).
LOTUSRECL = LOTUSREC*
LOTUSREC = version (INTEGER) ; r Version number */
elem(INTEGER, INTEGER, VALUE);
2 Diff 123.654
2 3
then the corresponding Turbo Prolog data structure would have the form
LotusRecL = [version(1029), r Symphony 1.0 */
elem(O, 0, int (2) ), r row 1, column A */
elem(O, l,label (IIDiff")), r row 1, column B */
elem(0,2,real (123.654)), r row 1, column C */
elem(l, 0, int (3) ) 1 r row 2, column A */
Since a Lotus file can be accessed in two different ways (either by reading
all cells in a single operation or by searching for a specific cell), let's deal
with the two methods separately. In both cases, however, as with Reflex
and dBASE III databases, there's no need to carry out any initialization. The
tool predicates that handle Lotus files automatically create the necessary
data structures.
The following example shows how to read all the cells from the
spreadsheet stored in the file XLOTUS. WRK on your Toolbox disk.
ReadAllCells(RecL) :-
openread (fp, "XLOTUS .wrk"), readdevice (fp), filemode (fp, 0),
r Ustcells */
makewindow(85,26,36," Lotus 1-2-3 & Symphony (tm) ",0,0,25,80),
list_recs(O,RecL).
The following program fragment shows how to search for a cell located at
row 3 in the file XLOTUS.WRK:
SearchRec :-
openread (fp, "Demo. wrk"), readdevice (fp), filemode (fp, 0),
This fragment along with the previous one, are in XLOTUS.PRO, whose
listing follows.
XLOTUS.PRO
project "xlotus"
clcu.1Da
FILE = fp
iDcl.ude "readext.pro"
iDcl.ude "lotus. pro"
predicate.
list Rees(Integer,LotusReeL)
list-Ree(Integer,Integer,LotusRee)
wr Version(Integer)
wr-elem(Value)
NoofNL(Integer)
PressAKey
doPrompt
c1aue.
list Rees( , []) :- !.
list-Rees (CurRow, [Ree IReeL] )
- list ree(CurRow,CurRow2,Ree),
PressAKey,
list_ Rees (CurRow2, ReeL) .
list ree(CurRow,CurRow,elem(CurRow,Col,Int))
- eursor(Row,J, Col2 = Col*8, eursor(Row,CoI2), wr_elem(Int).
list ree(CurRow,Row,elem(Row,Col,Int)) :- !,
- NL = Row-CurRow,
NoofNL(NL), Col2 = Col*8,
eursor(Row2,_), eursor(Row2,CoI2), wr_elem(Int).
list ree(CurRow,CurRow,version(V)) :-
- write(lI\t\tVersion: "),wr_Version(V).
wr elem(int(I)) :- writef(II\8",I).
wr-elem(real(I)) :- writef(I\8",I).
wr=elem(label(S)) :- writef(II\8",S).
doPrompt :-
makewindow(Nr,Att, , IMinR,MinC/NoofR,NoofC),
MinR2 = MinRtNoofR=r; MinC2 = MinCtNoofC/3t 1,
str len(1I Press a key",Len), Len2 = Len+1, bitxor(Att,8,Att2),
makewindow(Nr / Att2,0,"II,MinR2 / MinC2,1,Len2),
write (" Press a key"),
readdeviee (FP), readdeviee (keyboard), readehar U, readdeviee (FP) ,
removewindow.
7
The Parser Generator
This chapter demonstrates how to use the Toolbox's parser generator to
take a grammar specified by you and automatically create a parser for that
grammar. The chapter is organized in five main parts.
The first part is an overview of parsers, parser generators, and how they
work. It is intended to introduce the topic to those with limited knowledge
of parsers. The second part discusses how to define a grammar that
conforms to the Toolbox's requirements. The third section gives two
complete examples of input to and output from the parser generator, along
with examples of associated scanners. The fourth section describes how to
compile and use the Toolbox parser genera tor, and the final section
discusses how to recreate it using "bootstrapping."
1. Asks the scanner (commonly referred to as the lexical analyzer) for the
next token in the input source.
2. Checks that the token is part of the legal pattern specified by the
language's grammar; that is, error checking.
3. Imposes on the token, in relation to previous and/or succeeding
tokens, a structure that can be used by subsequent phases of the
compiler, interpreter, or other program.
The scanner can also attach some attributes to each token. For example, the
tokens X and Y in the above Pascal statement can be assigned an attribute
to indicate that they are identifiers.
The grammar
<SENTENCE> ::= <SUBJECT> likes <OBJECT>
does <SUBJECT> like <OBJECT>
<SUBJECT> ::= john I mary
<OBJECT> ::= <ADJECTIVE> <NOUN>
<ADJECTIVE> ::= big I medium I small
<NOUN> ::= books I cars
if a > 0 then
a = 0;
After describing the grammar using standard BNF notation, we'll convert it
to the format required by the Toolbox.
A valid program in this programming language consists of a series of
statements or sentences. These sentences may contain while statements,
if.. then .. else .. statements, write statements, and assignments. In the while,
if, and assignment statements, expressions are used. These can contain
addition, multiplication, exponentiation and relational operators, function
calls, and variables and constants.
To define this language by a suitable grammar, first state that the language
is a sequence of zero or more statements, each terminated by a semicolon:
<LANGUAGE> :: = { <STATEMENT>; I
where
<RELOP> :: = > 1 < 1 = 1 <= 1 >=
<IDENTIFIER> :: = <LETTER> { <LETTER> 1 <DIGIT> 1*
<STRING> :: = " { <LETTER> }* "
<INTEGER> ::= <DIGIT> ( <DIGIT> 1*
<LETTER> ::= AIBICIDIEIFIGIHI I IJIKI LIMINIOIPIQIRIS ITIUIVIWIXIYIZ 1
alblcidielflglhliljlkillminiolplqlrlsitlulvlwixlylzi
<DIGIT> ::= 0111213141516171819
Note that there are several deficiencies in the above grammar. Most
notably, there are no provisions for a signed integer and no characters like
punctuations and so forth in strings. Also note that the above grammar is
described using BNF notation. It does not conform to the rules that were
described in the last section. The following is the Toolbox version of the
grammar and can be given directly to the Toolbox parser generator:
productiona
EXP = EXP plus EXP -> plus(EXP,EXP),
EXP minus EXP -> minus (EXP, EXP)
EXP mult EXP -> mult(EXP,EXP),
EXP div EXP -> div(EXP,EXP)
rightassoc EXP power EXP -> power (EXP, EXP)
There were two primary changes made in converting the grammar above
from straight BNF to the Toolbox's format. First, cosmetic changes were
needed to remove the < and> surrounding non-terminals and change ::= to
=. Then, the grammar had to show how a Turbo Prolog term should be
associated with each defining production in the source language grammar.
Notice that if represented as a scanner token is if_ and that write becomes
write_. This is a useful habit to adopt to avoid confusion between Turbo
Prolog keywords and scanner tokens. Likewise, the tokenized forms of (
and) are lpar and rpar respectively. Also, integer values in the source text
are given in terms of the functor int( .. ) and identifiers in terms of id( ..).
Two complete examples of how the Toolbox parser generator works are
provided in the next section of this chapter. After studying these complete
examples, input the grammar given above to the parser generator, develop
an appropriate scanner for the grammar and test the system with the above
statements as input.
As mentioned previously, some terminal symbols carry an attribute along
with them. For example, the terminal <IDENTIFIER> carries the name of
the identifier and the terminal <INTEGER> carries the value of the integer.
There are many issues connected with such a grammar, including:
Precedence: Addition and multiplication are normally given different
priorities so that multiplication binds tighter than addition. For
example, when evaluating the expression 2 + 3 ,. 4, the result of 3 ,. 4 is
normally evaluated first. Priorities like this are normally reflected in the
grammar.
Associativity: In an expression like 2 + 3 + 4, the addition opera tor is
usually assumed to be left associative. The operation 2 + 3 is carried out
first and not 3 + 4. In the expression 2A 3A 4, the operation 3 A 4 should be
carried out first.
or as
1f a tba ( 1 b theA sentI) .le. sent2
In the Toolbox parser generator, these problems have been resolved by the
putting the following constraints on how the source-language grammar
should be specified:
Precedence: Productions for one production name should be separated
into groups having the same priority. Thus, plus (+) and minus (-)
should share the same group; multiplication (X) and division (I) should
belong to another.
Associativity: Operators are, by default, left associative. If they are right
associative like the exponentiation operator, they must be preceded by
the Toolbox keyword rightassoc.
Ambiguity: In considering the order of the productions, the parser
chooses productions appearing earlier in the production list in
preference to those appearing later. In the example above, according to
the grammar specified, the if statement with the else clause comes
before the if statement without an else. Therefore, the second of the two
interpretations above will be the one the parser chooses. In other words,
the order in which productions are defined in the grammar dictates the
priority by which the production rules are used.
you should require the generated parser to output the Prolog term:
1fthenebe(less(id("A"),int(0)),becomes(id("B"),int(4)),
becomes (id ("B") ,mult (int (3), id ("A"))))
Rather than do this for every possible sentence of the source language, base
the specification of your requirements on the grammar of the source
language. Suppose that you wish to generate a parser for (arithmetic)
expressions that satisfy the following grammar (note that the description of
this grammar conforms closely to the Toolbox's grammar specification
rules):
EXPRESSION = EXPRESSION plus EXPRESSION
id(STRING)
int (INTEGER)
This says that an EXPRESSION can take one of seven different forms, with
five of the forms containing sub-expressions. Thus, each of the following is
a sentence in the above grammar:
id(IAMOUNT")
int (456)
int(23) mult id(ICOST")
id(IJANSALES") plus id("FEBSALES") minus id("ADCOSTS")
id(M) mult id(C) power int(2)
Notice that the grammar is given in a form that uses language elements as
they would appear when output from the scanner. In particular, identifiers
and integer values have to be attached to the functors id and into The two
minus signs (-) separate defining productions for the graIIUnPr that have
the same priority, and the keyword rightassoc indicates a production that is
right associative.
productiOll8
EXP = EXP plus EXP -> plus (EXP ,EXP),
EXP minus EXP -> minus (EXP ,EXP)
EXP mult EXP -> mult(EXP,EXP),
EXP div EXP -> div(EXP,EXP)
rightassoc EXP power EXP -> power (EXP, EXP)
id (STRING) -> id (STRING),
int (INTEGER) -> int (INTEGER)
XPARS.DOM
1******************************************************************
Domain definitions
******************************************************************/
dOlU.1Da
EXP = plus (EXP,EXP) ;
minus (EXP ,EXP) ;
mult(EXP,EXP) ;
TOK = plus 0 ;
minus ();
mult 0 ;
divO;
power ();
id (STRING) ;
int (INTEGER);
niH
XPARS.SCA
pr.dicat
tokl(string,tokl)
maketok(string,tok, string, string)
str_ tok (string, tok)
c1au
tokl(STR, [t(TOK,O) ITOKL])
fronttoken (STR, STRTOK, STR1) , ! ,
maketok(STRTOK,TOK,STR1,STR2),
tokl(STR2,TOKL) .
tokl(_,[]) .
str tok("+",plus) :- !.
str-tok{"-",minus) :- !.
str-tok("*",mult) :- !.
str-tok ("1", div) :- !.
st(tok(""",power) :- !.
Notice that the tokenized forms of ( and ) are lpar and rpar, respectively.
This is a useful habit to adopt in order to avoid confusion between Turbo
Prolog keywords and scanner tokens. Also, integer values in the source text
are given in terms of the functor int( .. ) and identifiers in terms of id( .. ).
XPARS.PAR
/******************************************************************
Parsing predicates
******************************************************************/
pr.dicat
s exp(TOKL,TOKL,EXP)
s-expl (TOKL, TOKL,EXP)
s-exp5(TOKL,TOKL,EXP,EXP)
s-exp2(TOKL,TOKL,EXP)
s-exp6(TOKL,TOKL,EXP,EXP)
s- exp3 (TOKL, TOKL, EXP)
s- exp 7 (TOKL, TOKL, EXP , EXP)
( exp4 (TOKL, TOKL, EXP)
claua
s exp(LLl,LLO,EXP) :-
- s_expl(LLl,LLO,EXP).
s exp2(LL1,LLO,EXP ) :-
- s exp3(LLl,LL2,EXP),
s=exp6(LL2,LLO,EXP,EXP_).
s exp4([t(id(STRING), ) ILL),LL,id(STRING)) :- !.
s-exp4([t(int(INTEGER), ) ILL),LL,int(INTEGER)) !.
s=exp4 (LL,_,_) :- syntax_error (exp4,LL) ,f&11.
s exp5([t(plus, ) ILL1),LLO,EXP,EXP ) :- !,
- s exp2(LLI,LL2,EXP1), -
s-exp5 (LL2, LLO, plus (EXP ,EXP1) ,EXP ).
s exp5([t(minus, ) ILL1),LLO,EXP,EXP )
- s exp2(LL1~LL2,EXP1), -
:= !,
s- exp5 (LL2,LLO,minus (EXP,EXP1) ,EXP ).
s_exp5 (LL, LL, EXP, EXP) . -
s exp6([t(mult, ) ILL1),LLO,EXP,EXP ) :- !,
- s exp3(LLI,LL2,EXP1), -
s-exp6(LL2,LLO,mult(EXP,EXP1),EXP ).
s exp6([t(div, ) ILL1),LLO,EXP,EXP ) :- T,
- s exp3(LL1,LL2,EXP1), -
s-exp6(LL2,LLO,div(EXP,EXP1),EXP ).
s_exp6(LL,LL,EXP,EXP). -
XPARS.PRO
Try running the program and giving it the same goal previously given to
the scanner:
90-1: tokl(11/A+34*2",Tok_list).
Now take the output generated by the scanner <the tokenized version of the
original source string> and give it directly to the parser:
goal: s exp([t (int (1),0), t (div10), t (id ("A"), 0),
t (plus, 0), t (int (34),0), t (mult, 0), t (int (2),0) 1, _,EXP) .
Here the scanner has been told to tokenize the input string and then pass it
on to the parser. The solution is, therefore, a combination of the solutions to
the previous examples:
EXP = plus (div (int (1), id ("A") ) ,mult (int (34), int (2) ) )
1 Solution
Error Handling
The input for the Toolbox parser generator described in Table 7.1 is fairly
typical, except for coping with the complications of error trapping.
If there are type errors in the source-language input to the generated parser,
or if one of the variables referred to does not have a value, you can set up
the generated parser to point to the offending token in the source text. For
this purpose, it is possible to obtain the source-text cursor position of each
of the <source-language grammar) terminal symbols by appending
:CURSOR to the relevant scanner token. For example,
LABEL = id(STRING) : CURSOR -> id(STRING,CURSOR)
Notice that domains to the left and right of the ~ should also agree here.
Suppose your source language comprises only H..then.. else .. statements, in
which the logical expression can consist only of integer values and the <
sign. Suppose also that only assignment statements can follow the then and
else parts. Then the input to the parser generator could take the form
SENTENCE = if EXP theD ASSIGNMENT .1 ASSIGNMENT ->
iftheoela. (EXP , ASS IGNMENT, ASSI GNMENT)
EXP = int (INTEGER) lessthan int (INTEGER) -> logical (INTEGER, INTEGER)
assuming that the tokenized forms of = and < are equal and lessthan,
respectively.
Now, let's change this so that the parser generator produces code to keep
track of the cursor position for the identifier involved:
Let's give a specification that allows you to keep track of the cursor:
FUNCDEF = id(STRING):CURSOR lpar id(STRING):CURSOR rpar equal EXP ->
function (STRING, CURSOR, STRING, CURSOR)
production.
EXP = EXP plus EXP -> plus(EXP,EXP),
EXP minus EXP -> minus (EXP ,EXP)
EXP mult EXP -> mult(EXP,EXP),
EXP div EXP -> div(EXP,EXP)
rightassoc EXP power EXP
-> power(EXP,EXP),
EXP exclmmark -> factorial (EXP) ,
EXP questionmark EXP colon EXP
-> conditional(EXP,EXP,EXP)
id(STRING) lpar PARMLIST rpar
-> call(PROCID,PARMLIST),
id(STRING) -> var (STRING) ,
minus EXP -> neg(EXP),
int(INTEGER) -> int (INTEGER),
real (REAL) -> real (REAL) ,
str (STRING) -> str (STRING),
SENT = if EXP thID SENT el.e SENT -> iftheDelae (EXP, SENT, SENT),
if- EXP tbeD SENT -> iftha(EXP, SENT),
wbIle EXP do SENT -> wbile(EXP,SENT),
toto int (INTEGER) -> goto line(INTEGER),
toto id(STRING) -> goto=lbl (STRING)
Now, put the file XMINIGOL.GRM through the parser generator to create
the files XMINlGOL.OOM and XMINIGOL.PAR.
cIou1Da
EXP = plus(EXP,EXP);
minus(EXP,EXP);
mult(EXP,EXP);
div(EXP ,EXP);
power(EXP,EXP);
factorial(EXP);
conditional (EXP ,EXP ,EXP);
call (PROCID,PARMLIST);
var (STRING) ;
neg (EXP) ;
int ( INTEGER) ;
real (REAL) ;
str (STRING) ;
char (CHAR)
PARMLIST = EXP*
The Scanner
It's easier to try out the parser once you've implemented a scanner for
Minigol. What you need is a program that examines a Minigol source text
and tokenizes it into the tokens given in XMINIGOL.OOM.
The file XMINIGOL.SCA contains such a program, although five lines have
been commented out so that it can be incorporated into the larger program
in the next section. If you wish to run the scanner in standalone mode, it is
necessary to uncomment these five lines.
XMINIGOL.SCA
douin.
r CURSOR = integer */
r PROCID = STRING */
CURSORTOK = t(TOK,CURSOR)
TOKL = CURSORTOK*
r Include "XMINIGOLDOM" */
predicat
r scan_error(STRING,CURSOR) */
tokl(CURSOR,STRING,TOKL)
maketok (CURSOR, STRING, TOK, STRING, STRING, CURSOR)
str tok(STRING,TOK)
scan str(CURSOR,STRING,STRING,STRING)
search_ch(CHAR,STRING, INTEGER, INTEGER)
c1auae.
skipspaces(STR,STR2,NOOFSP)
frontchar (STR, CH, STRl), isspace (CH), !,
skipspaces(STRl,STR2,Nl),
NOOFSP = Nl +1.
skipspaces (STR,STR, 0)
isspace(' ').
isspace('\t').
isspace (' \n') .
str tok(I/,I/,comma) :- !.
str-tok(I/+",plus) :- !.
str-tok("-",minus) :- !.
str-tok(I/*I/,mult) :- !.
str-tok (1//", div) :- !.
str-tok(I/"",power) :- !.
str-tok(I/?I/,questionmark) !.
str-tok(I/: 1/, colon) :- !.
str-tok("!I/,exclmmark) :- !.
str-tok("(",lpar) :- !.
str-tok(")",rpar) :- !.
str-tok(llf",if) :- !.
str-tok("tha",tha) !.
str-tok("e1ae",el. ) !.
str-tok(lwh11e",while) :- !.
str-tok("clo",do) :- !.
str=tok("goto",90tO) :- I.
If you remove the comments and run the scanner with the goal
90&1: tokl(O,"if a+2*f(7) tha qoto labell
el whil. bool qoto 7", Tok_list)
the result is
Tok list = [t(if ,0),t(id("a"),3),t(plus,4),t(int(2),5),t(mult,6),t(id(IIfll), 7),
- t (lpar, 8), t (int (7),9), t (rpar, 10), t (tha, 12), t (qoto, 17),
t (id (lilabell") ,22), t (.11.,29), t (whil., 34), t (id (lihool") ,40),
t (qoto, 45), t (int (7),50))
XMINIGOL.PRO
douiD..
CURSOR = INTEGER
PROCID = STRING
clataba
source (STRING)
filename (STRING)
1Dclacle "xminigol.dom"
predicat
scan_error (STRING, CURSOR)
1Dclacle "xminigol.sca"
predicat
strlist str (STRINGLIST, STRING)
ed(STRING,CURSOR)
change (DBASEDOM)
reset flags
nondeterm repparse
parse
better error (CURSOR)
new_error (STRING, CURSOR)
predicat
expect (CURSORTOK, TOKL, TOKL)
syntax error (STRING, TOKL)
checkeiiipty (TOKL)
1Dclacle "xminigol.par"
clau
better error (CURSOR)
error ( , OLDCURSOR) ,OLDCURSOR >= CURSOR,!, f.il.
better_error lJ .
new error( , ) :- I'.tl'.ct(error( , )),f.11.
new=error(MSG,CURSOR) :- I'tI(error(MSG,CURSOR)).
90al
r
1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
COMPILE EDIT FILES QUIT
*/
Using the XMINIGOL example files as a basis, you can easily implement
the scanner (lexical analyzer) and parser for your own compiler. In order to
experiment with your own source language, you can modify the example
program this way:
Bootstrapping a Parser
Bootstrapping a parser means that you can take a parser generator and
input a grammar that describes itself. The parser generator then generates
another parser generator. In other words, it clones itself.
A common question is, Where did the first parser generator come from?
The first one in this case is the Toolbox parser generator, which has been
PRODUCTIONS = PRODUCTION+
PRODUCTION = PRODNAME equal PRODBODY -> p(PRODNAME,PRODBODY)
2
Reference Guide
217
218 Turbo Prolog Toolbox Owner's Handbook
c H A p T E R
8
Reference Guide
Introduction
This section defines and describes, in alphabetical order, all the Turbo
Prolog Toolbox tools. All the essential information about each
tool-predicate, declaration, flow pattern, function, parameters,
environment, and so on-is included. The environment comprises the
programs required to run the tool.
In addition, the following table summarizes the environments of all the
Toolbox files, listing the files required by each specific file.
The files are listed in alphabetical order, under the headings Prolog Files,
Object Files, and Example Files.
Prolog Files
BIOS None
BOXMENU TDOMS.PRO, TPREDS.PRO
COMGLOBS None
DBASE3 TDOMS.PRO, TPREDS.PRO, READEXT.PRO, REALINTS.OBJ
FILENAME TDOMS.PRO, TPREDS.PRO, LINEINP.PRO
GBAR TDOMS.PRO, GDOMS.PRO, GGLOBS.PRO, TPREDS.PRO,
GPREDS.PRO, GRAPHICS.OBJ, EGAGRAPH.OBJ
GDOMS None
GEGA TDOMS.PRO
GGLOBS GDOMS.PRO
GGRAPH TDOMS.PRO, GDOMS.PRO, TPREDS.PRO, GPREDS.PRO
GPIE TDOMS.PRO, TPREDS.PRO, GDOMS.PRO, GPREDS.PRO,
GRAPHICS.OBJ EGAGRAPH.OBJ
GPREDS GOOMS.PRO
HELP TDOMS.PRO, TPREDS.PRO
HELPDEF TDOMS.PRO, LONGMENU.PRO, STATUS.PRO,
TPREDS. PRO,LINEINP. PRO,
FILENAME.PRO, SCRHND.PRO, HELP.SCR
HNDBASIS TDOMS.PRO, TPREDS.PRO, MENU.PRO, STATUS.PRO,
LINEINP.PRO, SCRHND.PRO or VSCRHND.PRO
LINEINP TDOMS.PRO, TPREDS.PRO
LINEMENU TDOMS.PRO, TPREDS.PRO
LONGMENU TOOMS.PRO, TPREDS.PRO
LOTUS TDOMS.PRO, TPREDS.PRO, READEXT.PRO, REALINTS.OBJ
MENU TDOMS.PRO, TPREDS.PRO
MIXSCR GOODS.SCR, ORDERSCR, CUSTOMERSCR, INF.SCR,
INVOICE.SCR
PARSGEN PARSER.PRJ, PARSERDEF, TPREDS.PRO
PARSMAIN PARSER. PRJ (PARSGEN.OBJ), PARSERDEF, TPREDS.PRO,
LINEINP.PRO, FILENAME.PRO, STATUS.PRO,
PULLDOWN.PRO, PARSER.SCA, PARSER.PAR
PULLDOWN TDOMS.PRO, TPREDS.PRO
READEXT None
REFLEX TDOMS.PRO, TPREDS.PRO, READEXT.PRO, REALINTS.OBJ
REPORT TOOMS.PRO
RESIZE STATIJS.PRO, TOOMS.PRO, TPREDS.PRO
SCRDEF TOOMS.PRO, TPREDS.PRO, MENU.PRO, STATUS.PRO,
LINEINP.PRO, FILENAME.PRO, RESIZE.PRO
Example
axisLabels(l,"Length","Height")
Contained in
GGRAPH.PRO
Environment
TooMS.PRO, GooMS.PRO, TPREDS.PRO, GPREDS.PRO
See also
modifyAxes, makeAxes, refreshAxes
Remarks
The drawing speed can be increased by declaring the domains X and Yas
INTEGERs instead of REALs.
Example
draw([d(1,[p(70,100),p(90,19S)]),d(3,lp(400,300),p(200,20S)])])
Contained in
GGRAPH.PRO
Environment
TOOMS.PRO, GOOMS.PRO, TPREDS.PRO, GPREDS.PRO,
Predicate
jindScale(ScaleNo,MyDrawing,Xfactor,Yfactor)
Declaration
jindScale(ScaleNo ,Drawing,Factor,Factor)
Flowpattem
findScale(o,i,i,i)
Function
Evaluates a graphics image and then automatically defines an appropriate
scale so that the image can fit into a given window.
Parameters
The image is represented as a list of points, MyDrawing, belonging to the
domain DRAWING, which is defined as
X,Y = REAL
POINT = p (X, Y)
DRAWING = POINT*
Xfactor indicates the amount of stretch (if any) desired in the X direction,
when the images specified for this scale are represented on screen; Yfactor
indicates the amount of stretch in the Y direction expressed as a ratio to the
original.
Example
findScale(X,[p(1,V ,p(9,V,p(1,9)J,2,1.3)
Contained in
GGRAPH.PRO
Environment
TOOMS.PRO, GOOMS.PRO, TPREDS.PRO, GPREDS.PRO, GGRAPH.PRO
See also
defineScale, shiftScale
Remarks
Requires the definition of a project.
Contained in
DBASE3.PRO
Environment
TOOMS.PRO, lPREDS.PRO, READEXT.PRO, REALINTS.OBJ
See also
rd_dBase3File, rddBase3Rec
If, during a call, the first key pressed is not a cursor key, then BeforeString is
deleted. F8 can be used to re-establish the default text, while Ctrl-
Backspace-Del deletes it.
The input text may be up to 64K-the text will scroll in the window if
necessary.
Example
lineinput(3,5,40,7,7,"Address Label","Please type your first name",X)
Example
lineinpuCleave(3,5,40,7,7,"", "Which printer font?",X)
Contained in
LINEINP.PRO
Environment
rooMS.PRO, TPREDS.PRO
See also
lineinput
Example
lineinput_repeat(3,4,40 ,7,7,'''',"Date:",Z)
Contained in
LINEINP.PRO
Environment
TOOMS.PRO, TPREDS.PRO
Row1, Row2, Column1, Column2, and EndLine all must be in the range 0 to
31999.
Contained in
PICTOOLS.OBJ
Environment
GOOMS.PRO, GGLOBS.PRO
See also
savepic
This defines the interval Unit at which markings are to appear on the
relevant axis; whether the number marked is to appear in decimal form or
exponential form (FormatSpecifier equal to d or e respectively); and, finally,
the Field Width in which the numeric markings are to be displayed.
The last four parameters in makeAxes determine how much space should be
left between the borders of the window and the edge of the graphics screen.
All of these are given as text coordinates.
Example
makeAxes(l,-,-,marker(10,d,2),marker(10,d,3),2,3,2,l)
Predicate
modifyAxes(AxesNo,MyXmarker,MyYmarker)
Declaration
modifyAxes(Integer,XMarker,YMarker)
Flowpattem
modifyAxes(i,i,i)
Function
Used to modify (the markings on) a set of axes.
Parameters
AxesNo identifies the pair of axes to be affected and is the axes identifier
returned from a previous call of makeAxes. MyXmarker and MyYmarker both
have the following format:
marker (Unit, FormatSpecifier, FieldWidth)
This defines the interval Unit at which markings are to appear on the
relevant axis; whether the number marked is to appear in decimal form or
exponential form (FormatSpecifier equal to d or e repectively); and, finally,
the FieldWidth in which the numeric markings are to be displayed.
Example
modifyAxes(2,marker(10,d,4),marker(10,d,S
Contained in
GGRAPH.PRO
Environment
TOOMS.PRO, GOOMS.PRO, TPREDS.PRO, GPREDS.PRO
See also
makeAxes, refreshAxes
Remarks
Correct hardware connection must have been established (see Chapter 5).
Requires the creation of a project.
Example
~enRS232(1,256,256,7,O,3,O,2)
Contained in
SERIAL.OBI
Environment
CONGLOBS.PRO, TICKS.OBI
See also
closeRS232
Example
pdwaction(5,2):- dir("I,"*.*",X), ....
Contained in
PULLDOWN.PRO
Environment
TOOMS.PRO, TPREDS.PRO
slice(151,"Jul",3,2),
slice(6,"Aug",2,1)J),
Contained in
GPIE.PRO
Environment
TOOMS.PRO. TPREDS, GOOMS.PRO, GPREDS.PRO, GGLOBS.PRO,
GRAPHICS.OBI
See also
Piechart
Remarks
Requires the creation of a project.
Contained in
DBASE3.PRO
Environment
TOOMS.PRO, TPREDS.PRO, DBASE3.PRO, READEXT.PRO
S~e also
init_dBase3, rd_dBase3Rec
Remarks
Requires the creation of a project.
Contained in
LOTUS.PRO
Environment
TooMS.PRO, TPREDS.PRO, LOTUS.PRO, READEXT.PRO,
REALINTS.OBJ
See also
rd_LotusCell
Parameters
The parameters To tRees, ReflexTypeL, and TextPools are the values returned
by the init_Reflex predicate.
Contained in
REFLEX.PRO
Environment
TOOMS.PRO, 1PREDS.PRO, REFLEX.PRO, READEXT.PRO,
REALINTS.OBJ
See also
IniCReflex, rd_ReflexRee
Remarks
Requires the creation of a project.
Contained in
REFLEX.PRO
Environment
TOOMS.PRO, TI'REDS.PRO, REFLEX. PRO, READEXT.PRO,
REALINTS.OBJ
See also
init_Reflex, rd_ReflexFile
Example
readfilename(10,10,7,7,pro,"oldname.dat",NewName)
Each time a window is changed using resize, writescr is called. You must
define this predicate so that the screen is updated appropriately.
Example
resize
Contained in
RESIZE.PRO
Environment
STATUS.PRO, TOOMS.PRO, TPREDS.PRO
See also
status, writescr
clataba
r database declarations used in SCRHND */
insmode r Global insertmode */
act field (FNAME) r Actual field */
screen (SYMBOL, DBASEDOM) r Saving different screens */
value (FNAME, STRING) r Value of a field */
field (FNAME, TYPE, ROW, COL, LEN) r Screen definition */
txtfield (ROW, COL,LEN,STRING)
windsize(ROW,COL).
notopline
Example
scrhnd(on, .J
Contained iri
SCRHND.PRO (real-screen version); VSCRHND.PRO (virtual-screen
version)
Environment
TOOMS.PRO, TPREDS.PRO, STATUS.PRO, LINEINP.PRO
See also
createwindow, field_action, field_value, noinput
Contained in
SERIAL.OBI
Environment
COMGLOBS.PRO, TICKS.OBI
See also
openRS232
(In actual use, the SELECTOR can be of any TYPE convenient to the
programmer).
Flowpattem
treemenu(i,i,o)
Function
Implements a tree menu on a virtual screen. (The cursor keys can be used
to move around the tree.) The user makes a menu selection by pressing
Return or FlO.
Parameters
Displays a tree menu in which the tree is drawn up, down, left, or right
according to the value DirectionOfTreeDisplay is bound to.
MyTree must be bound to a TREE definition that determines, for each item,
the text describing that item, its position in the tree, and the code to be
returned when that item is selected. To this end, use is made of the tree
functor, which takes three arguments. The first is a String that gives the text
for that menu item; the second is the code to be returned if that menu item
is selected; and the third is a Treelist that specifies the rest of the tree.
Choice becomes bound to the code for the menu item chosen.
Example
treemenu(up,tree("start",l,
ltree("start...problem",2,lfree("gasoline_help" ,J,ll)1,)]),
CH)
Contained in
TREEMENU.PRO
A
Compiling a Project
Glossary 337
clip To use only that part of an image that fits inside the specified active
window.
dialog window The window in which external goals are given and their
results recorded.
expert system A program that has been fed enough information for it to
mimic the ability of an expert in a specified field. Its database is
supplemented by an inference engine so that it can analyze given facts.
expression A set of symbols that can be evaluated for a value, or a notation
representing a value.
external goal A goal entered in the dialog window by the user and given
to the program currently being worked on.
fact A relation between objects.
global A qualifier that allows more than one module access to certain
domains and predicates.
goal The collection of sub-goals that Turbo Prolog attempts to satisfy.
grammar A description of the specifications and structures that are
allowed in a source text.
identifier A symbolic name you define to represent variables or constants
in a program.
integer A whole number in the range -32768 to 32767.
module A Turbo Prolog program with global declarations that is part of a
project file. You can write, edit, and compile modules separately, and then
combine them into a single executable program.
non-terminals Special symbols that denote sets of strings in a grammar.
parser A routine or program that analyzes the syntactical structure of a
string of characters, based on the syntax specified by the programming
language.
parameters The objects and variables in a relation.
PC Personal computer; usually refers to an IBM PC or compatible.
pixel Literally, picture element. The smallest element of a display that can
be assigned color and intensity.
Glossary 339
340 Turbo Prolog Toolbox Owner's Handbook
Index
341
actfield 86 declarations
ADDERDEF.SCR 57 database 4
adding screen-definition types 87 domains 4
ambiquity 193 defineScale 103, 240
assembler See OBI files 4 Define Screen Layouts 54
associating actions with fields 61 defining scales 103
associating Help text with a field 86 deleting the input buffer 140
associating values with fields 57 delInBuCRS232 140, 241
associativity 193 deIOutBuCRS232140, 242
axislabels 224 directory file names 44
diskspace 243
B displayhelp 87
bargraph 120, 225 dosver 244
bargraph3d 120, 227 dot 96
BIOS calls 42 draw 105, 245
bootstrapping 213 drawing axes 106
border 229
box 230 E
boxmenu 23,231 Edit layout definition file 57
BOXMENU.PRO 23 editmsg81
boxmenu_leave 24, 233 ECA graphics 122
boxmenu_mult 24, 235 palettes 123
ellipse 246
C error handling 201
changestatus 237 EXE file 212
closeRS232 136, 238 expect 213
closing a serial port 136
COMCLOBS.PRO 132 F
communications field 50
polled 144 field_action 58, 61, 247
polled transmission 145 field_value 58,248
queue sizes 139 FILENAME.PRO 36
serial 134 findmatch 44, 249
converting coordinates 112, 113 findScale 112, 250
createwindow 51, 239 fixed fields 49, 55
creating new definitions from old 90 formatted reports
C See OBI files printing 90
curtain functor 28 fronttoken 197
D G
DATA.TRS 141 CBAR.PRO 119
data field 48 COOMS.PRO 95
DBASE3.PRO 165, 170 CECA.PRO 122
dBASE III files 170 getcols 114
343
opening a serial port 134 REALINTS.C 165
openRS23213~283 REALINTS.OBJ 165
output buffer 140 receiving from a serial port 139
p recording transactions 76
REFLEX. PRO 165
packet format 146 Reflex files 166
parser generator 181 refreshAxes 107
bootstrapping 213 refreshstatus 303
definition 181 remote serial devices
description 186 commmunication with 131
examples 193 removestatus 304
specifying input 187 report 91
syntax errors 213 REPORT.PRO 91
types 182 reserved windows 7
pdwaction 28,285 RESIZE.PRO 41
pdwstate28 resizewindow 305
PIC files resizing windows 41
loading 126 rightassoc 188
PICTOOLS.OBJ 126 rmdir306
pieChart 114, 287 running the Toolbox 5
plot 289 rxch_RS232139,307
polled communication 144 rxStr_Modem 155,308
pop_helpcontext 290
precedence 193 S
printer driver 141 savepic 126, 309
printing formatted reports 90 Save screen layout 56
productions 187 scale_text 314
pu1ldown 291 scale_virtual 315
PULLDOWN.PRO 26 scalecursor 104, 310
push_helpcontext 39, 293 scaled coordinates 103
scaleLine 104, 311
Q scalePlot 104, 312
queueSize 294 scalePolygon 105, 313
queuesize_RS232139 scanner 183
scr86
R SCRDEF.PRO 47, 53
Rd_dBase3File 171, 295 screen 89
rd_dBase3Rec 172, 296 screen-definition types
Rd_LotusCe11177, 297 adding 87
Rd_LotusFile 177, 298 screen-layout definitions 47
Rd_ReflexFile 166, 299 data field 49
rd_Ref1exRec 168, 300 fixed fields 49
READEXT.PRO 165 screenarea 114
readfilename 36, 301
345
VSCRHND.PRO 51 XLONGMNU.PRO 21
XLOTUS.PRO 177
W XLOTUS.WRK 177
WELCOME.PIC 127 XMADDERPRO 63
windows XMADDERSCR 61
resizing 41 XMAIL.PRO 51, 52
window size 50 XMAIL.SCR50, 51, 52
WKS records 175 XMENU.PRO 20
write 91 XMINIGOL.DOM 203
writescr 334 XMINIGOL.GRM 202
XMINIGOL.PAR 204
X XMINIGOL.SCA 206
XBARPRJ 120 XMODEM131
XBARPRO 120 XMODEM protoco1146
XBOXMENU.PRO 24 XPARS.DOM 196
XCAREERPRO 16 XPARS.GRM 195
XCLUB.DBA 70 XPARS.PAR 194,198
XCLUB.PRO 70, 73 XPICDEMO.PRO 127
XCLUB.SCR 71 XPIE.PRO 115
XCOMMU.PRO 156 XPOLLlNG.PRO 145
XDBASE3.DBF 171 XPRINTERPRO 141
XDBASE3.DBT 172 XREFLEX.PRO 169
XDBASE3.PRO 173 XREFLEX.RXD 166
XEGA.PRO 123 XREPORT.PRO 92
XFILENAM.PRO 37 XRESIZE.PRO 42
XGEOMTR.PRO 100 XSHOP.PRO 76, 77
XGRAPH.PRO 108 XSHOP.SCR 76
XHELP.DEF 39 XSTATUS.PRO 12
XHELP.PRO 41 XTERM.PRO 143
XIQ.PR018 XTRAVEL.PRO 65, 68
XLABEL.PRO 70 XTRAVEL.SCR 65
XLABEL.SCR SO, 82 XTREE.PRO 32
XLCAREERPRO 17 XXMODEM.PRO 147
XLINEINP.PRO 34
XLINEMNU.PRO 26
BORLAND -
INTERNATIONAL 4585 Scotts Valley Drive, Scotts Valley, CA 95066
All the SideKick windows stacked up over Lotus 1-2-3." Here's SideKick running over Lotus 1-2-3. In the
From bottom to top: SideKick's "Menu Window," ASCII SideKick Notepad you'll notice data that's been imported
Table, Notepad, Calculator, Appointment Calendar, Monthly directly from the Lotus screen. In the upper right you can
Calendar, and Phone Dialer. see the Calculator.
!if RAM resident-accepts new macro files !if Keyboard buffer increases 16 character
even while running other programs keyboard "type-ahead" buffer to 128
!if Pull-down menus characters
!if Superfast file encryption !if Real-time delay causes macro playback
!if Choice of two encryption schemes to pause for specified interval
!if On-line context-sensitive help !if Transparent display macros allow
creation of menus on top of application
!if One-finger mode reduces key programs
commands to single keystroke
!if Data entry and format control using
!if Screen OFF/ON blanks out and restores "fixed" or "variable" fields
screen to protect against "burn in"
!if Command stack recalls last 256
!if Partial or complete reorganization of characters entered
keyboard
Minimum system configuration: IBM PC, Xl, AT, PCjr, and true compatibles. PC-DOS (MS-DOS)
2.0 or greater. 128K RAM. One disk drive.
BORLAND
INTERNATIONAL
Super Key is a registered trademark of Borland International, Inc. IBM, XT, AT, and PCjr are
registered trademarks 01 International BUSiness Machines Corp. MS-DOS is a registered
trademark of Microsoft Corp. BOR 0062C
1 '11 11I811E IA1AIA'E
~r'~II: .AIAIE.
The high-performance database manager
that's so advanced it's easy to use!
Lets you organize, analyze and report information faster than ever before! If you manage mailing lists,
customer files, or even "your company's budgets-Reflex is the database manager for you!
Reflex is the acclaimed, high-performance database manager you've been waiting for. Reflex extends
database management with business graphics. Because a picture is often worth a 1000 words, Reflex
lets you extract critical information buried in mountains of data. With Reflex, when you look, you see.
The REPORT VIEW allows you to generate everything from mailing labels to sophisticated reports.
You can use database files created with Reflex or transferred from Lotus 1-2-3,e dBASE,e PFS: File,e
and other applications.
Minimum s,stem configuration: IBM PC, Xl, AT, and true compatibles. 384K RAM minimum. IBM Color Graphics Adapter, Hercules
Monochrome Graphics CArd, or equivalent. PC-DOS (MS-DOS) 2.0 or greater. Hard disk and mouse optional. Lotus 1-2-3, dBASE,
or PFS: File optional.
Whether you're a newcomer learning Reflex basics or an experienced "power user" looking for tips, Reflex:
The Workshop will help you quickly become an expert database analyst.
Minimum system configuration: IBM PC, AT, and Xl, and true compatibles. PCDOS (MSDOS) 2.0 or greater. 384K RAM minimum. Requires Reflel:
The Database Manager, and IBM Color Graphics Adapter, Hercules Monochrome Graphics Card or equivalent.
Reflex is a registered trademark and Reflex: The Workshop is a trademark of Borland/Analytica, Inc. IBM, AT, and XT are registered trademarks of International Business
Machines Corp. Hercules is a trademark of Hercules Computer Technology. MS-DOS is a registered trademark of Microsoft Corp. Copyright 1987 Borland International
BOR 0088B
If you use an IBM PC, you need
T U R B 0
Lightning
Turbo Lightning teams up If you ever write a You can teach Turbo
with the Random House word, think a word, or Lightning new words
Concise Word List to say a word, you need You can teach your new Turbo
check your spelling as Turbo Lightning Lightning your name, business
you type! associates' names, street
Turbo Lightning, using the names, addresses, correct
BO,OOO-word Random House capitalizations, and any
Dictionary, checks your spelling specialized words you use
as you type. If you misspell a frequently. Teach Turbo
word, it alerts you with a Lightning once, and it
"beep." At the touch of a key, knows forever.
Turbo Lightning opens a
window on top of your Turbo Lightning is the
application program and engine that powers
suggests the correct spelling. Borland's Turbo Lightning
Just press one key and the Library@
misspelled word is instantly Turbo Lightning brings
replaced with the correct word. electronic power to the
The Turbo Lightning Proofreader
Random House Concise Word
Turbo Lightning works List and Random House
hand-in-hand with the Thesaurus. They're at your
Random House Thesaurus fingertips-even while you're
to give you instant access running other programs. Turbo
to synonyms Lightning will also "drive"
soon-to-be-released
Turbo Lightning lets you
encyclopedias, extended
choose just the right word from
thesauruses, specialized
a list of alternates, so you
dictionaries, and many other
don't say the same thing the
popular reference works. You
same way every time. Once
get a head start with this
Turbo Lightning opens the
first volume in the Turbo
Thesaurus window, you see a
Lightning Library.
list of alternate words; select
the word you want, press
ENTER and your new word will The Turbo Lightning Thesaurus
instantly replace the original
word. Pure magic!
Turbo Lightning and Turbo Lightning Library are registered trademarks of Borland International. Inc.
IBM. XT. AT. and PCjr are registered trademarks of International Business Machines Corp. Random
House is a registered trademark of Random House. Inc. Copyright 1987 Borland International
BOR 0070B
Your Development Toolbox and Technical Reference Manual for Thrbo Lightning@
l I G H T N I N G
"The real future of Lightning clearly lies not with the spelling checker and thesaurus currently
included, but with other uses of its powerful look-up engine." Ted Silveira, Profiles
"This newest product from Borland has it all." Don Roy, Computing Nowl
Minimum system configuration: IBM PC, Xl, AT, PCjr, Portable, and true compatibles. 256K RAM minimum. PC-DOS (MS-DOS) 2.0
or greater. Turbo lightning software required. Optional-Turbo Pascal 3.0 or greater to edit and compile Turbo Pascal source code.
Turbo Pascal. Turbo Lightning and Turbo Lightning Library are registered trademarks and Lightning Word Wizard is a trademark of Borland International. Inc. Random
House is a registered trademark of Random House. Inc. IBM. XT. AT. and PCjr are registered trademarks of International Business Machines Corp. MS-DOS is a
registered trademark of Microsoft Corp. Cq>yright 1987 Borland International BOR0087B
Version 3.0 with 8087 support and BCD reals
MicroCalc: A sample spreadsheet on your disk "What I think the computer industry is headed
with ready-to-compile source code. for: well-documented, standard, plenty of
good features, and a reasonable price."
IBM~ PC Version: Supports Turtle Graphics, -Jerry Pournelle, BYTE
color, sound, full tree directories, window
routines, input/output redirection, and
much more.
LOOK AT TURBO NOW!
[it' More than 500,000 users worldwide. [it' Turbo Pascal named "Most
Significant Product of the Year" by
[it' Turbo Pascal is the de facto industry PC WEEK.
standard.
[it' Turbo Pascal 3.0-the fastest Pascal
[it' Turbo Pascal wins PC MAGAZINE'S development environment on the
award for technical excellence. planet, period.
Suggested Retail Price: $99.95; CP/M~-80 version without 8087 and BCD: $69.95
Features for 16-bit Systems: 8087 math co-processor support for intensive calculations.
Binary Coded Decimals (BCD): eliminates round-off error! Amust for any serious business application.
Minimum system configuration: 128K RAM minimum. Includes 8087 & BCD features for 16-bit MS-DOS 2.0 or later and
CP/M-86 1.1 or later. CP/M-80 version 2.2 or later 48K RAM minimum (8087 and BCD features not available). 8087
version requires 8087 or 80287 co-processor.
Turbo Pascal is iI registered trademlrk of BoI1and International. Inc. CP/M is a registered trademark
of Digital Research Inc. IBM is a registered badernark of International Business Machines Corp.
MS-DOS is a registered trademark 01 MicrOSlft Corp. VlrdStar is a registered tradenwk of
MicroPro International. Copyright 1987 Borland International BOA 00618
VERSION 2.0
For the Novice: It gives you a concise history of Pascal, tells you how to write a
simple program, and defines the basic programming terms you need to know.
Programmer's Guide: The heart of Turbo Pascal. The manual covers the fine pOints
of every aspect of Turbo Pascal programming: program structure, data types, control
structures, procedures and functions, scalar types, arrays, strings, pointers, sets, files,
and records.
Advanced Concepts: If you're an expert, you'll love the sections detailing such topics as
linked lists, trees, and graphs. You'll also find sample program examples for PC-DOS and
Ms-oos.e
10,000 lines of commented source code, demonstrations of 20 Turbo Pascal features, multiple-
choice quizzes, an interactive on-line tutor, and more!
Turbo Tutor may be the only reference work about Pascal and programming you'll ever need!
Minimum system configuration: Turbo Pascal 3.0. PC-DOS (MS-DOS) 2.0 or later. 192K RAM minimum (CP/M-80
version 2.2 or later: 64K RAM minimum).
BORLAND
INTERNATIONAL
TUIbo Pascal and Turbo Tutor Ire registered r.tdemIJks of Borland International Inc. CP/M is a
registered trademark of Digital Research Inc. MS-DOS is a registered trademark of Microsoft Corp.
Copyright 1987 Borland International BOA 0064C
Is The Perfect Complement To Turbo Pasca/~
It contains a complete library of Pascal procedures that
allows you to sort and search your data and build powerful database
applications. It's another set of tools from Borland that will give
even the beginning programmer the expert's edge.
Minimum system configuration: 128K RAM and one disk drive (CP/M80: 48K). 16bit systems: Turbo Pascal 2.0 or greater for
MS DOS or PCDOS 2.0 or greater. Turbo Pascal 2.1 or greater for CP/M86 1.0 or greater. 8bit systems: Turbo Pascal 2.0 or
greater for CP/M80 2.2 or greater.
Turbo Pascal and Turbo Database Toolbox are registered trademarks of Borland Intemational
Inc. CP/M is a registered trademark of Digital Research, inc. MS-DOS is a registered
trademark of Microsoft Corp. Copyright 1987 Borland international BOR 0063C
2VRBO PASCAl.
GRAPHlX2brX-BOX
A Library of Graphics Routines for Use with Turbo Pasca/
High-resolution graphics for your IBM" PC, AT," XT,'"' PCjf', true PC compatibles, and the Heath
Zenith Z-100:" Comes complete with graphics window management.
Even if you're new to Turbo Pascal programming, the Turbo Pascal Graphix Toolbox will get you started
right away. It's a collection of tools that will get you right into the fascinating world of high-resolution
business graphics, including graphics window management. You get immediate, satisfying results. And
we keep Royalty out of American business because you don't pay any-even if you distribute your own
compiled programs that include all or part of the Turbo Pascal Graphix Toolbox procedures
"While most people only talk about low-cost personal computer software, Borland has been doing
something about it. And Borland provides good technical support as part of the price."
John Markov & Paul Freiberger, syndicated columnists.
If you ever plan to create Turbo Pascal programs that make use of business graphics or scientific
graphics, you need the Turbo Pascal Graphix Too/box.
Suggested Retail Price: $69.95 (not copy protected)
Minimum system configuration: IBM PC, Xl, AT, PCjr, true compatibles and the Heath Zenith Z-100. Turbo Pascal 3.0 or later. 192K
RAM minimum. Two disk drives CIId an IBM Color Graphics Adapter (CGA), IBM Enhanced Graphics Adapter (EGA), Hercules Graphics
Card or compatible.
Turbo Pascal and Turbo Graphix Toolbox are registered trademarks of Borland International,
Inc. IBM, Xl AT, and PCjr are registered trademarks of International Business Machines
Corporation. Hercules Graphics Card is a trademark of Hercules Computer Technology. Heath
Zenith Z-100 is a trademark of Zenith Data Systems. Epson is a registered trademark of
Epson Corp. Copyright 1987 Borland Intemational BOR 0068C
2VRBO PASCAl.
DJ2OR2tnr.BOX@
It's All You Need To Build Your Own Text Editor
Or Word Processor
Build your own lightning-last editor and incor- Create your own word processor. We provide all
porate it 'into your Turbo Pascar programs. the editing routines. You plug in the features you want.
Turbo Editor Toolbox gives you easy-to-install You could build aWordStar@-like editor with pull-down
modules. Now you can integrate a fast and powerful menus like Microsoft's@ Word, and make it work as fast
editor into your own programs. You get the source as WordPerfect.@
code, the manual, and the know-how.
To demonstrate the tremendous power 01 Turbo Editor Toolbox, we give you the source code lor
two sample editors:
Simple Editor A complete editor ready to include in your programs. With windows, block commands, and
memory-mapped screen routines.
MicroStar A full-blown text editor with a complete pull-down menu user interface, plus a lot more.
Modify MicroStar's pull-down menu system and include it in your Turbo Pascal programs.
And Turbo Editor Toolbox has features that word processors selling for several hundred dollars can't begin to match.
Just to name a few:
[!] RAM-based editor. You can edit very large [!] Multiple windows. See and edit up to eight
files and yet editing is lightning fast. documents-or up to eight parts of the same
[!] Memory-mapped screen routines. In- document-all at the same time.
stant paging, scrolling, and text display. [!] Multitasking. Automatically save your
[!] Keyboard installation. Change control text. Plug in a digital clock, an appointment
keys from WordStar-like commands to any that alarm-see how it's done with MicroStar's
you prefer. "background" printing.
Best of all, source code is included for everything in the Editor Toolbox.
Suggested Retail Price: $69.95 (not copy protected)
Minimum system configuration: IBM PC, XT, AT, 3270, PCir, and true compatibles. PC-DOS (MS-DOS) 2.0 or greater. 192K RAM.
You must be using Turbo Pascal 3.0 for IBM and compatibles.
Turbo Pascal and Turbo Editor Toolbox are registered trademarks of Borland International, Inc.
WordStar is a registered trademark of MicroPro International Corp. Word and MS-DOS are
registered trademarks of Microsoft Corp. WordPerfect is a trademark of Satellite Software
International. IBM, XT, AT, and PCjr are registered trademarks of International Business Machines
Corp. BOR 0067B
TURBO PASCAL
IUliEBICAI IIE11111111111111l1
T
Minimum system configuration: IBM PC, XT, AT and true compatibles. PC-DOS (MS-DOS) 2.0 or later. 256K. Turbo Pascal 2.0 or later.
The graphics modules require a graphics monitor with an IBM CGA, IBM EGA, or Hercules compatible adapter card, and require the Turbo
Graphix Toolbox. MS-DOS generic version will not support Turbo Graphix Toolbox routines. An 8087 or 80287 numeric co-processor is
not required, but recommended for optimal performance.
Turbo Pascal Numerical Methods Toolbox is a trademark and Turbo Pascal and Turbo Graphix
Toolbox are registered trademarks of Borland International, Inc. IBM, XT, and AT are
BORLAND
INTERNATIONAL
registered trademarks of International Business Machines Corp. MS-DOS is a registered
trademark of Microsoft Corp. Hercules is a trademark of Hercules Computer Technology.
Apple is a registered trademark of Apple Computer, Inc. Macintosh is a trademark of Mcintosh
Laboratory, Inc. licensed to Apple Computer. Copyright 1967 Borland International BOR 0219A
TURBO BRIDGE
Now play the world's most popular card game-bridge. Play one-on-one with your computer or against up to
three other opponents. With Turbo Pascal source code, you can even program your own bidding or scoring
conventions.
"There has never been a bridge program written which plays at the expert level, and the ambitious user will
enjoy tackling that challenge, with the format already structured in the program. And for the inexperienced player,
the bridge program provides an easy-to-follow format that allows the user to start right out playing. The user can
'play bridge' against real competition without having to gather three other people."
-Kit Woolsey, writer of several articles and books on bridge,
and twice champion of the Blue Ribbon Pairs.
TURBO GO-MOKU
Prepare for battle when you challenge your computer to a game of Go-Moku-the exciting strategy game also
known as Pente. In this battle of wits, you and the computer take turns placing X's and D's on a grid of 19X19
squares until five pieces are lined up in a row. Vary the game if you like, using the source code available on your
disk.
Suggested Retail Price: $69.95 (not copy protected)
Minimum system configuration: PC, Xl, AT, Portable, 3270, PClr, and true compallb.es. PC-DOS (MS-DOS) 2.0 or laler. 192K
RAM minimum. To edll and compile Ihe Turbo Pascal source code, you musl be using Turbo Pascal 3.0 for IBM PCs and
compatibles.
~ 3-
:=:
$
D BORLANDI N T ERN A TID N A L
Turbo Pascal and Turbo GameWorks are regis.tered trademarks of Borland International. Inc.
Pente is a regislered trademark of Parker Brothers. IBM, XT, AT, and PCjr are registered
trademarks of International Business Machiles Corporation. MS-DOS is a registered trademark
of Microsoft Corporation. Copyright 1987 Borland International BOR0065C
the natural language of ArtiflCiallntelgence
Turbo Prolog brings fifth-generation supercomputer
power to your IBMPC!
Turbo Prolog takes Turbo Prolog provides
programming into a new, a fully integrated pro-
natural, and logical gramming environment
environment like Borland's Turbo
With Turbo Prolog, Pascal, the de facto
because of its natural, worldwide standard.
logical approach, both You get the
people new to programming complete Turbo
and professional programmers Prolog programming
can build powerful applica- system
tions such as expert systems, You get the 2DD-page
customized knowledge manual you're holding,
bases, natural language software that includes
interfaces, and smart the lightning-fast Turbo
information management systems. Prolog six-pass
Turbo Prolog is a declarative language which compiler and interactive editor, and the
uses deductive reasoning to solve free GeoBase natural query language
programming problems. database, which includes commented
source code on disk, ready to compile.
(GeoBase is a complete database designed
Turbo Prolog's development system and developed around U.S. geography.
includes: You can modify it or use it "as is.")
o A complete Prolog compiler that is a variation
of the Clocksin and Mellish Edinburgh
standard Prolog.
o A full-screen interactive editor.
Minimum system configuration: IBM PC, Xl, AT, Portable, 3270, PCjr
o Support for both graphic and text windows. and true compatibles. PC-DOS (MS-DOS) 2.0 or later. 384K RAM
o All the tools that let you build your own minimum.
expert systems and AI applications with
unprecedented ease. Suggested Retail Price: $99.95
(not copy protected)
--=
BORLAND
INTERNATIONAL
Turbo Prolog is a trademark and Turbo Pascal is a registered trademark of Borland International, Inc.
IBM, AT, XT, and PCjr are registered trademarks of International Business Machines Corp. MS-DOS is a
registered trademark of Microsoft Corp. Copyright 1987 Borland International BOR 0016D
-~
111111 IABIC
The high-speed BASIC you've been waiting lor!
You probably know us for our Turbo Pascale and Turbo Prolog." Well, we've done
it again! We've created Turbo Basic, because BASIC doesn't have to be slow.
If BASIC taught you how to walk, Turbo Basic will teach you how to run!
With Turbo Basic, your only speed is "Full Speed Ahead"! Turbo Basic is a complete development
environment with a lightning fast compiler, an interactive editor and a trace debugging system. And
because Turbo Basic is also compatible with BASICA, chances are that you already know how to use
Turbo Basic.
Turbo Basic ends the basic confusion
There's now one standard: Turbo Basic. And because Turbo Basic is a Borland product, the price is
right, the quality is there, and the power is at your fingertips. Turbo Basic is part of the fast-growing
Borland family of programming languages we call the "Turbo Family." And hundreds of thousands of
users are already using Borland's languages. So, welcome to a whole new generation of smart PC
users!
Free spreadsheet included with source code!
Yes, we've included MicroCalc, our sample spreadsheet, complete with source code, So you can get
started right away with a "real program," You can compile and run it "as is," or modify it.
Minimum system configuration: IBM PC, AT. XT or true compatibles. 256K. One floppy drive. PC-DOS (MS-DOS) 2.0 or later.
Turbo Basic and Turbo Pascal are registered trademarks and Turbo Prolog is a trademark of
Borland International, Inc. IBM, AT, and XT are registered trademarks of International Business
Machines Corp. MS-DOS is a registered trademark of Microsoft Corp.
Copyright 1987 Borland International BOR 0265A
Includes tree
MicroCalc spreadsheet
with source code
Suggested Retail Price: $99.95* (not copy protected) 'Introductory offer good through July 1, 1987.
Minimum system configuration: IBM PC, XT, AT and true compatibles. PC-DOS (MS-DOS) 2.0 or later. One floppy drive. 320K
Turbo C and Turbo Pascal are registered trademarks and Turbo Prolog is a trademark of Borland
International, Inc. Microsoft C and MS-DOS ere registered trademarks of Microsoft Corp. Lattice C
is a registered trademark of Lattice, Inc. IBM, XT, and AT are registered trademarks of International
Business Machines Corp. BOR 0243
E"'EIA: "E B'frEI~
The solution to your most complex
equations-in seconds!
If you're a scientist, engineer, financial analyst, student, teacher, or any other professional working with
equations, Eureka: The Solver can do your Algebra, Trigonometry and Calculus problems in a snap.
Eureka also handles maximization and minimization problems, plots functions, generates reports, and
saves an incredible amount of time. Even if you're not a computer specialist, Eureka can help you
solve your real-world mathematical problems fast, without having to learn numerical approximation
techniques. Using Borland's famous pull-down menu design and context-sensitive help screens, Eureka
is easy to learn and easy to use-as simple as a hand-held calculator.
X + exp(X) = 10 solved instantly instead of eventually!
Imagine you have to "solve for X," where X + exp(X) = 10, and you don't have Eureka: The Solver.
What you do have is a problem, because it's going to take a lot of time guessing at "X." With Eureka,
there's no guessing, no dancing in the dark-you get the right answer, right now. (PS: X = 2.0705799,
and Eureka solved that one in .4 of a second!)
How to use Eureka: The Solver
It's easy. You can then tell Eureka to
1. Enter your equation into the Evaluate your solution
full-screen editor Plot a graph
2. Select the "Solve" command Generate a report, then send the output
3. Look at the answer to your printer, disk file or screen
4. You're done Or all of the above
Minimum system configuration: IBM PC. AT, XT, Portable. Suggested Retail Price: $99.95
3270 and true compatibles. PC-DOS (MS-DOS) 2.0 and (not copy protected)
later. 384K.
Eureka: The Solver is a trademark of BorlClld International, Inc. IBM. AT. and XT are registered
trademarks of International Business Machiles Corp. MS-DOS is a registered trademark of
Microsoft Corp. Copyright 1987 Borland International BOR 0221A
'Introductory price expires July 1, 1987
.11,rlllfll
IJIJ : TIE IEBITI'
Inl"~ llSAIIIlBI Release 2.0
Macintosh'
The most complete and comprehensive collection of
desk accessories available for your Macintosh!
Thousands of users already know that SideKick is the best collection of desk accessories available
for the Macintosh. With our new Release 2.0, the best just got better.
We've just added two powerful high-performance tools to SideKick-Outlook": The Outliner
and MacPlan'": The Spreadsheet. They work in perfect harmony with each other and while you
run other programs!
Out/ook: The Outliner
It's the desk accessory with more power than a stand-alone outliner
A great desktop publishing tool, Outlook lets you incorporate both text and graphics
into your outlines
Works hand-in-hand with MacPlan
Allows you to work on several outlines at the same time
MacPlan: The Spreadsheet
Integrates spreadsheets and graphs
Does both formulas and straight numbers
Graph types include bar charts, stacked bar charts, pie charts and line graphs
Includes 12 example templates free!
Pastes graphics and data right into Outlook creating professional memos and reports, complete
with headers and footers.
~ Calendar ~
'"'
IN: Expenses
o Q,319Q Labor
~ Phone Log []I" 4661G Matff'ub:
~ 6219i Ovtmud
~ Analog clock (] 11.18' TollIlExpenas
~
El '"'
Alarm system .'8.43' hf'tProfit
~ Calculator
~ Report generator MacPlan does both spreadsheets and business
~ Telecommunications (new version now graphs. Paste them into your Outlook fifes and
supports XModem file transfer protocol) generate professional reports.
SideKick is a registered trademark and Outlook and MacPlan are trademarks 01 Borland
International, Inc. Macintosh is a trademark 01 Mcintosh Laboratory, Inc. licensed to Apple
Computer, Inc. Copyright 1987 Borland International BOR oo69D
Ir;,] '~~IEI; ,.,
AIABEI IA1AIA"
The easy-to-use relational database that thinks like a spreadsheet.
Reflex for the Mac lets you crunch numbers by entering formulas and link
databases by drawing on-screen lines.
5 free ready-to-use templates are included on the examples disk:
A sample 1040 tax application with Sched- A client billing application set up for a law
ule A, Schedule B, and Schedule 0, each office, but easily customized by any
contained in a separate report document. professional who bills time.
A portfolio analysis application with linked A parts explosion application that breaks
databases of stock purchases, sales, and down an object into its component parts
dividend payments. for cost analysis.
A checkbook application.
Reflex lor the Mac accomplishes all of these tasks without programming-using
spreadsheet-like formulas. Some other Reflex for the Mac features are:
Visual database design. Data types which include variable length text, number,
"What you see is what you get" report and form layout integer, automatically incremented sequence number,
with pictures. date, time, and logical.
Automatic restructuring 'of database files when data Up to 255 fields per record.
types are changed, or fields are added and deleted. Up to 16 files simultaneously open.
Display formats which include General, Decimal, Up to 16 Mac fonts and styles are selectable for
Scientific, Dollars, Percent. individual fields and labels.
., rile Edit Formot Detcrlbe Oelablle Search Mist Window
DlleBa.eO"erulew
components I.foo!
ComponentOf 1.1eg 1 0 - - . . allembl
Mokl1sPor\
,spertl.toe
"PerU 5
After opening the "Overview" window, you The link lines you draw establish both You can have multiple windows open
draw link lines between databases directly visual and electronic relationships between simultaneously to view all members of a
onto your Macintosh screen. your databases. linked set-which are interactive and truly
relational.
Critic's Choice
"... a powerful relational database ... uses a visual approach to information management." InloWorld
"... gives you a lot of freedom in report design; you can even import graphics." A+ Magazine
"... bridges the gap between the pretty programs and the power programs." Stewart Alsop, PC Letter
Minimum system configuration: Macintosh 512K or Macintosh Plus with one disk drive.
Turbo Pascal and SideKick are registered trademarks of Borland International, Inc. and Reflex is a
registered trademark of Borland/ Analytica. Inc. MaCintosh is a trademark of Mcintosh Laboratories. Inc. licensed
BORLAND
INTERNATIONAL
to Apple Computer with its express permission. Lisa is a registered trademark of Apple Computer. tnc. Inside
Macintosh is a copyright of Apple Computer. Inc.
Copyright 1987 Borland International BOR 0167A
Borland
Software
OBDBll fODAY I
- - - - - - - - I'
I In ,i
Orde~ I"'~' California,
I ByTo Credit I'
call I'
-------11
I
I
8OR0234 I
I
urbo Prolog, the natural language of Artificial Intelligence,
Minimum system requirements: IBM PC, Xl, AT or true compatibles. PC-DOS (MS-DOS)
2.0 or later. Requires Turbo Prolog 1.10 or higher. Dual-floppy disk drive or hard disk. S12K.
Turbo Prolog Toolbox and Turbo Prolog are trademarks 01 Borland International, Inc. Rellex is a registered Irademark
of Borland/Analytica, Inc. dBASE III is a registered trademark 01 Ashton-Tate. Lotus 1-2-3 and Symphony are registered
trademarks of Lotus Development Corp. IBM, XT, and AT are registered trademarks of International Business Machines
Corp. MS-DOS is ~ registered trademark of Microsoft Corp. BOA 0239