<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="02-class-library.css" type="text/css" title="System Class Library" charset="UTF-8"?>
<XML>
<Heading1>
<A ID="pgfId-1040657"></A>
<A ID="System Class Library"></A>
System Class Library</Heading1>
<Heading3>
<A ID="pgfId-1040661"></A>
Numbers</Heading3>
<Heading4>
<A ID="pgfId-1040658"></A>
Create a number</Heading4>
<Body1>
<A ID="pgfId-1040340"></A>
Numbers are typically created by literal numeric expressions, or by mathematical operations on numbers. Numbers in VisualWorks are real objects, instances of classes <Code>
Integer</Code>
 (really its subclasses <Code>
SmallInteger</Code>
, <Code>
LargePositiveInteger</Code>
, and <Code>
LargeNegativeInteger</Code>
), <Code>
Float</Code>
, <Code>
Fraction</Code>
, and <Code>
FixedPoint</Code>
.</Body1>
<Body1>
<A ID="pgfId-1040341"></A>
The following expressions create these numeric types and assign them to variables:</Body1>
<CodeSample>
<A ID="pgfId-1040342"></A>
x := 100							&#34;Integer&#34;
x := 5.3.							&#34;Float&#34;
x := 5.5d.						&#34;Double&#34;
x := 1/2.							&#34;Fraction&#34;
x := 99.95s.						&quot;FixedPoint&quot;
x := 1.555e3.						&#34;Float, in exponential notation&quot;
y := -3.955d2.						&#34;Double in exponential notation&quot;
x := 2r101						&#34;101 base 2&#34;
y := 16r1A						&#34;1A base 16&#34;</CodeSample>
<Heading4>
<A ID="pgfId-1040351"></A>
Arithmetic operations</Heading4>
<Body1>
<A ID="pgfId-1094773"></A>
The following expressions perform standard arithmetic operations:</Body1>
<CodeSample>
<A ID="pgfId-1040352"></A>
x + y 							&#34;Addition&#34;
x - y							&#34;Subtraction&#34;
x * y							&#34;Multiplication&#34;
x / y							&#34;Division&#34;
x // y							&#34;Divide, return integer part&quot;
x \\ y							&quot;Divide, return remainder&quot;</CodeSample>
<Heading4>
<A ID="pgfId-1040358"></A>
Round</Heading4>
<Body1>
<A ID="pgfId-1094775"></A>
The following expressions perform rounding operations:</Body1>
<CodeSample>
<A ID="pgfId-1040359"></A>
x := -5.5 rounded					&#34;Round to nearest integer&#34;
x := 5.8 floor						&quot;Round down&quot;
x := 5.2 ceiling					&quot;Round up&quot;
x := -5.8 truncated				&quot;Round toward zero&quot;
x := 5555.55555 roundTo: 0.01		&quot;Round to nearest multiple of&quot;
x := 5555.55555 truncateTo: 0.01	&#34;Truncate to nearest multiple of&#34;</CodeSample>
<Heading4>
<A ID="pgfId-1040365"></A>
Mathematical operations</Heading4>
<Body1>
<A ID="pgfId-1094785"></A>
The following expressions perform standard arithmetic operations:</Body1>
<CodeSample>
<A ID="pgfId-1040366"></A>
3 squared						&quot;Square&#34;
9 sqrt							&quot;Square root&quot;
5 ** 3							&#34;Raise to power&#34;
125 ** (1/3)						&quot;Root&quot;</CodeSample>
<Heading4>
<A ID="pgfId-1040371"></A>
Testing for equality</Heading4>
<Body1>
<A ID="pgfId-1094789"></A>
The following expressions perform various tests for equality:</Body1>
<CodeSample>
<A ID="pgfId-1040372"></A>
5.5 = 5.5							&#34;Equality&#34;
5 == 5							&#34;Identity&#34;
5 ~= 7							&quot;Not equal&quot;
5 ~~ 6							&quot;Not identical&quot;
5 &lt; 6							&quot;Less than&quot;
5&lt;= 6							&quot;Less than or equal&quot;
6 &gt; 5							&quot;Greater than&quot;
6 &gt;= 5							&#34;Greater than or equal&quot;
5 between: 1 and: 10				&quot;Inclusion in range&quot;</CodeSample>
<Heading4>
<A ID="pgfId-1040381"></A>
Get the minimum/maximum of two numbers</Heading4>
<Body1>
<A ID="pgfId-1094795"></A>
The following expressions perform minimum/maximum operations:</Body1>
<CodeSample>
<A ID="pgfId-1040382"></A>
5.5 min: 6.5						&quot;Return the minimum&quot;
5.5 max: 6.5						&quot;Return the maximum&quot;</CodeSample>
<Heading4>
<A ID="pgfId-1040384"></A>
Trigonometric functions</Heading4>
<Body1>
<A ID="pgfId-1094801"></A>
The following expressions perform trigonometric operations:</Body1>
<CodeSample>
<A ID="pgfId-1040385"></A>
x sin							&#34;Sine&#34;
x cos							&quot;Cosine&quot;
x tan							&quot;Tangent&quot;
x arcSin							&#34;Arcsine&#34;
x arcCos						&#34;Arccosine
x arcTan						&#34;Arctangent&#34;</CodeSample>
<Heading4>
<A ID="pgfId-1040391"></A>
Logarithmic functions</Heading4>
<Body1>
<A ID="pgfId-1094807"></A>
The following expressions perform logarithmic operations:</Body1>
<CodeSample>
<A ID="pgfId-1040392"></A>
x log							&quot;Base 10 log&quot;
x log: 7							&quot;Base n log&quot;
x ln								&#34;Natural log&#34;
x exp							&quot;Exponential&quot;</CodeSample>
<Heading4>
<A ID="pgfId-1040396"></A>
Test for number</Heading4>
<Body1>
<A ID="pgfId-1040397"></A>
To test if an object is a number of some kind, send a <Code>
respondsToArithmetic</Code>
 message to the object.</Body1>
<Body1>
<A ID="pgfId-1101442"></A>
If the object is a number, it responds <Code>
true</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040398"></A>
&#34;Print it&#34;
| x |
x := 55.
^x respondsToArithmetic</CodeSample>
<Heading4>
<A ID="pgfId-1040402"></A>
Test for integer</Heading4>
<Body1>
<A ID="pgfId-1040403"></A>
To test if a number is an integer, send an <Code>
isInteger</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040404"></A>
| x |
x := 55.
^x isInteger</CodeSample>
<Heading4>
<A ID="pgfId-1040407"></A>
Test for even or odd number</Heading4>
<Body1>
<A ID="pgfId-1040408"></A>
To test if a number is even, send an <Code>
even</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040409"></A>
| x |
x := 56.
^x even</CodeSample>
<Body1>
<A ID="pgfId-1040413"></A>
To test if a number is odd, send an <Code>
odd</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040414"></A>
| x |
x := 55.
^x odd</CodeSample>
<Heading4>
<A ID="pgfId-1040417"></A>
Test for zero</Heading4>
<Body1>
<A ID="pgfId-1040418"></A>
To test if a number is zero, send an <Code>
isZero</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040419"></A>
| x |
x := 0.
^x isZero</CodeSample>
<Heading4>
<A ID="pgfId-1040422"></A>
Test for zero or greater</Heading4>
<Body1>
<A ID="pgfId-1040423"></A>
Send a <Code>
positive</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040424"></A>
| x |
x := 55.
^x positive</CodeSample>
<Heading4>
<A ID="pgfId-1040427"></A>
Test for greater than zero</Heading4>
<Body1>
<A ID="pgfId-1040428"></A>
Send a <Code>
strictlyPositive</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040429"></A>
| x |
x := 55.
^x strictlyPositive</CodeSample>
<Heading4>
<A ID="pgfId-1040432"></A>
Test for less than zero</Heading4>
<Body1>
<A ID="pgfId-1040433"></A>
Send a <Code>
negative</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040434"></A>
| x |
x := -55.
^x negative</CodeSample>
<Heading4>
<A ID="pgfId-1040437"></A>
Get a number&#39;s sign as a multiplier</Heading4>
<Body1>
<A ID="pgfId-1040438"></A>
Send a <Code>
sign</Code>
 message to the number. The returned value is <Code>
1</Code>
 when the number is greater than zero, <Code>
-1</Code>
 when the number is less than zero, or 0.</Body1>
<CodeSample>
<A ID="pgfId-1040439"></A>
| x y |
x := -55.
y := x abs.
^y * (x sign)</CodeSample>
<Heading4>
<A ID="pgfId-1040443"></A>
Reverse a number&#39;s sign</Heading4>
<Body1>
<A ID="pgfId-1040444"></A>
Send a <Code>
negated</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040445"></A>
| x |
x := -55.
^x negated</CodeSample>
<Heading4>
<A ID="pgfId-1040448"></A>
Change a number&#39;s type</Heading4>
<Body1>
<A ID="pgfId-1040449"></A>
To change between many types of numbers, you merely send the message <Code>
asType</Code>
 to the number, where <I>
Type</I>
 is the number type you wish to change to.</Body1>
<CodeSample>
<A ID="pgfId-1040450"></A>
99.95 asFixedPoint: 2.				&#34;To fixed point with precision n&#34;
55 asFloat						&#34;To single-precision floating point&#34;
55 asDouble						&#34;To double-precision floating point&#34;
55.5 asRational					&#34;To rational (integer or fraction)&#34;</CodeSample>
<Heading4>
<A ID="pgfId-1040454"></A>
Get absolute value</Heading4>
<Body1>
<A ID="pgfId-1040455"></A>
Send an <Code>
abs</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040456"></A>
| x |
x := -55.5.
^x abs</CodeSample>
<Heading4>
<A ID="pgfId-1040459"></A>
Get reciprocal</Heading4>
<Body1>
<A ID="pgfId-1040460"></A>
Send a <Code>
reciprocal</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040461"></A>
| x |
x := 0.5.
^x reciprocal</CodeSample>
<Heading4>
<A ID="pgfId-1040464"></A>
Convert between degrees and radians</Heading4>
<Body1>
<A ID="pgfId-1040465"></A>
To convert from degrees to radians, send a <Code>
degreesToRadians</Code>
 message to the number:</Body1>
<CodeSample>
<A ID="pgfId-1040466"></A>
x degreesToRadians</CodeSample>
<Body1>
<A ID="pgfId-1040467"></A>
To convert from radians to degree, send a <Code>
radiansToDegrees</Code>
 message to the number:</Body1>
<CodeSample>
<A ID="pgfId-1040468"></A>
x radiansToDegrees</CodeSample>
<Heading4>
<A ID="pgfId-1040469"></A>
Convert to a point</Heading4>
<Body1>
<A ID="pgfId-1040470"></A>
Send an <Code>
asPoint</Code>
 message to the number. The returned point has the number as both its <Code>
x</Code>
 and <Code>
y</Code>
 coordinates.</Body1>
<CodeSample>
<A ID="pgfId-1040471"></A>
| x |
x := 55.
^x asPoint</CodeSample>
<Heading4>
<A ID="pgfId-1040474"></A>
Create a point</Heading4>
<Body1>
<A ID="pgfId-1040475"></A>
Send an <Code>
@</Code>
 message to a number to be the <Code>
x</Code>
 coordinate with another number as the argument to be the <Code>
y</Code>
 coordinate.</Body1>
<CodeSample>
<A ID="pgfId-1040476"></A>
| x y |
x := 55.
y := 100.
^x @ y</CodeSample>
<Heading4>
<A ID="pgfId-1040480"></A>
Create a character from a numeric value</Heading4>
<Body1>
<A ID="pgfId-1040481"></A>
Send an <Code>
asCharacter</Code>
 message to an integer. If the receiver is the numeric representation of a valid character, the character is returned; otherwise, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040482"></A>
| x |
x := 55.
^x asCharacter</CodeSample>
<Heading4>
<A ID="pgfId-1040485"></A>
Convert a number to a string</Heading4>
<Body1>
<A ID="pgfId-1040486"></A>
Send a <Code>
printString</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040487"></A>
| x |
x := 55.
^x printString</CodeSample>
<Body1>
<A ID="pgfId-1040490"></A>
To convert to a string but with a base other than 10, send a <Code>
printStringRadix:</Code>
 message to the number with the base as argument.</Body1>
<CodeSample>
<A ID="pgfId-1040491"></A>
| x |
x := 55.
^x printStringRadix: 16</CodeSample>
<Heading4>
<A ID="pgfId-1040494"></A>
Greatest common divisor</Heading4>
<Body1>
<A ID="pgfId-1040495"></A>
Send a <Code>
gcd:</Code>
 message to one of the two numbers. The argument is the second number.</Body1>
<CodeSample>
<A ID="pgfId-1040496"></A>
| x y |
x := 5.
y := 10.
^x gcd: y</CodeSample>
<Heading4>
<A ID="pgfId-1040500"></A>
Least common multiple</Heading4>
<Body1>
<A ID="pgfId-1040501"></A>
Send an <Code>
lcm:</Code>
 message to one of the two numbers. The argument is the second number.</Body1>
<CodeSample>
<A ID="pgfId-1040502"></A>
| x y |
x := 5.
y := 8.
^x lcm: y</CodeSample>
<Heading4>
<A ID="pgfId-1040507"></A>
Factorial of a number</Heading4>
<Body1>
<A ID="pgfId-1040508"></A>
Send a <Code>
factorial</Code>
 message to the number.</Body1>
<CodeSample>
<A ID="pgfId-1040510"></A>
| x |
x := 5.
^x factorial</CodeSample>
<Heading4>
<A ID="pgfId-1040514"></A>
Random Numbers</Heading4>
<Body1>
<A ID="pgfId-1040515"></A>
Generate random numbers with an instance of <Code>
Random</Code>
. A random number is a kind of stream, so it responds to stream messages such as next message to get the next number in the sequence.</Body1>
<Body1>
<A ID="pgfId-1040516"></A>
VisualWorks provides seven different streams of random numbers, identified as generators 1 through 7.</Body1>
<Heading4>
<A ID="pgfId-1040518"></A>
Generate a random number between 0 and 1</Heading4>
<StepStart>
<A ID="pgfId-1040520"></A>
Create a random stream of numbers by sending <Code>
new</Code>
 to the <Code>
Random</Code>
 class.</StepStart>
<StepCont>
<A ID="pgfId-1040522"></A>
Get the next number in the stream by sending <Code>
new</Code>
 to the random stream.</StepCont>
<CodeSample>
<A ID="pgfId-1040523"></A>
| randomStream x |
randomStream := Random new.
x := randomStream next.
^x</CodeSample>
<Heading4>
<A ID="pgfId-1040527"></A>
Generate a random integer in a specified range</Heading4>
<Body1>
<A ID="pgfId-1040528"></A>
A random stream returns fractional values between 0 and 1. To get a random stream of integers, you must convert the stream values. The example converts random values to a range.</Body1>
<StepStart>
<A ID="pgfId-1040530"></A>
Create a random stream of numbers by sending <Code>
new</Code>
 to <Code>
Random</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1040532"></A>
Define the beginning and ending values of the range.</StepCont>
<StepCont>
<A ID="pgfId-1040534"></A>
Derive the extent of the range.</StepCont>
<StepCont>
<A ID="pgfId-1040536"></A>
Get the next value from the random stream, then multiply it by the extent of the range, add the range&#39;s beginning value, and round the result.</StepCont>
<CodeSample>
<A ID="pgfId-1040537"></A>
| randomStream rangeStart rangeEnd rangeExtent x |
randomStream := Random new.
rangeStart := 1.
rangeEnd := 52.
rangeExtent := rangeEnd - rangeStart.
x := (randomStream next * rangeExtent + rangeStart) rounded.
^x</CodeSample>
<Heading4>
<A ID="pgfId-1040544"></A>
Reproduce a &#34;random&#34; sequence</Heading4>
<Body1>
<A ID="pgfId-1040545"></A>
To reproduce a specific sequence, you can specify a <BookTitle>
seed</BookTitle>
 value. the seed value can also be used to generate additional random features. </Body1>
<Body1>
<A ID="pgfId-1040547"></A>
Create the random stream by sending a <Code>
fromGenerator:seededWith:</Code>
 message to the <Code>
Random</Code>
 class. The first argument is an integer from 1 to 7, identifying one of the seven streams that VisualWorks provides. The second argument is a number that is used to select a position in the stream.</Body1>
<CodeSample>
<A ID="pgfId-1040548"></A>
| rangeStart rangeEnd rangeExtent randomStreamsequence |
rangeStart := 1.
rangeEnd := 52.
rangeExtent := rangeEnd - rangeStart.

randomStream := Random 
			fromGenerator: 1
			seededWith: 1.</CodeSample>
<Heading3>
<A ID="pgfId-1040556"></A>
Numeric Constants</Heading3>
<Heading4>
<A ID="pgfId-1040557"></A>
Zero</Heading4>
<Body1>
<A ID="pgfId-1040558"></A>
Send a <Code>
zero</Code>
 message to any numeric class. The zero value returned is an instance of the target class. </Body1>
<Body1>
<A ID="pgfId-1040560"></A>
To get a zero of the same class as an existing number, first get the class of that number by sending a class message to it and then send <Code>
zero</Code>
 to the resulting object.</Body1>
<CodeSample>
<A ID="pgfId-1040561"></A>
| x y z |
x := Float zero.
y := Integer zero.
z := x class zero.
^Array with: x with: y with: z</CodeSample>
<Heading4>
<A ID="pgfId-1040566"></A>
One</Heading4>
<Body1>
<A ID="pgfId-1040567"></A>
Send a <Code>
unity</Code>
 message to any numeric class. The value returned is an instance of the target class. </Body1>
<Body1>
<A ID="pgfId-1040568"></A>
To get a value of the same class as an existing number, first get the class of that number by sending a <Code>
class</Code>
 message to it and then send <Code>
unity</Code>
 to the resulting object.</Body1>
<CodeSample>
<A ID="pgfId-1040569"></A>
| x y z |
x := Float unity.
y := Integer unity.
z := x class unity.
^Array with: x with: y with: z</CodeSample>
<Heading4>
<A ID="pgfId-1040574"></A>
Pi</Heading4>
<Body1>
<A ID="pgfId-1040576"></A>
Send a <Code>
pi</Code>
 message to the <Code>
Float</Code>
 or <Code>
Double</Code>
 class. Note that <Code>
Float</Code>
 returns a single-precision version while <Code>
Double</Code>
 returns a double-precision version.</Body1>
<Body1>
<A ID="pgfId-1040578"></A>
To get a pi of the same class as an existing number, first get the class of that number and then send <Code>
pi</Code>
 to the resulting object.</Body1>
<CodeSample>
<A ID="pgfId-1040579"></A>
| x y z |
x := Float pi.
y := Double pi.
z := x class pi.
^Array with: x with: y with: z</CodeSample>
<Heading4>
<A ID="pgfId-1040584"></A>
Get the largest SmallInteger</Heading4>
<Body1>
<A ID="pgfId-1040585"></A>
This value is frequently used to specify an arbitrarily large number whose exact value is not important. </Body1>
<Body1>
<A ID="pgfId-1040586"></A>
Send a <Code>
maxVal</Code>
 message to the <Code>
SmallInteger</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1040587"></A>
| x |
x := SmallInteger maxVal.
^x</CodeSample>
<Heading4>
<A ID="pgfId-1040590"></A>
Get the smallest SmallInteger</Heading4>
<Body1>
<A ID="pgfId-1040591"></A>
Send a <Code>
minVal</Code>
 message to the <Code>
SmallInteger</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1040592"></A>
| x |
x := SmallInteger minVal.
^x</CodeSample>
<Body1>
<A ID="pgfId-1040057"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040884"></A>
Dates</Heading3>
<Heading4>
<A ID="pgfId-1040885"></A>
Create today&#39;s date</Heading4>
<Body1>
<A ID="pgfId-1040886"></A>
Send a <Code>
today</Code>
 message to the <Code>
Date</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1040887"></A>
| date |
date := Date today.
^date</CodeSample>
<Heading4>
<A ID="pgfId-1040890"></A>
Create a date from a string</Heading4>
<Body1>
<A ID="pgfId-1040891"></A>
Send a <Code>
readFrom:</Code>
 message to <Code>
Date</Code>
 with a readStream on a string containing the month, day, and year in any of several formats as shown.  When the string uses a two-digit abbreviation for the year a <Code>
Date</Code>
 is created for the current century today.  To avoid any ambiguity create a <Code>
Date</Code>
 using a four-digit year.</Body1>
<CodeSample>
<A ID="pgfId-1040892"></A>
| dates |
dates := OrderedCollection new.

dates
		add: (Date readFrom: 'January 31, 1994' readStream);
		add: (Date readFrom: '31 January 1994' readStream);
		add: (Date readFrom: '1/31/94' readStream);
		add: (Date readFrom: '1.31.1994' readStream);
		add: (Date readFrom: '1-31-1994' readStream).
^dates</CodeSample>
<Heading4>
<A ID="pgfId-1040903"></A>
Create a date from a day, month, and year</Heading4>
<Body1>
<A ID="pgfId-1040904"></A>
Send a <Code>
newDay:monthNumber:year:</Code>
 message to the <Code>
Date</Code>
 class. The newDay argument is the day number. The <Code>
monthNumber</Code>
 argument is the month number. The <Code>
year</Code>
 argument is the year, with or without the century part.  If a two-digit year is provided then it is applied to the current century today.  Use a four-digit year to avoid ambiguity.</Body1>
<CodeSample>
<A ID="pgfId-1040905"></A>
date1 := Date
		newDay: 31
		monthNumber: 1
		year: 1994.</CodeSample>
<Body1>
<A ID="pgfId-1040909"></A>
To specify the month by name, send a <Code>
newDay:month:year:</Code>
 message to <Code>
Date</Code>
, with the month argument as the unique first letters of a month name expressed as a <Code>
Symbol</Code>
. </Body1>
<CodeSample>
<A ID="pgfId-1040910"></A>
date2 := Date
		newDay: 31
		month: #Jan
		year: 1994.</CodeSample>
<Heading4>
<A ID="pgfId-1040914"></A>
Create a date by days since January 1</Heading4>
<Body1>
<A ID="pgfId-1040915"></A>
During a series of date computations that span several months in the same year, it can be helpful to treat a date as the number of days that it represents since the beginning of the year. After the computation is completed, you can convert the day-count back into a date.</Body1>
<Body1>
<A ID="pgfId-1040916"></A>
Send a <Code>
newDay:year:</Code>
 message to <Code>
Date</Code>
. The first argument is the number of days from the beginning of the year. The second argument is the year number.</Body1>
<CodeSample>
<A ID="pgfId-1040917"></A>
| date |
date := Date
		newDay: 32
		year: 1994.
^date</CodeSample>
<Heading4>
<A ID="pgfId-1040922"></A>
Create a date by days since 1901</Heading4>
<Body1>
<A ID="pgfId-1040923"></A>
During a series of date computations that span multiple years, it can be helpful to treat a date as the number of days that it represents since 1901 (in effect, the beginning of recorded time). After the computation is completed, you can convert the day-count back into a date.</Body1>
<Body1>
<A ID="pgfId-1040924"></A>
Send a <Code>
fromDays:</Code>
 message to <Code>
Date</Code>
. The argument is the number of days from the beginning of 1901. </Body1>
<CodeSample>
<A ID="pgfId-1040925"></A>
| date |
date := Date
		fromDays: (94 * 366).
^date</CodeSample>
<Heading4>
<A ID="pgfId-1040929"></A>
Get the day of the week</Heading4>
<Body1>
<A ID="pgfId-1040930"></A>
Send a <Code>
weekday</Code>
 message to a date. The name of the week day is expressed as a <Code>
Symbol</Code>
, such as <Code>
#Friday</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040931"></A>
| date |
date := Date today.
^date weekday</CodeSample>
<Heading4>
<A ID="pgfId-1040934"></A>
Get the day of the month</Heading4>
<Body1>
<A ID="pgfId-1040935"></A>
Send a <Code>
dayOfMonth</Code>
 message to a date. The day number within the month is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040936"></A>
| date |
date := Date today.
^date dayOfMonth</CodeSample>
<Heading4>
<A ID="pgfId-1040939"></A>
Get the day of the year</Heading4>
<Body1>
<A ID="pgfId-1040940"></A>
Send a <Code>
day</Code>
 message to a date. The day number within the year is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040941"></A>
| date |
date := Date today.
^date day</CodeSample>
<Heading4>
<A ID="pgfId-1040944"></A>
Count the days since 1901 began</Heading4>
<Body1>
<A ID="pgfId-1040945"></A>
Send an <Code>
asDays</Code>
 message to a date. The day number within the century is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040946"></A>
| date |
date := Date today.
^date asDays</CodeSample>
<Heading4>
<A ID="pgfId-1040949"></A>
Count the seconds since 1901 began</Heading4>
<Body1>
<A ID="pgfId-1040950"></A>
Send an <Code>
asSeconds</Code>
 message to a date. The number of seconds elapsed prior to the date in the century is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040951"></A>
| date |
date := Date today.
^date asSeconds</CodeSample>
<Heading4>
<A ID="pgfId-1040954"></A>
Get the name of the month</Heading4>
<Body1>
<A ID="pgfId-1040955"></A>
Send a <Code>
monthName</Code>
 message to a date. The month name is expressed as a <Code>
Symbol</Code>
, as in <Code>
#January</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040956"></A>
| date |
date := Date today.
^date monthName</CodeSample>
<Heading4>
<A ID="pgfId-1040959"></A>
Get the number of the month</Heading4>
<Body1>
<A ID="pgfId-1040960"></A>
Send a <Code>
monthIndex</Code>
 message to a date. </Body1>
<CodeSample>
<A ID="pgfId-1040961"></A>
| date |
date := Date today.
^date monthIndex</CodeSample>
<Heading4>
<A ID="pgfId-1040964"></A>
Count the days in the month</Heading4>
<Body1>
<A ID="pgfId-1040965"></A>
Send a <Code>
daysInMonth</Code>
 message to a date.</Body1>
<CodeSample>
<A ID="pgfId-1040966"></A>
| date |
date := Date today.
^date daysInMonth</CodeSample>
<Heading4>
<A ID="pgfId-1040969"></A>
Get the year number from a date</Heading4>
<Body1>
<A ID="pgfId-1040970"></A>
Send a <Code>
year</Code>
 message to a date.</Body1>
<CodeSample>
<A ID="pgfId-1040971"></A>
| date |
date := Date today.
^date year</CodeSample>
<Heading4>
<A ID="pgfId-1040974"></A>
Count the days in a year</Heading4>
<Body1>
<A ID="pgfId-1040975"></A>
Send a <Code>
daysInYear</Code>
 message to a date. </Body1>
<CodeSample>
<A ID="pgfId-1040976"></A>
| date |
date := Date today.
^date daysInYear</CodeSample>
<Heading4>
<A ID="pgfId-1040979"></A>
Count the days remaining in the year</Heading4>
<Body1>
<A ID="pgfId-1040980"></A>
Send a <Code>
daysLeftInYear</Code>
 message to a date. </Body1>
<CodeSample>
<A ID="pgfId-1040981"></A>
| date |
date := Date today.
^date daysLeftInYear</CodeSample>
<Heading4>
<A ID="pgfId-1040984"></A>
Test for leap year</Heading4>
<Body1>
<A ID="pgfId-1040985"></A>
Send a <Code>
leap</Code>
 message to a date. The result is 1 in a leap year and zero otherwise.</Body1>
<CodeSample>
<A ID="pgfId-1040986"></A>
| date |
date := Date today.
^date leap</CodeSample>
<Heading4>
<A ID="pgfId-1040989"></A>
Add days to a date</Heading4>
<Body1>
<A ID="pgfId-1040990"></A>
Send an <Code>
addDays:</Code>
 message to a date. The argument is the number of days to be added, and can be a negative number.</Body1>
<CodeSample>
<A ID="pgfId-1040991"></A>
| date daysToAdd |
date := Date today.
daysToAdd := 60.
^date addDays: daysToAdd</CodeSample>
<Heading4>
<A ID="pgfId-1040995"></A>
Subtract days from a date</Heading4>
<Body1>
<A ID="pgfId-1040996"></A>
Send a <Code>
subtractDays:</Code>
 message to a date. The argument is the number of days to be subtracted, and it can be a negative number.</Body1>
<CodeSample>
<A ID="pgfId-1040997"></A>
| date daysToSubtract |
date := Date today.
daysToSubtract := 60.
^date subtractDays: daysToSubtract</CodeSample>
<Heading4>
<A ID="pgfId-1041001"></A>
Get the number of days between two dates</Heading4>
<Body1>
<A ID="pgfId-1041002"></A>
Send a <Code>
subtractDate:</Code>
 message to a date. The argument is the date to be subtracted, which can be either before or after the first date.</Body1>
<CodeSample>
<A ID="pgfId-1041003"></A>
| date1 date2 |
date1 := Date today.
date2 := Date readFromString: '31 December 1999'.
^date1 subtractDate: date2</CodeSample>
<Heading4>
<A ID="pgfId-1041007"></A>
Get a previous day of the week</Heading4>
<Body1>
<A ID="pgfId-1041008"></A>
Send a <Code>
previous:</Code>
 message to a date. The argument is the name of the preceding weekday whose date you desire, expressed as a <Code>
Symbol</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041009"></A>
| date dayOfWeek |
date := Date today.
dayOfWeek := #Monday.
^date previous: dayOfWeek</CodeSample>
<Heading4>
<A ID="pgfId-1041013"></A>
Test/compare dates</Heading4>
<Body1>
<A ID="pgfId-1041014"></A>
Dates respond to many of the same test methods as numbers. Return values are booleans.</Body1>
<CodeSample>
<A ID="pgfId-1041015"></A>
date1 = date2									&#34;equality&#34;
date1 ~= date2								&quot;non-equality&quot;
date1 &lt; date2									&quot;earlier than&quot;
date1 &lt;= date2								&quot;earlier or equal&quot;
date1 &gt; date2									&quot;later than
date1 &gt;= date2								&quot;later or equal&quot;</CodeSample>
<Heading4>
<A ID="pgfId-1041022"></A>
Format a Date</Heading4>
<Body1>
<A ID="pgfId-1041023"></A>
A date can be formatted by specifying an array of format arguments sent with the <Code>
printFormat:</Code>
 message. The six elements are:</Body1>
<Bullet1>
<A ID="pgfId-1041024"></A>
Day&#39;s position in the string (1, 2, or 3)</Bullet1>
<Bullet1>
<A ID="pgfId-1041025"></A>
Month&#39;s position in the string (1, 2, or 3)</Bullet1>
<Bullet1>
<A ID="pgfId-1041026"></A>
Year&#39;s position in the string (1, 2, or 3)</Bullet1>
<Bullet1>
<A ID="pgfId-1041048"></A>
The separator character</Bullet1>
<Bullet1>
<A ID="pgfId-1041049"></A>
Month&#39;s format: 1 (numeric), 2 (abbreviation), or 3 (full name)</Bullet1>
<Bullet1>
<A ID="pgfId-1041029"></A>
Year&#39;s format: 1 (with century) or 2 (without century)</Bullet1>
<Body1>
<A ID="pgfId-1041030"></A>
Send a <Code>
printFormat:</Code>
 message to the date. The argument is an array of six elements.</Body1>
<CodeSample>
<A ID="pgfId-1041031"></A>
| date |
date := Date today.
^date printFormat: #(2 1 3 $- 3 1)</CodeSample>
<Body1>
<A ID="pgfId-1029452"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040893"></A>
Times</Heading3>
<Heading4>
<A ID="pgfId-1040894"></A>
Create the current time</Heading4>
<Body1>
<A ID="pgfId-1040895"></A>
Send a <Code>
now</Code>
 message to the <Code>
Time</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1040896"></A>
| time |
time := Time now.
^time</CodeSample>
<Heading4>
<A ID="pgfId-1040899"></A>
Create a time from a string</Heading4>
<Body1>
<A ID="pgfId-1040900"></A>
Send a <Code>
readFromString:</Code>
 message to <Code>
Time</Code>
. The argument is a string containing the hours, minutes, and seconds, separated by colons. The minutes and/or seconds can be omitted. The &#34;am/pm&#34; designation can be omitted (&#34;am&#34; is the default) and can be in upper- or lowercase.</Body1>
<CodeSample>
<A ID="pgfId-1040901"></A>
| times |
times := OrderedCollection new.

times
		add: (Time readFromString: '3:47:26 pm');
		add: (Time readFromString: '03:47');
		add: (Time readFromString: '::26 PM').
^times</CodeSample>
<Heading4>
<A ID="pgfId-1040909"></A>
Create a time by seconds since midnight</Heading4>
<Body1>
<A ID="pgfId-1040910"></A>
Send a <Code>
fromSeconds:</Code>
 message to <Code>
Time</Code>
. The argument is the number of seconds that have elapsed since midnight.</Body1>
<CodeSample>
<A ID="pgfId-1040911"></A>
| time |
time := Time fromSeconds: (60 * 60 * 4).
^time</CodeSample>
<Heading4>
<A ID="pgfId-1040914"></A>
Get seconds since the minute began</Heading4>
<Body1>
<A ID="pgfId-1040915"></A>
Send a <Code>
seconds</Code>
 message to the time.</Body1>
<CodeSample>
<A ID="pgfId-1040916"></A>
| time |
time := Time now.
^time seconds.</CodeSample>
<Heading4>
<A ID="pgfId-1040919"></A>
Get seconds since the day began</Heading4>
<Body1>
<A ID="pgfId-1040920"></A>
Send an <Code>
asSeconds</Code>
 message to the time.</Body1>
<CodeSample>
<A ID="pgfId-1040921"></A>
| time |
time := Time now.
^time asSeconds.</CodeSample>
<Heading4>
<A ID="pgfId-1040924"></A>
Get seconds since 1901</Heading4>
<Body1>
<A ID="pgfId-1040925"></A>
In time computations that span multiple days, it is sometimes convenient to represent each time as the number of seconds since 1901 began. </Body1>
<Body1>
<A ID="pgfId-1040926"></A>
Send a <Code>
totalSeconds</Code>
 message to <Code>
Time</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040927"></A>
| x |
x := Time totalSeconds.
^x</CodeSample>
<Heading4>
<A ID="pgfId-1040930"></A>
Getting seconds since the clock was reset</Heading4>
<Body1>
<A ID="pgfId-1040931"></A>
When you want to measure the number of milliseconds required by some process, you can take a reading of the millisecond clock both before and after the process. This reading is also sometimes used as a simple random number for temporary file naming and as a seed value for a random stream.</Body1>
<Body1>
<A ID="pgfId-1040932"></A>
Send a <Code>
millisecondClockValue</Code>
 message to <Code>
Time</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040933"></A>
&quot;Time 1000 repetitions of a block&quot;
| x |
x := Time millisecondClockValue.
1000 timesRepeat: 
		[|splitSecondCount|
   &quot;Answer milliseconds as a number between 0 and 999&quot;
		  splitSecondCount:=Time millisecondClockValue \\ 1000.
		  splitSecondCount &lt; 250
			ifTrue:[&quot;Spend no more than one quarter of any second in this block.
				        Show the millisecond count in the Transcript&quot;
				        Transcript show: splitSecondCount printString;cr]].
^Time millisecondClockValue - x</CodeSample>
<Heading4>
<A ID="pgfId-1040945"></A>
Get minutes since the hour began</Heading4>
<Body1>
<A ID="pgfId-1040946"></A>
Send a <Code>
minutes</Code>
 message to an instance of class <Code>
Time</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040947"></A>
| time |
time := Time now.
^time minutes.</CodeSample>
<Heading4>
<A ID="pgfId-1040950"></A>
Get hours since the day began</Heading4>
<Body1>
<A ID="pgfId-1040951"></A>
Send an <Code>
hours</Code>
 message to an instance of class <Code>
Time</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040952"></A>
| time |
time := Time now.
^time hours.</CodeSample>
<Heading4>
<A ID="pgfId-1040955"></A>
Add times and dates</Heading4>
<Body1>
<A ID="pgfId-1040956"></A>
Send an <Code>
addTime:</Code>
 message to an instance of class <Code>
Time</Code>
. The argument is either a <Code>
Time</Code>
 or a <Code>
Date</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040957"></A>
| time1 time2 |
time1 := Time readFromString: '5'.
time2 := Time readFromString: '8:51:39 am'.
^time1 addTime: time2</CodeSample>
<Heading4>
<A ID="pgfId-1040961"></A>
Subtract times and dates</Heading4>
<Body1>
<A ID="pgfId-1041082"></A>
Send an <Code>
subtractTime:</Code>
 message to an instance of class <Code>
Time</Code>
. The argument is either a <Code>
Time</Code>
 or a <Code>
Date</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040963"></A>
| time1 time2 |
time1 := Time readFromString: '5'.
time2 := Time readFromString: '8:51:39 am'.
^time2 subtractTime: time1</CodeSample>
<Heading4>
<A ID="pgfId-1040967"></A>
Create a time stamp</Heading4>
<Body1>
<A ID="pgfId-1040968"></A>
A time stamp is a common way to record the date and time that an event occurred. The <Code>
Time</Code>
 class provides a <Code>
dateAndTimeNow</Code>
 method returns an array containing two elements: the current date and the present time. </Body1>
<Body1>
<A ID="pgfId-1040971"></A>
Send a <Code>
dateAndTimeNow</Code>
 message to the <Code>
Time</Code>
 class. </Body1>
<CodeSample>
<A ID="pgfId-1040972"></A>
| dateTime |
dateTime := Time dateAndTimeNow.
^(dateTime at: 1) printString, ' ', (dateTime at: 2) printString.</CodeSample>
<Heading4>
<A ID="pgfId-1040975"></A>
Time a block of code</Heading4>
<Body1>
<A ID="pgfId-1040976"></A>
During the optimization phase of application development, it is useful to compare the run times of alternate implementations. A profiler tool, such as that provided in the Advanced Tools parcel, provides this information. A simpler utility is provided by the <Code>
Time</Code>
 class <Code>
millisecondsToRun:</Code>
 method.  This method may be used to determine the clock time in milliseconds to execute a block containing one or more Smalltalk statements.</Body1>
<StepStart>
<A ID="pgfId-1040978"></A>
Create a <Code>
BlockClosure</Code>
 containing one or more expressions to be tested. Repeating the expressions through <Code>
timesRepeat:</Code>
 usually improves the validity of the comparison.</StepStart>
<StepCont>
<A ID="pgfId-1040980"></A>
Send a <Code>
millisecondsToRun:</Code>
 message to the <Code>
Time</Code>
 class. The argument is the block you created in step 1.</StepCont>
<StepCont>
<A ID="pgfId-1040982"></A>
Repeat steps 1 and 2 for the second version of the code. If the second version is not ready yet, you can simply record the value from step 2 for later comparison.</StepCont>
<CodeSample>
<A ID="pgfId-1040983"></A>
| block1 block2 ms1 ms2 |

&quot;Test the speed of Time now and Date today.&quot;
block1 := [100 timesRepeat: [Time now. Date today]].
ms1 := Time
		millisecondsToRun: block1.

&quot;Test the speed of dateAndTimeNow, which does the same thing.&quot;
block2 := [100 timesRepeat: [Time dateAndTimeNow]].
ms2 := Time
		millisecondsToRun: block2.

^ms1 printString, '								', ms2 printString</CodeSample>
<Heading4>
<A ID="pgfId-1040996"></A>
Install a time zone as the system default</Heading4>
<Body1>
<A ID="pgfId-1040997"></A>
On machines that report Greenwich Mean Time (GMT) rather than local time, the <Code>
Time</Code>
 class converts GMT to local time with the aid of another class, <Code>
TimeZone</Code>
. A <Code>
TimeZone</Code>
 stores an offset from GMT for local time. </Body1>
<StepStart>
<A ID="pgfId-1041048"></A>
Create a new instance of <Code>
TimeZone</Code>
 by sending a <Code>
timeDifference:DST:at:from:to:startDay:</Code>
 message to the <Code>
TimeZone</Code>
 class, where:</StepStart>
<Bullet1>
<A ID="pgfId-1041049"></A>
<Code>
timeDifference</Code>
 is the offset in hours from GMT.</Bullet1>
<Bullet1>
<A ID="pgfId-1041050"></A>
<Code>
DST</Code>
 is the number of hours by which DST differs.</Bullet1>
<Bullet1>
<A ID="pgfId-1041002"></A>
<Code>
at</Code>
 is the number of hours after midnight at which DST begins and ends.</Bullet1>
<Bullet1>
<A ID="pgfId-1041003"></A>
<Code>
from</Code>
 is the number of the day on which DST begins in a nonleap year (it will be adjusted automatically during leap years).</Bullet1>
<Bullet1>
<A ID="pgfId-1041004"></A>
<Code>
to</Code>
 is the number of the day on which DST ends in a nonleap year.</Bullet1>
<Bullet1>
<A ID="pgfId-1041005"></A>
<Code>
startDay</Code>
 is the day of the week on which DST begins and ends.</Bullet1>
<StepCont>
<A ID="pgfId-1041007"></A>
Send a <Code>
setDefaultTimeZone:</Code>
 message to the <Code>
TimeZone</Code>
 class. The argument is the time zone you created in step 1.</StepCont>
<StepCont>
<A ID="pgfId-1041008"></A>
With the time zone set, se the <A href="03-tools.xml#id(Launcher)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">Launcher</A>&#39;s <UI-Label>
File-&gt;Save As...</UI-Label>
 command to save your image.</StepCont>
<CodeSample>
<A ID="pgfId-1041009"></A>
| newZone |
newZone := TimeZone
		timeDifference: -8
		DST: 1
		at: 2
		from: 97
		to: 304
		startDay: #Sunday.

TimeZone setDefaultTimeZone: newZone.</CodeSample>
<Heading4>
<A ID="pgfId-1041019"></A>
Install a null time zone</Heading4>
<Body1>
<A ID="pgfId-1041020"></A>
A null time zone does not alter the time returned by your computer.</Body1>
<StepStart>
<A ID="pgfId-1041022"></A>
Send a <Code>
setDefaultTimeZone:</Code>
 message to the <Code>
TimeZone</Code>
 class. The argument is the time zone you created in step 1.</StepStart>
<StepCont>
<A ID="pgfId-1041292"></A>
With the time zone set, se the <A href="03-tools.xml#id(Launcher)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">Launcher</A>&#39;s <UI-Label>
File-&gt;Save As...</UI-Label>
 command to save your image.</StepCont>
<CodeSample>
<A ID="pgfId-1041024"></A>
| nullZone |
nullZone := TimeZone null.
TimeZone setDefaultTimeZone: nullZone.</CodeSample>
<Heading4>
<A ID="pgfId-1041028"></A>
Set the time zone weekday</Heading4>
<StepStart>
<A ID="pgfId-1041030"></A>
Get the default time zone by sending a <Code>
default</Code>
 message to the <Code>
TimeZone</Code>
 class.</StepStart>
<StepCont>
<A ID="pgfId-1041032"></A>
Send a <Code>
weekDayToStartDST</Code>
 message to the default time zone. The argument is the name of the day on which DST is to begin and end, in the form of a <Code>
Symbol</Code>
.</StepCont>
<StepCont>
<A ID="pgfId-1041303"></A>
With the time zone set, se the <A href="03-tools.xml#id(Launcher)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">Launcher</A>&#39;s <UI-Label>
File-&gt;Save As...</UI-Label>
 command to save your image.</StepCont>
<CodeSample>
<A ID="pgfId-1041034"></A>
| zone |
zone := TimeZone default.
zone weekDayToStartDST: #Saturday.</CodeSample>
<Body1>
<A ID="pgfId-1029452"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040364"></A>
Collections</Heading3>
<Heading4>
<A ID="pgfId-1040365"></A>
Create an empty collection</Heading4>
<Body1>
<A ID="pgfId-1040366"></A>
Send a <Code>
new</Code>
 message to the desired collection class (in the example, <Code>
List</Code>
).</Body1>
<CodeSample>
<A ID="pgfId-1040367"></A>
| list |
list := List new.

list add: 'Leonardo';
		add: 'Michelangelo';
		add: 'Donatello';
		add: 'Raphael'.
^list.</CodeSample>
<Heading4>
<A ID="pgfId-1040375"></A>
Create a collection of a set size</Heading4>
<Body1>
<A ID="pgfId-1040376"></A>
Send a <Code>
new:</Code>
 message to the desired collection class (typically <Code>
Array</Code>
, but useful with other types of collections to avoid time-consuming grow operations as elements are added).</Body1>
<CodeSample>
<A ID="pgfId-1040377"></A>
| array |
array := Array new: 4.

array at: 1 put: 'Leonardo';
		at: 2 put: 'Michelangelo';
		at: 3 put: 'Donatello';
		at: 4 put: 'Raphael'.
^array.</CodeSample>
<Heading4>
<A ID="pgfId-1041713"></A>
Create an initialized collection </Heading4>
<Body1>
<A ID="pgfId-1041714"></A>
Send a <Code>
new:withAll:</Code>
 message to the desired collection class, with the initialization object.</Body1>
<CodeSample>
<A ID="pgfId-1040387"></A>
Array new: 16 withAll: 0.</CodeSample>
<Heading4>
<A ID="pgfId-1040388"></A>
Create an array with up to four elements</Heading4>
<Body1>
<A ID="pgfId-1040389"></A>
Send a <Code>
with:with:with:with:</Code>
 message to the <Code>
Array</Code>
 class, or a variant of that message containing as many <Code>
with:</Code>
 keywords as needed, up to four. The argument of each <Code>
with:</Code>
 keyword can be any object. </Body1>
<CodeSample>
<A ID="pgfId-1040390"></A>
array1 := Array with: 'Leonardo'.

array2 := Array
			with: 'Leonardo'
			with: 'Michelangelo'.</CodeSample>
<Heading4>
<A ID="pgfId-1040395"></A>
Create a literal array</Heading4>
<Body1>
<A ID="pgfId-1040396"></A>
Enclose the list of literal elements in parentheses, with a number-sign prefix. Any white-space character can be used to separate the elements.</Body1>
<CodeSample>
<A ID="pgfId-1040397"></A>
#( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael' )</CodeSample>
<Heading4>
<A ID="pgfId-1040398"></A>
Create a new collection from an old collection</Heading4>
<Body1>
<A ID="pgfId-1040399"></A>
Send a <Code>
withAll:</Code>
 message to the desired collection class (<Code>
List</Code>
).</Body1>
<CodeSample>
<A ID="pgfId-1040400"></A>
List withAll: Smalltalk keys</CodeSample>
<Heading4>
<A ID="pgfId-1040401"></A>
Get a collection&#39;s size</Heading4>
<Body1>
<A ID="pgfId-1040402"></A>
This is the number of used slots in the collection. The number of available slots is the capacity. Send a <Code>
size</Code>
 message to the collection. The response is an integer (in the example, <Code>
31</Code>
). </Body1>
<CodeSample>
<A ID="pgfId-1040403"></A>
| array |
array := ColorValue constantNames.
^array size</CodeSample>
<Heading4>
<A ID="pgfId-1040406"></A>
Get a collection&#39;s capacity</Heading4>
<Body1>
<A ID="pgfId-1040407"></A>
This is the total number of slots available.  They may not all be used.  The capacity can be expanded by growing the collection.  Send a <Code>
capacity</Code>
 message to the collection. The response is an integer.</Body1>
<CodeSample>
<A ID="pgfId-1040408"></A>
| set |
set := Set withAll: ColorValue constantNames.
^set capacity</CodeSample>
<Heading4>
<A ID="pgfId-1040411"></A>
Test if a collection is empty</Heading4>
<Body1>
<A ID="pgfId-1040412"></A>
Send an <Code>
isEmpty</Code>
 message to the collection. The response is <Code>
true</Code>
 when the collection has no elements and <Code>
false</Code>
 otherwise.</Body1>
<CodeSample>
<A ID="pgfId-1040413"></A>
| list |
list := List allInstances.

list isEmpty
		ifFalse: [^list first]</CodeSample>
<Heading4>
<A ID="pgfId-1040418"></A>
Add elements to a collection</Heading4>
<Body1>
<A ID="pgfId-1040419"></A>
A <Code>
List</Code>
, <Code>
Set</Code>
, or <Code>
Dictionary</Code>
 can add elements at any time. </Body1>
<StepStart>
<A ID="pgfId-1040421"></A>
Send an <Code>
add:</Code>
 message to a <Code>
List</Code>
 or <Code>
Set</Code>
. The argument can be any object.</StepStart>
<StepCont>
<A ID="pgfId-1040423"></A>
Send an <Code>
at:put:</Code>
 message to a <Code>
Dictionary</Code>
. The first argument is the lookup key, typically but not necessarily a <Code>
Symbol</Code>
. The second argument is the object that is associated with the key. </StepCont>
<CodeSample>
<A ID="pgfId-1040424"></A>
| list dict |
list := List new.
dict := Dictionary new.

list add: 'Leonardo';
			add: 'Michelangelo';
			add: 'Donatello';
			add: 'Raphael'.

dict at: #Leader put: 'Leonardo';
			at: #Member1 put: 'Michelangelo';
			at: #Member2 put: 'Donatello';
			at: #Member3 put: 'Raphael'.

^Array with: list with: dict</CodeSample>
<Heading4>
<A ID="pgfId-1040439"></A>
Insert an element at a location</Heading4>
<StepStart>
<A ID="pgfId-1040441"></A>
Send an <Code>
addFirst:</Code>
 message to a <Code>
List</Code>
. The argument is the element to be inserted at the beginning of the collection.</StepStart>
<StepCont>
<A ID="pgfId-1040443"></A>
Send an <Code>
add:before:</Code>
 message to a <Code>
List</Code>
. The first argument is the element to be inserted. The second argument is the element before which the insertion is to take place.</StepCont>
<StepCont>
<A ID="pgfId-1040445"></A>
Send an <Code>
add:beforeIndex:</Code>
 message to a <Code>
List</Code>
. The first argument is the element to be inserted. The second argument is the index of the element before which the insertion is to take place.</StepCont>
<CodeSample>
<A ID="pgfId-1040446"></A>
| list |
list := List new.

list add: 'Raphael';
			addFirst: 'Leonardo';
			add: 'Michelangelo' before: 'Raphael';
			add: 'Donatello' beforeIndex: 3.

^list</CodeSample>
<Heading4>
<A ID="pgfId-1040455"></A>
Add a collection of elements</Heading4>
<StepStart>
<A ID="pgfId-1040457"></A>
Send an <Code>
addAll:</Code>
 message to a <Code>
List</Code>
 or <Code>
Set</Code>
. The argument is a collection of elements to be added. Remember that a <Code>
Set</Code>
 will discard duplicate elements.</StepStart>
<StepCont>
<A ID="pgfId-1040459"></A>
Send an <Code>
addAllFirst:</Code>
 message to a <Code>
List</Code>
 (not a <Code>
Set</Code>
). The argument is the collection of elements to be inserted at the beginning of the list.</StepCont>
<StepCont>
<A ID="pgfId-1040461"></A>
Send an <Code>
addAll:beforeIndex:</Code>
 message to a <Code>
List</Code>
. The first argument is the collection to be inserted. The second argument is the index number of the element before which the new batch is to be inserted.</StepCont>
<CodeSample>
<A ID="pgfId-1040462"></A>
| sizes totalElements |
sizes := List new: 10000.

sizes addAll: (List allInstances collect: [ :list | list size]).
sizes addAllFirst: (Dictionary allInstances collect: [ :dict | dict size]).
sizes
			addAll: (Array allInstances collect: [ :array | array size]) 
			beforeIndex: 2.

totalElements := 0.
sizes do: [ :sz | totalElements := totalElements + sz].
^totalElements</CodeSample>
<Heading4>
<A ID="pgfId-1040474"></A>
Expand an array</Heading4>
<StepStart>
<A ID="pgfId-1040476"></A>
Send a <Code>
copyWith:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The argument is the object that is to be appended to the end of the copy.</StepStart>
<StepCont>
<A ID="pgfId-1040478"></A>
Replace the original array with the expanded copy.</StepCont>
<CodeSample>
<A ID="pgfId-1040479"></A>
| array copy |
array := #( 1 2 3 4 5 6 7 8 9 ).

copy := array copyWith: 10.
array := copy.
^array</CodeSample>
<Heading4>
<A ID="pgfId-1040485"></A>
Remove an element</Heading4>
<Body1>
<A ID="pgfId-1040486"></A>
Send a <Code>
remove:</Code>
 message to a <Code>
List</Code>
 or <Code>
Set</Code>
. The argument is the object to be removed.</Body1>
<CodeSample>
<A ID="pgfId-1040487"></A>
| list |
list := List withAll: ColorValue constantNames.

list remove: #red.
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040492"></A>
Supply an element-not-found response</Heading4>
<Body1>
<A ID="pgfId-1040493"></A>
Send a <Code>
remove:ifAbsent:</Code>
 message to a <Code>
List</Code>
 or <Code>
Set</Code>
. The first argument is the object to be removed. The second argument is a block containing the action or actions. </Body1>
<Body1>
<A ID="pgfId-1040494"></A>
An empty block is an effective means of taking no action-- that is, simply shutting off the error notifier that is displayed by default.</Body1>
<CodeSample>
<A ID="pgfId-1040495"></A>
| list |
list := List withAll: ColorValue constantNames.

list remove: #brickRed
			ifAbsent: [Dialog warn: 'You must be kidding -- brickRed?'].

list remove: #moonbeam ifAbsent: [ ].
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040503"></A>
Remove a subset</Heading4>
<Body1>
<A ID="pgfId-1040504"></A>
Send a <Code>
removeAll:</Code>
 message to a <Code>
List</Code>
 or <Code>
Set</Code>
. The argument is a collection containing the elements to be removed. If an element is not found, an error results. The subset can be contained in a different type of collection.</Body1>
<CodeSample>
<A ID="pgfId-1040505"></A>
| list |
list := List withAll: ColorValue constantNames.

list removeAll: #( #red #green #blue ).																			
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040510"></A>
Remove elements by index</Heading4>
<StepStart>
<A ID="pgfId-1040512"></A>
Send a <Code>
removeFirst</Code>
 message to a <Code>
List</Code>
 (but not a <Code>
Set</Code>
, <Code>
Array</Code>
, or <Code>
Dictionary</Code>
). The first element in the list will be removed. If the list is empty, an error results.</StepStart>
<StepCont>
<A ID="pgfId-1040514"></A>
Send a <Code>
removeFirst:</Code>
 message to a <Code>
List</Code>
. The argument is the number of elements to be removed from the front of the list.</StepCont>
<StepCont>
<A ID="pgfId-1040516"></A>
Send a <Code>
removeLast</Code>
 message to remove the last element.</StepCont>
<StepCont>
<A ID="pgfId-1040518"></A>
Send a <Code>
removeLast:</Code>
 message. The argument is the number of elements to be removed from the end of the list.</StepCont>
<StepCont>
<A ID="pgfId-1040520"></A>
Send a <Code>
removeFrom:to:</Code>
 message to a <Code>
List</Code>
. The first argument is the starting index of the range and the second argument is the ending index. An array containing the deleted elements is returned.</StepCont>
<StepCont>
<A ID="pgfId-1040522"></A>
Send a <Code>
removeFrom:to:returnElements:</Code>
 message to a <Code>
List</Code>
. The first and second arguments are index numbers identifying the range to be removed. The third argument is <Code>
false</Code>
 when you want <Code>
nil</Code>
 to be returned instead of an array containing the deleted elements--for large removal operations, this is more efficient.</StepCont>
<CodeSample>
<A ID="pgfId-1040523"></A>
| list |
list := List new: 25.
1 to: 25 do: [ :i | list add: i].

&quot;Removes 1&quot;
list removeFirst.

&quot;Removes 2 3 4 5 6&quot;
list removeFirst: 5.

&quot;Removes 25&quot;
list removeLast.

&quot;Removes 20 21 22 23 24&quot;
list removeLast: 5.

&quot;Removes 14 15 16 17 18&quot;
list removeFrom: 8 to: 12.

&quot;Removes 9 10 11 12 13&quot;
list removeFrom: 3 to: 7 returnElements: false.

^list</CodeSample>
<Heading4>
<A ID="pgfId-1040546"></A>
Remove elements that pass a test</Heading4>
<Body1>
<A ID="pgfId-1040547"></A>
Send a <Code>
removeAllSuchThat:</Code>
 message to a <Code>
List</Code>
. The argument is a block containing the test. The block must declare one argument variable for the element to be tested.</Body1>
<CodeSample>
<A ID="pgfId-1040548"></A>
| list |
list := List withAll: ColorValue constantNames.

list removeAllSuchThat: [ :name | name first == $r].
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040553"></A>
Remove an association from a dictionary</Heading4>
<StepStart>
<A ID="pgfId-1040555"></A>
Send a <Code>
removeKey:</Code>
 message to the dictionary. The argument is the key of the association that you want to remove. The removed value is returned. If the key is not found, an error results.</StepStart>
<StepCont>
<A ID="pgfId-1040557"></A>
To provide an alternative response to the key-not-found condition, send a <Code>
removeKey:ifAbsent:</Code>
 message to the dictionary. The first argument is the key to be removed and the second argument is a block that specifies the action to take if the key is not found. An empty block causes no action, which is the same as silently ignoring the condition.</StepCont>
<CodeSample>
<A ID="pgfId-1040558"></A>
| dict |
dict := Dictionary new.
dict at: #Leader put: 'Leonardo';
			at: #Member1 put: 'Michelangelo';
			at: #Member2 put: 'Donatello';
			at: #Member3 put: 'Raphael'.

dict removeKey: #Member2.

dict removeKey: #Villain ifAbsent: [ ].
^dict</CodeSample>
<Heading4>
<A ID="pgfId-1040569"></A>
Remove an element from an array</Heading4>
<StepStart>
<A ID="pgfId-1040571"></A>
Send a <Code>
copyWithout:</Code>
 message to an <Code>
Array</Code>
 (or a <Code>
List</Code>
). The argument is the object to be removed. Every occurrence of that object will be removed from the copy.</StepStart>
<StepCont>
<A ID="pgfId-1040573"></A>
Replace the original array with the copy.</StepCont>
<CodeSample>
<A ID="pgfId-1040574"></A>
| array copy |
array := #( 1 8 3 4 5 6 7 8 9 ).

copy := array copyWithout: 8.
array := copy.
^array</CodeSample>
<Heading4>
<A ID="pgfId-1040580"></A>
Replace elements</Heading4>
<Body1>
<A ID="pgfId-1040582"></A>
Send an <Code>
at:put:</Code>
 message to the collection. </Body1>
<Body1>
<A ID="pgfId-1040583"></A>
For a <Code>
Dictionary</Code>
, the first argument is the lookup key and the second argument is the value to be placed at that key. If the key does not exist, it will be added.</Body1>
<Body1>
<A ID="pgfId-1040584"></A>
For a <Code>
List</Code>
 or<Code>
 Array</Code>
, the first argument is the index number of the element to be replaced, and the second argument is the object that is to replace the old element.</Body1>
<CodeSample>
<A ID="pgfId-1040585"></A>
| list dict |
dict := Dictionary new.
dict at: #Leader put: 'Leonardo';
			at: #Member1 put: 'Michelangelo';
			at: #Member2 put: 'Donatello';
			at: #Member3 put: 'Raphael'.
list := List withAll: dict values.
list sort.

dict at: #Leader put: 'Rembrandt'.

list at: 1 put: 'Rembrandt'.

^Array with: list with: dict.</CodeSample>
<Heading4>
<A ID="pgfId-1040599"></A>
Replace all elements</Heading4>
<Body1>
<A ID="pgfId-1040600"></A>
Send an <Code>
atAllPut:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The argument is the object that is to replace all existing elements.</Body1>
<CodeSample>
<A ID="pgfId-1040601"></A>
| list |
list := List new.
1 to: 10 do: [ :number | list add: number ].

list atAllPut: 0.
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040607"></A>
Replace specified elements</Heading4>
<Body1>
<A ID="pgfId-1040608"></A>
Send an <Code>
atAll:put:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The first argument is a collection containing the index numbers of the elements to be replaced. The second argument is the object to be placed in those slots.</Body1>
<CodeSample>
<A ID="pgfId-1040609"></A>
| list |
list := List new.
list
	add: 'red';
	add: 'ghoulishGreen';
	add: 'red';
	add: 'blackAndBlue'.

list atAll: #( 1 3) put: 'bloodRed'.
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040619"></A>
Replace all occurrences of an object</Heading4>
<Body1>
<A ID="pgfId-1040620"></A>
Send a <Code>
replaceAll:with:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The first argument is the object whose occurrences you want to replace. The second argument is the replacement object.</Body1>
<CodeSample>
<A ID="pgfId-1040621"></A>
| list |
list := List new.
list
	add: 'red';
	add: 'ghoulishGreen';
	add: 'red';
	add: 'blackAndBlue'.

list replaceAll: 'red' with: 'bloodRed'.
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040631"></A>
Replace a subset with a new subset</Heading4>
<Body1>
<A ID="pgfId-1040632"></A>
Send a <Code>
replaceFrom:to:with:startingAt:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The first and second arguments are index numbers identifying the replacement range. The <Code>
with:</Code>
 argument is a collection containing the new elements. The <Code>
startingAt:</Code>
 argument is the index number in the new collection at which to begin copying the replacement elements.</Body1>
<CodeSample>
<A ID="pgfId-1040633"></A>
| mainList replacements |
mainList := #( 1 2 3 4 5 6 7 8 9 ).
replacements := #( 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 ).

mainList
		replaceFrom: 1
		to: mainList size
		with: replacements
		startingAt: 7.

^mainList</CodeSample>
<Heading4>
<A ID="pgfId-1040644"></A>
Copy elements</Heading4>
<Body1>
<A ID="pgfId-1040645"></A>
When copying a collection, you can modify literal elements such as numbers and strings without affecting the copy. For a nonliteral element, the copied collection holds onto the original object rather than a copy, and will reflect any changes you make to that object.</Body1>
<Body1>
<A ID="pgfId-1040646"></A>
Send a <Code>
copy</Code>
 message to the collection.</Body1>
<CodeSample>
<A ID="pgfId-1040647"></A>
| dict1 dict2 |
dict1 := Dictionary new.
dict1 at: #Leader put: 'Leonardo';
			at: #Member1 put: 'Michelangelo';
			at: #Member2 put: 'Donatello';
			at: #Member3 put: 'Raphael'.

dict2 := dict1 copy.

&quot;Change the original without changing the copy.&quot;
dict1 removeKey: #Leader.
dict1 at: #Leader put: 'Rembrandt'.

^Array with: dict1 with: dict2</CodeSample>
<Heading4>
<A ID="pgfId-1040661"></A>
Copy a subset</Heading4>
<Body1>
<A ID="pgfId-1040662"></A>
Send a <Code>
copyFrom:to:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The first argument is the starting index of the range you want to copy, and the second argument is the ending index.</Body1>
<CodeSample>
<A ID="pgfId-1040663"></A>
| list copy |
list := List new.
1 to: 10 do: [ :number | list add: number ].

copy := list copyFrom: 1 to: 3.
^copy</CodeSample>
<Heading4>
<A ID="pgfId-1040669"></A>
Combine two collections</Heading4>
<Body1>
<A ID="pgfId-1040670"></A>
Two ordered collections, such as a <Code>
List</Code>
 and an <Code>
Array</Code>
, can be combined, as shown in the basic step. This technique is widely used with strings (which are ordered collections of characters), but it can also be used with other kinds of ordered collections.</Body1>
<Body1>
<A ID="pgfId-1040671"></A>
Send a comma (,) message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The argument is another ordered collection. A new collection will be returned, of the same type as the first collection, containing the elements of both collections.</Body1>
<CodeSample>
<A ID="pgfId-1040672"></A>
| list array combinedList |
list := List withAll: ColorValue constantNames.
array := #( #bloodRed #ghoulishGreen #blackAndBlue ).

combinedList := list, array.
^combinedList</CodeSample>
<Heading4>
<A ID="pgfId-1040678"></A>
Find elements</Heading4>
<Body1>
<A ID="pgfId-1040679"></A>
Send an <Code>
at:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The argument is an index number. If the object is not found, zero is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040680"></A>
| list |
list := List withAll: ColorValue constantNames.

^list at: 1</CodeSample>
<Heading4>
<A ID="pgfId-1040684"></A>
Search a dictionary</Heading4>
<StepStart>
<A ID="pgfId-1040686"></A>
Send an <Code>
at:</Code>
 message to the dictionary. The argument is the lookup key. If the key does not exist, an error results.</StepStart>
<StepCont>
<A ID="pgfId-1040688"></A>
To avoid the key-not-found error, send an <Code>
at:ifAbsent:</Code>
 message. The second argument is an empty block (for no action) or a block containing actions to be taken if the key does not exist.</StepCont>
<StepCont>
<A ID="pgfId-1040690"></A>
To find the key that corresponds to a value, send a <Code>
keyAtValue:ifAbsent:</Code>
 message to the dictionary. The first argument is the object whose key is to be found. The second argument is a block containing the value-not-found action.</StepCont>
<CodeSample>
<A ID="pgfId-1040691"></A>
| dict found1 found2 found3 |
dict := Smalltalk.

found1 := dict at: #List.
found2 := dict at: #UnlikelyClassName ifAbsent: [nil].
found3 := dict keyAtValue: List ifAbsent: [nil].

^Array with: found1 with: found2 with: found3</CodeSample>
<Heading4>
<A ID="pgfId-1040699"></A>
Get the index of an object</Heading4>
<StepStart>
<A ID="pgfId-1040701"></A>
Send an <Code>
indexOf:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The argument is the object to be found. If the object is not an element, zero is returned.</StepStart>
<StepCont>
<A ID="pgfId-1040703"></A>
To search a subset of the <Code>
List</Code>
 or <Code>
Array</Code>
, send a <Code>
nextIndexOf:from:to:</Code>
 message. The first argument is the object to be found. The second and third arguments are indexes that define the search range. The returned index is relative to the beginning of the collection.</StepCont>
<StepCont>
<A ID="pgfId-1040705"></A>
To search backward from the end, send a <Code>
lastIndexOf:</Code>
 message. The index of the last occurrence is returned, or zero if none exists. The returned index is relative to the beginning of the collection.</StepCont>
<CodeSample>
<A ID="pgfId-1040706"></A>
| list found1 found2 found3 |
list := List withAll: #( #red #green #blue #red #yellow #blue).

found1 := list indexOf: #red.
found2 := list nextIndexOf: #red from: 2 to: 6.
found3 := list lastIndexOf: #red.

^Array with: found1 with: found2 with: found3</CodeSample>
<Heading4>
<A ID="pgfId-1040714"></A>
Find an object in a collection</Heading4>
<Body1>
<A ID="pgfId-1041464"></A>
To find out if an object is in a collection, send an <Code>
includes:</Code>
 message to the collection, with the object as argument. The return value is <Code>
true</Code>
 if the object is in the collection, and <Code>
false</Code>
 otherwise. </Body1>
<Body1>
<A ID="pgfId-1041465"></A>
To find out how many instances of an object are in a collection, send an <Code>
occurrencesOf:</Code>
 message to the collection, with the object as argument. The return value is the number of occurrences.</Body1>
<CodeSample>
<A ID="pgfId-1040717"></A>
| list found1 found2 |
list := List withAll: #( #red #green #blue #red #yellow #blue).

found1 := list includes: #red.
found2 := list occurrencesOf: #red.

^Array with: found1 with: found2</CodeSample>
<Heading4>
<A ID="pgfId-1040724"></A>
Get the element before or after an object</Heading4>
<Body1>
<A ID="pgfId-1040726"></A>
Send a <Code>
before:</Code>
 message to a <Code>
List</Code>
. The argument is the element before which the desired element is located. If the argument matches the first element, an error results.</Body1>
<Body1>
<A ID="pgfId-1040728"></A>
Send an <Code>
after:</Code>
 message to a <Code>
List</Code>
. The argument is the element after which the desired element is located. If the argument matches only the last element, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040729"></A>
| list found1 found2 |
list := List withAll: #( #red #green #blue #red #yellow #blue).

found1 := list before: #blue.
found2 := list after: #yellow.

^Array with: found1 with: found2</CodeSample>
<Heading4>
<A ID="pgfId-1040737"></A>
Find the first or last element</Heading4>
<Body1>
<A ID="pgfId-1040739"></A>
To get the first element, send a <Code>
first</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. If the collection is empty, an error results.</Body1>
<Body1>
<A ID="pgfId-1040741"></A>
To get the last element, send a <Code>
last</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. If the collection is empty, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040742"></A>
| list found1 found2 |
list := List withAll: #( #red #green #blue).

found1 := list first.
found2 := list last.

^Array with: found1 with: found2</CodeSample>
<Heading4>
<A ID="pgfId-1040749"></A>
Find a subset (sub-collection)</Heading4>
<Body1>
<A ID="pgfId-1040750"></A>
Send an <Code>
indexOfSubCollection:startingAt:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The first argument is the sub-collection to be found, which need not be the same type of collection. The second argument is the index number at which the search is to begin. The returned index number is relative to the beginning of the collection.</Body1>
<Body1>
<A ID="pgfId-1041894"></A>
If the sub-collection is not found, zero is returned. <Code>
indexOfSubCollection:startingAt: </Code>
searches for the sub-collection that appears in the same order as the target and with no elements between its elements.</Body1>
<CodeSample>
<A ID="pgfId-1040751"></A>
| list found1 found2 found3 |
list := List withAll: #( #red #green #blue #red #yellow #blue).

found1 := list 
			indexOfSubCollection: #( #red #yellow #blue) 
			startingAt: 1.
found2 := list 
			indexOfSubCollection: #( #yellow #red) 
			startingAt: 1.
found3 := list 
			indexOfSubCollection: #( #red #blue) 
			startingAt: 1.
^Array with: found1 with: found2 with: found3</CodeSample>
<Heading4>
<A ID="pgfId-1040765"></A>
Find elements that pass or fail a test</Heading4>
<Body1>
<A ID="pgfId-1040767"></A>
To collect all elements that pass a test, send a <Code>
select:</Code>
 message to a collection. The argument is a one-argument block containing the selection test.</Body1>
<Body1>
<A ID="pgfId-1040769"></A>
To collect all elements that fail a test, send a <Code>
reject:</Code>
 message to a collection. The argument is a one-argument block containing the rejection test.</Body1>
<Body1>
<A ID="pgfId-1040771"></A>
To get the first element that passes a test, send a <Code>
detect:ifNone:</Code>
 message to a collection. The first argument is a one-argument block containing the test. The second argument is a no-argument block containing the action to take if no element passes the test.</Body1>
<CodeSample>
<A ID="pgfId-1040772"></A>
| list found1 found2 found3 |
list := List withAll: Smalltalk classNames.

&quot;Select classes with 'Example' in their names.&quot;
found1 := list
			select: [ :nextElement | 
				(nextElement indexOfSubCollection: 'Example'
					startingAt: 1) &gt; 0].

&quot;Reject classes with 'Example' in their names.&quot;
found2 := list
			reject: [ :nextElement |
				(nextElement indexOfSubCollection: 'Example'
					startingAt: 1) &gt; 0].

&quot;Detect the first class beginning with 'R'.&quot;
found3 := list 
			detect: [ :nextElement | nextElement first == $R]
			ifNone: [0].

^Array with: found1 with: found2 with: found3</CodeSample>
<Heading4>
<A ID="pgfId-1040793"></A>
Test whether collections are the same</Heading4>
<Body1>
<A ID="pgfId-1040794"></A>
A collection can be compared to another collection. The collections can be compared for either equality of elements or identity of elements.</Body1>
<Body1>
<A ID="pgfId-1040795"></A>
To test for equality of elements, send a <Code>
=</Code>
 message to one of the collections with the other collection as the argument. to test for identity of elements, send a <Code>
==</Code>
 message.</Body1>
<CodeSample>
<A ID="pgfId-1040796"></A>
| list1 list2 copyIsEqual copyWithChangedElementIsEqual |
list1 := List withAll: ColorValue constantNames.
list2 := list1 copy.

copyIsEqual := list1 = list2.

list2 at: 1 put: #burntOrange.
copyWithChangedElementIsEqual := list1 = list2.

^Array with: copyIsEqual with: copyWithChangedElementIsEqual.</CodeSample>
<Heading4>
<A ID="pgfId-1040806"></A>
Subtracting one set from another</Heading4>
<Body1>
<A ID="pgfId-1040807"></A>
Send a - (minus) message to a <Code>
Set</Code>
 or <Code>
Dictionary</Code>
. The argument is another set or dictionary. A similar type of collection is returned, containing the elements that occur in the first set but not the second.</Body1>
<CodeSample>
<A ID="pgfId-1040808"></A>
| set1 set2 |
set1 := Set withAll: ColorValue constantNames.
set2 := set1 select: [ :name | 
			(name indexOfSubCollection: 'light' startingAt: 1) &gt; 0].

^set1 - set2</CodeSample>
<Heading4>
<A ID="pgfId-1040814"></A>
Sort a collection in ascending order</Heading4>
<Body1>
<A ID="pgfId-1040815"></A>
A sorted collection can be sorted, as long as its elements respond to <Code>
&lt;</Code>
 and <Code>
=</Code>
 messages. </Body1>
<Body1>
<A ID="pgfId-1040816"></A>
Send a <Code>
sort</Code>
 message to a sorted collection, such as a <Code>
List</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040817"></A>
| list |
list := List withAll: #( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael').

list sort.
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040822"></A>
Define a sort order</Heading4>
<Body1>
<A ID="pgfId-1040823"></A>
Send a <Code>
sortWith:</Code>
 message to a sorted collection. The argument is a block containing the test for determining whether one element precedes another. The block must declare two arguments to contain the two elements being compared. The block should return <Code>
true</Code>
 if the first argument should precede the second.  The block should return <Code>
false</Code>
 otherwise. (In the example, the test causes the elements to be sorted in descending order.)</Body1>
<CodeSample>
<A ID="pgfId-1040824"></A>
| list |
list := List withAll: #( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael').

list sortWith: [ :element1 :element2 | element1 &gt; element2].
^list</CodeSample>
<Heading4>
<A ID="pgfId-1040829"></A>
Make an unsorted collection sortable</Heading4>
<Body1>
<A ID="pgfId-1040831"></A>
Send an <Code>
asSortedCollection</Code>
 message to the collection. A <Code>
SortedCollection</Code>
 is returned, with the collection&#39;s elements in ascending order.</Body1>
<Body1>
<A ID="pgfId-1040833"></A>
To customize the sort order, send an <Code>
asSortedCollection:</Code>
 message to the collection. The argument is a block that compares two elements and answers <Code>
true</Code>
 when the first element is to precede the second element.</Body1>
<CodeSample>
<A ID="pgfId-1040834"></A>
| array1 sort1 array2 sort2 |

array1 := #( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael').
sort1 := array1 asSortedCollection.
array2 := #( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael').
sort2 := array2 asSortedCollection: [ :name1 :name2 | name1 &gt; name2].

^Array with: sort1 with: sort2.</CodeSample>
<Heading4>
<A ID="pgfId-1040842"></A>
Reverse the order of elements</Heading4>
<Body1>
<A ID="pgfId-1040843"></A>
Send a <Code>
reverse</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
 (or any ordered collection). A new instance of the same type of collection is returned, with the elements in reverse order (but not explicitly sorted).</Body1>
<CodeSample>
<A ID="pgfId-1040844"></A>
| array reversedArray |
array := #( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael').

reversedArray := array reverse.
^reversedArray</CodeSample>
<Heading4>
<A ID="pgfId-1040849"></A>
Change collection classes</Heading4>
<Body1>
<A ID="pgfId-1040850"></A>
Any collection can be converted to a <Code>
List</Code>
, an <Code>
Array</Code>
, or a <Code>
Set</Code>
, by sending an <Code>
asList</Code>
, <Code>
asArray</Code>
, or <Code>
asSet</Code>
 message to the collection. The original collection is not converted, but an instance of the desired type of collection is returned containing the original collection&#39;s elements, and the original collection remains unchanged.</Body1>
<CodeSample>
<A ID="pgfId-1040851"></A>
| array list set |
array := ColorValue constantNames.

list := array asList.
set := array asSet.
array := set asArray.
^Array with: list with: set with: array</CodeSample>
<Heading4>
<A ID="pgfId-1040858"></A>
Loop through a collection</Heading4>
<Body1>
<A ID="pgfId-1040859"></A>
Send a <Code>
do:</Code>
 message to a collection. The argument is a block that performs a series of operations on an element. The block is repeated for each element in the collection, and it is expected to declare one argument variable to hold the next element to be processed.</Body1>
<CodeSample>
<A ID="pgfId-1040860"></A>
| list color |
list := List withAll: ColorValue constantNames.
list sort.

list do: [ :colorName |
			Transcript show: colorName asString; cr.
			color := ColorValue perform: colorName.
			Transcript
				show: color red printString;
				tab;
				show: color green printString;
				tab;
				show: color blue printString;
				cr; cr].</CodeSample>
<Heading4>
<A ID="pgfId-1040874"></A>
Loop in reverse order</Heading4>
<Body1>
<A ID="pgfId-1040875"></A>
Send a <Code>
reverseDo:</Code>
 message to a collection. The argument is a block that performs a series of operations on an element. The block is repeated for each element in the collection, starting with the last and proceeding toward the first element. The block is expected to declare one argument variable to hold the next element to be processed.</Body1>
<CodeSample>
<A ID="pgfId-1040876"></A>
| list color |
list := List withAll: ColorValue constantNames.
list sort.

list reverseDo: [ :colorName |
			Transcript show: colorName asString; cr.
			color := ColorValue perform: colorName.
			Transcript
				show: color red printString;
				tab;
				show: color green printString;
				tab;
				show: color blue printString;
			cr; cr].</CodeSample>
<Heading4>
<A ID="pgfId-1040890"></A>
Loop on lookup keys</Heading4>
<Body1>
<A ID="pgfId-1040891"></A>
Send a <Code>
keysDo:</Code>
 message to an ordered collection such as a <Code>
Dictionary</Code>
, <Code>
List</Code>
, or <Code>
Array</Code>
. The argument is a one-argument block that performs a series of operations using the lookup key for each element. </Body1>
<Body1>
<A ID="pgfId-1040892"></A>
Send a <Code>
keysAndValuesDo:</Code>
 message to an ordered collection such as a <Code>
Dictionary</Code>
, <Code>
List</Code>
, or <Code>
Array</Code>
. The argument is a two-argument block that performs a series of operations using the lookup key and associated value for each element. </Body1>
<CodeSample>
<A ID="pgfId-1040893"></A>
| dict randomGenerator gc randomX randomY colorValue |
randomGenerator := Random new.
gc := (ExamplesBrowser prepareScratchWindowOfSize: 300@400) 
			graphicsContext.

dict := Dictionary new.
ColorValue constantNames do: [ :colorName |
			colorValue := ColorValue perform: colorName.
			dict at: colorName put: colorValue].

dict keysDo: [ :colorName |
			randomX := randomGenerator next * 300.
			randomY := randomGenerator next * 300.
			colorName displayOn: gc at: (randomX @ randomY)].

dict keysAndValuesDo: [ :colorName :color |
			randomX := randomGenerator next * 300.
			randomY := randomGenerator next * 300.
			gc paint: color.
		colorName displayOn: gc at: (randomX @ randomY)].</CodeSample>
<Heading4>
<A ID="pgfId-1040913"></A>
Collect the results of iteration</Heading4>
<Body1>
<A ID="pgfId-1040914"></A>
Send a <Code>
collect:</Code>
 message to a collection. The argument is a block that processes an element and returns an object that is to become an element in the result collection. The block is expected to declare one argument variable for the next element to be processed.</Body1>
<CodeSample>
<A ID="pgfId-1040915"></A>
| list capitalizedName initial |
list := List withAll: ColorValue constantNames.
list sort.

list collect: [ :colorName |
			capitalizedName := colorName asString.
			initial := (capitalizedName at: 1) asUppercase.
			capitalizedName at: 1 put: initial.
		capitalizedName].</CodeSample>
<Heading4>
<A ID="pgfId-1040924"></A>
Looping through two collections</Heading4>
<Body1>
<A ID="pgfId-1040925"></A>
Send a <Code>
with:do:</Code>
 message to a <Code>
List</Code>
 or <Code>
Array</Code>
. The first argument is another <Code>
List</Code>
 or <Code>
Array</Code>
 of the same size as the first. The second argument is a block that performs a series of operations on a pair of elements, one from each of the two collections. The block is expected to declare two argument variables, one for each of the elements.</Body1>
<CodeSample>
<A ID="pgfId-1040926"></A>
| array1 array2 dict |
array1 := #( #Leader #Member1 #Member2 #Member3).
array2 := #( 'Leonardo' 'Michelangelo' 'Donatello' 'Raphael' ).
dict := Dictionary new.

array1 with: array2 do: [ :array1Element :array2Element |
			dict at: array1Element put: array2Element].

^dict</CodeSample>
<Body1>
<A ID="pgfId-1040057"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040901"></A>
Characters and Strings</Heading3>
<Heading4>
<A ID="pgfId-1040903"></A>
Create a character literal</Heading4>
<Body1>
<A ID="pgfId-1040904"></A>
To create a character as a separate entity, rather than as part of a string, use its literal form preceding the character with a dollar sign.</Body1>
<CodeSample>
<A ID="pgfId-1040905"></A>
| char |
char := $C.
^char</CodeSample>
<Heading4>
<A ID="pgfId-1040908"></A>
Create a nondisplaying character</Heading4>
<Body1>
<A ID="pgfId-1040909"></A>
Several nondisplaying characters have <Code>
Character</Code>
 class messages to create them: <Code>
backspace</Code>
, <Code>
cr</Code>
, <Code>
del</Code>
, <Code>
esc</Code>
, <Code>
leftArrow</Code>
, <Code>
lf</Code>
, <Code>
newPage</Code>
, <Code>
space</Code>
, <Code>
tab</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040910"></A>
| char |
char := Character cr.
^char</CodeSample>
<Heading4>
<A ID="pgfId-1040913"></A>
Create a character from a numeric code</Heading4>
<Body1>
<A ID="pgfId-1040914"></A>
Send a <Code>
value:</Code>
 message to the <Code>
Character</Code>
 class. The argument is the numeric Unicode representation for the character. </Body1>
<CodeSample>
<A ID="pgfId-1040915"></A>
| char |
char := Character value: 67.
^char</CodeSample>
<Heading4>
<A ID="pgfId-1040918"></A>
Create a composed character</Heading4>
<Body1>
<A ID="pgfId-1040919"></A>
Send a <Code>
composeDiacritical:</Code>
 message to a character. The argument is a diacritical character, which can be obtained by sending <Code>
diacriticalNamed:</Code>
 to the <Code>
Character</Code>
 class with a symbol naming the diacritical character.</Body1>
<CodeSample>
<A ID="pgfId-1040920"></A>
| baseChar diacrit composedChar |
baseChar := $a.
diacrit := Character diacriticalNamed: #grave.
composedChar := baseChar composeDiacritical: diacrit.
^composedChar</CodeSample>
<Heading4>
<A ID="pgfId-1040925"></A>
Create a string literal</Heading4>
<Body1>
<A ID="pgfId-1040926"></A>
Enclose the desired characters in single quotes.</Body1>
<CodeSample>
<A ID="pgfId-1040927"></A>
| string |
string := 'This is a string.'.
^string</CodeSample>
<Heading4>
<A ID="pgfId-1040930"></A>
Create an empty string</Heading4>
<Body1>
<A ID="pgfId-1040931"></A>
Send a <Code>
new</Code>
 message to the <Code>
String</Code>
 class. This is equivalent to enclosing nothing between single quotes.</Body1>
<CodeSample>
<A ID="pgfId-1040932"></A>
| emptyString |
emptyString := String new.
^emptyString</CodeSample>
<Heading4>
<A ID="pgfId-1040935"></A>
Create a string of a set size</Heading4>
<Body1>
<A ID="pgfId-1040937"></A>
Send a <Code>
new:</Code>
 message to the <Code>
String</Code>
 class with an integer specifying the string length. </Body1>
<Body1>
<A ID="pgfId-1040938"></A>
By default, each character is a null. To supply another character, send a <Code>
new:withAll:</Code>
 message to the <Code>
String</Code>
 class with the number of characters, and the fill character as the second argument.</Body1>
<CodeSample>
<A ID="pgfId-1040939"></A>
| nullString zeroString |

nullString := String new: 10.
zeroString := String new: 10 withAll: $0.
^Array with: nullString with: zeroString</CodeSample>
<Heading4>
<A ID="pgfId-1040944"></A>
Create a string from a character</Heading4>
<Body1>
<A ID="pgfId-1040945"></A>
Send a <Code>
with:</Code>
 message to the <Code>
String</Code>
 class. The argument is the character that is to be the sole element of the string.</Body1>
<CodeSample>
<A ID="pgfId-1040946"></A>
| oneCharString |
oneCharString := String with: Character tab.
^oneCharString</CodeSample>
<Heading4>
<A ID="pgfId-1040949"></A>
Test for character attributes</Heading4>
<Body1>
<A ID="pgfId-1040950"></A>
Messages are provided in the Character class to test whether a character is alphabetic (English a-z or A-Z), alphanumeric (a-z, A-Z, or 0-9), a letter (a-z, A-Z, or in a set of non-English letters), and a vowel.</Body1>
<CodeSample>
<A ID="pgfId-1040951"></A>
| char responses |
char := $a.
responses := Array new: 4.

responses 
		at: 1 put: char isAlphabetic;
		at: 2 put: char isAlphaNumeric;
		at: 3 put: char isLetter;
		at: 4 put: char isVowel.
^responses</CodeSample>
<Heading4>
<A ID="pgfId-1040961"></A>
Test if a character is a digit</Heading4>
<Body1>
<A ID="pgfId-1040962"></A>
Send an <Code>
isDigit</Code>
 message to a character. The response is <Code>
true</Code>
 when the character is in the range 0-9.</Body1>
<CodeSample>
<A ID="pgfId-1040963"></A>
| char |
char := $5.
^char isDigit</CodeSample>
<Heading4>
<A ID="pgfId-1040966"></A>
Test for upper- and lower-case</Heading4>
<Body1>
<A ID="pgfId-1040968"></A>
Send an <Code>
isLowercase</Code>
 message to the character. The response is <Code>
true</Code>
 when the character is a lowercase letter.</Body1>
<Body1>
<A ID="pgfId-1040970"></A>
Send an <Code>
isUppercase</Code>
 message to find out whether the character is an uppercase letter.</Body1>
<CodeSample>
<A ID="pgfId-1040971"></A>
| char isLower isUpper |
char := $C.

isLower := char isLowercase.
isUpper := char isUppercase.

^Array with: isLower with: isUpper.</CodeSample>
<Heading4>
<A ID="pgfId-1040978"></A>
Test for white space</Heading4>
<Body1>
<A ID="pgfId-1040979"></A>
Send an <Code>
isSeparator</Code>
 message to the character. The response is <Code>
true</Code>
 when the character is a space, tab, carriage return, line feed, form feed, or null.</Body1>
<CodeSample>
<A ID="pgfId-1040980"></A>
| char |
char := Character cr.
^char isSeparator</CodeSample>
<Heading4>
<A ID="pgfId-1040983"></A>
Test for composed character</Heading4>
<Body1>
<A ID="pgfId-1040985"></A>
Send an <Code>
isComposed</Code>
 message to the character. The response is <Code>
true</Code>
 when the character is composed of a base character plus a diacritical mark.</Body1>
<Body1>
<A ID="pgfId-1040987"></A>
To find out whether a character is a diacritical mark (alone), send an <Code>
isDiacritical</Code>
 message.</Body1>
<CodeSample>
<A ID="pgfId-1040988"></A>
| char |
char := Character diacriticalNamed: #grave.
^Array
		with: char isComposed
		with: char isDiacritical</CodeSample>
<Heading4>
<A ID="pgfId-1040993"></A>
Change character case</Heading4>
<Body1>
<A ID="pgfId-1040994"></A>
To convert a string to all lowercase letters, send an <Code>
asLowercase</Code>
 message to the string. To convert a string to all uppercase, send an <Code>
asUppercase</Code>
 message.</Body1>
<CodeSample>
<A ID="pgfId-1040996"></A>
| string |
string := 'North American Fertilizer Company'.

^string asUppercase</CodeSample>
<Body1>
<A ID="pgfId-1041000"></A>
To change the case of a selected character, send an <Code>
asUppercase</Code>
 or <Code>
asLowercase</Code>
 message to the character. </Body1>
<CodeSample>
<A ID="pgfId-1041001"></A>
| string prevCharIsSeparator newChar |
string := 'NORTH AMERICAN FERTILIZER COMPANY'.
prevCharIsSeparator := true.

string keysAndValuesDo: [ :index :char |
		prevCharIsSeparator
			ifTrue: [newChar := char asUppercase]
			ifFalse: [newChar := char asLowercase].
		string at: index put: newChar.
		prevCharIsSeparator := char isSeparator].

^string</CodeSample>
<Heading4>
<A ID="pgfId-1041013"></A>
Get a string&#39;s length</Heading4>
<Body1>
<A ID="pgfId-1041014"></A>
Send a <Code>
size</Code>
 message to the string.</Body1>
<CodeSample>
<A ID="pgfId-1041015"></A>
| string |
string := '123456789'.
^string size</CodeSample>
<Heading4>
<A ID="pgfId-1041018"></A>
Get a string&#39;s width in pixels</Heading4>
<Body1>
<A ID="pgfId-1041019"></A>
Send a <Code>
widthOfString:</Code>
 message to the graphics context of the display surface on which the string will be displayed. The argument is the string. The width in pixels is returned.</Body1>
<CodeSample>
<A ID="pgfId-1041020"></A>
| window string width |
window := ScheduledWindow new.
string := 'Hello, world'.

width := window graphicsContext
		widthOfString: string.
^width</CodeSample>
<Heading4>
<A ID="pgfId-1041027"></A>
Compare characters and strings</Heading4>
<Body1>
<A ID="pgfId-1041028"></A>
Characters and strings respond to the same comparison messages as most objects: <Code>
=</Code>
, <Code>
==</Code>
, <Code>
&lt;</Code>
, <Code>
&gt;</Code>
, and so on. </Body1>
<Body1>
<A ID="pgfId-1041029"></A>
Characters are compared based on their numeric equivalents. </Body1>
<CodeSample>
<A ID="pgfId-1041030"></A>
char1 = char2																&#34;equality&#34;</CodeSample>
<Body1>
<A ID="pgfId-1041031"></A>
To compare based on identity, send an <Code>
==</Code>
 or <Code>
~~</Code>
 (not identical) message to the object. Two different strings cannot be identical, though two variables that refer to the same string are identical.</Body1>
<CodeSample>
<A ID="pgfId-1041032"></A>
| str1 str2 str3 |
str1 := 'Excellent'.
str2 := 'Excellent'.
str3 := str1.

^Array
		with: (str1 == str2) with: (str1 == str3)</CodeSample>
<Heading4>
<A ID="pgfId-1041039"></A>
Compare by sorting order</Heading4>
<Body1>
<A ID="pgfId-1041041"></A>
Send a <Code>
&lt;</Code>
, <Code>
&gt;</Code>
, <Code>
&lt;=</Code>
 , or <Code>
&gt;=</Code>
 message to the object. </Body1>
<Body1>
<A ID="pgfId-1041042"></A>
In most cases, ordering is determined by alphabetical order, without regarding case.  However, if two strings have the same letters but differ by case, their order is determined by the numeric value of the characters. </Body1>
<CodeSample>
<A ID="pgfId-1041043"></A>
| str1 str2 str3 |

str1 := 'north'.
str2 := 'North'.
str3 := 'northwest'.

^Array
		with: (str1 &lt; str2)
		with: (str2 &lt; str1)
		with: (str1 &lt; str3)
		with: (str2 &lt; str3)</CodeSample>
<Heading4>
<A ID="pgfId-1041052"></A>
Compare strings ignoring case</Heading4>
<Body1>
<A ID="pgfId-1041053"></A>
Send a <Code>
sameAs:</Code>
 message to one of the strings. The argument is the second string.</Body1>
<CodeSample>
<A ID="pgfId-1041054"></A>
| str1 str2 str3 |
str1 := 'north'.
str2 := 'North'.
str3 := 'northwest'.

^Array
		with: (str1 sameAs: str2)
		with: (str1 sameAs: str3)
		with: (str2 sameAs: str3)</CodeSample>
<Heading4>
<A ID="pgfId-1041063"></A>
Rate the similarity of two strings</Heading4>
<Body1>
<A ID="pgfId-1041065"></A>
Send a <Code>
sameCharacters:</Code>
 message to one of the strings. The argument is the second string. An integer is returned, indicating how many of the beginning characters are the same (including case) in the two strings.</Body1>
<Body1>
<A ID="pgfId-1041067"></A>
Send a <Code>
spellAgainst:</Code>
 message to one of the strings, with the second string as argument. An integer from 1 (entirely different) through 100 (equal) is returned.</Body1>
<CodeSample>
<A ID="pgfId-1041068"></A>
| str1 str2 str3 |
str1 := 'north'.
str2 := 'North'.
str3 := 'northwest'.

^Array
		with: (str1 sameCharacters: str2)
		with: (str1 sameCharacters: str3)
		with: (str1 spellAgainst: str2)
		with: (str1 spellAgainst: str3)</CodeSample>
<Heading4>
<A ID="pgfId-1041078"></A>
Search strings</Heading4>
<Body1>
<A ID="pgfId-1041080"></A>
To get the index of a character, send an <Code>
indexOf:</Code>
 message to the string. The argument is the search character. If it is not found, zero is returned.</Body1>
<Body1>
<A ID="pgfId-1041082"></A>
To find the starting index of a substring, send a <Code>
findString:startingAt:ifAbsent:</Code>
 message to the string. The first argument is the substring to be found. The second argument is the character position at which the search is to begin. The third argument is a block containing actions to be taken if the substring is not found (often an empty block, to avoid the default error).</Body1>
<CodeSample>
<A ID="pgfId-1041083"></A>
| classComment searchChar searchString index1 index2 |
classComment := String comment.
searchChar := $&lt;.
searchString := 'Class Variables:'.

index1 := classComment indexOf: searchChar.
index2 := classComment 
		findString: searchString
		startingAt: 1
		ifAbsent: [ ].

^Array with: index1 with: index2</CodeSample>
<Heading4>
<A ID="pgfId-1041095"></A>
Search while ignoring case</Heading4>
<Body1>
<A ID="pgfId-1041096"></A>
Send a <Code>
findString:ignoreCase:useWildcards:</Code>
 message to the string. The <Code>
findString</Code>
 argument is the substring to be found. The <Code>
ignoreCase</Code>
 argument is true when case difference is to be ignored. The <Code>
useWildcards</Code>
 argument is <Code>
true</Code>
 when the number sign and asterisk are to be interpreted as wildcard characters rather than literal characters. </Body1>
<Body1>
<A ID="pgfId-1041097"></A>
Because the presence of an asterisk wildcard affects the endpoint of the found string, this message returns an <Code>
Interval</Code>
 identifying the index range of the found string. A zero interval is returned when the search string is not found.</Body1>
<CodeSample>
<A ID="pgfId-1041098"></A>
| classComment searchString interval |
classComment := String comment.
searchString := 'Var*:'.

interval := classComment 
		findString: searchString
		startingAt: 1
		ignoreCase: true
		useWildcards: true.

^classComment 
		copyFrom: interval first 
		to: interval last</CodeSample>
<Heading4>
<A ID="pgfId-1041111"></A>
Combine two strings</Heading4>
<Body1>
<A ID="pgfId-1041112"></A>
In simple situations, you can combine two strings using a comma. </Body1>
<CodeSample>
<A ID="pgfId-1041113"></A>
| firstName lastName fullName space |
firstName := 'Bill'.
lastName := 'Clinton'.
space := String with: Character space.

fullName := firstName, space, lastName.
^fullName</CodeSample>
<Heading4>
<A ID="pgfId-1041120"></A>
Combine strings using a stream</Heading4>
<Body1>
<A ID="pgfId-1041121"></A>
For concatenating several strings, it is more efficient to use a stream.</Body1>
<StepStart>
<A ID="pgfId-1041122"></A>
Create a stream by sending an <Code>
on:</Code>
 message to the <Code>
WriteStream</Code>
 class. The argument is typically an empty string, but it could be any string, such as a preassembled report heading.</StepStart>
<StepCont>
<A ID="pgfId-1041124"></A>
Append each string in the series to the stream by sending a <Code>
nextPutAll:</Code>
 message to the stream, with the string as argument.</StepCont>
<StepCont>
<A ID="pgfId-1041126"></A>
Get the stream contents in the form of a string by sending a <Code>
contents</Code>
 message to the stream.</StepCont>
<CodeSample>
<A ID="pgfId-1041127"></A>
| classNames formalList |
classNames := Smalltalk classNames.
formalList := WriteStream on: String new.
classNames do: [ :name |
		formalList nextPutAll: 'Class: ';
			nextPutAll: name;						
			cr].

^formalList contents</CodeSample>
<Heading4>
<A ID="pgfId-1041136"></A>
Extract a substring</Heading4>
<Body1>
<A ID="pgfId-1041137"></A>
When a string contains two or more parts, getting the parts as separate strings is a common requirement. </Body1>
<Body1>
<A ID="pgfId-1041138"></A>
Send a <Code>
copyFrom:to:</Code>
 message to the string. The first argument is the starting index and the second argument is the ending index of the desired substring.</Body1>
<CodeSample>
<A ID="pgfId-1041139"></A>
| fullName firstName lastName spaceIndex |
fullName := 'Mahatma Gandhi'.
spaceIndex := fullName indexOf: Character space.

firstName := fullName
		copyFrom: 1 
		to: spaceIndex - 1.
lastName := fullName 
		copyFrom: spaceIndex + 1 
		to: fullName size.

^Array with: firstName with: lastName</CodeSample>
<Heading4>
<A ID="pgfId-1041151"></A>
Copy a prefix</Heading4>
<Body1>
<A ID="pgfId-1041152"></A>
Send a <Code>
copyUpTo:</Code>
 message to the string. The argument is the character that marks the end of the prefix (but is not included in it).</Body1>
<CodeSample>
<A ID="pgfId-1041153"></A>
| fullName firstName |
fullName := 'Boris Yeltsin'.

firstName := fullName copyUpTo: Character space.
^firstName</CodeSample>
<Heading4>
<A ID="pgfId-1041158"></A>
Remove or replace a substring</Heading4>
<Body1>
<A ID="pgfId-1041159"></A>
Removing characters is accomplished by creating a copy in which the unwanted characters have been replaced by an empty string.</Body1>
<StepStart>
<A ID="pgfId-1041161"></A>
Send a <Code>
copyReplaceFrom:to:with:</Code>
 message to the string. The first and second arguments are the index locations of the starting and stopping characters in the substring that is to be replaced. The <Code>
with:</Code>
 argument is the new substring, which need not be the same size as the original substring.</StepStart>
<StepCont>
<A ID="pgfId-1041163"></A>
To insert a substring without removing any characters in the existing string, make the ending index less than the starting index.</StepCont>
<StepCont>
<A ID="pgfId-1041165"></A>
To remove characters, replace them with an empty string.</StepCont>
<CodeSample>
<A ID="pgfId-1041166"></A>
| colorNames magentaStart yellowStart |
colorNames := 'cyan magenta yellow'.
magentaStart := colorNames findString: 'magenta' startingAt: 1.

&quot;Replace magenta with oddDarkReddishColor.&quot;
colorNames := colorNames
		copyReplaceFrom: magentaStart
		to: magentaStart + 'magenta' size - 1
		with: 'oddDarkReddishColor'.

&quot;Insert newColor before oddDarkReddishColor.&quot;
colorNames := colorNames
		copyReplaceFrom: magentaStart
		to: magentaStart - 1
		with: 'newColor '.

&quot;Remove yellow.&quot;
yellowStart := colorNames findString: 'yellow' startingAt: 1.
colorNames := colorNames
		copyReplaceFrom: yellowStart
		to: yellowStart + 'yellow' size - 1
		with: String new.

^colorNames</CodeSample>
<Heading4>
<A ID="pgfId-1041190"></A>
Replace multiple occurrences of a substring</Heading4>
<Body1>
<A ID="pgfId-1041191"></A>
When a string contains multiple occurrences of a substring, you can replace all occurrences by using this technique.</Body1>
<Body1>
<A ID="pgfId-1041192"></A>
Send a <Code>
copyReplaceAll:with:</Code>
 message to the string. The first argument is the substring that is to be replaced. The second argument is the replacement substring.</Body1>
<CodeSample>
<A ID="pgfId-1041193"></A>
| colorNames |
colorNames := String new.
ColorValue constantNames do: [ :name |
		colorNames := colorNames, name asString, ' '].

colorNames := colorNames
		copyReplaceAll: 'Gray'
		with: 'Grey'.
^colorNames</CodeSample>
<Heading4>
<A ID="pgfId-1041202"></A>
Abbreviate a string by ellipsis</Heading4>
<Body1>
<A ID="pgfId-1041203"></A>
For long strings, you can display the beginning and ending of the string, inserting an ellipsis (...) in place of the missing characters.</Body1>
<Body1>
<A ID="pgfId-1041204"></A>
Send a <Code>
contractTo:</Code>
 message to the string. The argument is the number of characters in the abbreviation, including three for the ellipsis. Half of the abbreviation will be taken from the beginning of the string and the other half from the end.</Body1>
<CodeSample>
<A ID="pgfId-1041205"></A>
| string contractedString |
string := 'North American Free Trade Agreement'.

contractedString := string contractTo: 15.
^contractedString</CodeSample>
<Heading4>
<A ID="pgfId-1041210"></A>
Abbreviate by removing all vowels</Heading4>
<Body1>
<A ID="pgfId-1041211"></A>
Send a <Code>
dropFinalVowels</Code>
 message to the string. An abbreviated string will be returned, in which only the leading vowel (if any) remains.</Body1>
<CodeSample>
<A ID="pgfId-1041212"></A>
| string noVowelString |
string := 'North American Free Trade Agreement'.
noVowelString := string dropFinalVowels.
^noVowelString</CodeSample>
<Heading4>
<A ID="pgfId-1041216"></A>
Insert line-end characters</Heading4>
<Body1>
<A ID="pgfId-1041217"></A>
In Smalltalk methods, certain conventions of indentation and line wrapping make the code more readable. Sometimes a string disrupts the readability of the code because it contains embedded carriage returns. This technique allows you to keep the entire string on one line without sacrificing the embedded returns.</Body1>
<StepStart>
<A ID="pgfId-1041219"></A>
For each embedded carriage return in the string, substitute a backslash character (\). </StepStart>
<StepCont>
<A ID="pgfId-1041221"></A>
Send a <Code>
withCRs</Code>
 message to the string to convert the backslashes back to carriage returns.</StepCont>
<CodeSample>
<A ID="pgfId-1041222"></A>
Dialog 
		request: 'This string\has 3 lines\when displayed.' withCRs
		initialAnswer: 'No response needed'.</CodeSample>
<Body1>
<A ID="pgfId-1029452"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040928"></A>
Text and Fonts</Heading3>
<Heading4>
<A ID="pgfId-1040929"></A>
Create a text object</Heading4>
<Body1>
<A ID="pgfId-1040930"></A>
A <Code>
ComposedText</Code>
 is graphical object consisting of a string and a set of display attributes, such as boldness, font, and color. Use a composed text to format a text&#39;s appearance.</Body1>
<Body1>
<A ID="pgfId-1040931"></A>
To create a composed text object, send an <Code>
asComposedText</Code>
 message to a string.</Body1>
<CodeSample>
<A ID="pgfId-1040932"></A>
| string txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
string := ComposedText comment.

txt := string asComposedText.

txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1040939"></A>
Set text display attributes</Heading4>
<StepStart>
<A ID="pgfId-1040941"></A>
Create an instance of <Code>
Text</Code>
, typically by sending an <Code>
asText</Code>
 message to the string that is the basis for the composed text.</StepStart>
<StepCont>
<A ID="pgfId-1040943"></A>
Create a <Code>
TextAttributes</Code>
, or get one from the dictionary that is held by the <Code>
TextAttributes</Code>
 class by sending a <Code>
styleNamed:</Code>
 message to <Code>
TextAttributes</Code>
.</StepCont>
<StepCont>
<A ID="pgfId-1040945"></A>
Send a <Code>
withText:style:</Code>
 message to the <Code>
ComposedText</Code>
 class. The first argument is the text. The second argument is the <Code>
TextAttributes</Code>
.</StepCont>
<CodeSample>
<A ID="pgfId-1040946"></A>
| txt gc textStyle |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := ComposedText comment asText.
textStyle := TextAttributes styleNamed: #large.

txt := ComposedText
		withText: txt
		style: textStyle.

txt displayOn: gc at:5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1040957"></A>
Get available text styles</Heading4>
<Body1>
<A ID="pgfId-1040958"></A>
Instances of <Code>
TextAttributes</Code>
, <Code>
VariableTextAttributes</Code>
, or its subclasses are used to define and share text styles throughout VisualWorks.  The most common of these instances are available from a class dictionary in <Code>
TextAttributes</Code>
. The dictionary keys of these text styles may be determined by sending the message <Code>
styles</Code>
 to <Code>
TextAttributes</Code>
.  The answer is a set with a symbol for each style in the dictionary.</Body1>
<CodeSample>
<A ID="pgfId-1040960"></A>
^TextAttributes styles</CodeSample>
<Body1>
<A ID="pgfId-1040962"></A>
To access a text style, send the message <Code>
styleNamed:</Code>
 to the class <Code>
TextAttributes</Code>
 and provide the text style name symbol as argument.</Body1>
<CodeSample>
<A ID="pgfId-1040964"></A>
^TextAttributes styleNamed: #large</CodeSample>
<Body1>
<A ID="pgfId-1040966"></A>
Text style selections are identified in the VisualWorks Settings Tool at its <UI-Label>
Default Font</UI-Label>
 page and in the UI Painter Properties Tool for any widget that displays text.  These selections correspond to the following text style symbols in the <Code>
TextAttributes</Code>
 dictionary.  Note that <Code>
#default</Code>
, <Code>
#large</Code>
, <Code>
#systemDefault</Code>
, <Code>
#small</Code>
, and <Code>
#fixed</Code>
 are a scaled text styles (i.e. instances of <Code>
VariableSizeTextAttributes</Code>
).</Body1>
<CodeSample>
<A ID="pgfId-1042229"></A>
Properties Tool Font								Style     Settings Tool - Default Font

Default								#default                Medium
Constant Large								#pixelLarge
Constant Medium								#pixelDefault
Constant Small								#pixelSmall
Constant Fixed								#pixelFixed
Scaled Large								#large                  Large
Scaled Medium								#systemDefault
Scaled Small								#small                 Small
Scaled Fixed								#fixed                  Fixed</CodeSample>
<Heading4>
<A ID="pgfId-1042233"></A>
Display a text object</Heading4>
<Body1>
<A ID="pgfId-1042230"></A>
A <Code>
ComposedText</Code>
 is a <A href="10-glossary.xml#id(visual component)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">visual component</A>, so you can display it on a display surface. The example shows how to display on a graphics context, but more usually you display it on a textual widget using its access procedures.</Body1>
<StepStart>
<A ID="pgfId-1040982"></A>
Get the graphics context from the display surface by sending a <Code>
graphicsContext</Code>
 message.</StepStart>
<StepCont>
<A ID="pgfId-1040983"></A>
Send a <Code>
displayOn:</Code>
 message to the composed text. The argument is the graphics context of the display surface.</StepCont>
<CodeSample>
<A ID="pgfId-1040984"></A>
| txt gc |
txt := ComposedText comment asComposedText.
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1040988"></A>
Set the text line length</Heading4>
<Body1>
<A ID="pgfId-1040989"></A>
When a composed text is displayed in a text widget, its width is adjusted automatically by the widget. This example shows how to set the line length if the text is displayed directly on a scratch window. </Body1>
<StepStart>
<A ID="pgfId-1040991"></A>
Send a <Code>
compositionWidth:</Code>
 message to the composed text. The argument is the line length in pixels.</StepStart>
<StepCont>
<A ID="pgfId-1040992"></A>
To get the current line length, send a <Code>
compositionWidth</Code>
 message.</StepCont>
<CodeSample>
<A ID="pgfId-1040993"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := VisualComponent comment asComposedText.

txt compositionWidth: 380.

txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1041000"></A>
Disable word wrapping</Heading4>
<Body1>
<A ID="pgfId-1041001"></A>
Word-wrapping for text can be disabled for columnar material or other text that would be disrupted by wrapping. This only works when displaying a text directly on a display surface. Text widgets do not consult the text about word wrapping, so you must turn off word wrapping in the text widget itself.</Body1>
<Body1>
<A ID="pgfId-1041002"></A>
Send a <Code>
wordWrap:</Code>
 message to the composed text. The argument is <Code>
false</Code>
 to disable wrapping and <Code>
true</Code>
 to turn it on.</Body1>
<CodeSample>
<A ID="pgfId-1041003"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := ComposedText comment asComposedText.
txt compositionWidth: 380.

txt wordWrap: false.

txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1041011"></A>
Set text alignment</Heading4>
<Body1>
<A ID="pgfId-1041012"></A>
By default, a composed text starts each new line flush against the left margin. The alignment can be changed for the text. </Body1>
<StepStart>
<A ID="pgfId-1041013"></A>
For flush-left text (the default), send a <Code>
leftFlush</Code>
 message to the composed text.</StepStart>
<StepCont>
<A ID="pgfId-1041015"></A>
For flush-right text, send <Code>
rightFlush</Code>
.</StepCont>
<StepCont>
<A ID="pgfId-1041016"></A>
For centered text, send <Code>
centered</Code>
.</StepCont>
<StepCont>
<A ID="pgfId-1041017"></A>
For text that aligns with both left and right margins, send <Code>
justified</Code>
.</StepCont>
<CodeSample>
<A ID="pgfId-1041018"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := VisualComponent comment asComposedText.
txt compositionWidth: 380.

txt rightFlush.

txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1041026"></A>
Set text indents</Heading4>
<StepStart>
<A ID="pgfId-1041028"></A>
Send a <Code>
firstIndent:</Code>
 message to the composed text. The argument is the width in pixels of the first line&#39;s indentation from the left edge.</StepStart>
<StepCont>
<A ID="pgfId-1041030"></A>
To set the indent for later lines, send a <Code>
restIndent:</Code>
 message to the composed text. The argument is the width of the indentation from the left edge for all lines after the first line.</StepCont>
<CodeSample>
<A ID="pgfId-1041031"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'Line 1\Line 2\Line 3\Line 4' 
		withCRs asComposedText.
txt compositionWidth: 380.

txt firstIndent: 50.
txt restIndent: 100.

txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1041041"></A>
Set tab stops</Heading4>
<StepStart>
<A ID="pgfId-1041043"></A>
Get a copy of the <Code>
TextAttributes</Code>
 from the composed text by sending a <Code>
textStyle</Code>
 message followed by a <Code>
copy</Code>
 message.</StepStart>
<StepCont>
<A ID="pgfId-1041045"></A>
Send a <Code>
useTabs:</Code>
 message to the text style. The argument is an array containing one or more tab settings. Each setting is an integer indicating how many pixels separate that tab stop from the <Code>
restIndent</Code>
 setting. When each tab is an equal distance from its predecessor, the array can contain a single integer indicating that separation distance.</StepCont>
<StepCont>
<A ID="pgfId-1041047"></A>
Install the modified text style in the composed text by sending a <Code>
textStyle:</Code>
 message to the text, with the style as the argument.</StepCont>
<CodeSample>
<A ID="pgfId-1041048"></A>
| txt gc style tab |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
tab := String with: Character tab.
txt := ('Line 1\Line 2\Line 3\',
			tab, '1 Tab\',
			tab, tab, '2 Tabs\',
			tab, tab, tab, '3 Tabs').
txt := txt withCRs asComposedText.
txt compositionWidth: 380.

txt firstIndent: 50.
txt restIndent: 100.

style := txt textStyle copy.
style useTabs: #( 15 ).
txt textStyle: style.

txt displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1041066"></A>
Get text size in characters</Heading4>
<Body1>
<A ID="pgfId-1041067"></A>
A <Code>
ComposedText</Code>
 holds a <Code>
Text</Code>
, which in turn holds a <Code>
String</Code>
. Like a <Code>
String</Code>
, a <Code>
Text</Code>
 can supply its size, measured in characters. When you need to know how many characters a <Code>
ComposedText</Code>
 contains, the basic steps show how to query the underlying <Code>
Text</Code>
.</Body1>
<StepStart>
<A ID="pgfId-1041069"></A>
Get the underlying <Code>
Text</Code>
 object from the composed text by sending a <Code>
text</Code>
 message.</StepStart>
<StepCont>
<A ID="pgfId-1041071"></A>
Send a <Code>
size</Code>
 message to the <Code>
Text</Code>
.</StepCont>
<CodeSample>
<A ID="pgfId-1041072"></A>
| composedText plainText |
composedText := Object comment asComposedText.

plainText := composedText text.

^plainText size</CodeSample>
<Heading4>
<A ID="pgfId-1041078"></A>
Print a text object</Heading4>
<Body1>
<A ID="pgfId-1041079"></A>
A composed text can be printed on the default printer by sending a <Code>
hardcopy</Code>
 message to the text.</Body1>
<Body1>
<A ID="pgfId-1041080"></A>
Send a <Code>
hardcopy</Code>
 message to a composed text.</Body1>
<CodeSample>
<A ID="pgfId-1041081"></A>
| txt |
txt := Object comment asComposedText.

txt hardcopy.</CodeSample>
<Heading4>
<A ID="pgfId-1041085"></A>
Find/replace in text</Heading4>
<Body1>
<A ID="pgfId-1041086"></A>
A <Code>
ComposedText</Code>
 has a <Code>
Text</Code>
, which has a <Code>
String</Code>
. The normal string search and replace techniques for strings are used on the embedded string.</Body1>
<StepStart>
<A ID="pgfId-1041088"></A>
Get the string from the composed text by sending a <Code>
string</Code>
 message to the text.</StepStart>
<StepCont>
<A ID="pgfId-1041090"></A>
Send a <Code>
findString:startingAt:ignoreCase:useWildcards:</Code>
 message to the string. The <Code>
findString</Code>
 argument is the substring to be found. The <Code>
startingAt</Code>
 argument is the index position at which the search is to begin. The <Code>
ignoreCase</Code>
 argument is <Code>
true</Code>
 when case difference is to be disregarded. The <Code>
useWildcards</Code>
 argument is <Code>
true</Code>
 when the pound sign (<Code>
#</Code>
) and asterisk (<Code>
*</Code>
) are to be treated as wildcard characters, with the pound sign taking the place of any single character and the asterisk taking the place of zero or more characters.</StepCont>
<CodeSample>
<A ID="pgfId-1041091"></A>
| composedText string |
composedText := Object comment asComposedText.

string := composedText string.

^string
		 findString: 'Var*:'
		startingAt: 1
		ignoreCase: true
		useWildcards: true.</CodeSample>
<Heading4>
<A ID="pgfId-1041101"></A>
Compare text objects</Heading4>
<Body1>
<A ID="pgfId-1041102"></A>
A <Code>
ComposedText</Code>
 can only tell whether it is the same object as another text. The equality (<Code>
=</Code>
) comparison has the same effect as an identity (<Code>
==</Code>
) comparison. For more detailed comparisons, test the underlying <Code>
Text</Code>
 objects, which compare their underlying strings.</Body1>
<StepStart>
<A ID="pgfId-1041103"></A>
To test whether two variables reference the same <Code>
ComposedText</Code>
 object, send an <Code>
=</Code>
 message to one variable, with the second variable as the argument.</StepStart>
<StepCont>
<A ID="pgfId-1041104"></A>
To test whether two different instances of <Code>
ComposedText</Code>
 have equal <Code>
Text</Code>
 objects and hence equal strings, get the text from each composed text and compare using an <Code>
=</Code>
 message.</StepCont>
<CodeSample>
<A ID="pgfId-1041105"></A>
| txt1 txt2 equal equivalent |
txt1 := Object comment asComposedText.
txt2 := Object comment asComposedText.

equal := txt1 = txt2.
equivalent := txt1 text = txt2 text.

^Array with: equal with: equivalent</CodeSample>
<Heading4>
<A ID="pgfId-1041113"></A>
Change case</Heading4>
<Body1>
<A ID="pgfId-1041114"></A>
The underlying <Code>
Text</Code>
 that is held by a composed text can be converted to uppercase or lowercase. </Body1>
<StepStart>
<A ID="pgfId-1041116"></A>
Get the underlying <Code>
Text</Code>
 from the composed text by sending a <Code>
text</Code>
 message, and then change the case by sending either an <Code>
asUppercase</Code>
 or <Code>
asLowercase</Code>
 message.</StepStart>
<StepCont>
<A ID="pgfId-1041118"></A>
Install the changed text by sending a <Code>
text:</Code>
 message to the composed text. The argument is the changed text.</StepCont>
<CodeSample>
<A ID="pgfId-1041119"></A>
| composedText capText gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
composedText := 'Hello, World' asComposedText.

capText := composedText text asUppercase.
composedText text: capText.

composedText displayOn: gc at: 5@5.</CodeSample>
<Heading4>
<A ID="pgfId-1041127"></A>
Apply character formats</Heading4>
<Body1>
<A ID="pgfId-1041128"></A>
A composed text has a <Code>
TextAttributes</Code>
 object, which specifies the display characteristics of each character in the text. A default set of text attributes are used unless you supply an alternate.</Body1>
<Body1>
<A ID="pgfId-1041129"></A>
Send an <Code>
emphasizeFrom:to:with:</Code>
 message to a <Code>
Text</Code>
. The first and second arguments identify the character range to be modified. The third argument is the emphasis value. Standard emphases are <Code>
#bold</Code>
, <Code>
#italic</Code>
, <Code>
#serif</Code>
, <Code>
#underline</Code>
, <Code>
#strikeout</Code>
, <Code>
#large</Code>
, and <Code>
#small</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041130"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'normal bold italic serif underline strikeout large small' asText.

txt emphasizeFrom: 8 to: 11 with: #bold.
txt emphasizeFrom: 13 to: 18 with: #italic.
txt emphasizeFrom: 20 to: 24 with: #serif.
txt emphasizeFrom: 26 to: 34 with: #underline.
txt emphasizeFrom: 36 to: 44 with: #strikeout.
txt emphasizeFrom: 46 to: 50 with: #large.
txt emphasizeFrom: 52 to: 56 with: #small.

txt displayOn: gc at: 5@25.</CodeSample>
<Body1>
<A ID="pgfId-1041143"></A>
To apply multiple attributes to a range of characters, such as bold and italic, an array containing the emphases is be used.</Body1>
<CodeSample>
<A ID="pgfId-1041144"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'normal bold&amp;italic large&amp;bold&amp;italic&amp;underline' asText.

txt emphasizeFrom: 8 to: 18 with: #( #bold #italic).
txt emphasizeFrom: 20 to: txt size 
		with: #( #large #bold #italic #underline).

txt displayOn: gc at: 5@25.</CodeSample>
<Body1>
<A ID="pgfId-1041155"></A>
When an entire text is to be given the same emphasis, you can send an <Code>
emphasizeAllWith:</Code>
 message to the <Code>
Text</Code>
.  The argument is the emphasis value or an array containing multiple emphasis values:</Body1>
<CodeSample>
<A ID="pgfId-1041157"></A>
txt emphasizeAllWith: #( #bold #italic).</CodeSample>
<Body1>
<A ID="pgfId-1041159"></A>
Because boldfacing an entire text is a common operation, a convenient means of applying the <Code>
#bold</Code>
 emphasis to a text is provided.  Send an <Code>
allBold</Code>
 message to the <Code>
Text</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041161"></A>
txt allBold displayOn: gc at: 5@25.</CodeSample>
<Body1>
<A ID="pgfId-1041163"></A>
Color and typeface family emphases may also be specified for text using a text style with the default set of text attributes.</Body1>
<Heading4>
<A ID="pgfId-1042088"></A>
Apply HTML text formats</Heading4>
<Body1>
<A ID="pgfId-1042089"></A>
The default set of text attributes also includes text emphases that emulate text formatting tags in HTML.  Simply use the HTML tag name as the emphasis symbol over the desired range of text.</Body1>
<Body1>
<A ID="pgfId-1042090"></A>
Send an <Code>
emphasizeFrom:to:with:</Code>
 message to a <Code>
Text</Code>
. The first and second arguments identify the range of characters to be affected.  The third argument is the emphasis value.  Standard text emphases that emulate the HTML tag formats are <Code>
#H1</Code>
 through <Code>
#H6</Code>
, <Code>
#STRONG</Code>
, <Code>
#CITE</Code>
, <Code>
#CODE</Code>
, <Code>
#EM</Code>
, <Code>
#VAR</Code>
, <Code>
#KBD</Code>
, <Code>
#SAMP</Code>
, and <Code>
#TT</Code>
.  Many of these HTML tags have equivalents.</Body1>
<CodeSample>
<A ID="pgfId-1042091"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

txt := 'H1 H2 H3 H4 H5 H6 STRONG CITE CODE' asText.
txt emphasizeFrom: 1 to: 2 with: #H1.				     		&quot;Level 1 Heading&quot;
txt emphasizeFrom: 4 to: 5 with: #H2.							&quot;Level 2 Heading&quot;
txt emphasizeFrom: 7 to: 8 with: #H3.							&quot;Level 3 Heading&quot;
txt emphasizeFrom: 10 to: 11 with: #H4.							&quot;Level 4 Heading&quot;
txt emphasizeFrom: 13 to: 14 with: #H5.							&quot;Level 5 Heading&quot;
txt emphasizeFrom: 16 to: 17 with: #H6.							&quot;Level 6 Heading&quot;
txt emphasizeFrom: 19 to: 24 with: #STRONG.							&quot;Bold&quot;
txt emphasizeFrom: 26 to: 29 with: #CITE.						&quot;Citation&quot;
txt emphasizeFrom: 31 to: 33 with: #CODE.							&quot;Fixed width&quot;
txt displayOn: gc at: 5@25.

txt := 'EM VAR KBD SAMP TT' asText.
txt emphasizeFrom: 1 to: 2 with: #EM.							&quot;Emphasis&quot;
txt emphasizeFrom: 4 to: 6 with: #VAR.							&quot;Variable name&quot;
txt emphasizeFrom: 8 to: 10 with: #KBD.							&quot;Typewriter&quot;
txt emphasizeFrom: 12 to: 15 with: #SAMP.							&quot;Literal&quot;
txt emphasizeFrom: 17 to: 18 with: #TT.							&quot;Teletype&quot;
txt displayOn: gc at: 5@50.</CodeSample>
<Heading4>
<A ID="pgfId-1041164"></A>
Set font size</Heading4>
<Body1>
<A ID="pgfId-1041165"></A>
Two of the standard text emphases, <Code>
#small</Code>
 and <Code>
#large</Code>
, give you control over the font size within a narrow range.</Body1>
<StepStart>
<A ID="pgfId-1041167"></A>
Send an <Code>
emphasizeFrom:to:with:</Code>
 message to the composed text&#39;s underlying <Code>
Text</Code>
. The first and second arguments define the character range by specifying the starting and stopping indexes. The third argument is <Code>
#small</Code>
 or <Code>
#large</Code>
, depending on whether you want the font size to be slightly smaller or slightly larger than normal. The actual size depends on the fonts available from the operating system, and on some platforms it may not differ at all.</StepStart>
<StepCont>
<A ID="pgfId-1041169"></A>
To return to the default size, apply a <Code>
nil</Code>
 emphasis to the text.</StepCont>
<CodeSample>
<A ID="pgfId-1041170"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'large small' asText.

txt emphasizeFrom: 1 to: 5 with: #large.
txt emphasizeFrom: 7 to: 11 with: #small.
txt displayOn: gc at: 5@25.

txt emphasizeAllWith: nil.
txt displayOn: gc at: 5@40.</CodeSample>
<Heading4>
<A ID="pgfId-1041180"></A>
Set text color</Heading4>
<Body1>
<A ID="pgfId-1041181"></A>
The default text style that supports standard emphasis values for text objects also supports color and patterns.</Body1>
<Body1>
<A ID="pgfId-1041182"></A>
Send an <Code>
emphasizeFrom:to:with:</Code>
 message to the underlying <Code>
Text</Code>
 of a composed text. The first and second arguments identify the range of characters to be affected. The third argument is an association, which is created by sending a <Code>
-&gt;</Code>
 message to the lookup key (<Code>
#color</Code>
), with the desired color as the argument.</Body1>
<CodeSample>
<A ID="pgfId-1041183"></A>
| txt gc boldBlue |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'BLACK RED GRAY BOLDBLUE' asText.

txt emphasizeFrom: 7 to: 9 with: #color -&gt; ColorValue red.
txt emphasizeFrom: 11 to: 14 with: #color -&gt; ColorValue gray.

boldBlue := Array with: #bold with: #color -&gt; ColorValue blue.
txt emphasizeFrom: 16 to: 23 with: boldBlue.
txt displayOn: gc at: 5@25.</CodeSample>
<Heading4>
<A ID="pgfId-1041194"></A>
Set text typeface family</Heading4>
<Body1>
<A ID="pgfId-1041196"></A>
The default font belongs to Helvetica, Arial, or a similar font family, depending on the operating system.  For other fonts a text emphasis attribute may be set to choose a font from a another typeface family.  This emphasis is available for any text style set for default character attributes.</Body1>
<Body1>
<A ID="pgfId-1041198"></A>
Send an <Code>
emphasizeFrom:to:with:</Code>
 message to the underlying <Code>
Text</Code>
 of a <Code>
ComposedText</Code>
. The first and second arguments identify the range of characters to be affected.  The third argument is an association, which is created by sending a <Code>
-&gt;</Code>
 message to the lookup key (<Code>
#family</Code>
), with the name string or an array of name strings for the font family to use. The name may include the wildcard character &#39;<Code>
*</Code>
&#39; to match a family name with a partial description.  The font available for the family that matches closest to the name offered in the argument will be used.  If an array of family names is specified the first matching font family in the array will be used.  If no font is available from any family name specified a font from the text style&#39;s default font family is used.</Body1>
<Body1>
<A ID="pgfId-1041200"></A>
There are also two predefined single key text emphases that offer some control over the choice of font family: <Code>
#serif</Code>
 (for a serif font such as Times) and <Code>
#sansSerif</Code>
 (for a sans serif font such as Helvetica).</Body1>
<CodeSample>
<A ID="pgfId-1041202"></A>
| txt gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'normal courier times helvetica terminal foobar' asText.

txt emphasizeFrom: 8 to: 14 with: #family-&gt;'courier'.
txt emphasizeFrom: 16 to: 20 with: #family-&gt;'times*'. &quot;Matches Times New Roman or Times&quot;
txt emphasizeFrom: 22 to: 30 with: #family-&gt;'helvetica'.
txt emphasizeFrom: 32 to: 39 with: #family-&gt;'terminal'.
&#34;Use the default font for a family unknown to the installation&#34;
txt emphasizeFrom: 40 to: 45 with: #family-&gt;'foobar'.

txt displayOn: gc at: 5@25.</CodeSample>
<Heading4>
<A ID="pgfId-1041262"></A>
Create a text style with new emphases</Heading4>
<Body1>
<A ID="pgfId-1041263"></A>
A composed text&#39;s <Code>
TextAttributes</Code>
 holds an instance of <Code>
CharacterAttributes</Code>
, which defines the emphases that are available to the text. Associated with each emphasis symbol is a block that operates on a <Code>
FontDescription</Code>
, held by the <Code>
CharacterAttributes</Code>
, which specifies the font size, family, boldness, and so on.</Body1>
<Body1>
<A ID="pgfId-1041264"></A>
Note that a composed text applies the same line spacing to its entire text, so mixing font sizes is effective within only a narrow range for each composed text. Similarly, only a single alignment, indent, and tab stop setting remain in effect for a composed text.  Separate instances of <Code>
ComposedText</Code>
 are recommended in such situations.</Body1>
<StepStart>
<A ID="pgfId-1041266"></A>
Create a new instance of <Code>
CharacterAttributes</Code>
 by sending a <Code>
newWithDefaultAttributes</Code>
 message to the <Code>
CharacterAttributes</Code>
 class. This message initializes the <Code>
CharacterAttributes</Code>
 with the standard emphases such as <Code>
#bold</Code>
 and <Code>
#italic</Code>
, so you don&#39;t have to redefine them.</StepStart>
<StepCont>
<A ID="pgfId-1041268"></A>
Install an instance of <Code>
FontDescription</Code>
 in the new <Code>
CharacterAttributes</Code>
 by sending a <Code>
setDefaultQuery:</Code>
 message. The argument can be either a new instance of <Code>
FontDescription</Code>
 or, as in the example, a copy of the default font description from an existing text style&#39;s character attributes. The advantage of copying an existing font description is that you retain the existing settings.</StepCont>
<StepCont>
<A ID="pgfId-1041270"></A>
Customize the <Code>
CharacterAttributes</Code>
 as desired. Define a new emphasis by sending an <Code>
at:put:</Code>
 message to the character attributes. The first argument is the name of the emphasis (<Code>
#title</Code>
). The second argument is a block that sends a <Code>
pixelSize:</Code>
 message to the block argument, with the desired size of the font (in pixels, not in points).  The example defines a new emphasis called <Code>
#title</Code>
, which specifies that the font must be 24 pixels in height.</StepCont>
<StepCont>
<A ID="pgfId-1041272"></A>
Create a new <Code>
TextAttributes</Code>
 by sending a <Code>
characterAttributes:</Code>
 message to the <Code>
TextAttributes</Code>
 class. The argument is the <Code>
CharacterAttributes</Code>
 that you customized in step 3.</StepCont>
<StepCont>
<A ID="pgfId-1041274"></A>
If you intend to display unusually large or small text, as in the example, adjust the line spacing and baseline of the text style. The line spacing is set by sending a <Code>
lineGrid:</Code>
 message to the text style, with an argument at least a few pixels larger than the largest font size. To set the baseline, which is the distance between the top of the line and the imaginary line on which capital letters rest, send a <Code>
baseline:</Code>
 message to the text style; the argument is the distance in pixels.</StepCont>
<StepCont>
<A ID="pgfId-1041276"></A>
Install the custom text style by sending a <Code>
textStyle:</Code>
 message to the composed text. The argument is the custom <Code>
TextAttributes</Code>
 from step 5.</StepCont>
<StepCont>
<A ID="pgfId-1041278"></A>
Apply the new emphasis to the desired portions of the composed text&#39;s underlying <Code>
Text</Code>
.</StepCont>
<CodeSample>
<A ID="pgfId-1041279"></A>
| txt gc ca ta |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := Object comment asComposedText.
txt compositionWidth: 300.

&quot;Create and install a custom text style.&quot;
ca := CharacterAttributes newWithDefaultAttributes.
ca setDefaultQuery: txt textStyle defaultFont.
ca at: #title put: [ :fontDesc | fontDesc pixelSize: 24].
ta := TextAttributes characterAttributes: ca.
ta lineGrid: 27; baseline: 18.
txt textStyle: ta.

txt text emphasizeAllWith: #title.
txt displayOn: gc at: 5@25.</CodeSample>
<Body1>
<A ID="pgfId-1041295"></A>
In this example text emphases <Code>
#redlined</Code>
 and <Code>
#fixed</Code>
 are added to the <Code>
CharacterAttributes</Code>
 instance.  The <Code>
#redlined</Code>
 emphasis colors text red and underlines it whereas <Code>
#fixed</Code>
 selects a fixed width font.  Three windows are opened to show variations of <Code>
#title</Code>
, <Code>
#redlined</Code>
, and <Code>
#fixed</Code>
 emphases to its text displayed.</Body1>
<CodeSample>
<A ID="pgfId-1041298"></A>
| displayBlock txt ca textAttr |
&#34;This block enables a window to be opened displaying its composed text argument&#34;
	displayBlock := 
		[:text | 
		| view |
		view := ComposedTextView new 
				model: text asValue; 
				textStyle: text textStyle.
			ScheduledWindow new
				 label: text; 
				 component: (LookPreferences edgeDecorator on: view); 
				 openWithExtent: 300 @ 200].

	ca := CharacterAttributes newWithDefaultAttributes.
	ca setDefaultQuery: FontDescription new.
	ca at: #title put: [:fontDesc | fontDesc pixelSize: 24].
	ca at: #fixed put: [:fontDesc | fontDesc fixedWidth: true].
	ca at: #redlined put: [:fontDesc | fontDesc underline: true; color: ColorValue red].
	textAttr := TextAttributes characterAttributes: ca.
	textAttr gridForFont: #title withLead: 2.

	&quot;Display a window with text emphasized in title size&quot;
	txt := ('This is title font' asText emphasizeAllWith: #title) asComposedText.
	txt textStyle: textAttr.
	displayBlock value: txt.

	&quot;Change the text to display redlined and display it in a new window&quot;
	txt text: ('This is red lined font' asText emphasizeAllWith: #redlined).
	displayBlock value: txt.

	&quot;Change the text to display redlined, bold, fixed width at title size and display it in a new window&quot;
	txt text: ('This is bold red lined title fixed font' 
		asText emphasizeAllWith: #(#redlined #bold #title #fixed)).
	displayBlock value: txt</CodeSample>
<Heading4>
<A ID="pgfId-1041333"></A>
Adjust line spacing and baseline</Heading4>
<Body1>
<A ID="pgfId-1041334"></A>
When a text style is created its line spacing and baseline may be changed using the <Code>
lineGrid:</Code>
 and <Code>
baseline:</Code>
 messages.  These changes are often necessary to adjust spacing between lines of small or large text.  The line spacing is set by sending a <Code>
lineGrid:</Code>
 message to the text style, with an argument at least a few pixels larger that the largest font size.  To set the baseline, which is the distance between the top of the line and the imaginary line on which capital letters rest, send a <Code>
baseline:</Code>
 message to the text style; the argument is the distance in pixels.</Body1>
<Body1>
<A ID="pgfId-1041372"></A>
Alternately, instead of declaring text line spacing and baseline these quantities may be setup appropriately for an given text emphasis by using the <Code>
gridForFont:withLead:</Code>
 message.  Send a <Code>
gridForFont:withLead:</Code>
 message to the <Code>
TextAttributes</Code>
 that is held by the composed text. The first argument is the name of the text emphasis (<Code>
#title</Code>
). If this argument is <Code>
nil</Code>
 then the spacing adjustments apply to text without emphasis.  The second argument is the leading, which is the vertical space to be left between one line and the next-- typically zero to two pixels. This adjusts both the line spacing and the baseline to suit the font&#39;s size.</Body1>
<CodeSample>
<A ID="pgfId-1041373"></A>
| txt gc ca ta |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := Object comment asComposedText.

&quot;Create and install a custom text style.&quot;
ca := CharacterAttributes newWithDefaultAttributes.
ca setDefaultQuery: txt textStyle defaultFont.
ca at: #title put: [ :fontDesc | fontDesc pixelSize: 24].
ta := TextAttributes characterAttributes: ca.
ta gridForFont: #title
		withLead: 2.
txt textStyle: ta.

txt text emphasizeAllWith: #title.
txt compositionWidth: 300.
txt displayOn: gc at: 5@25.</CodeSample>
<Heading4>
<A ID="pgfId-1041391"></A>
Set font preferences for a text style</Heading4>
<Body1>
<A ID="pgfId-1041393"></A>
A <Code>
FontDescription</Code>
 is a specification for a font based on typeface family, encoding, name, size or other attributes.  An attribute in a <Code>
FontDescription</Code>
 may be left at or set to <Code>
nil</Code>
 so that particular attribute is ignored in the search for an appropriate font.  A <Code>
CharacterAttributes</Code>
 or <Code>
VariableCharacterAttributes</Code>
 references a <Code>
FontDescription</Code>
 instance to which it may further refine according to the emphases applied in a <Code>
Text</Code>
 instance.  The <Code>
FontDescription</Code>
 is ultimately used to search for the best platform font that matches its specification.  A <Code>
FontDescription</Code>
 may be so loosely specified that any font may be chosen or so tightly specified that it may find no font that satisfies its criteria.</Body1>
<Body1>
<A ID="pgfId-1041395"></A>
A <Code>
FontDescription</Code>
 may have the following attributes set:</Body1>
<DefItem>
<A ID="pgfId-1041397"></A>
name</DefItem>
<DefDscrp>
<A ID="pgfId-1041879"></A>
the name for the font as a string.  The wildcard pattern &#39;<Code>
*</Code>
&#39; may be included to match any characters in its position.  Setting the font name implies that an exact match for this font is wanted on the platform.  This is often too restrictive for use between several installations.</DefDscrp>
<DefItem>
<A ID="pgfId-1041399"></A>
family</DefItem>
<DefDscrp>
<A ID="pgfId-1041880"></A>
a string or an array containing one or more strings.  Each string names a font family or includes the wildcard pattern &#39;<Code>
*</Code>
&#39; for partial matching.  When an array is used a match is attempted up on the first element before succeeding elements are tried.  A string containing only an asterisk is used as the final element in the array to indicate that any alternate is preferable to a <Code>
&#34;font not found&#34;</Code>
 error.</DefDscrp>
<DefItem>
<A ID="pgfId-1041401"></A>
encoding</DefItem>
<DefDscrp>
<A ID="pgfId-1041887"></A>
a string for the desired font encoding</DefDscrp>
<DefItem>
<A ID="pgfId-1041403"></A>
manufacturer</DefItem>
<DefDscrp>
<A ID="pgfId-1041890"></A>
a string or array of strings indentifying the font manufactruer to match.  A wildcard pattern may be included for partial matching.  For some platforms this specification is not relevant.</DefDscrp>
<DefItem>
<A ID="pgfId-1041405"></A>
pixelSize</DefItem>
<DefDscrp>
<A ID="pgfId-1041893"></A>
the font size in pixels</DefDscrp>
<DefItem>
<A ID="pgfId-1041407"></A>
boldness</DefItem>
<DefDscrp>
<A ID="pgfId-1041896"></A>
a number between 0 and 1 for the font boldness desired.  A value above 0.5 implies the font should appear bold.</DefDscrp>
<DefItem>
<A ID="pgfId-1041409"></A>
serif</DefItem>
<DefDscrp>
<A ID="pgfId-1041899"></A>
<Code>
true</Code>
 if a serif font should be used.</DefDscrp>
<DefItem>
<A ID="pgfId-1041411"></A>
color</DefItem>
<DefDscrp>
<A ID="pgfId-1041902"></A>
the color the font should appear in other than black.</DefDscrp>
<DefItem>
<A ID="pgfId-1041413"></A>
fixedWidth</DefItem>
<DefDscrp>
<A ID="pgfId-1041907"></A>
<Code>
true</Code>
 if a fixed width font should be used (e.g. Courier).</DefDscrp>
<DefItem>
<A ID="pgfId-1041415"></A>
italic</DefItem>
<DefDscrp>
<A ID="pgfId-1041910"></A>
<Code>
true</Code>
 for an italic font.</DefDscrp>
<DefItem>
<A ID="pgfId-1041417"></A>
strikeout</DefItem>
<DefDscrp>
<A ID="pgfId-1041913"></A>
<Code>
true</Code>
 if a line should be drawn through the text.</DefDscrp>
<DefItem>
<A ID="pgfId-1041419"></A>
underline</DefItem>
<DefDscrp>
<A ID="pgfId-1041916"></A>
<Code>
true</Code>
 to underline the font.</DefDscrp>
<Body1>
<A ID="pgfId-1041421"></A>
Create a new instance of <Code>
FontDescription</Code>
 and set the preferences desired.  Alternately, the <Code>
FontDescription</Code>
 may be modified from a copy obtained from the default text style as in</Body1>
<CodeSample>
<A ID="pgfId-1041423"></A>
defaultFontDesc := TextAttributes default defaultFont copy.</CodeSample>
<Body1>
<A ID="pgfId-1041425"></A>
Create a <Code>
TextAttributes</Code>
 with default text attributes by sending the message <Code>
defaultFontQuery:</Code>
 to it.  Use the <Code>
FontDescription</Code>
 created earlier as its argument.  If you wish to create a text style with custom text attributes then install the <Code>
FontDescription</Code>
 to the <Code>
CharacterAttributes</Code>
 instance with the message <Code>
setDefaultQuery:</Code>
 then create the <Code>
TextAttributes</Code>
 instance by passing the message <Code>
characterAttributes:</Code>
 with the <Code>
CharacterAttributes</Code>
 instance.</Body1>
<Body1>
<A ID="pgfId-1041427"></A>
The example shows how new text styles for <Code>
ComposedText</Code>
 instances may be created by specifying only the <Code>
FontDescription</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041430"></A>
| displayBlock txt |
&#34;This block enables a window to be opened displaying its composed text argument&#34;
displayBlock := [:text| | view |
view := ComposedTextView  new
	model:  text asValue;
	textStyle:  text textStyle.
ScheduledWindow new
	label: text;
	component: (LookPreferences edgeDecorator on: view);
	openWithExtent: 300@200].

&#34;Display a window with text emphasized 24 pixels high&#34;
txt := 'This is title font'  asComposedText.
txt textStyle: (TextAttributes defaultFontQuery: (FontDescription new pixelSize: 24)).
displayBlock value: txt.

&#34;Display a window with text emphasized red and underlined&#34;
txt := 'This is red lined font'  asComposedText.
txt textStyle:  (TextAttributes defaultFontQuery: (FontDescription new underline: true; color: ColorValue red)).
displayBlock value: txt.

&#34;Display red lined, bold, and fixed width text in 24 pixel size in a new window&#34;
txt := 'This is red lined bold title serif font'  asComposedText.
txt textStyle:  (TextAttributes defaultFontQuery: (FontDescription new 
												pixelSize: 24;
												boldness: 0.8;
												color: ColorValue red;
												underline: true;
												fixedWidth: true)).
displayBlock value: txt.</CodeSample>
<Heading4>
<A ID="pgfId-1041461"></A>
Set font family for a text style</Heading4>
<Body1>
<A ID="pgfId-1041463"></A>
The default font belongs to Helvetica, Arial, or a similar font family, depending on the operating system.  To use a font from one or more alternate families modify the family attribute of the <Code>
FontDescription</Code>
 for the text style.  If you wish to change the font for a limited range of text use the <Code>
#family</Code>
 text emphasis and provide a string or array of strings for the font family to use.</Body1>
<StepStart>
<A ID="pgfId-1041465"></A>
Create a new <Code>
FontDescription</Code>
 and send a <Code>
family:</Code>
 message to it. The argument is an array containing one or more strings. Each string names a font family or a wildcard pattern for partial matching. A string containing an asterisk is frequently used as the final element in the array to indicate that any alternate is preferable to a <Code>
&#34;font not found&#34;</Code>
 error. </StepStart>
<StepCont>
<A ID="pgfId-1041468"></A>
Create a text style by sending a <Code>
defaultFontQuery:</Code>
 message to the <Code>
TextAttributes</Code>
 class. The argument is the <Code>
FontDescription</Code>
 from step 2.</StepCont>
<StepCont>
<A ID="pgfId-1041470"></A>
Adjust the line spacing to suit the font by sending a <Code>
gridForFont:withLead:</Code>
 message to the text style. The first argument is <Code>
nil</Code>
 in this case. The second argument is the amount of leading (space) between lines of text (typically zero to two pixels).</StepCont>
<StepCont>
<A ID="pgfId-1041472"></A>
Install the text style in the composed text by sending a <Code>
textStyle:</Code>
 message to the composed text. The argument is the text style from step 2.</StepCont>
<CodeSample>
<A ID="pgfId-1041473"></A>
| txt gc ta fd |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := Object comment asComposedText.

&quot;Create and use a text style for this font.&quot;
fd := FontDescription new
		family: #( 'bookman' 'times*' '*' );
		serif: true;
		fixedWidth: false;
		pixelSize: 14.
ta := TextAttributes defaultFontQuery: fd.
ta gridForFont: nil
		withLead: 2.
txt textStyle: ta.

txt compositionWidth: 300.
txt displayOn: gc at: 5@25.</CodeSample>
<Heading4>
<A ID="pgfId-1041490"></A>
Set font name for a text style</Heading4>
<Body1>
<A ID="pgfId-1041491"></A>
Create a new <Code>
FontDescription</Code>
 and send a <Code>
name:</Code>
 message to it. The argument is a string that names a font family or a wildcard pattern for partial matching. (The example takes the list of available fonts from the operating system and uses the first one.)</Body1>
<CodeSample>
<A ID="pgfId-1041492"></A>
| txt gc ca ta fd |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := Object comment asComposedText.

&quot;Create and install a custom text style.&quot;
fd := FontDescription new
		name: (Screen default listFontNames at: 1).
ta := TextAttributes defaultFontQuery: fd.
ta gridForFont: nil
		withLead: 2.
txt textStyle: ta.

txt compositionWidth: 300.
txt displayOn: gc at: 5@25. </CodeSample>
<Heading4>
<A ID="pgfId-1041507"></A>
Set font pixel size</Heading4>
<Body1>
<A ID="pgfId-1041509"></A>
Create a new <Code>
FontDescription</Code>
 or access an existing one and send a <Code>
pixelSize:</Code>
 message to it.  The argument is the desired font size in pixels.</Body1>
<Body1>
<A ID="pgfId-1041511"></A>
On platforms such as MS Windows or for PostScript printers font size is usually measured in points.  On MS Windows, the font pixel size equivalent to a given point size is given by the following relationship for most VGA or better screen resolutions:</Body1>
<CodeSample>
<A ID="pgfId-1041513"></A>
pixelSize := (pointSize * (96/72) asFloat) rounded.</CodeSample>
<Body1>
<A ID="pgfId-1041515"></A>
The example below creates a text style for a 22 pixel font given the default font preferences.</Body1>
<CodeSample>
<A ID="pgfId-1041517"></A>
| txt gc ca ta fd |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := Object comment asComposedText.

&quot;Copy the default font description and set its pixel size to 22&#34;
fd := txt textStyle defaultFont copy.
fd pixelSize: 22.
ta := TextAttributes defaultFontQuery: fd.
ta gridForFont: nil
		withLead: 2.
txt textStyle: ta.

txt compositionWidth: 300.
txt displayOn: gc at: 5@25.</CodeSample>
<Body1>
<A ID="pgfId-1041532"></A>
If the text style is scaled (i.e. the text style is an instance of <Code>
VariableSizeTextAttributes</Code>
) then changing the pixel size of its FontDescription will have no effect in text size. Scaled text styles need to be rescaled instead.  Text styles <Code>
#default</Code>
, <Code>
#small</Code>
, <Code>
#large</Code>
, <Code>
#systemDefault</Code>
, and <Code>
#fixed</Code>
 are scaled. Send the message <Code>
scalingFactor:</Code>
 to the scaled text style.  The argument is a ratio of the desired pixel size to the preferred pixel size.</Body1>
<Heading4>
<A ID="pgfId-1041535"></A>
Create a scaled text style</Heading4>
<Body1>
<A ID="pgfId-1041537"></A>
When text is displayed on different screen sizes or resolutions often there is a need to resize text for better visibility.  A text style based on an instance of  <Code>
VariableSizeTextAttributes</Code>
 permits composed text to be scaled relative to a single preferred font pixel size set for the VisualWorks <Code>
Locale</Code>
. A <Code>
VariableCharacterAttributes</Code>
 instance is used with a <Code>
VariableSizeTextAttributes</Code>
 to define the emphases and scaling applied to a composed text.  Instances of <Code>
VariableSizeTextAttributes</Code>
 and <Code>
VariableCharacterAttributes</Code>
 will work in place of <Code>
TextAttributes</Code>
 and <Code>
CharacterAttributes</Code>
 instances; all respond to the same methods to define emphases and format text.  The pixel size attribute for a <Code>
FontDescription</Code>
 installed in a <Code>
VariableCharacterAttributes</Code>
 instance is not used however.  Instead, the <Code>
scalingFactor:</Code>
 message to either a <Code>
VariableSizeTextAttributes</Code>
 or <Code>
VariableCharacterAttributes</Code>
 instance determines text size. </Body1>
<StepStart>
<A ID="pgfId-1041539"></A>
Create a new text style from <Code>
VariableSizeTextAttributes</Code>
 by sending its class the message <Code>
defaultFontQuery:</Code>
 with a <Code>
FontDescription</Code>
.  The example uses the <Code>
FontDescription</Code>
 from the default text style. Alternately, an instance of <Code>
VariableSizeTextAttributes</Code>
 may be created by sending the message <Code>
characterAttributes:</Code>
 with an instance of <Code>
VariableCharacterAttributes</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1041540"></A>
To scale the text style either larger or smaller than the preferred pixel size send the message <Code>
scalingFactor:</Code>
 to the text style from step 1.  The argument is a ratio of the desired pixel size to the preferred pixel size.  For example, if the preferred pixel size is 16 a scaling of 1.5 displays the font at a pixel size of 24.</StepCont>
<StepCont>
<A ID="pgfId-1041542"></A>
Install the text style in the composed text by sending a <Code>
textStyle:</Code>
 message to the composed text. The argument is the text style from step 2.</StepCont>
<CodeSample>
<A ID="pgfId-1042694"></A>
| gc fd largeScaledStyle smallScaledStyle txt |
gc := ExamplesBrowser prepareScratchWindow graphicsContext.

fd := TextAttributes default defaultFont.
&quot;Create scaled text styles&quot;
smallScaledStyle := VariableSizeTextAttributes defaultFontQuery: fd. smallScaledStyle scalingFactor: 0.5.
largeScaledStyle := VariableSizeTextAttributes defaultFontQuery: fd. largeScaledStyle scalingFactor: 2.

&quot;Display text one half the preferred pixel size&quot;
txt:= ComposedText withText: 'This text is scaled small' style: smallScaledStyle.
txt displayOn: gc at: 5@25.

&quot;Display text normal size&quot;
txt:= 'This text is scaled normal' asComposedText.
txt displayOn: gc at: 5@50. 

&quot;Display text twice the preferred pixel size&quot;
txt:= ComposedText withText: 'This text is scaled large' style: largeScaledStyle.
 txt displayOn: gc at: 5@75. </CodeSample>
<Heading4>
<A ID="pgfId-1042698"></A>
Add a text style to the font selection menu</Heading4>
<Body1>
<A ID="pgfId-1042695"></A>
All widgets that display text have a selection of text styles available in a Property Tool when they are under edit in the UI Painter canvas. You can expand the menu to include a custom text style.</Body1>
<StepStart>
<A ID="pgfId-1041567"></A>
Create the desired text style. In the example, a 24-pixel font is created.</StepStart>
<StepCont>
<A ID="pgfId-1041569"></A>
Install the text style in the system&#39;s dictionary of styles by sending a <Code>
styleNamed:put:</Code>
 message to the <Code>
TextAttributes</Code>
 class. The first argument is a lookup name, specified as a <Code>
Symbol</Code>
--a capitalized version of the name will appear in the fonts menu. The second argument is the custom text style.</StepCont>
<CodeSample>
<A ID="pgfId-1041570"></A>
| fd ta |
fd := FontDescription new pixelSize: 24.
ta := TextAttributes defaultFontQuery: fd.
ta gridForFont: fd withLead: 2.

TextAttributes styleNamed: #title put: ta.</CodeSample>
<Heading4>
<A ID="pgfId-1041577"></A>
Set preferred font family</Heading4>
<Body1>
<A ID="pgfId-1041579"></A>
Each text style that displays a different typeface will use a <Code>
FontDescription</Code>
 with a font family list different by either name, number, or order (without use of emphasis).  There is a way to override this and have all text styles choose first a font from a common list of one or more preferred font families.  If no font is found from this family preference list then the text style searches its own list of font families.  </Body1>
<StepStart>
<A ID="pgfId-1041581"></A>
Access the current <Code>
Locale</Code>
 and send the message <Code>
preferredFontFamily:</Code>
 to it.  For the argument provide an array with one or more font family name strings.  The wildcard character &#39;<Code>
*</Code>
&#39; may be used in a name for partial matching.  The example shown below sets the preferred font family to be <Code>
&#39;system&#39;</Code>
 or, if that is not available, then <Code>
&#39;gill&#39;</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1041582"></A>
Refresh the windows that are already open by sending a <Code>
resetViews</Code>
 message to the <Code>
TextAttributes</Code>
 class. When they are redisplayed, they will use the new family preferences.</StepCont>
<CodeSample>
<A ID="pgfId-1041584"></A>
Locale current preferredFontFamily: #(&#39;system&#39; &#39;gill&#39;). 
TextAttributes resetViews.</CodeSample>
<Body1>
<A ID="pgfId-1041587"></A>
Normally the family preference list is empty.  To clear family preferences set the list to be empty. </Body1>
<CodeSample>
<A ID="pgfId-1041589"></A>
Locale current preferredFontFamily: #().</CodeSample>
<Body1>
<A ID="pgfId-1041591"></A>
To determine what the current font family preferences are, if any, send the accessor message <Code>
preferredFontFamily</Code>
 to the current <Code>
Locale</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041593"></A>
^Locale current preferredFontFamily</CodeSample>
<Heading4>
<A ID="pgfId-1041595"></A>
Set preferred font pixel size</Heading4>
<Body1>
<A ID="pgfId-1041597"></A>
When a scaled text style is used such as <Code>
#default</Code>
 the font is scaled relative to the preferred pixel size set for the current <Code>
Locale</Code>
.  One can globally resize all scaled text styles in VisualWorks by changing the preferred font pixel size.</Body1>
<StepStart>
<A ID="pgfId-1041599"></A>
Access the current Locale and send the message <Code>
preferredPixelSize:</Code>
 to it.  Provide a font pixel size as an integer for the argument.   </StepStart>
<StepCont>
<A ID="pgfId-1041600"></A>
Refresh the windows that are already open by sending a <Code>
resetViews</Code>
 message to the <Code>
TextAttributes</Code>
 class. When they are redisplayed, text using a scaled text style will be resized.</StepCont>
<CodeSample>
<A ID="pgfId-1041601"></A>
Locale current preferredPixelSize:18.
TextAttributes resetViews.</CodeSample>
<Body1>
<A ID="pgfId-1041604"></A>
To determine what the preferred font pixel size is send the accessor message <Code>
preferredPixelSize</Code>
 to the current <Code>
Locale</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041606"></A>
^Locale current preferredPixelSize</CodeSample>
<Heading4>
<A ID="pgfId-1041616"></A>
Get platform fonts</Heading4>
<Body1>
<A ID="pgfId-1041617"></A>
When you develop an application for a single platform, rather than for portability to several platforms, specifying a platform-specific font directly gives you the greatest control over font selection. </Body1>
<StepStart>
<A ID="pgfId-1041620"></A>
Get the default <Code>
Screen</Code>
 by sending a <Code>
default</Code>
 message to that class.</StepStart>
<StepCont>
<A ID="pgfId-1041622"></A>
Get the list of platform font names by sending a <Code>
listPlatformFonts</Code>
 message to the default screen.</StepCont>
<CodeSample>
<A ID="pgfId-1041623"></A>
initialize
		platformFonts := SelectionInList 
			with: Screen default listFontNames.

		platformFonts selectionIndexHolder onChangeSend: #changedFont to: self. </CodeSample>
<Body1>
<A ID="pgfId-1042740"></A>
<B>
Online example: </B>
<CodeExample xml:link="simple" href="Font2.pcl" show="embed" actuate="auto">
Font2Example</CodeExample>
</Body1>
<Heading4>
<A ID="pgfId-1042141"></A>
Change the default font</Heading4>
<Body1>
<A ID="pgfId-1042142"></A>
The default font that is used by VisualWorks tools to display textual information can be changed as shown in the basic steps. Widgets in which the <Code>
Default</Code>
 font has been selected, both in system tools and in your applications, are also affected.</Body1>
<StepStart>
<A ID="pgfId-1042143"></A>
Send a <Code>
setDefaultTo:</Code>
 message to the <Code>
TextAttributes</Code>
 class. The argument is the <Code>
Symbol</Code>
 that names the desired text style. The text style must have been defined and installed in the fonts menu previously.</StepStart>
<StepCont>
<A ID="pgfId-1042144"></A>
Refresh the windows that are already open by sending a <Code>
resetViews</Code>
 message to the <Code>
TextAttributes</Code>
 class. When they are redisplayed, they will use the new default.</StepCont>
<CodeSample>
<A ID="pgfId-1042145"></A>
TextAttributes setDefaultTo: #default.
TextAttributes resetViews.</CodeSample>
<Heading4>
<A ID="pgfId-1042122"></A>
Apply the platform default font</Heading4>
<Body1>
<A ID="pgfId-1042123"></A>
The <Code>
System</Code>
 font is selected to mimic the appearance of the platform font for the current UI look. A widget that uses the <Code>
System</Code>
 font has the best chance of looking like other applications on any platform on which it is deployed.</Body1>
<Body1>
<A ID="pgfId-1042124"></A>
The <Code>
System</Code>
 text style can be applied to any composed text.</Body1>
<StepStart>
<A ID="pgfId-1042125"></A>
Get the look policy class as set by the UI look settings by sending a <Code>
preferenceFor:</Code>
 message to the <Code>
UISettings</Code>
 class, with the argument <Code>
#defaultLook</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1042126"></A>
Obtain the system text style by sending message <Code>
systemTextStyle</Code>
 to the look policy class from step 1.</StepCont>
<StepCont>
<A ID="pgfId-1042127"></A>
Send a <Code>
textStyle:</Code>
 message to the composed text. The argument is the text style from step 2.</StepCont>
<CodeSample>
<A ID="pgfId-1042128"></A>
| txt gc lookPolicyClass |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
txt := 'Hello, World' asComposedText.

lookPolicyClass := UISettings preferenceFor: #defaultLook.
txt textStyle: lookPolicyClass systemTextStyle.

txt displayOn: gc at: 5@25.</CodeSample>
<Body1>
<A ID="pgfId-1029452"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040352"></A>
Text Files</Heading3>
<Heading4>
<A ID="pgfId-1040354"></A>
Create a disk file</Heading4>
<Body1>
<A ID="pgfId-1040355"></A>
Send an <Code>
asFilename</Code>
 message to the string identifying the desired file or directory. The disk file or directory is not affected by the mere creation of a <Code>
Filename</Code>
 object. Because no explicit link exists to the disk file or directory, you need not do anything explicit to release the external resource when you are finished with it.</Body1>
<CodeSample>
<A ID="pgfId-1040356"></A>
| name filename |
name := 'test.tmp'.
filename := name asFilename.
^filename</CodeSample>
<Heading4>
<A ID="pgfId-1040360"></A>
Create a disk directory</Heading4>
<Body1>
<A ID="pgfId-1040361"></A>
Send a <Code>
makeDirectory</Code>
 message to the <Code>
Filename</Code>
 representing the desired directory. If the disk directory already exists, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040362"></A>
| directory |
directory := 'test' asFilename.
directory makeDirectory.
^directory exists</CodeSample>
<Heading4>
<A ID="pgfId-1040366"></A>
Construct a portable file name</Heading4>
<Body1>
<A ID="pgfId-1040367"></A>
Send a <Code>
construct:</Code>
 message to the <Code>
Filename</Code>
 representing the parent directory. When a pathname is to represent a hierarchy of nested parent directories, use a series of such <Code>
construct:</Code>
 messages.</Body1>
<CodeSample>
<A ID="pgfId-1040368"></A>
| unixDir portableDir |
unixDir := 'visual/utils' asFilename.

portableDir := 'visual' asFilename
			construct: 'utils'.

unixDir inspect.
portableDir inspect.</CodeSample>
<Heading4>
<A ID="pgfId-1040376"></A>
Check whether a file or directory exists</Heading4>
<Body1>
<A ID="pgfId-1040377"></A>
Send an <Code>
exists</Code>
 message to the <Code>
Filename</Code>
. If the disk file or directory exists, <Code>
true</Code>
 is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040378"></A>
| unlikelyFile |
unlikelyFile := 'qqqqzzzz' asFilename.
^unlikelyFile exists</CodeSample>
<Heading4>
<A ID="pgfId-1040390"></A>
Get the working directory</Heading4>
<Body1>
<A ID="pgfId-1040391"></A>
Send a <Code>
defaultDirectory</Code>
 message to the <Code>
Filename</Code>
 class. A <Code>
Filename</Code>
 representing the working directory is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040392"></A>
| workingDir |
workingDir := Filename defaultDirectory.
^workingDir</CodeSample>
<Heading4>
<A ID="pgfId-1040395"></A>
Get the parent directory</Heading4>
<Body1>
<A ID="pgfId-1040396"></A>
Send a <Code>
directory</Code>
 message to the <Code>
Filename</Code>
. A <Code>
Filename</Code>
 representing the parent directory is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040397"></A>
| dir parentDir |
dir := Filename defaultDirectory.

parentDir := dir directory.
^parentDir</CodeSample>
<Heading4>
<A ID="pgfId-1040402"></A>
Get the parts of a pathname</Heading4>
<Bullet1>
<A ID="pgfId-1040404"></A>
To get the entire pathname as a string, send an <Code>
asString</Code>
 message to the <Code>
Filename</Code>
.</Bullet1>
<Bullet1>
<A ID="pgfId-1040406"></A>
To get the directory part of a pathname, send a <Code>
head</Code>
 message to the <Code>
Filename</Code>
. A string containing the directory&#39;s pathname is returned.</Bullet1>
<Bullet1>
<A ID="pgfId-1040408"></A>
To get the file part of the pathname, send a <Code>
tail</Code>
 message. A string containing the file&#39;s name is returned.</Bullet1>
<CodeSample>
<A ID="pgfId-1040409"></A>
| filename pathString dirString fileString |
filename := Filename defaultDirectory.

pathString := filename asString.
dirString := filename head.
fileString := filename tail.

^'
PATH: ', pathString, '
DIRECTORY: ', dirString, '
FILE: ', fileString</CodeSample>
<Heading4>
<A ID="pgfId-1040420"></A>
Distinguish a file from a directory</Heading4>
<Body1>
<A ID="pgfId-1040421"></A>
Send an <Code>
isDirectory</Code>
 message to the <Code>
Filename</Code>
. If the <Code>
Filename</Code>
 represents a disk directory, <Code>
true</Code>
 is returned. If it represents a disk file, <Code>
false</Code>
 is returned. If neither a file nor a directory with a matching name exists, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040422"></A>
| dir |
dir := Filename defaultDirectory.
^dir isDirectory</CodeSample>
<Heading4>
<A ID="pgfId-1040425"></A>
Get the access and modification times</Heading4>
<StepStart>
<A ID="pgfId-1040427"></A>
Get a dictionary containing dates and times associated with a file or directory by sending a <Code>
dates</Code>
 message to the <Code>
Filename</Code>
. </StepStart>
<StepCont>
<A ID="pgfId-1040429"></A>
Get the desired date-time pair by sending an <Code>
at:</Code>
 message to the dictionary. The argument is <Code>
#accessed</Code>
 for the time at which the file&#39;s contents were most recently accessed. The argument is <Code>
#modified</Code>
 for the time of the most recent modification to the file&#39;s contents. The argument is <Code>
#statusChanged</Code>
 for the time of the most recent change in external attributes of the file, such as ownership and permissions. </StepCont>
<Body1>
<A ID="pgfId-1040430"></A>
If the operating system does not support the requested type of information, nil is returned; otherwise, an array containing a date and a time is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040431"></A>
| newFile stream datesDict modifyDates modifyDate modifyTime |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.
datesDict := newFile dates.
modifyDates := datesDict at: #modified.
modifyDates isNil 
			ifFalse: [
				modifyDate := modifyDates first.
				modifyTime := modifyDates last].
^'</CodeSample>
<Heading4>
<A ID="pgfId-1040758"></A>
Get the size of a file</Heading4>
<Body1>
<A ID="pgfId-1040759"></A>
Send a <Code>
fileSize</Code>
 message to the <Code>
Filename</Code>
. If the file exists, the number of characters it contains is returned. If the file does not exist, an error results. If the <Code>
Filename</Code>
 represents a disk directory rather than a disk file, zero is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040760"></A>
| newFile stream |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

^newFile fileSize.</CodeSample>
<Heading4>
<A ID="pgfId-1040443"></A>
Get the contents of a file</Heading4>
<Body1>
<A ID="pgfId-1040444"></A>
Send a <Code>
contentsOfEntireFile</Code>
 message to a <Code>
Filename</Code>
 representing a disk file. A string is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040445"></A>
| newFile stream contents |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

contents := newFile contentsOfEntireFile.
^contents</CodeSample>
<Heading4>
<A ID="pgfId-1040453"></A>
Get the contents of a directory</Heading4>
<Body1>
<A ID="pgfId-1040454"></A>
Send a <Code>
directoryContents</Code>
 message to a <Code>
Filename</Code>
 representing a disk directory. An array of file and subdirectory names is returned.</Body1>
<CodeSample>
<A ID="pgfId-1040455"></A>
| workingDir contents |
workingDir := Filename defaultDirectory.

contents := workingDir directoryContents.
^contents</CodeSample>
<Heading4>
<A ID="pgfId-1040460"></A>
Store text in a file</Heading4>
<Body1>
<A ID="pgfId-1040461"></A>
Putting a string into a disk file involves using a stream. The technique illustrated erases any existing file contents.</Body1>
<StepStart>
<A ID="pgfId-1040463"></A>
Create a <Code>
Filename</Code>
 by sending an <Code>
asFilename</Code>
 message to a string containing the pathname.</StepStart>
<StepCont>
<A ID="pgfId-1040465"></A>
Create a stream for writing characters onto the file by sending a <Code>
writeStream</Code>
 message to the <Code>
Filename</Code>
.</StepCont>
<StepCont>
<A ID="pgfId-1040467"></A>
Send the string&#39;s characters to the file by sending a <Code>
nextPutAll:</Code>
 message to the stream. The argument is the string. This operation can be repeated for a series of strings.</StepCont>
<StepCont>
<A ID="pgfId-1040469"></A>
Close the stream by sending a <Code>
close</Code>
 message to it.</StepCont>
<CodeSample>
<A ID="pgfId-1040470"></A>
| newFile stream |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

^newFile contentsOfEntireFile</CodeSample>
<Heading4>
<A ID="pgfId-1040477"></A>
Append text to a file</Heading4>
<Body1>
<A ID="pgfId-1040478"></A>
When creating the stream, send an <Code>
appendStream</Code>
 message to the <Code>
Filename</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1040479"></A>
| filename stream |
filename := 'testFile' asFilename.

&quot;Creating the file.&quot;
stream := filename writeStream.
stream nextPutAll: 'FIRST STRING'.
stream close.

&quot;Appending&quot;
stream := filename appendStream.
stream nextPutAll: ' -- SECOND STRING'.
stream close.

^filename contentsOfEntireFile</CodeSample>
<Heading4>
<A ID="pgfId-1040493"></A>
Open an editor on a file</Heading4>
<Body1>
<A ID="pgfId-1040494"></A>
The VisualWorks text editor allows the user to alter the contents of a file. For read-only access to the file, create a canvas containing a read-only text editor or a text editor with a limited menu.</Body1>
<Body1>
<A ID="pgfId-1040495"></A>
Send an <Code>
edit</Code>
 message to the <Code>
Filename</Code>
. If the <Code>
Filename</Code>
 represents a disk directory, an error results. If the <Code>
Filename</Code>
 represents a nonexistent file, an editor is opened with which the user can create the contents of the file.</Body1>
<CodeSample>
<A ID="pgfId-1040496"></A>
| newFile stream |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

newFile edit.</CodeSample>
<Heading4>
<A ID="pgfId-1040503"></A>
Delete a file or directory</Heading4>
<Body1>
<A ID="pgfId-1040504"></A>
On operating systems such as UNIX that support multiple pathnames for the same physical disk file or directory, deleting as shown here removes the reference that is identified by the pathname, but it does not delete the physical file or directory if another reference exists.</Body1>
<StepStart>
<A ID="pgfId-1040506"></A>
If necessary, confirm that the disk file or directory to be deleted exists by sending an <Code>
exists</Code>
 message to the <Code>
Filename</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1040508"></A>
Send a <Code>
delete</Code>
 message to the <Code>
Filename</Code>
.</StepCont>
<CodeSample>
<A ID="pgfId-1040509"></A>
| newFile stream pretest posttest |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.
pretest := newFile exists.

newFile delete.
posttest := newFile exists.

^'
EXISTS BEFORE DELETION: ', pretest printString, '
EXISTS AFTER DELETION: ', posttest printString.</CodeSample>
<Heading4>
<A ID="pgfId-1040522"></A>
Copy a file</Heading4>
<Body1>
<A ID="pgfId-1040523"></A>
Send a copyTo: message to the Filename. The argument is a string containing the pathname of the copy. If the Filename represents a directory or a nonexistent disk file, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040524"></A>
| newFile stream |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

newFile copyTo: 'testFile.tmp'.

^'testFile.tmp' asFilename exists.</CodeSample>
<Heading4>
<A ID="pgfId-1040533"></A>
Move a file</Heading4>
<Body1>
<A ID="pgfId-1040534"></A>
Send a <Code>
moveTo:</Code>
 message to the <Code>
Filename</Code>
. The argument is a string containing the new pathname, which can include a different directory. If the <Code>
Filename</Code>
 represents a directory or a nonexistent disk file, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040535"></A>
| newFile stream |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

newFile moveTo: 'testFile.tmp'.

^'testFile.tmp' asFilename exists.</CodeSample>
<Heading4>
<A ID="pgfId-1040544"></A>
Rename a file</Heading4>
<Body1>
<A ID="pgfId-1040545"></A>
Send a <Code>
renameTo:</Code>
 message to the <Code>
Filename</Code>
. The argument is a string containing the new pathname, which can include a different directory. If the <Code>
Filename</Code>
 represents a directory or a nonexistent disk file, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040546"></A>
| newFile stream |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

newFile renameTo: 'testFile2.tmp'.

^'testFile2.</CodeSample>
<Heading4>
<A ID="pgfId-1040555"></A>
Compare two filenames or files</Heading4>
<StepStart>
<A ID="pgfId-1040557"></A>
To compare two filenames, send an <Code>
=</Code>
 message to one <Code>
Filename</Code>
. The argument is the second <Code>
Filename</Code>
. If they have the same pathname (that is, they point to the same physical disk file), <Code>
true</Code>
 is returned.</StepStart>
<StepCont>
<A ID="pgfId-1040559"></A>
To compare the contents of two disk files, get the contents of each file by sending <Code>
contentsOfEntireFile</Code>
 messages to the <Code>
Filenames</Code>
. Then send an <Code>
=</Code>
 message to one of the resulting strings, with the other string as the argument.</StepCont>
<CodeSample>
<A ID="pgfId-1040560"></A>
| file1 file2 stream pathsAreEqual contentsAreEqual |
file1 := 'fileOne' asFilename.
file2 := 'fileTwo' asFilename.
stream := file1 writeStream.
stream nextPutAll: Object comment.
stream close.
file1 copyTo: file2 asString.

pathsAreEqual := (
			file1 = file2).
contentsAreEqual := (
			file1 contentsOfEntireFile = file2 contentsOfEntireFile).

^'
PATHS ARE EQUAL: ', pathsAreEqual printString, '
CONTENTS ARE EQUAL: ', contentsAreEqual printString.</CodeSample>
<Heading4>
<A ID="pgfId-1040576"></A>
Compare directories</Heading4>
<Body1>
<A ID="pgfId-1040578"></A>
To compare the contents of two disk directories, get the contents of each directory by sending <Code>
directoryContents</Code>
 messages to the <Code>
Filenames</Code>
. Then send an <Code>
=</Code>
 message to one of the resulting arrays, with the other array as the argument.</Body1>
<CodeSample>
<A ID="pgfId-1040579"></A>
| dir1 dir2 pathsAreEqual contentsAreEqual |
dir1 := Filename defaultDirectory.
dir2 := dir1 directory.

pathsAreEqual := (
			dir1 = dir2).
contentsAreEqual := (
			dir1 directoryContents = dir2 directoryContents).

^'
PATHS ARE EQUAL: ', pathsAreEqual printString, '
CONTENTS ARE EQUAL: ', contentsAreEqual printString.</CodeSample>
<Heading4>
<A ID="pgfId-1040591"></A>
Print a file</Heading4>
<Body1>
<A ID="pgfId-1040592"></A>
Some operating systems support printing a text file directly, and others require that it first be converted to or a printer-specific format. The technique shown here prints a file regardless of the operating system, by converting the file contents to a composed text.</Body1>
<StepStart>
<A ID="pgfId-1040594"></A>
Get the contents of the file by sending a <Code>
contentsOfEntireFile</Code>
 message to the <Code>
Filename</Code>
. Convert the resulting string to a <Code>
ComposedText</Code>
 by sending an <Code>
asComposedText</Code>
 message to it.</StepStart>
<StepCont>
<A ID="pgfId-1040596"></A>
Print the composed text by sending a <Code>
hardcopy</Code>
 message to it.</StepCont>
<CodeSample>
<A ID="pgfId-1040597"></A>
| newFile stream contents composedText |
newFile := 'testFile' asFilename printTextFile.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

contents := newFile contentsOfEntireFile.
composedText := contents asComposedText.
composedText hardcopy.</CodeSample>
<Heading4>
<A ID="pgfId-1040606"></A>
Print a file directly</Heading4>
<Body1>
<A ID="pgfId-1040607"></A>
Send a <Code>
printTextFile</Code>
 message to the <Code>
Filename</Code>
. If text file printing is not supported by the operating system, an error results.</Body1>
<CodeSample>
<A ID="pgfId-1040608"></A>
| newFile stream |
newFile := 'testFile' asFilename printTextFile.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

newFile printTextFile</CodeSample>
<Heading4>
<A ID="pgfId-1040615"></A>
Write fields to a data file</Heading4>
<StepStart>
<A ID="pgfId-1040617"></A>
Create a write stream on the file by sending a <Code>
writeStream</Code>
 message to the <Code>
Filename</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1040619"></A>
Create a block in which, for each field of data, a <Code>
nextPutAll:</Code>
 message is sent to the stream with the data string as argument, followed by a <Code>
nextPut:</Code>
 message with the separator character as argument.</StepCont>
<StepCont>
<A ID="pgfId-1040621"></A>
Send an <Code>
ensure:</Code>
 message to the data-writing block. The argument is another block that closes the stream by sending a <Code>
close</Code>
 message to it.</StepCont>
<StepCont>
<A ID="pgfId-1040623"></A>
To confirm the operation, open an editor on the data file.</StepCont>
<CodeSample>
<A ID="pgfId-1040624"></A>
| dataFile stream separator writingBlock |
dataFile := 'dataFile' asFilename.
separator := $,.								&quot;comma&quot;

stream := dataFile writeStream.
writingBlock := [
			ColorValue constantNames do: [ :color |
				stream nextPutAll: color.
				stream nextPut: separator]].
writingBlock ensure: [stream close].

dataFile edit.</CodeSample>
<Heading4>
<A ID="pgfId-1040636"></A>
Read fields from a data file</Heading4>
<StepStart>
<A ID="pgfId-1040638"></A>
Create a read stream on the file by sending a <Code>
readStream</Code>
 message to the <Code>
Filename</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1040640"></A>
Create a block in which the next field of data is fetched by sending an <Code>
upTo:</Code>
 message to the stream, with the separator character as the argument. This is repeated by placing it within an inner block that is repeated until the end of the stream is encountered.</StepCont>
<StepCont>
<A ID="pgfId-1040642"></A>
Send an <Code>
ensure:</Code>
 message to the data-reading block. The argument is another block that closes the stream by sending a <Code>
close</Code>
 message to it.</StepCont>
<CodeSample>
<A ID="pgfId-1040643"></A>
| dataFile stream separator writingBlock colorNames readingBlock |
dataFile := 'dataFile' asFilename.
separator := $,.								&quot;comma&quot;

&quot;Write data&quot;
stream := dataFile writeStream.
writingBlock := [
			ColorValue constantNames do: [ :color |
				stream nextPutAll: color.
				stream nextPut: separator]].
writingBlock ensure: [stream close].

&quot;Read data&quot;
stream := dataFile readStream.
colorNames := OrderedCollection new.
readingBlock := [
			[stream atEnd] whileFalse: [
				colorNames add: (stream upTo: separator)]].
readingBlock ensure: [stream close].

^colorNames</CodeSample>
<Heading4>
<A ID="pgfId-1040664"></A>
Set file permissions</Heading4>
<Body1>
<A ID="pgfId-1040665"></A>
On operating systems such as UNIX that support file and directory permissions, the permission to change a file can be added or removed as shown in the basic steps.</Body1>
<StepStart>
<A ID="pgfId-1040667"></A>
To remove the permission to change the contents of a file or directory, send a <Code>
makeUnwritable</Code>
 message to the <Code>
Filename</Code>
. </StepStart>
<StepCont>
<A ID="pgfId-1040669"></A>
To restore the writing permission, send a <Code>
makeWritable</Code>
 message.</StepCont>
<StepCont>
<A ID="pgfId-1040671"></A>
To find out whether the writing permission is enabled, send a <Code>
canBeWritten</Code>
 message. If the file or directory does not exist, a response of <Code>
true</Code>
 indicates that the parent directory is writable. The <Code>
canBeWritten</Code>
 test works on all operating systems.</StepCont>
<CodeSample>
<A ID="pgfId-1040672"></A>
| newFile stream removed restored |
newFile := 'testFile' asFilename.
stream := newFile writeStream.
stream nextPutAll: Object comment.
stream close.

newFile makeUnwritable.
removed := newFile canBeWritten.

newFile makeWritable.
restored := newFile canBeWritten.

^'
PERMISSION REMOVED: ', removed printString, '
PERMISSION RESTORED: ', restored printString.</CodeSample>
<Body1>
<A ID="pgfId-1040057"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040917"></A>
Geometrics</Heading3>
<Heading4>
<A ID="pgfId-1040919"></A>
Display a point</Heading4>
<Body1>
<A ID="pgfId-1040920"></A>
Displaying a single point is occasionally needed for building a dotted pattern. This is done by displaying a dot.</Body1>
<StepStart>
<A ID="pgfId-1040922"></A>
Create a <Code>
Point</Code>
 by sending an <Code>
@</Code>
 message to the integer representing the x coordinate. The argument is the y coordinate.</StepStart>
<StepCont>
<A ID="pgfId-1040924"></A>
Display the point by sending a <Code>
displayLineFrom:to:</Code>
 message to the graphics context. The first argument is the point and the second argument is a neighboring point, which can be derived by adding 1 to the point.</StepCont>
<CodeSample>
<A ID="pgfId-1040925"></A>
| gc random points |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
random := Random new.
points := OrderedCollection new.

&quot;Create 1000 random points in a 100-pixel square.&quot;
1000 timesRepeat: [
		points add: ((random next * 100) @ (random next * 100))].

&quot;Display each random point.&quot;
points do: [ :pt |
		gc displayLineFrom: pt to: pt + 1]</CodeSample>
<Heading4>
<A ID="pgfId-1040937"></A>
Draw a line</Heading4>
<Body1>
<A ID="pgfId-1040938"></A>
To draw a straight line directly on a display surface:</Body1>
<StepStart>
<A ID="pgfId-1040940"></A>
Get the graphics context of the display surface by sending a <Code>
graphicsContext</Code>
 message.</StepStart>
<StepCont>
<A ID="pgfId-1040942"></A>
Send a <Code>
displayLineFrom:to:</Code>
 message to the graphics context. The first argument is the starting point of the line and the second argument is the endpoint.</StepCont>
<CodeSample>
<A ID="pgfId-1040943"></A>
| gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
5 to: 400 by: 5 do: [ :i | 								gc displayLineFrom: 0@i to: i@400]. </CodeSample>
<Heading4>
<A ID="pgfId-1040946"></A>
Create and display a line segment</Heading4>
<Body1>
<A ID="pgfId-1040947"></A>
Creating a <Code>
LineSegment</Code>
 is useful when your application needs to perform an operation on the line, such as determining its length or scaling it.</Body1>
<StepStart>
<A ID="pgfId-1040949"></A>
Create a line segment by sending a <Code>
from:to:</Code>
 message to the <Code>
LineSegment</Code>
 class. The first argument is the starting point of the line and the second argument is the endpoint.</StepStart>
<StepCont>
<A ID="pgfId-1040950"></A>
Perform any desired operations on the line (in the example, the x dimension is exaggerated by a factor of 10).</StepCont>
<StepCont>
<A ID="pgfId-1040952"></A>
Wrap the line segment in a stroking wrapper by sending an <Code>
asStroker</Code>
 message to it. This equips the line with the ability to render itself.</StepCont>
<StepCont>
<A ID="pgfId-1040954"></A>
Display the wrapped line segment by sending a <Code>
displayOn:</Code>
 message to its stroking wrapper. The argument is the graphics context of the display surface.</StepCont>
<CodeSample>
<A ID="pgfId-1040955"></A>
| gc line scaleFactor |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
scaleFactor := 10@1.

5 to: 400 by: 5 do: [ :i |
		line := LineSegment from: 0@i to: i@400.
		line := line scaledBy: scaleFactor.
		line asStroker displayOn: gc].</CodeSample>
<Heading4>
<A ID="pgfId-1040963"></A>
Create and display a polyline</Heading4>
<Body1>
<A ID="pgfId-1040964"></A>
A jointed, multi-segmented line, or polyline, can be instantiated and drawn as a <Code>
PolyLine</Code>
<A ID="marker-1040965"></A>
.</Body1>
<Body1>
<A ID="pgfId-1040966"></A>
Create a <Code>
Polyline</Code>
 by sending a <Code>
vertices:</Code>
 message to the <Code>
Polyline</Code>
 class. The argument is the collection of vertices. Then wrap the polyline in a stroking wrapper (using <Code>
asStroker</Code>
) and display it on the graphics context (using <Code>
displayOn:</Code>
).</Body1>
<CodeSample>
<A ID="pgfId-1040967"></A>
| gc points x y radians polyline |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
points := OrderedCollection new.
0 to: 360 by: 30 do: [ :angle |
		radians := angle degreesToRadians.
		x := 200 - (200 * radians cos).
		y := 200 - (200 * radians sin).
		points add: x@y].
gc displayPolyline: points.
polyline := Polyline vertices: points.
0.9 to: 0.1 by: -0.1 do: [ :scale |
		polyline := polyline scaledBy: scale.
		polyline asStroker displayOn: gc].</CodeSample>
<Heading4>
<A ID="pgfId-1040980"></A>
Create and display a curved line</Heading4>
<Body1>
<A ID="pgfId-1040981"></A>
A <Code>
Spline</Code>
 is a smooth line that curves at each point in a collection.</Body1>
<StepStart>
<A ID="pgfId-1040983"></A>
Create a <Code>
Spline</Code>
 by sending a <Code>
controlPoints:</Code>
 message to the <Code>
Spline</Code>
 class. The argument is a collection of points.</StepStart>
<StepCont>
<A ID="pgfId-1040985"></A>
Wrap the spline in a stroking wrapper by sending an <Code>
asStroker</Code>
 message to it.</StepCont>
<StepCont>
<A ID="pgfId-1040987"></A>
Display the wrapped spline by sending a <Code>
displayOn:</Code>
 message to the stroking wrapper. The argument is the graphics context.</StepCont>
<CodeSample>
<A ID="pgfId-1040988"></A>
| gc points spline random x y |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
points := OrderedCollection new.
random := Random new.

&quot;Collect 10 random points.&quot;
10 timesRepeat: [
		x := random next * 400.
		y := random next * 400.
		points add: x@y.
		gc displayDotOfDiameter: 8 at: points last].

spline := Spline controlPoints: points.
spline asStroker displayOn: gc.</CodeSample>
<Heading4>
<A ID="pgfId-1041002"></A>
Create and display a bezier curve</Heading4>
<StepStart>
<A ID="pgfId-1041004"></A>
Create a bezier curve by sending a <Code>
start:end:controlPoint1:controlPoint2:</Code>
 message to the <Code>
Bezier</Code>
 class. Each of the arguments is a point.</StepStart>
<StepCont>
<A ID="pgfId-1041006"></A>
Wrap the bezier curve in a stroking wrapper by sending an <Code>
asStroker</Code>
 message to it.</StepCont>
<StepCont>
<A ID="pgfId-1041008"></A>
Display the wrapped spline by sending a <Code>
displayOn:</Code>
 message to the stroking wrapper. The argument is the graphics context.</StepCont>
<CodeSample>
<A ID="pgfId-1041009"></A>
| gc points bezier random x y |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
points := OrderedCollection new.
random := Random new.

&quot;Collect 10 random points.&quot;
4 timesRepeat: [
		x := random next * 400.
		y := random next * 400.
		points add: x@y.
		gc displayDotOfDiameter: 8 at: points last].

bezier := Bezier
		start: (points at: 1)
		end: (points at: 2)
		controlPoint1: (points at: 3)
		controlPoint2: (points at: 4).
bezier asStroker displayOn: gc.</CodeSample>
<Heading4>
<A ID="pgfId-1041027"></A>
Create and display a polygon</Heading4>
<Body1>
<A ID="pgfId-1041029"></A>
A polygon is a filled <Code>
Polyline</Code>
<A ID="marker-1041028"></A>
. A polygon can be created and displayed from a collection of vertices. </Body1>
<StepStart>
<A ID="pgfId-1041031"></A>
Send a <Code>
displayPolygon:</Code>
 message to the graphics context of the display surface. The argument is a collection of points, each point representing one vertex of the polygon.</StepStart>
<StepCont>
<A ID="pgfId-1041033"></A>
Alternatively, create an instance of <Code>
Polyline</Code>
 by sending a <Code>
vertices:</Code>
 message to the <Code>
Polyline</Code>
 class, with the vertex points as the argument. Wrap the polyline in a stroking or filling wrapper (using <Code>
asStroker</Code>
 or <Code>
asFiller</Code>
) and display the wrapped polygon by sending <Code>
displayOn:</Code>
 to the wrapper with the graphics context as argument. A variant of <Code>
displayOn:</Code>
 (used here) enables you to specify the origin--that is, the upper- left corner of the rectangle containing the polygon.</StepCont>
<CodeSample>
<A ID="pgfId-1041528"></A>
| gc points x y radians polyline origin |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
points := OrderedCollection new.
0 to: 360 by: 30 do: [ :angle |
		radians := angle degreesToRadians.
		x := 200 - (200 * radians cos).
		y := 200 - (200 * radians sin).
		points add: x@y].

gc displayPolygon: points.

polyline := Polyline vertices: points.
0.9 to: 0.1 by: -0.1 do: [ :scale |
		gc paint: (ColorValue brightness: 1 - scale).
		polyline := polyline scaledBy: scale.
		origin := 200@200 - (polyline bounds width / 2).
		polyline asFiller displayOn: gc at: origin].</CodeSample>
<Heading4>
<A ID="pgfId-1041532"></A>
Create and display a rectangle</Heading4>
<Body1>
<A ID="pgfId-1041529"></A>
A <Code>
Rectangle</Code>
 is a special case of a polygon that provides an extended set of operations because it is so commonly used in constructing complex views. A rectangle is commonly created by specifying its origin point and either its lower-right corner or its extent, as shown in the variant.</Body1>
<StepStart>
<A ID="pgfId-1041054"></A>
Create a rectangle (in the example, <Code>
rect1</Code>
) by sending an <Code>
extent:</Code>
 message to the point representing the origin. The argument is a point whose x value indicates the width of the rectangle and whose y value indicates the height.</StepStart>
<StepCont>
<A ID="pgfId-1041056"></A>
Alternatively, create a rectangle (<Code>
rect2</Code>
) by sending a <Code>
corner:</Code>
 message to the origin point. The argument is the lower-right corner point.</StepCont>
<StepCont>
<A ID="pgfId-1041058"></A>
Wrap the rectangle in a stroking or filling wrapper (using <Code>
asStroker</Code>
 or <Code>
asFiller</Code>
) and display the resulting wrapper on a graphics context.</StepCont>
<CodeSample>
<A ID="pgfId-1041059"></A>
| gc rect1 rect2 border |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

&quot;Black rectangle&quot;
rect1 := 100@100 extent: 200@200.
rect1 asFiller displayOn: gc.

&quot;Gray rectangle&quot;
border := 3.
rect2 := (rect1 origin + border) corner: (rect1 corner - border).
rect2 asFiller displayOn: (gc paint: ColorValue gray).</CodeSample>
<Heading4>
<A ID="pgfId-1041070"></A>
Create and display a circle</Heading4>
<Body1>
<A ID="pgfId-1041071"></A>
A circle is created by specifying its center point and radius, as shown in the basic steps. </Body1>
<StepStart>
<A ID="pgfId-1041073"></A>
Send a <Code>
center:radius:</Code>
 message to the <Code>
Circle</Code>
 class. The first argument is the center point of the circle. The second argument is an integer indicating the radius of the circle.</StepStart>
<StepCont>
<A ID="pgfId-1041075"></A>
Wrap the circle in a stroking or filling wrapper by sending <Code>
asStroker</Code>
 or <Code>
asFiller</Code>
 to it.</StepCont>
<StepCont>
<A ID="pgfId-1041077"></A>
Display the wrapped circle by sending <Code>
displayOn:</Code>
 to it, with the graphics context as argument.</StepCont>
<CodeSample>
<A ID="pgfId-1041078"></A>
| gc circle |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

&quot;Blue filled circle&quot;
circle := Circle center: 200@200 radius: 100.
circle asFiller displayOn: (gc paint: ColorValue blue).

&quot;Black stroked circle&quot;
gc paint: ColorValue black; lineWidth: 2.
circle asStroker displayOn: gc.</CodeSample>
<Heading4>
<A ID="pgfId-1041088"></A>
Create and display a filled circle</Heading4>
<Body1>
<A ID="pgfId-1041089"></A>
Send a <Code>
displayDotOfDiameter:at:</Code>
 message to the graphics context of the display surface. The first argument is the diameter of the circle. The second argument is the center point.</Body1>
<CodeSample>
<A ID="pgfId-1041090"></A>
| gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

gc displayDotOfDiameter: 200 at: 200@200.</CodeSample>
<Heading4>
<A ID="pgfId-1041094"></A>
Create and display an ellipse</Heading4>
<Body1>
<A ID="pgfId-1041095"></A>
An ellipse is created by specifying the rectangle that encloses it, as well as the beginning angle and the number of degrees traversed (the sweep angle) from that starting angle. For a complete ellipse, the angles are 0 and 360, as shown in the second variant. When the bounding rectangle is a square, the ellipse is circular.</Body1>
<StepStart>
<A ID="pgfId-1041097"></A>
For a stroked ellipse, send a <Code>
displayArcBoundedBy:startAngle:sweepAngle:</Code>
 message to the graphics context. The first argument is the rectangle that encloses the ellipse. The second argument is 0 and the third argument is 360.</StepStart>
<StepCont>
<A ID="pgfId-1041099"></A>
For a filled ellipse, send a <Code>
displayWedgeBoundedBy:startAngle:sweepAngle:</Code>
 message to the graphics context, with the same arguments as above.</StepCont>
<StepCont>
<A ID="pgfId-1041101"></A>
Alternatively, create an instance of <Code>
EllipticalArc</Code>
 by sending a <Code>
boundingBox:startAngle:sweepAngle:</Code>
 message to that class. The arguments are the same as above. Then wrap the ellipse in a stroking or filling wrapper and display it on the graphics context.</StepCont>
<CodeSample>
<A ID="pgfId-1041102"></A>
| gc ellipse |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

&quot;Black stroked ellipse&quot;
gc displayArcBoundedBy: (150@100 extent: 100@200)
		startAngle: 0
		sweepAngle: 360.

&quot;Black filled ellipse&quot;
gc displayWedgeBoundedBy: (160@110 extent: 80@180)
		startAngle: 0
		sweepAngle: 360.

&quot;Red ellipse&quot;
ellipse := EllipticalArc
		boundingBox: (150@175 extent: 100@50)
		startAngle: 0
		sweepAngle: 360.
ellipse asFiller displayOn: (gc paint: ColorValue red)</CodeSample>
<Heading4>
<A ID="pgfId-1041121"></A>
Create and display an arc</Heading4>
<Body1>
<A ID="pgfId-1041122"></A>
Use the same technique as for displaying a full ellipse, but the <Code>
startAngle</Code>
 argument is the angle at which the arc or wedge begins, measured in degrees clockwise from the 3 o&#39;clock position. The <Code>
sweepAngle</Code>
 argument is the number of degrees spanned by the arc, measured clockwise from the starting angle.</Body1>
<CodeSample>
<A ID="pgfId-1041123"></A>
| gc arc box |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
box := 150@100 extent: 100@200.

&quot;Black stroked arc&quot;
gc displayArcBoundedBy: box
		startAngle: 0
		sweepAngle: 180.

&quot;Black filled arc&quot;
gc displayWedgeBoundedBy: box
		startAngle: 180
		sweepAngle: 90.

&quot;Red arc&quot;
arc := EllipticalArc
		boundingBox: box
		startAngle: 270
		sweepAngle: 90.
arc asFiller displayOn: (gc paint: ColorValue red)</CodeSample>
<Heading4>
<A ID="pgfId-1041143"></A>
Set the line thickness</Heading4>
<Body1>
<A ID="pgfId-1041144"></A>
By default, lines, arcs, and polygons are drawn with a one-pixel line. When you increase the line thickness, extra pixels are spread evenly on both sides of the actual line.</Body1>
<Body1>
<A ID="pgfId-1041145"></A>
Send a <Code>
lineWidth:</Code>
 message to the graphics context of the display surface. The argument is an integer indicating the number of pixels of thickness.</Body1>
<CodeSample>
<A ID="pgfId-1041146"></A>
| gc rect |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
rect := 10@10 extent: 30@30.

2 to: 20 by: 2 do: [ :width |
		gc lineWidth: width.
		rect moveBy: 30@30.
		rect asStroker displayOn: gc].</CodeSample>
<Heading4>
<A ID="pgfId-1041154"></A>
Set the line cap style</Heading4>
<Body1>
<A ID="pgfId-1041155"></A>
By default, lines and arcs are drawn with butt ends. When two thick lines share an endpoint, butt ends produce a notched joint. Changing the cap style to projecting fixes this by extending each end of the line by half of its thickness. Another solution is to use round ends, which extend the ends in a semicircle.</Body1>
<Body1>
<A ID="pgfId-1041156"></A>
Send a <Code>
capStyle:</Code>
 message to the graphics context of the display surface. The argument is derived by sending a <Code>
capButt</Code>
, <Code>
capProjecting</Code>
, or <Code>
capRound</Code>
 message to the <Code>
GraphicsContext</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1041157"></A>
| gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
gc lineWidth: 20.

&quot;Butt line caps -- the default&quot;
gc capStyle: GraphicsContext capButt.
gc displayLineFrom: 100@100 to: 300@100.
gc displayLineFrom: 300@100 to: 300@300.

&quot;Projecting line caps&quot;
gc capStyle: GraphicsContext capProjecting.
gc displayLineFrom: 100@150 to: 250@150.
gc displayLineFrom: 250@150 to: 250@300.

&quot;Round line caps&quot;
gc capStyle: GraphicsContext capRound.
gc displayLineFrom: 100@200 to: 200@200.
gc displayLineFrom: 200@200 to: 200@300.</CodeSample>
<Heading4>
<A ID="pgfId-1041175"></A>
Set the line join style</Heading4>
<Body1>
<A ID="pgfId-1041176"></A>
By default, a polyline or polygon is drawn with mitered joints. In some situations, a beveled or rounded joint is preferable. The basic step shows how to change the join style.</Body1>
<Body1>
<A ID="pgfId-1041177"></A>
Send a <Code>
joinStyle:</Code>
 message to the graphics context of the display surface. The argument is derived by sending a <Code>
joinMiter</Code>
, <Code>
joinBevel</Code>
, or <Code>
joinRound</Code>
 message to the <Code>
GraphicsContext</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1041178"></A>
| gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
gc lineWidth: 30.

&quot;Miter joins -- the default&quot;
gc joinStyle: GraphicsContext joinMiter.
gc displayPolyline: 
		(Array with: 100@200 with: 200@50 with: 300@200).

&quot;Bevel joins&quot;
gc joinStyle: GraphicsContext joinBevel.
gc displayPolyline: 
		(Array with: 100@300 with: 200@150 with: 300@300).

&quot;Round joins&quot;
gc joinStyle: GraphicsContext joinRound.
gc displayPolyline: 
		(Array with: 100@400 with: 200@250 with: 300@400).</CodeSample>
<Heading4>
<A ID="pgfId-1041196"></A>
Color a graphic</Heading4>
<Body1>
<A ID="pgfId-1041197"></A>
By default, a color-based display surface (<Code>
ApplicationWindow</Code>
 or <Code>
Pixmap</Code>
) displays geometric objects in black. You change the color by installing a new paint (color or pattern) in the graphics context.</Body1>
<Body1>
<A ID="pgfId-1041198"></A>
Send a <Code>
paint:</Code>
 message to the graphics context of the display surface. The argument is a color or pattern.</Body1>
<CodeSample>
<A ID="pgfId-1041685"></A>
| gc circle colors |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
circle := Circle center: 200@200 radius: 200.
colors := ColorValue constantNames.

colors do: [ :colorName |
		gc paint: (ColorValue perform: colorName).
		circle := circle scaledBy: 0.9.
		circle asFiller displayOn: gc]</CodeSample>
<Heading4>
<A ID="pgfId-1041686"></A>
Store a color with a graphical object</Heading4>
<Body1>
<A ID="pgfId-1041687"></A>
When the graphic object is going to be reused the color information needs to be kept with it. Using a wrapper keeps track of the paint to be used for its component.</Body1>
<StepStart>
<A ID="pgfId-1041211"></A>
Wrap the geometric object in a stroking or filling wrapper by sending <Code>
asStroker</Code>
 or <Code>
asFiller</Code>
 to it.</StepStart>
<StepCont>
<A ID="pgfId-1041213"></A>
Wrap the stroking or filling wrapper in a <Code>
GraphicsAttributesWrapper</Code>
 by sending an <Code>
on:</Code>
 message to that class, with the wrapper from the basic step as the argument.</StepCont>
<StepCont>
<A ID="pgfId-1041215"></A>
Create a new <Code>
GraphicsAttributes</Code>
 and send a <Code>
paint:</Code>
 message to it. The argument is a color or pattern.</StepCont>
<StepCont>
<A ID="pgfId-1041217"></A>
Install the graphics attributes in the <Code>
GraphicsAttributesWrapper</Code>
 by sending an <Code>
attributes:</Code>
 message with the attributes as the argument.</StepCont>
<StepCont>
<A ID="pgfId-1041219"></A>
Display the graphics attributes wrapper by sending a <Code>
displayOn:at:</Code>
 message to it. The first argument is the graphics context of the display surface. The second argument is the origin point at which the geometric object is to be displayed.</StepCont>
<CodeSample>
<A ID="pgfId-1041220"></A>
| gc circle wrapper1 wrapper2 random pt attributes1 attributes2 |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
circle := Circle center: 0@0 radius: 50.

wrapper1 := GraphicsAttributesWrapper on: circle asFiller.
attributes1 := GraphicsAttributes new paint: ColorValue red.
wrapper1 attributes: attributes1.

wrapper2 := GraphicsAttributesWrapper on: circle asFiller.
attributes2 := GraphicsAttributes new paint: ColorValue blue.
wrapper2 attributes: attributes2.

random := Random new.
100 timesRepeat: [
		pt := random next * 300 + 50 @ (random next * 300 + 50).
		wrapper1 displayOn: gc at: pt.
		pt := random next * 300 + 50 @ (random next * 300 + 50).
		wrapper2 displayOn: gc at: pt]</CodeSample>
<Heading4>
<A ID="pgfId-1041238"></A>
Integrate a graphic into an application</Heading4>
<Body1>
<A ID="pgfId-1041239"></A>
Integrating a graphic relies on the fact that a view is automatically sent a <Code>
displayOn:</Code>
 message whenever its containing window is damaged. A model can also redisplay a graphic when it changes</Body1>
<StepStart>
<A ID="pgfId-1041242"></A>
In the view that is responsible for displaying the graphic, create a <Code>
displayOn:</Code>
 method. This method creates the graphic object based on data from the model and displays the graphic objects on the graphics context. This method is triggered whenever an <Code>
invalidate</Code>
 message is received by the view.</StepStart>
<CodeSample>
<A ID="pgfId-1041244"></A>
displayOn: aGraphicsContext
		self model isNil ifTrue: [^self].

		self model strokes do: [ :stroke |
			aGraphicsContext displayPolyline: stroke].</CodeSample>
<StepCont>
<A ID="pgfId-1041249"></A>
In any method in the domain model that affects the graphic, send a <Code>
changed:with:</Code>
 message to <Code>
self</Code>
. The first argument is a symbol identifying the nature of the change. The second argument is needed by the view to display the appropriate graphic.</StepCont>
<CodeSample>
<A ID="pgfId-1041250"></A>
add: aPoint
		&quot;Add aPoint to the current stroke.&quot;

		self strokes last add: aPoint.
		self changed: #stroke with: self currentLineSegment.</CodeSample>
<StepCont>
<A ID="pgfId-1041256"></A>
When the change in the model is such that the view needs no data or control parameter, use <Code>
nil</Code>
 as the second argument in the <Code>
changed:with:</Code>
 message. </StepCont>
<CodeSample>
<A ID="pgfId-1041257"></A>
eraseAll
		&quot;Erase my contents.&quot;

		self strokes removeAll: self strokes copy.
		self changed: #erase with: nil.</CodeSample>
<StepCont>
<A ID="pgfId-1041263"></A>
In the view (<Code>
SketchView</Code>
), create an <Code>
update:with:</Code>
 method in an updating protocol. This method is invoked by the model whenever it changes and is responsible for updating its display based on the aspect of the model that changed. </StepCont>
<CodeSample>
<A ID="pgfId-1041264"></A>
update: anAspect with: anObject
		&quot;When a point is added to the model...&quot;
		anAspect == #stroke
			ifTrue: [anObject asStroker displayOn: self graphicsContext].

		&quot;When the model erases its contents...&quot;
		anAspect == #erase
			ifTrue: [self invalidate].</CodeSample>
<StepCont>
<A ID="pgfId-1041273"></A>
When an entirely new model is given to the view using its <Code>
model:</Code>
 method, the view sends <Code>
invalidate</Code>
 to itself, again causing a <Code>
displayOn:</Code>
 message to be sent to the view with the appropriate graphics context. Because <Code>
model:</Code>
 overrides an inherited method with that name, begin the method by invoking the inherited version by sending a <Code>
model:</Code>
 message to <Code>
super</Code>
.</StepCont>
<CodeSample>
<A ID="pgfId-1041274"></A>
model: aModel
		super model: aModel.
		self invalidate.

		&quot;Tell the controller where to send menu messages.&quot;
		self controller performer: aModel.</CodeSample>
<Body1>
<A ID="pgfId-1041760"></A>
<B>
Online example: </B>
<CodeExample xml:link="simple" href="CustomView.pcl" show="embed" actuate="auto">
CustomViewExample</CodeExample>
, <CodeExample xml:link="simple" href="CustomView.pcl" show="embed" actuate="auto">
Sketch</CodeExample>
 and <CodeExample xml:link="simple" href="CustomView.pcl" show="embed" actuate="auto">
SketchView</CodeExample>
</Body1>
<Body1>
<A ID="pgfId-1029452"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040361"></A>
<A ID="Images, Cursors, and Icons"></A>
Images, Cursors, and Icons</Heading3>
<Heading4>
<A ID="pgfId-1040374"></A>
Capturing a screen image programmatically</Heading4>
<StepStart>
<A ID="pgfId-1040376"></A>
In a Workspace, send a <Code>
fromUser</Code>
 message to the <Code>
Image</Code>
 class. The cursor changes to a cross-hair.</StepStart>
<CodeSample>
<A ID="pgfId-1040377"></A>
| gc capturedImage |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
capturedImage := Image fromUser.
capturedImage displayOn: gc.</CodeSample>
<StepCont>
<A ID="pgfId-1040381"></A>
Press the &lt;Select&gt; mouse button at the upper-left corner of the desired rectangle, drag to the lower-right corner, and then release the mouse button.</StepCont>
<Body1>
<A ID="pgfId-1041521"></A>
<B>
See also:</B>
</Body1>
<Bullet1>
<A ID="pgfId-1041522"></A>
<A href="07-frameworks.xml#id(Capture an image from the screen)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">Capture an image from the screen</A></Bullet1>
<Heading4>
<A ID="pgfId-1040382"></A>
Creating a blank image</Heading4>
<Body1>
<A ID="pgfId-1040383"></A>
Send an <Code>
extent:depth:palette:</Code>
 message to the <Code>
Image</Code>
 class. The <Code>
extent</Code>
 argument is a <Code>
Point</Code>
 whose <I>
x</I>
 coordinate controls the width of the image (in pixels) and whose <I>
y</I>
 coordinate controls the height. The <Code>
depth</Code>
 argument is an integer indicating the color depth of the image. The <Code>
palette</Code>
 argument is a color palette from which the image draws its colors.</Body1>
<CodeSample>
<A ID="pgfId-1040384"></A>
| blankImage palette |
palette := Screen default colorPalette.

blankImage := Image
			extent: 8@8
			depth: (palette depth)
			palette: palette.
^blankImage</CodeSample>
<Heading4>
<A ID="pgfId-1040392"></A>
Create an image from a display surface</Heading4>
<Body1>
<A ID="pgfId-1040393"></A>
Send an <Code>
asImage</Code>
 message to a display surface (window, <Code>
Pixmap</Code>
, or <Code>
Mask</Code>
). In the case of a window, the window must not be overlapped by other windows.</Body1>
<CodeSample>
<A ID="pgfId-1040394"></A>
| gc window image |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
window := Window currentWindow.
			window raise.

image := window asImage.
image displayOn: gc.</CodeSample>
<Heading4>
<A ID="pgfId-1040401"></A>
Create an image from a byte array</Heading4>
<Body1>
<A ID="pgfId-1040402"></A>
Send an <Code>
extent:depth:palette:bits:pad:</Code>
 message to the <Code>
Image</Code>
 class. The <Code>
bits</Code>
 argument is a <Code>
ByteArray</Code>
 specifying the color for each pixel, using the color encodings from the palette with a multiple of 32 bits per row. The <Code>
pad</Code>
 argument is 8, 16, or 32. Because each row in the byte array must contain a multiple of 32 bits, the pad size appends 8 bits to a 24-bit row, 16 bits to a 16-bit row (as in the example), or none to a 32-bit row, as a convenience.</Body1>
<CodeSample>
<A ID="pgfId-1040826"></A>
| gc lampImage |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

lampImage := Image
			extent: 16@16
			depth: 1
			palette: MappedPalette whiteBlack
			bits: #[
				2r00011111 2r11111000
				2r00011111 2r11111000
				2r00111111 2r11111100
				2r00111111 2r11111100
				2r00111111 2r11111100
				2r01111111 2r11111110
				2r01111111 2r11111110
				2r11111111 2r11111111
				2r11111111 2r11111111
				2r00000011 2r11000000
				2r00001111 2r11110000
				2r00011111 2r11111000
				2r00011111 2r11111000
				2r00001111 2r11110000
				2r00001111 2r11110000
				2r00000111 2r11100000]
			pad: 16.

lampImage displayOn: gc at: 10@10.</CodeSample>
<Heading4>
<A ID="pgfId-1040847"></A>
<A ID="Load an image from a file"></A>
Load an image from a file</Heading4>
<Body1>
<A ID="pgfId-1041041"></A>
Send a <Code>
fromFile:</Code>
 message to class <Code>
ImageReader</Code>
.</Body1>
<CodeSample>
<A ID="pgfId-1041053"></A>
| image |
image := (ImageReader fromFile:'myfile.bmp') image.
^bitmap</CodeSample>
<Body1>
<A ID="pgfId-1041045"></A>
Specify the bitmap file pathname in place of  '<Platform>
myfile.bmp</Platform>
'.</Body1>
<Heading4>
<A ID="pgfId-1040432"></A>
Display an image</Heading4>
<Body1>
<A ID="pgfId-1040433"></A>
An image can display itself on a graphics context. Note that an image&#39;s palette cannot be color-based if you intend to display it on a coverage-based <Code>
Mask</Code>
 rather than a color-based <Code>
Window</Code>
 or <Code>
Pixmap</Code>
.</Body1>
<StepStart>
<A ID="pgfId-1040435"></A>
Send a <Code>
displayOn:</Code>
 message to the image. The argument is the graphics context of the display surface on which the image is to be displayed.</StepStart>
<StepCont>
<A ID="pgfId-1040437"></A>
To specify a display origin other than the default <Code>
0@0</Code>
, send a <Code>
displayOn:at:</Code>
 message to the image. The first argument is the graphics context and the second argument is a <Code>
Point</Code>
 indicating the origin of the image relative to the display surface&#39;s origin.</StepCont>
<CodeSample>
<A ID="pgfId-1040438"></A>
| gc logo |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
logo := LogoExample logo.
logo convertForGraphicsDevice: Screen default.

logo displayOn: gc.
logo displayOn: gc at: 50@50.</CodeSample>

<Body1>The <Code>convertForGraphicsDevice:</Code> message is necessary to ensure that the image displays properly, by making sure that the color depth and bits per pixel are correct. While it is not always required, it is strongly recommended, especially for images that are read from files.</Body1>
<Heading4>
<A ID="pgfId-1040444"></A>
Create a display surface bearing an image</Heading4>
<Body1>
<A ID="pgfId-1040445"></A>
A common situation requires creating a hidden display surface (<Code>
Mask</Code>
 or <Code>
Pixmap</Code>
) of the same size as an image and then displaying the image on it. </Body1>
<Body1>
<A ID="pgfId-1040446"></A>
Send an <Code>
asRetainedMedium</Code>
 message to the image. If the image has a color-based palette, a <Code>
Pixmap</Code>
 will be returned. If the image has a coverage-based palette, a <Code>
Mask</Code>
 will be returned.</Body1>
<CodeSample>
<A ID="pgfId-1040447"></A>
| image pixmap |
image := LogoExample logo.

pixmap := image asRetainedMedium.
^pixmap</CodeSample>
<Heading4>
<A ID="pgfId-1040452"></A>
Display a masked image on a label or button</Heading4>
<Body1>
<A ID="pgfId-1040453"></A>
A graphic label may be displayed in place of text for an action button, radio button, check box, or label.</Body1>
<StepStart>
<A ID="pgfId-1040454"></A>
Select the action button, radio button, check box, or label in the canvas.</StepStart>
<StepCont>
<A ID="pgfId-1040455"></A>
In the <A href="03-tools.xml#id(GUI Painter Tool)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">GUI Painter Tool</A>, turn on the widget&#39;s <UI-Label>
Label is Image</UI-Label>
 property.</StepCont>
<StepCont>
<A ID="pgfId-1040456"></A>
In the <UI-Label>
Message</UI-Label>
 property field, enter the name of the method that returns a graphic image (usually a <A href="10-glossary.xml#id(resource method)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">resource method</A>).</StepCont>
<StepCont>
<A ID="pgfId-1040457"></A>
<UI-Label>
Apply</UI-Label>
 the properties and <UI-Label>
Install</UI-Label>
 the canvas.</StepCont>
<Body1>
<A ID="pgfId-1040458"></A>
An <Code>
OpaqueImage</Code>
 may be used as the graphic label with the image background subtracted when it is created from an <Code>
Image</Code>
 and a <Code>
Mask</Code>
.</Body1>
<StepStart>
<A ID="pgfId-1040460"></A>
Create an accessor method that answers a new <Code>
OpaqueImage</Code>
 created by sending the message <Code>
figure:mask:</Code>
 to it.  Provide as arguments the <Code>
Image</Code>
 to serve as the graphic and a matching <Code>
Mask</Code>
 whose pixels for the background to be subtracted are white and the remaining pixels are black.</StepStart>
<StepCont>
<A ID="pgfId-1040461"></A>
Enter the name of this method in the <UI-Label>
Message</UI-Label>
 property field for the widget as in step 3 above.</StepCont>
<CodeSample>
<A ID="pgfId-1040462"></A>
	&#34;Show an opaque image to be used as a label&#34;
	| gc logo |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
			logo := OpaqueImage
				figure: OpaqueLabelExample logoImage
				shape: OpaqueLabelExample logoMask.
logo displayOn: gc.</CodeSample>
<Body1>
<A ID="pgfId-1041496"></A>
<B>
Online example: </B>
<CodeExample xml:link="simple" href="OpqLabel.pcl" show="embed" actuate="auto">
OpaqueLabelExample</CodeExample>
</Body1>
<Heading4>
<A ID="pgfId-1040469"></A>
Set the color value of a pixel</Heading4>
<Body1>
<A ID="pgfId-1040470"></A>
You can specify the color of a pixel by specifying its color value. The colors must exist in the image's palette.</Body1>
<StepStart>
<A ID="pgfId-1040472"></A>
To get the current color of a pixel, send a <Code>
valueAtPoint:</Code>
 message to the image. The argument is a <Code>
Point</Code>
 indicating the coordinates of the pixel in the image.</StepStart>
<StepCont>
<A ID="pgfId-1040474"></A>
To change the color of a pixel, send a <Code>
valueAtPoint:put:</Code>
 message to the image. The first argument is the location of the pixel, and the second is a color that exists in the image&#39;s palette. </StepCont>
<CodeSample>
<A ID="pgfId-1040475"></A>
| gc logo oldColor newColor white black |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
logo := LogoExample logo.
white := ColorValue white.
black := ColorValue black.

&quot;Change each black pixel to white, and vice versa.&quot;
0 to: logo height -1 do: [ :y |
			0 to: logo width - 1 do: [ :x |
				oldColor := logo valueAtPoint: x@y.
				oldColor = white
					ifTrue: [newColor := black]
					ifFalse: [newColor := white].

				logo valueAtPoint: x@y put: newColor]].

logo displayOn: gc</CodeSample>
<Heading4>
<A ID="pgfId-1040492"></A>
Set a pixel color by numeric value</Heading4>
<StepStart>
<A ID="pgfId-1040494"></A>
To get the current color number of a pixel, send an <Code>
atPoint:</Code>
 message to the image. The argument is a <Code>
Point</Code>
 indicating the coordinates of the pixel in the image. The number that identifies the pixel color in the image&#39;s palette is returned.</StepStart>
<StepCont>
<A ID="pgfId-1040496"></A>
To change the color of a pixel, send an <Code>
atPoint:put:</Code>
 message to the image. The first argument is the location of the pixel and the second argument is a color number that exists in the image&#39;s palette. </StepCont>
<CodeSample>
<A ID="pgfId-1040497"></A>
| gc logo oldColor newColor |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
logo := LogoExample logo.

&quot;Change each black pixel to white, and vice versa.&quot;
0 to: logo height -1 do: [ :y |
			0 to: logo width - 1 do: [ :x |
				oldColor := logo atPoint: x@y.
				oldColor = 1
					ifTrue: [newColor := 0]
					ifFalse: [newColor := 1].

				logo atPoint: x@y put: newColor]].

logo displayOn: gc</CodeSample>
<Heading4>
<A ID="pgfId-1040512"></A>
Mask a rectangular part of an image</Heading4>
<Body1>
<A ID="pgfId-1040513"></A>
Sometimes an image contains extraneous material that needs to be removed. </Body1>
<StepStart>
<A ID="pgfId-1040515"></A>
Create a display surface containing the image by sending an <Code>
asRetainedMedium</Code>
 message to the image.</StepStart>
<StepCont>
<A ID="pgfId-1040517"></A>
Send a <Code>
completeContentsOfArea:</Code>
 message to the display surface. The argument is a rectangle that defines the desired portion of the image. The copied portion is returned as an image.</StepCont>
<CodeSample>
<A ID="pgfId-1040518"></A>
| gc logo subImage pixmap copyRect |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
logo := LogoExample logo magnifiedBy: 2@2.

pixmap := logo asRetainedMedium.
copyRect := 0@0 extent: (logo width @ logo height / 2) rounded.

subImage := pixmap completeContentsOfArea: copyRect.
subImage displayOn: gc at: 10@10.</CodeSample>
<Heading4>
<A ID="pgfId-1040527"></A>
Mask an irregular part of an image</Heading4>
<StepStart>
<A ID="pgfId-1040529"></A>
Create a display surface on which the image has been displayed by sending <Code>
asRetainedMedium</Code>
 to the image.</StepStart>
<StepCont>
<A ID="pgfId-1040531"></A>
Create the desired mask by sending an <Code>
extent:</Code>
 message to the <Code>
Mask</Code>
 class. The argument is a <Code>
Point</Code>
 indicating the size of the mask. You can display the desired shape or shapes on the <Code>
Mask</Code>
 as with a window or other display surface (in the example, a solid oval is displayed). The shapes on the mask define the regions through which the image will be visible.</StepCont>
<StepCont>
<A ID="pgfId-1040533"></A>
Send a <Code>
copyArea:from:sourceOffset:destinationOffset:</Code>
 message to the graphics context of the destination display surface (in the example, the scratch window). The <Code>
copyArea</Code>
 argument is the mask. The <Code>
from</Code>
 argument is the graphics context of the source display surface (the pixmap containing the logo). The <Code>
sourceOffset</Code>
 argument is a <Code>
Point</Code>
 indicating the origin of the mask when placed over the source display surface. The <Code>
destinationOffset</Code>
 argument is the origin of the subimage when displayed on the destination display surface.</StepCont>
<CodeSample>
<A ID="pgfId-1040534"></A>
| gc logo pixmap ovalMask |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
logo := LogoExample logo magnifiedBy: 2@2.
pixmap := logo asRetainedMedium.

ovalMask := Mask extent: 66@66.
ovalMask graphicsContext
			displayWedgeBoundedBy: ovalMask bounds
			startAngle: 0
			sweepAngle: 360.

gc copyArea: ovalMask
			from: pixmap graphicsContext
			sourceOffset: 0@0
		destinationOffset: 10@10.</CodeSample>
<Heading4>
<A ID="pgfId-1040549"></A>
Expand/shrink an image</Heading4>
<Body1>
<A ID="pgfId-1040551"></A>
You can get a copy of an image that has been magnified or shrunken in the <I>
x</I>
 dimension, the <I>
y</I>
 dimension, or both, as shown in the basic steps.</Body1>
<StepStart>
<A ID="pgfId-1040553"></A>
To get an expanded copy of an image, send a <Code>
magnifiedBy:</Code>
 message to the image. The argument is a <Code>
Point</Code>
 whose <Code>
x</Code>
 value is multiplied by the width of the image to derive the width of the expanded version; similarly, the <Code>
y</Code>
 value controls the height of the expanded version.</StepStart>
<StepCont>
<A ID="pgfId-1040555"></A>
To shrink an image, send a <Code>
shrunkenBy:</Code>
 message to the image. The argument is a point that is used as a divisor to reduce the width and height in the shrunken version.</StepCont>
<CodeSample>
<A ID="pgfId-1040556"></A>
| gc logo bigLogo tinyLogo |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
logo := LogoExample logo.

bigLogo := logo magnifiedBy: 1@2.
tinyLogo := logo shrunkenBy: 1@2.

logo displayOn: gc.
bigLogo displayOn: gc at: logo extent.
tinyLogo displayOn: gc at: logo extent + bigLogo extent.</CodeSample>
<Heading4>
<A ID="pgfId-1040567"></A>
Flop an image</Heading4>
<Body1>
<A ID="pgfId-1040568"></A>
Sometimes you need a mirror copy of an image. The basic steps show how to get a reflected copy in which the imaginary mirror is aligned with the <I>
x</I>
 axis, the <I>
y</I>
 axis, or both. This process of rotating an image about the <I>
x</I>
 axis or the <I>
y</I>
 axis is known as <I>
flopping an image</I>
, from the photographic process in which a negative is flopped onto its backside to produce a mirror image.</Body1>
<StepStart>
<A ID="pgfId-1040570"></A>
To flop an image about the x axis, send a <Code>
reflectedInX</Code>
 message to the image.</StepStart>
<StepCont>
<A ID="pgfId-1040572"></A>
To flop an image about the y axis, send a <Code>
reflectedInY</Code>
 message.</StepCont>
<StepCont>
<A ID="pgfId-1040574"></A>
To flop an image about both axes, send a <Code>
reflectedInX</Code>
 message followed by a <Code>
reflectedInY</Code>
 message.</StepCont>
<CodeSample>
<A ID="pgfId-1040575"></A>
| gc helpImage |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
helpImage := ToolbarIconLibrary help20x20 image.

helpImage 
			displayOn: gc at: 10@10.
helpImage reflectedInX 
			displayOn: gc at: 60@10.
helpImage reflectedInY
			displayOn: gc at: 10@60.
helpImage reflectedInX reflectedInY
		displayOn: gc at: 60@60.</CodeSample>
<Heading4>
<A ID="pgfId-1040587"></A>
Rotate an image</Heading4>
<Body1>
<A ID="pgfId-1040588"></A>
You can rotate an image about the z axis in 90-degree increments.</Body1>
<StepStart>
<A ID="pgfId-1040589"></A>
Send a <Code>
rotatedByQuadrants:</Code>
 message to the image. The argument is an integer indicating how many 90-degree rotations you want. A rotated copy of the image is returned.</StepStart>
<CodeSample>
<A ID="pgfId-1041306"></A>
| gc helpImage rotatedImage |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
helpImage := ToolbarIconLibrary help20x20 image.

rotatedImage := helpImage rotatedByQuadrants: 1.

helpImage 
		displayOn: gc at: 10@10.
rotatedImage 
		displayOn: gc at: 60@10.</CodeSample>
<Heading4>
<A ID="pgfId-1041307"></A>
Reuse a rotated image</Heading4>
<Body1>
<A ID="pgfId-1041308"></A>
Each rotated copy uses time and memory resources. For a series of rotations, you can reduce the resources required by reusing the same scratch image for each subsequent copy. The scratch image must be of the same size as the unrotated image, so this technique works only when all images in the series are the same size.</Body1>
<StepStart>
<A ID="pgfId-1040603"></A>
Create a scratch image the same size as the image that is to be rotated by sending a <Code>
copyEmpty</Code>
 message to the original image.</StepStart>
<StepCont>
<A ID="pgfId-1040605"></A>
Send a <Code>
rotateByQuadrants:to:</Code>
 message to the image to be copied. The first argument is the number of quadrants to rotate the image. The second argument is the scratch image.</StepCont>
<CodeSample>
<A ID="pgfId-1040606"></A>
| gc helpImage scratchImage |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
helpImage := ToolbarIconLibrary help20x20 image.

scratchImage := helpImage copyEmpty.

1 to: 4 do: [ :quads |
			helpImage rotateByQuadrants: quads to: scratchImage.
		scratchImage displayOn: gc at: (60 * quads) @ 10]</CodeSample>
<Heading4>
<A ID="pgfId-1040615"></A>
Layer images</Heading4>
<Body1>
<A ID="pgfId-1040616"></A>
You can achieve a variety of layering effects by combining two images and applying a filtering algorithm to the overlapping portions. VisualWorks provides 16 built-in algorithms, called <I>
combination rules</I>
, numbered 0 through 15, and the more commonly used rules have names. </Body1>
<StepStart>
<A ID="pgfId-1040618"></A>
To preserve the destination image in its unchanged state, make a copy on which to merge the source image.</StepStart>
<StepCont>
<A ID="pgfId-1040620"></A>
Send a <Code>
copy:from:in:rule:</Code>
 message to the destination image (in the example, <Code>
triangle</Code>
). The <Code>
copy</Code>
 argument is a rectangle identifying the region in the destination image to be merged with the source image (the lower part of the triangle). The <Code>
from</Code>
 argument is the origin of the rectangle within the source image (the origin of the circle, because we want to copy the entire circle). The <Code>
in</Code>
 argument is the source image. The <Code>
rule</Code>
 argument is an integer identifying a combination rule (which can be derived by sending <Code>
and</Code>
, <Code>
over</Code>
, <Code>
erase</Code>
, <Code>
reverse</Code>
, <Code>
under</Code>
, or <Code>
reverseUnder</Code>
 to the <Code>
RasterOp</Code>
 class).</StepCont>
<CodeSample>
<A ID="pgfId-1040621"></A>
| gc triangle circle scratch |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

triangle := Pixmap extent: 50@100.
triangle graphicsContext
			displayPolygon: (Array
				with: 0@0
				with: 0@50
				with: 50@50).
triangle := triangle asImage.

circle := Pixmap extent: 50@50.
circle graphicsContext
			displayDotOfDiameter: 50
			at: 25@25.
circle := circle asImage.

0 to: 15 do: [ :rule |
			scratch := triangle copy.
			scratch
				copy: (0@20 extent: 50@50)
				from: 0@0
				in: circle
				rule: rule.

		scratch displayOn: gc at: (50 * rule \\ 400) @ (50 * rule // 400 * 100)]</CodeSample>
<Heading4>
<A ID="pgfId-1040647"></A>
Cache an image</Heading4>
<Body1>
<A ID="pgfId-1040648"></A>
A <Code>
CachedImage</Code>
 combines the longevity of an <Code>
Image</Code>
 with the displaying speed of a display surface. Whenever its display surface is unavailable, as when it has been destroyed by a save-and-restart operation, it is recreated from the image automatically. This relieves your application from having to recreate such display surfaces manually. </Body1>
<Body1>
<A ID="pgfId-1040649"></A>
Note that a <Code>
CachedImage</Code>
 must be treated like a display surface, not an image. </Body1>
<Body1>
<A ID="pgfId-1040650"></A>
Create a <Code>
CachedImage</Code>
 by sending an <Code>
on:</Code>
 message to that class. The argument is the image that is to be cached.</Body1>
<CodeSample>
<A ID="pgfId-1040651"></A>
| gc logo |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

logo := CachedImage on: LogoExample logo.
logo displayOn: gc.</CodeSample>
<Heading4>
<A ID="pgfId-1040656"></A>
Animate an image</Heading4>
<Body1>
<A ID="pgfId-1040657"></A>
Animating an image, or any graphic object, consists of creating a loop in which the object is drawn and erased at successive locations along a path. For smooth animation, use <I>
double buffering</I>
, which erases and draws only changed pixels. </Body1>
<StepStart>
<A ID="pgfId-1040659"></A>
Create a <Code>
Pixmap</Code>
 of the same size as the window on which the animation is to take place by sending an <Code>
extent:</Code>
 message to the <Code>
Pixmap</Code>
 class. The argument is a rectangle with the window&#39;s dimensions, which can be derived by sending a <Code>
clippingBounds</Code>
 message to the window&#39;s graphics context.</StepStart>
<StepCont>
<A ID="pgfId-1040661"></A>
Create a loop in which the erase-and-display operations occur.</StepCont>
<StepCont>
<A ID="pgfId-1040663"></A>
Inside the loop, begin by moving the origin of each object to be animated.</StepCont>
<StepCont>
<A ID="pgfId-1040665"></A>
Still inside the loop, erase the <Code>
Pixmap</Code>
 by sending a <Code>
clear</Code>
 message to it.</StepCont>
<StepCont>
<A ID="pgfId-1040667"></A>
Still inside the loop, display each animated object in its new location.</StepCont>
<StepCont>
<A ID="pgfId-1040669"></A>
Still inside the loop, display the <Code>
Pixmap</Code>
 on the window.</StepCont>
<CodeSample>
<A ID="pgfId-1040670"></A>
| gc buffer logo windowSize origin1 origin2 jump bufferGC |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
windowSize := gc clippingBounds extent.
logo := LogoExample logo.
origin1 := 0@0.
origin2 := 360@0.
jump := 5.

buffer := Pixmap extent: windowSize.
bufferGC := buffer graphicsContext.

80 timesRepeat: [ 
			origin1 := origin1 + jump.
			origin2 := (origin2 x - jump) @ (origin2 y + jump).
			
			&quot;Clear the buffer, then assemble the next scene.&quot;
			buffer clear.
			logo displayOn: bufferGC at: origin1.
			logo displayOn: bufferGC at: origin2.

			&quot;Display the next scene.&quot;
		buffer displayOn: gc]</CodeSample>
<Heading4>
<A ID="pgfId-1040692"></A>
Use a standard cursor</Heading4>
<Body1>
<A ID="pgfId-1040693"></A>
The <Code>
Cursor</Code>
 class provides methods for accessing the built-in cursors. Send one of those messages to the <Code>
Cursor</Code>
 class to access the corresponding cursor. </Body1>
<CodeSample>
<A ID="pgfId-1040694"></A>
| gc cursor |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

cursor := Cursor wait.
cursor displayOn: gc at: 10@10.</CodeSample>
<Heading4>
<A ID="pgfId-1040699"></A>
Create a new cursor</Heading4>
<StepStart>
<A ID="pgfId-1041507"></A>
Create an image that provides the pictorial element in the cursor. If you use the <A href="03-tools.xml#id(Image Editor)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">Image Editor</A> to create the image, you must convert its palette to a color-based palette rather than a coverage-based one. To do so, edit the resource method that defines the image, substituting <Code>
MappedPalette whiteBlack</Code>
 (or another two-color palette) for the default <Code>
CoveragePalette monoMaskPalette</Code>
.</StepStart>
<StepCont>
<A ID="pgfId-1040704"></A>
Create a coverage-based image that defines the opaque portion of the first image. The Image Editor can be used to create this image. Typically, it is the same shape as the image from step 1, but completely darkened and one pixel larger on each side.</StepCont>
<StepCont>
<A ID="pgfId-1040706"></A>
Create the cursor by sending an <Code>
image:mask:hotSpot:name:</Code>
 message to the <Code>
Cursor</Code>
 class. The <Code>
image</Code>
 argument is the color-based image that you created in step 1. The <Code>
mask</Code>
 argument is the coverage-based image from step 2. The <Code>
hotSpot</Code>
 argument is a point indicating which pixel in the image is the control point. The <Code>
name</Code>
 argument is a string containing a descriptive name for the cursor. The name is of little importance, but it is displayed when you inspect a cursor.</StepCont>
<CodeSample>
<A ID="pgfId-1040707"></A>
| cursor colorImage maskImage |
colorImage := CursorExample townCrierForCursor.
maskImage := CursorExample shadow.

cursor := Cursor
		image: colorImage
		mask: maskImage
		hotSpot: 8@8
		name: 'townCrier'.
cursor showWhile: [(Delay forSeconds: 3) wait].</CodeSample>
<Body1>
<A ID="pgfId-1041077"></A>
<B>
Online example: </B>
<CodeExample xml:link="simple" href="Cursor.pcl" show="embed" actuate="auto">
CursorExample</CodeExample>
</Body1>
<Heading4>
<A ID="pgfId-1040717"></A>
Change the current cursor</Heading4>
<Body1>
<A ID="pgfId-1040718"></A>
Changing the cursor is a means of indicating to the user of your application that a certain kind of input is expected or that progress is being made</Body1>
<Body1>
<A ID="pgfId-1040720"></A>
Send a <Code>
showWhile:</Code>
 message to the cursor. The argument is a block containing the actions that are to take place while the cursor is in its changed state. After the actions in the block are finished, the cursor will return to normal automatically. (In the example, the controller changes the cursor for as long as it holds onto control.)</Body1>
<CodeSample>
<A ID="pgfId-1041441"></A>
controlLoop
			&quot;Change the cursor to a cross-hair for drawing.&quot;

			Cursor crossHair showWhile: [super controlLoop].</CodeSample>
<Body1>
<A ID="pgfId-1041442"></A>
<B>
Online example: </B>
<CodeExample xml:link="simple" href="CustomView.pcl" show="embed" actuate="auto">
CustomViewExample</CodeExample>
 and <CodeExample xml:link="simple" href="CustomView.pcl" show="embed" actuate="auto">
SketchController</CodeExample>
</Body1>
<Heading4>
<A ID="pgfId-1041443"></A>
Create an icon</Heading4>
<Body1>
<A ID="pgfId-1040726"></A>
Most often used to represent a collapsed window, an icon typically provides a pictorial clue to the nature of the window. </Body1>
<StepStart>
<A ID="pgfId-1040728"></A>
Create an <Code>
Image</Code>
 containing the pictorial element for the icon. You can use the <A href="03-tools.xml#id(Image Editor)" xml:link="simple" show="replace" actuate="user" CLASS="XRef">Image Editor</A> to create the image and save it in a method (in the example, the image is returned by the <Code>
townCrier</Code>
 method of the <Code>
CursorExample</Code>
 class).</StepStart>
<StepCont>
<A ID="pgfId-1040730"></A>
Create a <Code>
Mask</Code>
 containing the image by sending an <Code>
asRetainedMedium</Code>
 message to the image. </StepCont>
<StepCont>
<A ID="pgfId-1040732"></A>
Create an icon by sending an <Code>
image:</Code>
 message to the <Code>
Icon</Code>
 class. The argument is the mask from step 2.</StepCont>
<CodeSample>
<A ID="pgfId-1040733"></A>
| icon gc image mask |

image := CursorExample townCrier.
mask := image asRetainedMedium.

gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

icon := Icon image: mask.
icon displayOn: gc at: 10@10.</CodeSample>
<Body1>
<A ID="pgfId-1040742"></A>
Note that the <Code>
Icon</Code>
 instance takes care of reconstructing the <Code>
Mask</Code>
 instance when you quit and restart VisualWorks.</Body1>
<Heading4>
<A ID="pgfId-1040743"></A>
Associate an icon with a window</Heading4>
<Body1>
<A ID="pgfId-1040744"></A>
The default icon that VisualWorks displays for each collapsed window may not be appropriate for your application&#39;s windows. The basic step shows how to associate a custom icon with a window. This is typically done in the method that creates the window.</Body1>
<Body1>
<A ID="pgfId-1040745"></A>
Send an <Code>
icon:</Code>
 message to the window. The argument is the icon that is to be displayed when the window is collapsed.</Body1>
<CodeSample>
<A ID="pgfId-1040746"></A>
| icon window mask |
mask := CursorExample townCrier asRetainedMedium.
icon := Icon image: mask.
window := ApplicationWindow new.

window icon: icon.

window open.
(Delay forSeconds: 1) wait.
window collapse.</CodeSample>
<Body1>
<A ID="pgfId-1040057"></A>
</Body1>
<Heading3>
<A ID="pgfId-1040890"></A>
Colors</Heading3>
<Heading4>
<A ID="pgfId-1040892"></A>
Create a color by name</Heading4>
<Body1>
<A ID="pgfId-1040893"></A>
A set of predefined colors is provided by the <Code>
ColorValue</Code>
 class. To create an instance of a predefined color value, send its name to the class:</Body1>
<CodeSample>
<A ID="pgfId-1040894"></A>
| gc color |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

color := ColorValue cyan.

gc paint: color.
gc displayDotOfDiameter: 400 at: 200@200.</CodeSample>
<Heading4>
<A ID="pgfId-1040901"></A>
Create an RGB color</Heading4>
<Body1>
<A ID="pgfId-1040902"></A>
Send a <Code>
red:green:blue:</Code>
 message to the <Code>
ColorValue</Code>
 class. All arguments are numbers between zero and one, representing the intensity of their respective colors. (In the example, the intensity of green is varied while the red and blue intensities remain at zero.)</Body1>
<CodeSample>
<A ID="pgfId-1040903"></A>
| gc origin |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
origin := 0@0.

1 to: 0 by: -0.01 do: [ :grn |
		gc paint: (ColorValue red: 0.0 green: grn blue: 0.0).
		origin := origin + 4.
		gc displayRectangle: (origin extent: 400 - origin)]</CodeSample>
<Heading4>
<A ID="pgfId-1040911"></A>
Create an HSB color</Heading4>
<Body1-Keep>
<A ID="pgfId-1040912"></A>
Send a <Code>
hue:saturation:brightness:</Code>
 message to the <Code>
ColorValue</Code>
 class. The <Code>
hue</Code>
 argument is a number from 0 to 1, where 0 is red, 0.333 is green, 0.667 is blue, and 1 is red again. The <Code>
saturation</Code>
 argument is a number from 0 to 1, representing minimum vividness (white) to full color; a more saturated color makes an object appear closer to the viewer. The <Code>
brightness</Code>
 argument is a number from 0 to 1, representing minimum brightness (black) to full color; varying the brightness is useful for representing shadows.</Body1-Keep>
<CodeSample>
<A ID="pgfId-1040913"></A>
| gc r x y |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
r := 50.
gc lineWidth: 2.

gc translation: 150@150.
0 to: 1 by: 0.005 do: [ :i |
		x := (i * Float pi) cos * r.
		y := (i * Float pi) sin * r / 2.
		gc paint: (ColorValue hue: 0.0 saturation: 0.5 brightness: i).
		gc displayLineFrom: x@y to: 0@-100 ].

gc translation: 200@200.
0 to: 1 by: 0.005 do: [ :i |
		x := (i * Float pi) cos * r.
		y := (i * Float pi) sin * r / 2.
		gc paint: (ColorValue hue: 0.0 saturation: 0.75 brightness: i).
		gc displayLineFrom: x@y to: 0@-100 ].

gc translation: 250@250.
0 to: 1 by: 0.005 do: [ :i |
		x := (i * Float pi) cos * r.
		y := (i * Float pi) sin * r / 2.
		gc paint: (ColorValue hue: 0.0 saturation: 1.0 brightness: i).
		gc displayLineFrom: x@y to: 0@-100 ]</CodeSample>
<Heading4>
<A ID="pgfId-1040938"></A>
Create a coverage</Heading4>
<Body1>
<A ID="pgfId-1040939"></A>
In a window or <Code>
Pixmap</Code>
, each pixel can be assigned a different color. In a <Code>
Mask</Code>
, each pixel is assigned a level of opaqueness, either 0 (transparent) or 1 (opaque). Each opaque pixel in the mask causes the corresponding pixel in the image to be displayed. A <Code>
CoverageValue</Code>
 is used to represent the level of opaqueness associated with a pixel.</Body1>
<Body1>
<A ID="pgfId-1040941"></A>
Send a <Code>
coverage:</Code>
 message to the <Code>
CoverageValue</Code>
 class. The argument is 0 (transparent) or 1 (opaque). As an alternative, you can also send a <Code>
transparent</Code>
 or <Code>
opaque</Code>
 message to the <Code>
CoverageValue</Code>
 class.</Body1>
<CodeSample>
<A ID="pgfId-1040942"></A>
| gc mask |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
mask := Mask extent: 400@400.

mask graphicsContext 
		displayDotOfDiameter: 400 at: 200@200.

mask graphicsContext 
		paint: (CoverageValue coverage: 0);
		displayRectangle: (59@59 extent: 283@283).

mask displayOn: gc at: 0@0.</CodeSample>
<Heading4>
<A ID="pgfId-1040954"></A>
Create a tiled pattern</Heading4>
<Body1>
<A ID="pgfId-1040955"></A>
A <Code>
Pattern</Code>
 is created by filling a space with a single graphic image that is repeated over and over, like tiles covering a floor. </Body1>
<StepStart>
<A ID="pgfId-1040957"></A>
Create the graphic image that will serve as the repeating tile in the pattern. You can also use a window, <Code>
Pixmap</Code>
, or <Code>
Mask</Code>
 as the tile.</StepStart>
<StepCont>
<A ID="pgfId-1040959"></A>
Send an <Code>
asPattern</Code>
 message to the tile.</StepCont>
<CodeSample>
<A ID="pgfId-1040960"></A>
| gc tile |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

tile := Image parcPlaceDigitalkLogo shrunkenBy: 4@4.
tile := tile asPattern.

gc paint: tile.
gc displayRectangle: (50@50 extent: 300@300).</CodeSample>
<Heading4>
<A ID="pgfId-1040968"></A>
Adjust a pattern&#39;s phase</Heading4>
<Body1>
<A ID="pgfId-1040969"></A>
By default, the first tile in the pattern is displayed at the origin of the display surface. You can shift that first tile, and with it the entire pattern. This shift, known as the tile phase, is sometimes helpful for aligning the edges of the tiles with the edges of the graphic object that is being painted, as in the variant.</Body1>
<Body1>
<A ID="pgfId-1040970"></A>
Send a <Code>
tilePhase:</Code>
 message to the graphics context of the display surface on which the patterned object is to be displayed. The argument is a point that defines the origin of the first tile in the pattern. (As in the example, the tile phase is often the same as the origin of the painted object, which aligns the tiles with the top and left edges of the object.)</Body1>
<CodeSample>
<A ID="pgfId-1040971"></A>
| gc tile |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
tile := Image parcPlaceDigitalkLogo shrunkenBy: 4@4.
tile := tile asPattern.
gc paint: tile.

gc tilePhase: 50@50.

gc displayRectangle: (50@50 extent: 300@300).</CodeSample>
<Heading4>
<A ID="pgfId-1040980"></A>
Apply a color or pattern</Heading4>
<Body1>
<A ID="pgfId-1040981"></A>
Send a <Code>
paint:</Code>
 message to the graphics context of the display surface on which the object is to be displayed. The argument is a color, a pattern, or in the case of a <Code>
Mask</Code>
, a coverage.</Body1>
<CodeSample>
<A ID="pgfId-1040982"></A>
| gc tile |
tile := Pixmap extent: 10@10.
gc := tile graphicsContext.

&quot;Tile background&quot;
gc paint: ColorValue chartreuse.
gc displayRectangle: (0@0 extent: 10@10).

&quot;Tile foreground&quot;
gc paint: ColorValue red.
gc displayDotOfDiameter: 10 at: 4@4.

&quot;Patterned circle&quot;
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
gc paint: tile asPattern.
gc displayDotOfDiameter: 400 at: 200@200.</CodeSample>
<Heading4>
<A ID="pgfId-1040998"></A>
Change a color palette</Heading4>
<Body1>
<A ID="pgfId-1040999"></A>
In a graphic image, each pixel is associated with a color in the image&#39;s palette of colors. One way of changing the color scheme is to substitute a different palette. </Body1>
<StepStart>
<A ID="pgfId-1041001"></A>
Create an array containing the new colors. To access the existing palette&#39;s array of colors, send a <Code>
palette</Code>
 message to the image, and then send a <Code>
colors</Code>
 message to the resulting palette. You can then modify the color array as desired (in the example, we locate the white entry and substitute the color yellow).</StepStart>
<StepCont>
<A ID="pgfId-1041003"></A>
Create a new palette by sending a <Code>
withColors:</Code>
 message to the <Code>
MappedPalette</Code>
 class. The argument is the new or modified color array.</StepCont>
<StepCont>
<A ID="pgfId-1041005"></A>
Install the new palette by sending a <Code>
palette:</Code>
 message to the image. The argument is the new palette.</StepCont>
<CodeSample>
<A ID="pgfId-1041007"></A>
| gc palette image colors whiteIndex |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
image := InputFieldSpec paletteIcon asImage.

colors := image palette colors.
whiteIndex := colors indexOf: ColorValue white.
colors at: whiteIndex put: ColorValue yellow.

palette := MappedPalette withColors: colors.

image := image palette: palette.
image displayOn: gc at: 10@10.</CodeSample>
<Heading4>
<A ID="pgfId-1041019"></A>
Convert an image to use the default palette</Heading4>
<Body1>
<A ID="pgfId-1041020"></A>
Send a <Code>
convertToPalette:</Code>
 message to the image. The argument is the default color palette, which can be accessed by sending a <Code>
default</Code>
 message to the <Code>
Screen</Code>
 class and then sending a <Code>
colorPalette</Code>
 message to the resulting screen object. (For a coverage-based image, send a <Code>
coveragePalette</Code>
 message instead of <Code>
colorPalette</Code>
.)</Body1>
<CodeSample>
<A ID="pgfId-1041021"></A>
| gc image |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
image := Image parcPlaceDigitalkLogo magnifiedBy: 2@2.

image := image convertToPalette: Screen default colorPalette.
image displayOn: gc at: 10@10.</CodeSample>
<Heading4>
<A ID="pgfId-1041027"></A>
Change color rendering policy</Heading4>
<Body1>
<A ID="pgfId-1041028"></A>
When a graphic image contains a color that does not exist in the screen&#39;s palette, a neighboring color is used instead. VisualWorks provides three different renderers for deciding which color to substitute for a missing color. Of the three, <Code>
NearestPaint</Code>
 is the fastest and is the default on color screens. <Code>
OrderedDither</Code>
 is the default on monochrome and gray-scale screens. <Code>
ErrorDiffusion</Code>
 uses a more sophisticated color-blending algorithm than <Code>
OrderedDither</Code>
 does, but it tends to be slower.</Body1>
<Body1>
<A ID="pgfId-1041029"></A>
Send a <Code>
convertForGraphicsDevice:renderedBy:</Code>
 message to the image. The first argument is typically <Code>
Screen default</Code>
. The second argument is <Code>
NearestPaint</Code>
 when you want to use the nearest available paint from the screen&#39;s palette, <Code>
OrderedDither</Code>
 when you want to synthesize the nonexistent color by blending neighboring colors, and <Code>
ErrorDiffusion</Code>
 when you want to use a more sophisticated (but often slower) blending algorithm.</Body1>
<CodeSample>
<A ID="pgfId-1041336"></A>
&quot;THIS EXAMPLE IS INTENDED TO BE USED ON
A COLOR SCREEN. IT CAN TAKE SEVERAL MINUTES.&quot;
| gc r g b im |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
im := Image
		extent: 60@60 
		depth: 15 
		palette: (FixedPalette 
			redShift: 10 redMask: 31
			greenShift: 5 greenMask: 31
			blueShift: 0 blueMask: 31).
0 to: 59 do: [:x |
		0 to: 59 do: [:y |
			r := 1 - ((x@y - (10@10)) r / 30) max: 0.
			g := 1 - ((x@y - (20@50)) r / 30) max: 0.
			b := 1 - ((x@y - (50@30)) r / 30) max: 0.
			im atPoint: x@y put: (im palette 
				indexOfPaintNearest: (ColorValue red: r green: g blue: b))]].

(im convertForGraphicsDevice: Screen default 
		renderedBy: NearestPaint new)
			displayOn: gc at: 10@10.

(im convertForGraphicsDevice: Screen default
		renderedBy: OrderedDither new)
			displayOn: gc at: 80@10.

(im convertForGraphicsDevice: Screen default 
		renderedBy: ErrorDiffusion new)
			displayOn: gc at: 150@10.</CodeSample>
<Heading4>
<A ID="pgfId-1041337"></A>
Convert an image to a Palette</Heading4>
<Body1>
<A ID="pgfId-1041338"></A>
Send a <Code>
convertToPalette:renderedBy:</Code>
 message to the image. The first argument is the desired palette (in the example, a monochrome palette). The second argument is the desired renderer (a <Code>
NearestPaint</Code>
, an <Code>
OrderedDither</Code>
, or an <Code>
ErrorDiffusion</Code>
).</Body1>
<CodeSample>
<A ID="pgfId-1041062"></A>
| gc r g b im |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.
im := Image
		extent: 60@60
		depth: 15 palette: (FixedPalette 
			redShift: 10 redMask: 31
			greenShift: 5 greenMask: 31
			blueShift: 0 blueMask: 31).
0 to: 59 do: [:x |
		0 to: 59 do: [:y |
			r := 1 - ((x@y - (10@10)) r / 30) max: 0.
			g := 1 - ((x@y - (20@50)) r / 30) max: 0.
			b := 1 - ((x@y - (50@30)) r / 30) max: 0.
			im atPoint: x@y put: (im palette 
				indexOfPaintNearest: (ColorValue brightness: 1-((1-r)*(1-g)*(1-b))))]].

(im convertToPalette: MappedPalette whiteBlack
		renderedBy: NearestPaint new)
			displayOn: gc at: 10@10.

(im convertToPalette: MappedPalette whiteBlack
		renderedBy: OrderedDither new)
			displayOn: gc at: 80@10.

(im convertToPalette: MappedPalette whiteBlack
		renderedBy: ErrorDiffusion new)
			displayOn: gc at: 150@10.</CodeSample>
<Heading4>
<A ID="pgfId-1041089"></A>
Set the rendering policy for nonimage graphics</Heading4>
<StepStart>
<A ID="pgfId-1041091"></A>
Install a paint policy in the graphics context of the display surface by sending a <Code>
paintPolicy:</Code>
 message to the graphics context. The argument is a <Code>
PaintPolicy</Code>
, typically a new instance.</StepStart>
<StepCont>
<A ID="pgfId-1041093"></A>
Set the rendering algorithm by sending a <Code>
paintRenderer:</Code>
 message to the paint policy. The argument is a <Code>
NearestPaint</Code>
 or an <Code>
OrderedDither</Code>
 (but not an <Code>
ErrorDiffusion</Code>
, which is only used with images). By default, a new <Code>
OrderedDither</Code>
 has an order of 6, which means it synthesizes 65 (2 to the sixth, plus 1) intermediate color values between each pair of neighboring colors in the palette. You can set the order by sending an <Code>
order:</Code>
 message to the <Code>
OrderedDither</Code>
 class to create an instance; the argument is the desired order number.</StepCont>
<CodeSample>
<A ID="pgfId-1041094"></A>
| gc |
gc := (ExamplesBrowser prepareScratchWindow) graphicsContext.

gc paintPolicy: (PaintPolicy new imageRenderer: OrderedDither new).
gc paintPolicy paintRenderer: NearestPaint new.
0 to: 60 by: 4 do: [:i | 
		0 to: 60 by: 4 do: [:j |
			gc paint: (ColorValue red: i/60 green: j/60 blue: 0).
			gc displayRectangle: (i@j+(10@10) extent: 4@4)]].

gc paintPolicy paintRenderer: (OrderedDither order: 1).
0 to: 60 by: 4 do: [:i | 
		0 to: 60 by: 4 do: [:j |
			gc paint: (ColorValue red: i/60 green: j/60 blue: 0).
			gc displayRectangle: (i@j+(80@10) extent: 4@4)]].

gc paintPolicy paintRenderer: (OrderedDither order: 6).
0 to: 60 by: 4 do: [:i | 
		0 to: 60 by: 4 do: [:j |
			gc paint: (ColorValue red: i/60 green: j/60 blue: 0).
			gc displayRectangle: (i@j+(150@10) extent: 4@4)]].</CodeSample>
<Body1>
<A ID="pgfId-1029452"></A>
</Body1>
</XML>
