Tk Source Code

Check-in [4beac0b5]
Login
Bounty program for improvements to Tcl and certain Tcl packages.
Tcl 2019 Conference, Houston/TX, US, Nov 4-8
Send your abstracts to [email protected]
or submit via the online form by Sep 9.

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:New files from René Zaumseil. Tkpath is now included in TIP #510.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | tip-510
Files: files | file ages | folders
SHA3-256: 4beac0b550a4fa98e4a91f50ad50ede766ddf9f5d770986e413f5498e2ef8430
User & Date: fvogel 2018-11-30 21:40:04
Context
2018-12-03
18:59
Add a missing file from René Zaumseil check-in: 8a818458 user: fvogel tags: tip-510
2018-11-30
21:40
New files from René Zaumseil. Tkpath is now included in TIP #510. check-in: 4beac0b5 user: fvogel tags: tip-510
2018-11-29
08:21
Remove one more mention of rbcMain check-in: 268b5548 user: fvogel tags: tip-510
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to doc/graph.n.md.

1
2
3
4









































5
6
7
8

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

111

112







































































































113
114



115
116




117
118
119



120
121

122
123
124



125
126

127















































































































128
129



130























131
132
133
134
135
136
137
138
...
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
...
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
....
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
....
1853
1854
1855
1856
1857
1858
1859













1860
1861
1862
1863
1864
1865

1866
1867
1868
1869
1870
1871
1872
1873



# graph(n) -- 2D graph for plotting X-Y coordinate data

*   [NAME]((#NAME)
*   [SYNOPSIS](#SYNOPSIS)









































*   [DESCRIPTION](#DESCRIPTION)
*   [INTRODUCTION](#INTRODUCTION)
*   [SYNTAX](#SYNTAX)
*   [GRAPH OPERATIONS](#GRAPH-OPERATIONS)

  * [pathName axis](#pathName-axis) *operation ?arg?...*
  * [pathName binding](#pathName-binding) *?crosshairs? ?findelement? ?legend? ?zoom?*
  * [pathName bar](#pathName-bar) *elemName ?option value?...*
  * [pathName cget](#pathName-cget) *option*
  * [pathName configure](#pathName-configure) *?option value?...*
  * [pathName crosshairs](#pathName-crosshairs) *operation ?arg?*
  * [pathName element](#pathName-element) *operation ?arg?...*
  * [pathName extents](#pathName-extents) *item*
  * [pathName grid](#pathName-grid) *operation ?arg?...*
  * [pathName invtransform](#pathName-invtransform) *winX winY*
  * [pathName inside](#pathName-inside) *x y*
  * [pathName legend](#pathName-legend) *operation ?arg?...*
  * [pathName line](#pathName-line) *operation arg...*
  * [pathName marker](#pathName-marker) *operation ?arg?...*
  * [pathName postscript](#pathName-postscript) *operation ?arg?...*
  * [pathName snap](#pathName-snap) *?switches? outputName*
  * [pathName transform](#pathName-transform) *x y*
  * [pathName xaxis](#pathName-xaxis) *operation ?arg?...*
  * [pathName x2axis](#pathName-x2axis) *operation ?arg?...*
  * [pathName yaxis](#pathName-yaxis) *operation ?arg?...*
  * [pathName y2axis](#pathName-y2axis) *operation ?arg?...*
* [AXIS COMPONENT](#AXIS-COMPONENT)
  * [pathName axis bind](#pathName-axis-bind) *tagName ?sequence? ?command?*
  * [pathName axis cget](#pathName-axis-cget) *axisName option*
  * [pathName axis configure](#pathName-axis-configure) *axisName ?axisName?... ?option value?...*
  * [pathName axis create](#pathName-axis-create) *axisName ?option value?...*
  * [pathName axis delete](#pathName-axis-delete) *?axisName?...*
  * [pathName axis invtransform](#pathName-axis-invtransform) *axisName value*
  * [pathName axis limits](#pathName-axis-limits) *axisName*
  * [pathName axis names](#pathName-axis-names) *?pattern?...*
  * [pathName axis transform](#pathName-axis-transform) *axisName value*
  * [pathName axis view](#pathName-axis-view) *axisName*
* [CROSSHAIRS COMPONENT](#)
  * [pathName crosshairs cget](#pathName-crosshairs-cget) *option*
  * [pathName crosshairs configure](#pathName-crosshairs-configure) *?option value?...*
  * [pathName crosshairs off](#pathName-crosshairs-off)
  * [pathName crosshairs on](#pathName-crosshairs-on)
  * [pathName crosshairs toggle](#pathName-crosshairs-toggle)
* [ELEMENT COMPONENT](#ELEMENT-COMPONENT)
  * [pathName element activate](#pathName-element-activate) *elemName ?index?...*
  * [pathName element bind](#pathName-element-bind) *tagName ?sequence? ?command?*
  * [pathName element cget](#pathName-element-cget) *elemName option*
  * [pathName element closest](#pathName-element-closest) *x y varName ?option value?... ?elemName?...*
  * [pathName element configure](#pathName-element-configure) *elemName ?elemName... ?option value?...*
  * [pathName element create](#pathName-element-create) *elemName ?option value?...*
  * [pathName element deactivate](#pathName-element-deactivate) *elemName ?elemName?...*
  * [pathName element delete](#pathName-element-delete) *?elemName?...*
  * [pathName element exists](#pathName-element-exists) *elemName*
  * [pathName element names](#pathName-element-names) *?pattern?...*
  * [pathName element show](#pathName-element-show) *?nameList?*
  * [pathName element type](#pathName-element-type) *elemName*
* [GRID COMPONENT](#GRID-COMPONENT)
  * [pathName grid cget](#pathName-grid-cget) *option*
  * [pathName grid configure](#pathName-grid-configure) *?option value?...*
  * [pathName grid off](#pathName-grid-off)
  * [pathName grid on](#pathName-grid-on)
  * [pathName grid toggle](#pathName-grid-toggle)
* [LEGEND COMPONENT](#LEGEND-COMPONENT)
  * [pathName legend activate](#pathName-legend-activate) *pattern...*
  * [pathName legend bind](#pathName-legend-bind) *tagName ?sequence? ?command?*
  * [pathName legend cget](#pathName-legend-cget) *option*
  * [pathName legend configure](#pathName-legend-configure) *?option value?...*
  * [pathName legend deactivate](#pathName-legend-deactivate) *pattern...*
  * [pathName legend get](#pathName-legend-get) *pos*
* [PEN COMPONENT](#PEN-COMPONENT)
  * [pathName pen cget](#pathName-pen-cget) *penName option*
  * [pathName pen configure](#pathName-pen-configure) *penName ?penName... ?option value?...*
  * [pathName pen create](#pathName-pen-create) *penName ?option value?...*
  * [pathName pen delete](#pathName-pen-delete) *?penName?...*
  * [pathName pen names](#pathName-pen-names) *?pattern?...*
* [POSTSCRIPT COMPONENT](#POSTSCRIPT-COMPONENT)
  * [pathName postscript cget](#pathName-postscript-cget) *option*
  * [pathName postscript configure](#pathName-postscript-configure) *?option value?...*
  * [pathName postscript output](#pathName-postscript-output) *?fileName? ?option value?...*
* [MARKER COMPONENT](#MARKER-COMPONENT)
  * [pathName marker after](#pathName-marker-after) *markerId ?afterId?*
  * [pathName marker before](#pathName-marker-before) *markerId ?beforeId?*
  * [pathName marker bind](#pathName-marker-bind) *tagName ?sequence? ?command?*
  * [pathName marker cget](#pathName-marker-cget) *option*
  * [pathName marker configure](#pathName-marker-configure) *markerId ?option value?...*
  * [pathName marker create](#pathName-marker-create) *type ?option value?...*
  * [pathName marker delete](#pathName-marker-delete) *?name?...*
  * [pathName marker exists](#pathName-marker-exists) *markerId*
  * [pathName marker names](#pathName-marker-names) *?pattern?*
  * [pathName marker type](#pathName-marker-type) *markerId*
  * [BITMAP MARKERS](#BITMAP-MARKERS)
  * [pathName marker create bitmap](#pathName-marker-create-bitmap) *?option value?...*
  * [IMAGE MARKERS](#IMAGE-MARKERS)
  * [pathName marker create image](#pathName-marker-create-image) *?option value?...*
  * [LINE MARKERS](#LINE-MARKERS)
  * [pathName marker create line](#pathName-marker-create-line) *?option value?...*
  * [POLYGON MARKERS](#POLYGON-MARKERS)
  * [pathName marker create polygon](#pathName-marker-create-polygon) *?option value?...*
  * [TEXT MARKERS](#TEXT-MARKERS)
  * [pathName marker create text](#pathName-marker-create-text) *?option value?...*
  * [WINDOW MARKERS](#WINDOW-MARKERS)
  * [pathName marker create window](#pathName-marker-create-window) *?option value?...*
*   [GRAPH COMPONENT BINDINGS](#GRAPH-COMPONENT-BINDINGS)
*   [C LANGUAGE API](#[C-LANGUAGE-API)
*   [SPEED TIPS](#SPEED-TIPS)
*   [LIMITATIONS](#LIMITATIONS)
*   [EXAMPLE](#EXAMPLE)

*   [KEYWORDS](#KEYWORDS)









































































































<a name="NAME"></a>
## NAME 




graph - 2D graph for plotting X-Y coordinate data.





<a name="SYNOPSIS"></a>
## SYNOPSIS 




**graph** *pathName ?option value?...*


<a name="DESCRIPTION"></a>
## DESCRIPTION 




The graph command creates a graph for plotting two-dimensional data (X-Y coordinates). It has many configurable components: coordinate axes, elements, legend, grid lines, cross hairs, etc. They allow you to customize the look and feel of the graph.

















































































































<a name="INTRODUCTION"></a>
## INTRODUCTION 



























The graph command creates a new window for plotting two-dimensional data (X-Y coordinates). Data points are plotted in a rectangular area displayed in the center of the new window. This is the plotting area. The coordinate axes are drawn in the margins around the plotting area. By default, the legend is displayed in the right margin. The title is displayed in top margin.

The graph widget is composed of several components: coordinate axes, data elements, legend, grid, cross hairs, pens, postscript, and annotation markers.

**axis**
    The graph has four standard axes (x, x2, y, and y2), but you can create and display any number of axes. Axes control what region of data is displayed and how the data is scaled. Each axis consists of the axis line, title, major and minor ticks, and tick labels. Tick labels display the value at each major tick.

**crosshairs**
................................................................................

**pen**
    Pens define attributes (both symbol and line style) for elements. Data elements use pens to specify how they should be drawn. A data element may use many pens at once. Here, the particular pen used for a data point is determined from each element's weight vector (see the element's -weight and -style options).

**postscript**
    The widget can generate encapsulated PostScript output. This component has several options to configure how the PostScript is generated.

<a name="SYNTAX"></a>
## SYNTAX

**graph** *pathName ?-style line|bar|strip? ?option value?...*

The graph command creates a new window pathName and makes it into a graph widget. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist. Additional options may be specified on the command line or in the option database to configure aspects of the graph such as its colors and font. See the configure operation below for the exact details about what option and value pairs are valid.

The *-style* option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is "line".

If successful, graph returns the path name of the widget. It also creates a new Tcl command by the same name. You can use this command to invoke various operations that query or modify the graph. The general form is:

**pathName** *operation ?arg?...*

Both operation and its arguments determine the exact behavior of the command. The operations available for the graph are described in the section.

The command can also be used to access components of the graph.

**pathName component** *operation ?arg?...*

A graph is composed of several components: coordinate axes, data elements, legend, grid, cross hairs, postscript, and annotation markers. Instead of one big set of configuration options and operations, the graph is partitioned, where each component has its own configuration options and operations that specifically control that aspect or part of the graph.

The operation, now located after the name of the component, is the function to be performed on that component. Each component has its own set of operations that manipulate that component. They will be described below in their own sections.

<a name="GRAPH-OPERATIONS"></a>
## GRAPH OPERATIONS

<a name="pathName-axis"></a>
**pathName axis** *operation ?arg?...*

> See the [AXIS COMPONENT](#AXIS-COMPONENT) section.

<a name="pathName-bar"></a>
................................................................................
**pathName cget** *option*

> Returns the current value of the configuration option given by option. Option may be any option described below for the configure operation.

<a name="pathName-configure"></a>
**pathName configure** *?option value?...*

> Queries or modifies the configuration options of the graph. If option isn't specified, a list describing the current options for pathName is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the option option is set to value. The following options are valid.

> **-aspect** *width/height*

> > Force a fixed aspect ratio of width/height, a floating point number.

> **-background** *color*

> > Sets the background color. This includes the margins and legend, but not the plotting area.

> **-borderwidth** *pixels*

> > Sets the width of the 3-D border around the outside edge of the widget. The -relief option determines if the border is to be drawn. The default is 2.

> **-bottommargin** *pixels*

> > If non-zero, overrides the computed size of the margin extending below the X-coordinate axis. If pixels is 0, the automatically computed size is used. The default is 0.

> **-bufferelements** *boolean*

> > Indicates whether an internal pixmap to buffer the display of data elements should be used. If boolean is true, data elements are drawn to an internal pixmap. This option is especially useful when the graph is redrawn frequently while the remains data unchanged (for example, moving a marker across the plot). See the section. The default is 1.

> **-cursor** *cursor*

> > Specifies the widget's cursor. The default cursor is crosshair.

> **-font** *fontName*

> > Specifies the font of the graph title. The default is `*-Helvetica-Bold-R-Normal-*-18-180-*`.

> **-halo** *pixels*

> > Specifies a maximum distance to consider when searching for the closest data point (see the element's closest operation below). Data points further than pixels away are ignored. The default is 0.5i.

> **-height** *pixels*

> > Specifies the requested height of widget. The default is 4i.

> **-invertxy** *boolean*

> > Indicates whether the placement X-axis and Y-axis should be inverted. If boolean is true, the X and Y axes are swapped. The default is 0.

> **-justify** *justify*

> > Specifies how the title should be justified. This matters only when the title contains more than one line of text. Justify must be left, right, or center. The default is center.

> **-leftmargin** *pixels*

> > If non-zero, overrides the computed size of the margin extending from the left edge of the window to the Y-coordinate axis. If pixels is 0, the automatically computed size is used. The default is 0.

> **-plotbackground** *color*

> > Specifies the background color of the plotting area. The default is white.

> **-plotborderwidth** *pixels*

> > Sets the width of the 3-D border around the plotting area. The -plotrelief option determines if a border is drawn. The default is 2.

> **-plotpadx** *pad*

> > Sets the amount of padding to be added to the left and right sides of the plotting area. Pad can be a list of one or two screen distances. If pad has two elements, the left side of the plotting area entry is padded by the first distance and the right side by the second. If pad is just one distance, both the left and right sides are padded evenly. The default is 8.

> **-plotpady** *pad*

> > Sets the amount of padding to be added to the top and bottom of the plotting area. Pad can be a list of one or two screen distances. If pad has two elements, the top of the plotting area is padded by the first distance and the bottom by the second. If pad is just one distance, both the top and bottom are padded evenly. The default is 8.

> **-plotrelief** *relief*

> > Specifies the 3-D effect for the plotting area. Relief specifies how the interior of the plotting area should appear relative to rest of the graph; for example, raised means the plot should appear to protrude from the graph, relative to the surface of the graph. The default is sunken.

> **-relief** *relief*

> > Specifies the 3-D effect for the graph widget. Relief specifies how the graph should appear relative to widget it is packed into; for example, raised means the graph should appear to protrude. The default is flat.

> **-rightmargin** *pixels*

> > If non-zero, overrides the computed size of the margin extending from the plotting area to the right edge of the window. By default, the legend is drawn in this margin. If pixels is 0, the automatically computed size is used. The default is 0.

> **-takefocus** *focus*

> > Provides information used when moving the focus from window to window via keyboard traversal (e.g., Tab and Shift-Tab). If focus is 0, this means that this window should be skipped entirely during keyboard traversal. 1 means that the this window should always receive the input focus. An empty value means that the traversal scripts make the decision whether to focus on the window. The default is "".

> **-tile** *image*

> > Specifies a tiled background for the widget. If image isn't "", the background is tiled using image. Otherwise, the normal background color is drawn (see the -background option). Image must be an image created using the Tk image command. The default is "".

> **-title** *text*

> > Sets the title to text. If text is "", no title will be displayed.

> **-topmargin** *pixels*

> > If non-zero, overrides the computed size of the margin above the x2 axis. If pixels is 0, the automatically computed size is used. The default is 0.

> **-width** *pixels*

> > Specifies the requested width of the widget. The default is 5i.

<a name="pathName-crosshairs"></a>
**pathName crosshairs** *operation ?arg?*

> See the [CROSSHAIRS COMPONENT](#CROSSHAIRS-COMPONENT) section.

<a name="pathName-element"></a>
................................................................................

Only one element or marker can be picked during an event. This means, that if the mouse is directly over both an element and a marker, only the uppermost component is selected. This isn't true for legend entries. Both a legend entry and an element (or marker) binding commands will be invoked if both items are picked.

It is possible for multiple bindings to match a particular event. This could occur, for example, if one binding is associated with the element name and another is associated with one of the element's tags (see the -bindtags option). When this occurs, all of the matching bindings are invoked. A binding associated with the element name is invoked first, followed by one binding for each of the element's bindtags. If there are multiple matching bindings for a single tag, then only the most specific binding is invoked. A continue command in a binding script terminates that script, and a break command terminates that script and skips any remaining scripts for the event, just as for the bind command.

The -bindtags option for these components controls addition tag names which can be matched. Implicitly elements and markers always have tags matching their names. Setting the value of the -bindtags option doesn't change this.

Some common bindings can be set with the [pathName binding](#pathName-binding) command.

## <a name="C-LANGUAGE-API"></a>
## C LANGUAGE API 

You can manipulate data elements from the C language. There may be situations where it is too expensive to translate the data values from ASCII strings. Or you might want to read data in a special file format.

Data can manipulated from the C language using graph vectors. You specify the X-Y data coordinates of an element as vectors and manipulate the vector from C. The graph will be redrawn automatically after the vectors are updated.
................................................................................
> <code>
	# Print the graph into file "file.ps"  
	.g postscript output file.ps -maxpect yes -decorations no  
</code>

This generates a file file.ps containing the encapsulated PostScript of the graph. The option -maxpect says to scale the plot to the size of the page. Turning off the -decorations option denotes that no borders or color backgrounds should be drawn (i.e. the background of the margins, legend, and plotting area will be white).














<a name="KEYWORDS"></a>
## KEYWORDS

graph, widget

<a name="COPYRIGHT"></a>

## COPYRIGHT

&copy; 1995-1997 Roger E. Critchlow Jr.

&copy; 2001 George A. Howlett.

&copy; 2018 René Zaumseil <[email protected]>





<
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
<
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
>
>

<
>
>
>
>

|
<
>
>
>

<
>

|
<
>
>
>

<
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|







 







|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>





|
>








>
>
>
1
2

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

257
258
259
260

261
262
263
264
265
266

267
268
269
270

271
272
273

274
275
276
277

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
...
440
441
442
443
444
445
446
447
448























449
450
451
452
453
454
455
...
488
489
490
491
492
493
494
495
































































































496
497
498
499
500
501
502
....
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
....
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
# graph(n) -- 2D graph for plotting X-Y coordinate data


*   [SYNOPSIS](#SYNOPSIS)  
*   [STANDARD OPTIONS](#STANDARD-OPTIONS)  
  [-background or -bg, background, Background](options.htm#M-background)  
  [-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
  [-cursor, cursor, Cursor](options.htm#M-cursor)  
  [-foreground or -fg, foreground, Foreground](options.htm#M-foreground)  
  [-height, height, Height](options.htm#M-height)  
  [-width, width, Width](options.htm#M-width)  
*   [WIDGET-SPECIFIC OPTIONS](#WIDGET-SPECIFIC-OPTIONS)  
  [-aspect, aspect, Aspect](#-aspect) *width/height*  
  [-barmode, barMode, BarMode](#-barmode)  
  [-barwidth, barWidth, BarWidth](#-barwidth)  
  [-baseline, baseline, Baseline](#-baseline)  
  [-bottommargin, bottomMargin, Margin](#-bottommargin) *pixels*  
  [-bottomvariable, bottomVariable, BottomVariable](#-bottomvariable)  
  [-bufferelements, bufferElements, BufferElements](#-bufferelements) *boolean*  
  [-buffergraph, bufferGraph, BufferGraph](#-buffergraph)  
  [-style, style, Style](#-style) *line|bar|strip*  
  [-data, data, Data](#-data)  
  [-datacommand, dataCommand, DataCommand](#-datacommand)  
  [-font, font, Font](#-font) *fontName*  
  [-halo, halo, Halo](#-halo) *pixels*  
  [-highlightbackground, highlightBackground, HighlightBackground](#-highlightbackground)  
  [-highlightcolor, highlightColor, HighlightColor](#-highlightcolor)  
  [-highlightthickness, highlightThickness, HighlightThickness](#-highlightthickness)  
  [-invertxy, invertXY, InvertXY](#-invertxy) *boolean*  
  [-justify, justify, Justify](#-justify) *justify*  
  [-leftmargin or -lm, leftMargin, Margin](#-leftmargin) *pixels*  
  [-leftvariable, leftVariable, LeftVariable](#-leftvariable)  
  [-plotbackground, plotBackground, Background](#-plotbackground) *color*  
  [-plotborderwidth, plotBorderWidth, BorderWidth](#-plotborderwidth) *pixels*  
  [-plotpadx, plotPadX, PlotPad](#-plotpadx) *pad*  
  [-plotpady, plotPadY, PlotPad](#-plotpadx) *pad*  
  [-plotrelief, plotRelief, Relief](#-plotrelief) *relief*  
  [-relief, relief, Relief](#-relief) *relief*  
  [-rightmargin or -rm, rightMargin, Margin](#-rightmargin) *pixels*  
  [-rightvariable, rightVariable, RightVariable](#-rightvariable)  
  [-shadow, shadow, Shadow](#-shadow)  
  [-takefocus, takeFocus, TakeFocus](#-takefocus)  
  [-title, title, Title](#-title) *text|image*  
  [-topmargin or -tm, topMargin, Margin](#-topmargin) *pixels*  
  [-topvariable, topVariable, TopVariable](#-topvariable)  
*   [DESCRIPTION](#DESCRIPTION)  



*   [WIDGET COMMAND](#WIDGET-COMMAND)  
  [*pathName* **axis**](#pathName-axis) *operation ?arg?...*  
  [*pathName* **binding**](#pathName-binding) *?crosshairs? ?findelement? ?legend? ?zoom?*  
  [*pathName* **bar**](#pathName-bar) *elemName ?option value?...*  
  [*pathName* **cget**](#pathName-cget) *option*  
  [*pathName* **configure**](#pathName-configure) *?option value?...*  
  [*pathName* **crosshairs**](#pathName-crosshairs) *operation ?arg?*  
  [*pathName* **element**](#pathName-element) *operation ?arg?...*  
  [*pathName* **extents**](#pathName-extents) *item*  
  [*pathName* **grid**](#pathName-grid) *operation ?arg?...*  
  [*pathName* **invtransform**](#pathName-invtransform) *winX winY*  
  [*pathName* **inside**](#pathName-inside) *x y*  
  [*pathName* **legend**](#pathName-legend) *operation ?arg?...*  
  [*pathName* **line**](#pathName-line) *operation arg...*  
  [*pathName* **marker**](#pathName-marker) *operation ?arg?...*  
  [*pathName* **postscript**](#pathName-postscript) *operation ?arg?...*  
  [*pathName* **snap**](#pathName-snap) *?switches? outputName*  
  [*pathName* **transform**](#pathName-transform) *x y*  
  [*pathName* **xaxis**](#pathName-xaxis) *operation ?arg?...*  
  [*pathName* **x2axis**](#pathName-x2axis) *operation ?arg?...*  
  [*pathName* **yaxis**](#pathName-yaxis) *operation ?arg?...*  
  [*pathName* **y2axis**](#pathName-y2axis) *operation ?arg?...*  
* [AXIS COMPONENT](#AXIS-COMPONENT)  
  [*pathName* **axis bind**](#pathName-axis-bind) *tagName ?sequence? ?command?*  
  [*pathName* **axis cget**](#pathName-axis-cget) *axisName option*  
  [*pathName* **axis configure**](#pathName-axis-configure) *axisName ?axisName?... ?option value?...*  
  [*pathName* **axis create**](#pathName-axis-create) *axisName ?option value?...*  
  [*pathName* **axis delete**](#pathName-axis-delete) *?axisName?...*  
  [*pathName* **axis invtransform**](#pathName-axis-invtransform) *axisName value*  
  [*pathName* **axis limits**](#pathName-axis-limits) *axisName*  
  [*pathName* **axis names**](#pathName-axis-names) *?pattern?...*  
  [*pathName* **axis transform**](#pathName-axis-transform) *axisName value*  
  [*pathName* **axis view**](#pathName-axis-view) *axisName*  
* [CROSSHAIRS COMPONENT](#)  
  [*pathName* **crosshairs cget**](#pathName-crosshairs-cget) *option*  
  [*pathName* **crosshairs configure**](#pathName-crosshairs-configure) *?option value?...*  
  [*pathName* **crosshairs off**](#pathName-crosshairs-off)  
  [*pathName* **crosshairs on**](#pathName-crosshairs-on)  
  [*pathName* **crosshairs toggle**](#pathName-crosshairs-toggle)  
* [ELEMENT COMPONENT](#ELEMENT-COMPONENT)  
  [*pathName* **element activate**](#pathName-element-activate) *elemName ?index?...*  
  [*pathName* **element bind**](#pathName-element-bind) *tagName ?sequence? ?command?*  
  [*pathName* **element cget**](#pathName-element-cget) *elemName option*  
  [*pathName* **element closest**](#pathName-element-closest) *x y varName ?option value?... ?elemName?...*  
  [*pathName* **element configure**](#pathName-element-configure) *elemName ?elemName... ?option value?...*  
  [*pathName* **element create**](#pathName-element-create) *elemName ?option value?...*  
  [*pathName* **element deactivate**](#pathName-element-deactivate) *elemName ?elemName?...*  
  [*pathName* **element delete**](#pathName-element-delete) *?elemName?...*  
  [*pathName* **element exists**](#pathName-element-exists) *elemName*  
  [*pathName* **element names**](#pathName-element-names) *?pattern?...*  
  [*pathName* **element show**](#pathName-element-show) *?nameList?*  
  [*pathName* **element type**](#pathName-element-type) *elemName*  
* [GRID COMPONENT](#GRID-COMPONENT)  
  [*pathName* **grid cget**](#pathName-grid-cget) *option*  
  [*pathName* **grid configure**](#pathName-grid-configure) *?option value?...*  
  [*pathName* **grid off**](#pathName-grid-off)  
  [*pathName* **grid on**](#pathName-grid-on)  
  [*pathName* **grid toggle**](#pathName-grid-toggle)  
* [LEGEND COMPONENT](#LEGEND-COMPONENT)  
  [*pathName* **legend activate**](#pathName-legend-activate) *pattern...*  
  [*pathName* **legend bind**](#pathName-legend-bind) *tagName ?sequence? ?command?*  
  [*pathName* **legend cget**](#pathName-legend-cget) *option*  
  [*pathName* **legend configure**](#pathName-legend-configure) *?option value?...*  
  [*pathName* **legend deactivate**](#pathName-legend-deactivate) *pattern...*  
  [*pathName* **legend get**](#pathName-legend-get) *pos*  
* [PEN COMPONENT](#PEN-COMPONENT)  
  [*pathName* **pen cget**](#pathName-pen-cget) *penName option*  
  [*pathName* **pen configure**](#pathName-pen-configure) *penName ?penName... ?option value?...*  
  [*pathName* **pen create**](#pathName-pen-create) *penName ?option value?...*  
  [*pathName* **pen delete**](#pathName-pen-delete) *?penName?...*  
  [*pathName* **pen names**](#pathName-pen-names) *?pattern?...*  
* [POSTSCRIPT COMPONENT](#POSTSCRIPT-COMPONENT)  
  [*pathName* **postscript cget**](#pathName-postscript-cget) *option*  
  [*pathName* **postscript configure**](#pathName-postscript-configure) *?option value?...*  
  [*pathName* **postscript output**](#pathName-postscript-output) *?fileName? ?option value?...*  
* [MARKER COMPONENT](#MARKER-COMPONENT)  
  [*pathName* **marker after**](#pathName-marker-after) *markerId ?afterId?*  
  [*pathName* **marker before**](#pathName-marker-before) *markerId ?beforeId?*  
  [*pathName* **marker bind**](#pathName-marker-bind) *tagName ?sequence? ?command?*  
  [*pathName* **marker cget**](#pathName-marker-cget) *option*  
  [*pathName* **marker configure**](#pathName-marker-configure) *markerId ?option value?...*  
  [*pathName* **marker create**](#pathName-marker-create) *type ?option value?...*  
  [*pathName* **marker delete**](#pathName-marker-delete) *?name?...*  
  [*pathName* **marker exists**](#pathName-marker-exists) *markerId*  
  [*pathName* **marker names**](#pathName-marker-names) *?pattern?*  
  [*pathName* **marker type**](#pathName-marker-type) *markerId*  
  [BITMAP MARKERS](#BITMAP-MARKERS)  
  [*pathName* **marker create bitmap**](#pathName-marker-create-bitmap) *?option value?...*  
  [IMAGE MARKERS](#IMAGE-MARKERS)  
  [*pathName* **marker create image**](#pathName-marker-create-image) *?option value?...*  
  [LINE MARKERS](#LINE-MARKERS)  
  [*pathName* **marker create line**](#pathName-marker-create-line) *?option value?...*  
  [POLYGON MARKERS](#POLYGON-MARKERS)  
  [*pathName* **marker create polygon**](#pathName-marker-create-polygon) *?option value?...*  
  [TEXT MARKERS](#TEXT-MARKERS)  
  [*pathName* **marker create text**](#pathName-marker-create-text) *?option value?...*  
  [WINDOW MARKERS](#WINDOW-MARKERS)  
  [*pathName* **marker create window**](#pathName-marker-create-window) *?option value?...*  
*   [GRAPH COMPONENT BINDINGS](#GRAPH-COMPONENT-BINDINGS)  
*   [C LANGUAGE API](#[C-LANGUAGE-API)  
*   [SPEED TIPS](#SPEED-TIPS)  
*   [LIMITATIONS](#LIMITATIONS)  
*   [EXAMPLE](#EXAMPLE)  
*   [CREDITS](#CREDITS)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="SYNOPSIS"></a>
## SYNOPSIS 

**graph** *pathName ?-style line|bar|strip? ?option value?...*

The graph command creates a new window pathName and makes it into a graph widget. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist. Additional options may be specified on the command line or in the option database to configure aspects of the graph such as its colors and font. See the configure operation below for the exact details about what option and value pairs are valid.

The *-style* option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is "line".

If successful, graph returns the path name of the widget. It also creates a new Tcl command by the same name. You can use this command to invoke various operations that query or modify the graph. The general form is:

**pathName** *operation ?arg?...*

Both operation and its arguments determine the exact behavior of the command. The operations available for the graph are described in the section.

The command can also be used to access components of the graph.

**pathName component** *operation ?arg?...*

A graph is composed of several components: coordinate axes, data elements, legend, grid, cross hairs, postscript, and annotation markers. Instead of one big set of configuration options and operations, the graph is partitioned, where each component has its own configuration options and operations that specifically control that aspect or part of the graph.

The operation, now located after the name of the component, is the function to be performed on that component. Each component has its own set of operations that manipulate that component. They will be described below in their own sections.

<a name="STANDARD-OPTIONS"></a>
## STANDARD OPTIONS

[-background or -bg, background, Background](options.htm#M-background) This includes the margins and legend, but not the plotting area.  
[-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
[-cursor, cursor, Cursor](options.htm#M-cursor)  
[-foreground or -fg, foreground, Foreground](options.htm#M-foreground)  
[-height, height, Height](options.htm#M-height) The default is 4i.  
[-width, width, Width](options.htm#M-width) The default is 5i.  

See the [options][] manual entry for details on the standard options.

<a name="WIDGET-SPECIFIC-OPTIONS"></a>
## WIDGET-SPECIFIC OPTIONS

<a name="-aspect"></a>
Command-Line Name: **-aspect**  
Database Name: **aspect**  
Database Class: **Aspect**

> > Force a fixed aspect ratio of width/height, a floating point number.

<a name="-barmode"></a>
Command-Line Name: **-barmode**  
Database Name: **barMode**  
Database Class: **BarMode**

<a name="-barwidth"></a>
Command-Line Name: **-barwidth**  
Database Name: **barWidth**  
Database Class: **BarWidth**

<a name="-baseline"></a>
Command-Line Name: **-baseline**  
Database Name: **baseline**  
Database Class: **Baseline**

<a name="-bottommargin"></a>
Command-Line Name: **-bottommargin or -bm**  
Database Name: **bottomMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin extending below the X-coordinate axis. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-bottomvariable"></a>
Command-Line Name: **-bottomvariable**  
Database Name: **bottomVariable**  
Database Class: **BottomVariable**

<a name="-bufferelements"></a>
Command-Line Name: **-bufferelements**  
Database Name: **bufferElements**  
Database Class: **BufferElements**

> > Indicates whether an internal pixmap to buffer the display of data elements should be used. If boolean is true, data elements are drawn to an internal pixmap. This option is especially useful when the graph is redrawn frequently while the remains data unchanged (for example, moving a marker across the plot). See the section. The default is 1.

<a name="-buffergraph"></a>
Command-Line Name: **-buffergraph**  
Database Name: **bufferGraph**  
Database Class: **BufferGraph**

<a name="-style"></a>
Command-Line Name: **-style**  
Database Name: **style**  
Database Class: **Style**

The option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is **line**.

> **line**

> > Display X-Y plotchart

> **bar**

> > Display barchart.

> **strip**

> > Display stripchart.

<a name="-data"></a>

Command-Line Name: **-data**  
Database Name: **data**  
Database Class: **Data**


<a name="-datacommand"></a>
Command-Line Name: **-datacommand**  
Database Name: **dataCommand**  
Database Class: **DataCommand**

<a name="-font"></a>

Command-Line Name: **-font**  
Database Name: **font**  
Database Class: **Font**


> > Specifies the font of the graph title. The default is `*-Helvetica-Bold-R-Normal-*-18-180-*`.

<a name="-halo"></a>

Command-Line Name: **-halo**  
Database Name: **halo**  
Database Class: **Halo**


> > Specifies a maximum distance to consider when searching for the closest data point (see the element's closest operation below). Data points further than pixels away are ignored. The default is 0.5i.

<a name="-highlightbackground"></a>
Command-Line Name: **-highlightbackground**  
Database Name: **highlightBackground**  
Database Class: **HighlightBackground**

<a name="-highlightcolor"></a>
Command-Line Name: **-highlightcolor**  
Database Name: **highlightColor**  
Database Class: **HighlightColor**

<a name="-highlightthickness"></a>
Command-Line Name: **-highlightthickness**  
Database Name: **highlightThickness**  
Database Class: **HighlightThickness**

<a name="-invertxy"></a>
Command-Line Name: **-invertxy**  
Database Name: **invertXY**  
Database Class: **InvertXY**

> > Indicates whether the placement X-axis and Y-axis should be inverted. If boolean is true, the X and Y axes are swapped. The default is 0.

<a name="-justify"></a>
Command-Line Name: **-justify**  
Database Name: **justify**  
Database Class: **Justify**

> > Specifies how the title should be justified. This matters only when the title contains more than one line of text. Justify must be left, right, or center. The default is center.

<a name="-leftmargin"></a>
Command-Line Name: **-leftmargin or -lm**  
Database Name: **leftMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin extending from the left edge of the window to the Y-coordinate axis. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-leftvariable"></a>
Command-Line Name: **-leftvariable**  
Database Name: **leftVariable**  
Database Class: **LeftVariable**

<a name="-plotbackground"></a>
Command-Line Name: **-plotbackground**  
Database Name: **plotBackground**  
Database Class: **Background**

> > Specifies the background color of the plotting area. The default is white.

<a name="-plotborderwidth"></a>
Command-Line Name: **-plotborderwidth**  
Database Name: **plotBorderWidth**  
Database Class: **BorderWidth**

> > Sets the width of the 3-D border around the plotting area. The -plotrelief option determines if a border is drawn. The default is 2.

<a name="-plotpadx"></a>
Command-Line Name: **-plotpadx**  
Database Name: **plotPadX**  
Database Class: **PlotPad**


> > Sets the amount of padding to be added to the left and right sides of the plotting area. Pad can be a list of one or two screen distances. If pad has two elements, the left side of the plotting area entry is padded by the first distance and the right side by the second. If pad is just one distance, both the left and right sides are padded evenly. The default is 8.

<a name="-plotpady"></a>
Command-Line Name: **-plotpady**  
Database Name: **plotPadY**  
Database Class: **PlotPad**

> > Sets the amount of padding to be added to the top and bottom of the plotting area. Pad can be a list of one or two screen distances. If pad has two elements, the top of the plotting area is padded by the first distance and the bottom by the second. If pad is just one distance, both the top and bottom are padded evenly. The default is 8.

> **-plotrelief**
<a name="-plotrelief"></a>
Command-Line Name: **-plotrelief**  
Database Name: **plotRelief**  
Database Class: **Relief**

> > Specifies the 3-D effect for the plotting area. Relief specifies how the interior of the plotting area should appear relative to rest of the graph; for example, raised means the plot should appear to protrude from the graph, relative to the surface of the graph. The default is sunken.

> **-relief** *relief*
<a name="-relief"></a>
Command-Line Name: **-relief**  
Database Name: **relief**  
Database Class: **Relief**

> > Specifies the 3-D effect for the graph widget. Relief specifies how the graph should appear relative to widget it is packed into; for example, raised means the graph should appear to protrude. The default is flat.

<a name="-rightmargin"></a>
Command-Line Name: **-rightmargin**  
Database Name: **rightMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin extending from the plotting area to the right edge of the window. By default, the legend is drawn in this margin. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-rightvariable"></a>
Command-Line Name: **-rightvariable**  
Database Name: **rightVariable**  
Database Class: **RightVariable**

<a name="-shadow"></a>
Command-Line Name: **-shadow**  
Database Name: **shadow**  
Database Class: **Shadow**

> **-takefocus** *focus*
<a name="-takefocus"></a>
Command-Line Name: **-takefocus**  
Database Name: **takeFocus**  
Database Class: **TakeFocus**

> > Provides information used when moving the focus from window to window via keyboard traversal (e.g., Tab and Shift-Tab). If focus is 0, this means that this window should be skipped entirely during keyboard traversal. 1 means that the this window should always receive the input focus. An empty value means that the traversal scripts make the decision whether to focus on the window. The default is "".

<a name="-tile"></a>

Command-Line Name: **-tile**  
Database Name: **tile**  
Database Class: **Title**

> **image**

> > Specifies a tiled background for the widget. If image isn't "", the background is tiled using image. Otherwise, the normal background color is drawn (see the -background option). Image must be an image created using the Tk image command. The default is "".

> **text**

> > Sets the title to text. If text is "", no title will be displayed.

<a name="-topmargin"></a>
Command-Line Name: **-topmargin**  
Database Name: **topMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin above the x2 axis. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-topvariable"></a>
Command-Line Name: **-topvariable**  
Database Name: **topVariable**  
Database Class: **TopVariable**

<a name="DESCRIPTION"></a>
## DESCRIPTION 

The graph command creates a new window for plotting two-dimensional data (X-Y coordinates). Data points are plotted in a rectangular area displayed in the center of the new window. This is the plotting area. The coordinate axes are drawn in the margins around the plotting area. By default, the legend is displayed in the right margin. The title is displayed in top margin. They allow you to customize the look and feel of the graph.

The graph widget is composed of several components: coordinate axes, data elements, legend, grid, cross hairs, pens, postscript, and annotation markers.

**axis**
    The graph has four standard axes (x, x2, y, and y2), but you can create and display any number of axes. Axes control what region of data is displayed and how the data is scaled. Each axis consists of the axis line, title, major and minor ticks, and tick labels. Tick labels display the value at each major tick.

**crosshairs**
................................................................................

**pen**
    Pens define attributes (both symbol and line style) for elements. Data elements use pens to specify how they should be drawn. A data element may use many pens at once. Here, the particular pen used for a data point is determined from each element's weight vector (see the element's -weight and -style options).

**postscript**
    The widget can generate encapsulated PostScript output. This component has several options to configure how the PostScript is generated.

<a name="WIDGET-COMMAND"></a>
## WIDGET COMMAND
























<a name="pathName-axis"></a>
**pathName axis** *operation ?arg?...*

> See the [AXIS COMPONENT](#AXIS-COMPONENT) section.

<a name="pathName-bar"></a>
................................................................................
**pathName cget** *option*

> Returns the current value of the configuration option given by option. Option may be any option described below for the configure operation.

<a name="pathName-configure"></a>
**pathName configure** *?option value?...*

> Query or modify the configuration options of the widget. If no *option* is specified, returns a list describing all of the available options for pathName (see [Tk_ConfigureInfo][] for information on the format of this list). If *option* is specified with no *value*, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more *option-value* pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. *Option* may have any of the values accepted by the **graph** command. 

































































































<a name="pathName-crosshairs"></a>
**pathName crosshairs** *operation ?arg?*

> See the [CROSSHAIRS COMPONENT](#CROSSHAIRS-COMPONENT) section.

<a name="pathName-element"></a>
................................................................................

Only one element or marker can be picked during an event. This means, that if the mouse is directly over both an element and a marker, only the uppermost component is selected. This isn't true for legend entries. Both a legend entry and an element (or marker) binding commands will be invoked if both items are picked.

It is possible for multiple bindings to match a particular event. This could occur, for example, if one binding is associated with the element name and another is associated with one of the element's tags (see the -bindtags option). When this occurs, all of the matching bindings are invoked. A binding associated with the element name is invoked first, followed by one binding for each of the element's bindtags. If there are multiple matching bindings for a single tag, then only the most specific binding is invoked. A continue command in a binding script terminates that script, and a break command terminates that script and skips any remaining scripts for the event, just as for the bind command.

The -bindtags option for these components controls addition tag names which can be matched. Implicitly elements and markers always have tags matching their names. Setting the value of the -bindtags option doesn't change this.

Some common bindings can be set with the [*pathName* **binding**](#pathName-binding) command.

## <a name="C-LANGUAGE-API"></a>
## C LANGUAGE API 

You can manipulate data elements from the C language. There may be situations where it is too expensive to translate the data values from ASCII strings. Or you might want to read data in a special file format.

Data can manipulated from the C language using graph vectors. You specify the X-Y data coordinates of an element as vectors and manipulate the vector from C. The graph will be redrawn automatically after the vectors are updated.
................................................................................
> <code>
	# Print the graph into file "file.ps"  
	.g postscript output file.ps -maxpect yes -decorations no  
</code>

This generates a file file.ps containing the encapsulated PostScript of the graph. The option -maxpect says to scale the plot to the size of the page. Turning off the -decorations option denotes that no borders or color backgrounds should be drawn (i.e. the background of the margins, legend, and plotting area will be white).

<a name="CREDITS"></a>
## CREDITS

[BLT][] was originally develeoped by George A. Howlett. It can be found at <https://sourceforge.net/projects/blt/>.

Refactored [BLT][] Components ([Rbc][]), includes data vectors and graph widgets from the original [BLT][]. Both can be found at sourceforge.

User visible changes to the original [Rbc][] code are:

- widget name is **graph**
- new **-style** *line|bar|strip* option instead of three different commands **graph**, **barchart** and **stripchart**
- no unique abbreviations of widget commands

<a name="KEYWORDS"></a>
## KEYWORDS

graph, widget

<a name="COPYRIGHT"></a>:1

## COPYRIGHT

&copy; 1995-1997 Roger E. Critchlow Jr.

&copy; 2001 George A. Howlett.

&copy; 2018 René Zaumseil <[email protected]>

[BLT]: <https://sourceforge.net/projects/blt/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>

Added doc/path.n.md.


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
# path(n) -- 2D canvas widget

*   [SYNOPSIS](#SYNOPSIS)
*   [STANDARD OPTIONS](#STANDARD-OPTIONS)  
  [-background or -bg, background, Background](options.htm#M-background)   
  [-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
  [-cursor, cursor, Cursor](options.htm#M-cursor)  
  [-highlightbackground, highlightBackground, HighlightBackground](options.htm#M-highlightbackground)  
  [-highlightcolor, highlightColor, HighlightColor](options.htm#M-highlightcolor)  
  [-highlightthickness, highlightThickness, HighlightThickness](options.htm#M-highlightthickness)  
  [-insertbackground, insertBackground, Foreground](options.htm#M-insertbackground)  
  [-insertborderwidth, insertBorderWidth, BorderWidth](options.htm#M-insertborderwidth)  
  [-insertofftime, insertOffTime, OffTime](options.htm#M-insertofftime)  
  [-insertontime, insertOnTime, OnTime](options.htm#M-insertontime)  
  [-insertwidth, insertWidth, InsertWidth](options.htm#M-insertwidth)  
  [-relief, relief, Relief](options.htm#M-relief)  
  [-selectbackground, selectBackground, Foreground](options.htm#M-selectbackground)  
  [-selectborderwidth, selectBorderWidth, BorderWidth](options.htm#M-selectborderwidth)  
  [-selectforeground, selectForeground, Background](options.htm#M-selectforeground)  
  [-takefocus, takeFocus, TakeFocus](options.htm#M-takefocus)  
  [-xscrollcommand, xScrollCommand, ScrollCommand](options.htm#M-xscrollcommand)  
  [-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  
* [WIDGET-SPECIFIC OPTIONS](#WIDGET-SPECIFIC-OPTIONS)  
  [-closeenough, closeEnough, CloseEnough](#-closeenough)  
  [-confine, confine, Confine](#-confine)  
  [-height, height, Height](#-height)  
  [-scrollregion, scrollRegion, ScrollRegion](#-scrollregion)  
  [-state, state, State](#-state)  
  [-tagstyle, tagstyle, Tagstyle](#-tagstyle)  
  [-width, width, Width](#-width)  
  [-xscrollincrement, xScrollIncrement, ScrollIncrement](#-xscrollincrement)  
  [-yscrollincrement, yScrollIncrement, ScrollIncrement](#-yscrollincrement)  
*   [DESCRIPTION](#DESCRIPTION)  
  * [DISPLAY LIST](#DISPLAY-LIST)  
  * [ITEM IDS AND TAGS](#ITEM-IDS-AND-TAGS)  
  * [COORDINATES](#COORDINATES)  
  * [TEXT INDICES](#TEXT-INDICES)  
  * [TRANSFORMATIONS](#TRANSFORMATIONS)    
  [**path::matrix rotate**](#path::matrix-rotate) *angle ?cx? ?cy?*  
  [**path::matrix scale**](#path::matrix-scale) *sx ?sy?*  
  [**path::matrix flip**](#path::matrix-flip) *?cx? ?cy? ?fx? ?fy?*  
  [**path::matrix rotateflip**](#path::matrix-rotateflip) *?angle? ?cx? ?cy? ?fx? ?fy?*  
  [**path::matrix skewx**](#path::matrix-skewx) *?angle?*  
  [**path::matrix skewy**](#path::matrix-skewy) *?angle?*  
  [**path::matrix move**](#path::matrix-move) *dx dy*  
  [**path::matrix mult**](#path::matrix-mult) *ma mb*  
  * [STYLES](#STYLES)  
  [**path::style cget**](#path::style-cget) *token option*  
  [**path::style configure**](#path::style-configure) *token ?option? ?value option value...?*  
  [**path::style create**](#path::style-create) *?fillOptions strokeOptions?*  
  [**path::style delete**](#path::style-delete) *token*  
  [**path::style inuse**](#path::style-inuse) *token*  
  [**path::style names**](#path::style-names)  
  * [GRADIENTS](#GRADIENTS)  
  [**path::gradient cget**](#path::gradient-cget) *token option*  
  [**path::gradient configure**](#path::gradient-configure) *token ?option? ?value option value...?*  
  [**path::gradient create**](#path::gradient-create) *type ?-key value ...?*  
  [**path::gradient delete**](#path::gradient-delete) *token*  
  [**path::gradient inuse**](#path::gradient-inuse) *token*  
  [**path::gradient names**](#path::gradient-names)  
  [**path::gradient type**](#path::gradient-type) *token*  
  * [SURFACE](#SURFACE)  
  [**path::surface names**](#path::surface-names)  
  [**path::surface new**](#path::surface-new) *width height*  
*   [WIDGET COMMAND](#WIDGET-COMMAND)  
  [*pathName* **addtag**](#pathName-addtag) *tag searchSpec ?arg arg ...?*  
  [*pathName* **ancestors**](#pathName-ancestors) *tagOrId*  
  [*pathName* **bind**](#pathName-bind) *tagOrId ?sequence? ?command?*  
  [*pathName* **canvasy**](#pathName-canvasy) *screeny ?gridspacing?*  
  [*pathName* **cget**](#pathName-cget) *option*  
  [*pathName* **children**](#pathName-children) *tagOrId*  
  [*pathName* **configure**](#pathName-configure) *?option? ?value? ?option value ...?*  
  [*pathName* **coords**](#pathName-coords) *tagOrId ?x0 y0 ...?*  
  [*pathName* **create**](#pathName-create) *type x y ?x y ...? ?option value ...?*  
  [*pathName* **dchars**](#pathName-dchars) *tagOrId first ?last?*  
  [*pathName* **delete**](#pathName-delete) *?*tagOrId* *tagOrId* ...?*  
  [*pathName* **depth**](#pathName-depth) *tagOrId*  
  [*pathName* **distance**](#pathName-distance) *tagOrId x y*  
  [*pathName* **dtag**](#pathName-dtag) *tagOrId ?tagToDelete?*  
  [*pathName* **find**](#pathName-find) *searchCommand ?arg arg ...?*  
  [*pathName* **firstchild**](#pathName-firstchild) *tagOrId*  
  [*pathName* **focus**](#pathName-focus) *?*tagOrId*?*  
  [*pathName* **gettags**](#pathName-gettags) *tagOrId*  
  [*pathName* **gradient**](#pathName-gradient) *command ?options?*  
  [*pathName* **icursor**](#pathName-icursor) *tagOrId index*   
  [*pathName* **imove**](#pathName-imove) *tagOrId index x y*  
  [*pathName* **index**](#pathName-index) *tagOrId index*  
  [*pathName* **insert**](#pathName-insert) *tagOrId beforeThis string*  
  [*pathName* **itemcget**](#pathName-itemcget) *tagOrId option*  
  [*pathName* **itemconfigure**](#pathName-itemconfigure) *tagOrId ?option? ?value? ?option value ...?*  
  [*pathName* **itempdf**](#pathName-itempdf) *tagOrId ?extgsProc objProc gradProc?*  
  [*pathName* **lastchild**](#pathName-lastchild) *tagOrId*  
  [*pathName* **lower**](#pathName-lower) *tagOrId ?belowThis?*  
  [*pathName* **move**](#pathName-move) *tagOrId xAmount yAmount*  
  [*pathName* **moveto**](#pathName-moveto) *tagOrId xPos yPos*  
  [*pathName* **nextsibling**](#pathName-nextsibling) *tagOrId*  
  [*pathName* **parent**](#pathName-parent) *tagOrId*  
  [*pathName* **prevsibling**](#pathName-prevsibling) *tagOrId*  
  [*pathName* **raise**](#pathName-raise) *tagOrId ?aboveThis?*  
  [*pathName* **rchars**](#pathName-rchars) *tagOrId first last string*  
  [*pathName* **scale**](#pathName-scale) *tagOrId xOrigin yOrigin xScale yScale*  
  [*pathName* **scan**](#pathName-scan) *option args*  
  [*pathName* **select**](#pathName-select) *option ?*tagOrId* arg?*  
  [*pathName* **style**](#pathName-style) *cmd ?options?*  
  [*pathName* **type**](#pathName-type) *tagOrId*  
  [*pathName* **types**](#pathName-types)  
  [*pathName* **xview**](#pathName-xview) *?args?*  
  [*pathName* **yview**](#pathName-yview) *?args?*  
*   [ITEM TYPES](#ITEM-TYPES)  
  * [COMMON ITEM OPTIONS](#COMMON-ITEM-OPTIONS)  
  [**-fill** *color\|gradientToken*](#ITEM-fill)  
  [**-fillopacity** *value*](#ITEM-fillopacity)  
  [**-fillrule** *nonzero\|evenodd*](#ITEM-fillrule)  
  [**-stroke** *color*](#ITEM-stroke)  
  [**-strokedasharray** *dashArray*](#ITEM-strokedasharray)  
  [**-strokelinecap** *butt\|round\|square*](#ITEM-strokelinecap)  
  [**-strokelinejoin** *miter\|round\|bevel*](#ITEM-strokelinejoin)  
  [**-strokemiterlimit** *float*](#ITEM-strokemiterlimit)  
  [**-strokeopacity** *value*](#ITEM-strokeopacity)  
  [**-strokewidth** *float*](#ITEM-strokewidth)  
  [**-matrix** *{a b c d tx ty}*](#ITEM-matrix)  
  [**-parent** *tagOrId*](#ITEM-parent)  
  [**-state** *active\|disabled\|normal\|hidden*](#ITEM-state)  
  [**-style** *styleToken*](#ITEM-style)  
  [**-tags** *tagList*](#ITEM-tags)  
  [**-startarrow** *boolean*](#ITEM-startarrow)  
  [**-startarrowlength** *float*](#ITEM-startarrowlength)  
  [**-startarrowwidth** *float*](#ITEM-startarrowwidth)  
  [**-startarrowfill** *float*](#ITEM-startarrowfill)  
  [**-endarrow** *boolean*](#ITEM-endarrow)  
  [**-endarrowlength** *float*](#ITEM-endarrowlength)  
  [**-endarrowwidth** *float*](#ITEM-endarrowwidth)  
  [**-endarrowfill** *float*](#ITEM-endarrowfill)  
  * [GROUP ITEM](#GROUP-ITEM)  
  [*pathName* **create group**](#pathName-create-group) *?fillOptions strokeOptions genericOptions?*  
  * [PATH ITEMS](#PATH-ITEM)  
  [*pathName* **create path**](#pathName-create-path) *pathSpec ?fillOptions strokeOptions arrowOptions genericOptions?*  
  * [LINE ITEM](#LINE-ITEM)  
  [*pathName* **create line**](#pathName-create-line) *x1 y1 x2 y2 ?strokeOptions arrowOptions genericOptions?*  
  * [POLYLINE ITEM](#POLYLINE-ITEM)  
  [*pathName* **create polyline**](#pathName-create-polyline) *x1 y1 x2 y2 .... ?strokeOptions arrowOptions genericOptions?*  
  * [POLYGON ITEM](#POLYGON-ITEM)  
  [*pathName* **create polygon**](#pathName-create-polygon) *x1 y1 x2 y2 .... ?fillOptions strokeOptions genericOptions?*  
  * [RECT ITEM](#RECT-ITEM)  
  [*pathName* **create rect**](#pathName-create-rect) *x1 y1 x2 y2 ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*  
  * [CIRCLE ITEM](#CIRCLE-ITEM)  
  [*pathName* **create circle**](#pathName-create-circle) *cx cy ?-r fillOptions strokeOptions genericOptions?*  
  * [ELLIPSE ITEM](#ELLIPSE-ITEM)  
  [*pathName* **create ellipse**](#pathName-create-ellipse) *cx cy ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*  
  * [IMAGE ITEM](#IMAGE-ITEM)  
  [*pathName* **create image**](#pathName-create-image) *x y ?-image -width -height genericOptions?*  
  * [TEXT ITEM](#TEXT-ITEM)  
  [*pathName* **create text**](#pathName-create-text) *x y ?-text string? ?-textanchor start\|middle\|end\|n\|w\|s\|e\|nw\|ne\|sw\|se\|c? ?-fontfamily fontname -fontsize float? ?-fontslant normal\|italic\|oblique? ?-fontweight normal\|bold? ?fillOptions strokeOptions genericOptions? ?-filloverstroke BOOLEAN?*  
  * [WINDOW ITEM](#WINDOW-ITEM)  
  [*pathName* **create window**](#pathName-create-window) *x y ?option value ...?*  
*   [CREDITS](#CREDITS)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="SYNOPSIS"></a>
## SYNOPSIS

**path** *pathName ?options?*

The **path** command creates a new Tcl command whose name is *pathName*. This command may be used to invoke various operations on the widget.

<a name="STANDARD-OPTIONS"></a>
## STANDARD OPTIONS

[-background or -bg, background, Background](options.htm#M-background)  
[-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
[-cursor, cursor, Cursor](options.htm#M-cursor)  
[-highlightbackground, highlightBackground, HighlightBackground](options.htm#M-highlightbackground)  
[-highlightcolor, highlightColor, HighlightColor](options.htm#M-highlightcolor)  
[-highlightthickness, highlightThickness, HighlightThickness](options.htm#M-highlightthickness)  
[-insertbackground, insertBackground, Foreground](options.htm#M-insertbackground)  
[-insertborderwidth, insertBorderWidth, BorderWidth](options.htm#M-insertborderwidth)  
[-insertofftime, insertOffTime, OffTime](options.htm#M-insertofftime)  
[-insertontime, insertOnTime, OnTime](options.htm#M-insertontime)  
[-insertwidth, insertWidth, InsertWidth](options.htm#M-insertwidth)  
[-relief, relief, Relief](options.htm#M-relief)  
[-selectbackground, selectBackground, Foreground](options.htm#M-selectbackground)  
[-selectborderwidth, selectBorderWidth, BorderWidth](options.htm#M-selectborderwidth)  
[-selectforeground, selectForeground, Background](options.htm#M-selectforeground)  
[-takefocus, takeFocus, TakeFocus](options.htm#M-takefocus)  
[-xscrollcommand, xScrollCommand, ScrollCommand](options.htm#M-xscrollcommand)  
[-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  

See the [options][] manual entry for details on the standard options.

<a name="WIDGET-SPECIFIC-OPTIONS"></a>
## WIDGET-SPECIFIC OPTIONS

<a name="-closeenough"></a>
Command-Line Name: **-closeenough**  
Database Name: **closeEnough**  
Database Class: **CloseEnough**

> Specifies a floating-point value indicating how close the mouse cursor must be to an item before it is considered to be "inside" the item. Defaults to 1.0. 

<a name="-confine"></a>
Command-Line Name: **-confine**  
Database Name: **confine**  
Database Class: **Confine**

> Specifies a boolean value that indicates whether or not it should be allowable to set the canvas's view outside the region defined by the **scrollRegion** argument. Defaults to true, which means that the view will be constrained within the scroll region. 

<a name="-height"></a>
Command-Line Name: **-height**  
Database Name: **height**  
Database Class: **Height**

> Specifies a desired window height that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the [COORDINATES][] section below. 

<a name="-scrollregion"></a>
Command-Line Name: **-scrollregion**  
Database Name: **scrollRegion**  
Database Class: **ScrollRegion**

> Specifies a list with four coordinates describing the left, top, right, and bottom coordinates of a rectangular region. This region is used for scrolling purposes and is considered to be the boundary of the information in the canvas. Each of the coordinates may be specified in any of the forms given in the [COORDINATES][] section below. 

<a name="-state"></a>
Command-Line Name: **-state**  
Database Name: **state**  
Database Class: **State**

> Modifies the default state of the canvas where state may be set to one of: **normal**, **disabled**, or **hidden**. Individual canvas objects all have their own state option which may override the default state. Many options can take separate specifications such that the appearance of the item can be different in different situations. The options that start with **active** control the appearance when the mouse pointer is over it, while the option starting with **disabled** controls the appearance when the state is disabled. Canvas items which are **disabled** will not react to canvas bindings. 

<a name="-tagstyle"></a>
Command-Line Name: **-tagstyle**  
Database Name: **tagstyle**  
Database Class: **Tagstyle**

> Define working with tags. Possible values are *expr\|exact\|glob*. Default is *expr*. TODO

<a name="-width"></a>
Command-Line Name: **-width**  
Database Name: **width**  
Database Class: **Width**

> Specifies a desired window width that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the [COORDINATES][] section below. 

<a name="-xscrollincrement"></a>
Command-Line Name: **-xscrollincrement**  
Database Name: **xScrollIncrement**  
Database Class: **ScrollIncrement**

> Specifies an increment for horizontal scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the horizontal view in the window will be constrained so that the canvas x coordinate at the left edge of the window is always an even multiple of **xScrollIncrement**; furthermore, the units for scrolling (e.g., the change in view when the left and right arrows of a scrollbar are selected) will also be **xScrollIncrement**. If the value of this option is less than or equal to zero, then horizontal scrolling is unconstrained. 

<a name="-yscrollincrement"></a>
Command-Line Name: **-yscrollincrement**  
Database Name: **yScrollIncrement**  
Database Class: **ScrollIncrement**

> Specifies an increment for vertical scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the vertical view in the window will be constrained so that the canvas y coordinate at the top edge of the window is always an even multiple of **yScrollIncrement**; furthermore, the units for scrolling (e.g., the change in view when the top and bottom arrows of a scrollbar are selected) will also be **yScrollIncrement**. If the value of this option is less than or equal to zero, then vertical scrolling is unconstrained. 

<a name="DESCRIPTION"></a>
## DESCRIPTION

The **path** command creates a new window (given by the pathName argument) and makes it into a canvas widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the canvas such as its colors and 3-D relief. The **path** command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

Canvas widgets implement structured graphics. A canvas displays any number of items, which may be things like rectangles, circles, lines, and text. Items may be manipulated (e.g. moved or re-colored) and commands may be associated with items in much the same way that the [bind][] command allows commands to be bound to widgets. For example, a particular command may be associated with the <Button-1> event so that the command is invoked whenever button 1 is pressed with the mouse cursor over an item. This means that items in a canvas can have behaviors defined by the Tcl scripts bound to them. 

This widget implements a canvas widget which is modelled after its [SVG][] counterpart. Items are put in a tree structure with a persistent root item with id 0. All other items are descendants of this root item. The path items, described below, are by default a child of the root item, but can be configured to be a child of any group item using the -parent option.

<a name="DISPLAY-LIST"></a>
### DISPLAY LIST

The items in a canvas are ordered for purposes of display, with the first item in the display list being displayed first, followed by the next item in the list, and so on. Items later in the display list obscure those that are earlier in the display list and are sometimes referred to as being "on top" of earlier items. When a new item is created it is placed at the end of the display list, on top of everything else. Widget commands may be used to re-arrange the order of the display list.

Window items are an exception to the above rules. The underlying window systems require them always to be drawn on top of other items. In addition, the stacking order of window items is not affected by any of the canvas widget commands; you must use the Tk [raise][] command and [lower][] command instead. 

Items can be structured using groups.

A group item is merely a placeholder for other items, similar to how a frame widget is a container for other widgets. It is a building block for the tree structure. Unlike other items, and unlike frame widgets, it doesn't display anything. It has no coordinates which is an additional difference. The root item is a special group item with id 0 and tags equal to "root". The root group can be configured like other items, but its -tags and -parent options are read only. Group items define the canvas tree structure:

      0----
          1
          2
          3
          4
          5----
              6
              7
          8----
              9
             10
         11
         12

Antialiasing, if available, is controlled by the variable **path::antialias**. To switch on set it to 1.

<a name="ITEM-IDS-AND-TAGS"></a>
### ITEM IDS AND TAGS

Items in a canvas widget may be named in either of two ways: by id or by tag. Each item has a unique identifying number, which is assigned to that item when it is created. The id of an item never changes and id numbers are never re-used within the lifetime of a canvas widget. 
Each item may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, "x123" is OK but "123" is not. The same tag may be associated with many different items. This is commonly done to group items in various interesting ways; for example, all selected items might be given the tag "selected". 

The tag **all** is implicitly associated with every item in the canvas; it may be used to invoke operations on all the items in the canvas. Note that this presently also includes the root item which can result in some unexpected behavior. In many case you can operate on the root item (0) instead. As an example, if you want to move, scale etc. all items in canvas, then do:

> <code>
    pathName move 0 x y  
</code>

The tag **current** is managed automatically by Tk; it applies to the current item, which is the topmost item whose drawn area covers the position of the mouse cursor (different item types interpret this in varying ways; see the individual item type documentation for details). If the mouse is not in the canvas widget or is not over an item, then no item has the **current** tag. 

When specifying items in canvas widget commands, if the specifier is an integer then it is assumed to refer to the single item with that id. If the specifier is not an integer, then it is assumed to refer to all of the items in the canvas that have a tag matching the specifier. The symbol *tagOrId* is used below to indicate that an argument specifies either an id that selects a single item or a tag that selects zero or more items. 

*tagOrId* may contain a logical expressions of tags by using operators: "**&&**", "**\|\|**", "**^**", "**!**", and parenthesized subexpressions. For example: 

> <code>
    .c find withtag {(a&&!b)||(!a&&b)}  
</code>

or equivalently:
 
> <code>
    .c find withtag {a^b}  
</code>

will find only those items with either "a" or "b" tags, but not both. 

Some widget commands only operate on a single item at a time; if *tagOrId* is specified in a way that names multiple items, then the normal behavior is for the command to use the first (lowest) of these items in the display list that is suitable for the command. Exceptions are noted in the widget command descriptions below. 

<a name="COORDINATES"></a>
### COORDINATES

All coordinates related to canvases are stored as floating-point numbers. Coordinates and distances are specified in screen units, which are floating-point numbers optionally followed by one of several letters. If no letter is supplied then the distance is in pixels. If the letter is **m** then the distance is in millimeters on the screen; if it is **c** then the distance is in centimeters; **i** means inches, and **p** means printers points (1/72 inch). Larger y-coordinates refer to points lower on the screen; larger x-coordinates refer to points farther to the right. Coordinates can be specified either as an even number of parameters, or as a single list parameter containing an even number of x and y coordinate values. 

The command **path::pixelalign** says how the platform graphics library draw when we specify integer coordinates. Some libraries position a one pixel wide line exactly at the pixel boundaries, and smears it out, if antialiasing, over the adjecent pixels. This can look blurred since a one pixel wide black line suddenly becomes a two pixel wide grey line.  It seems that cairo and quartz (MacOSX) do this, while gdi+ on Windows doesn't. This command just provides the info for you so you may take actions. Either you can manually position lines with odd integer widths at the center of pixels (adding 0.5), or set the **path::depixelize** equal to 1, see below.

With the boolean variable **path::depixelize** equal to 1 we try to adjust coordinates for objects with integer line widths.

There can be subtle differences compared to the original canvas. One such situation is where an option value has switched from an integer to float (double).

<a name="TEXT-INDICES"></a>
### TEXT INDICES

Text items support the notion of an index for identifying particular positions within the item. In a similar fashion, line and polygon items support index for identifying, inserting and deleting subsets of their coordinates. Indices are used for commands such as inserting or deleting a range of characters or coordinates, and setting the insertion cursor position. An index may be specified in any of a number of ways, and different types of items may support different forms for specifying indices. Text items support the following forms for an index; if you define new types of text-like items, it would be advisable to support as many of these forms as practical. Note that it is possible to refer to the character just after the last one in the text item; this is necessary for such tasks as inserting new text at the end of the item. Lines and Polygons do not support the insertion cursor and the selection. Their indices are supposed to be even always, because coordinates always appear in pairs. 

*number*

> A decimal number giving the position of the desired character within the text item. 0 refers to the first character, 1 to the next character, and so on. If indexes are odd for lines and polygons, they will be automatically decremented by one. A number less than 0 is treated as if it were zero, and a number greater than the length of the text item is treated as if it were equal to the length of the text item. For polygons, numbers less than 0 or greater then the length of the coordinate list will be adjusted by adding or subtracting the length until the result is between zero and the length, inclusive. 

**end**

> Refers to the character or coordinate just after the last one in the item (same as the number of characters or coordinates in the item). 

**insert**

> Refers to the character just before which the insertion cursor is drawn in this item. Not valid for lines and polygons. 

**sel.first**

> Refers to the first selected character in the item. If the selection is not in this item then this form is illegal. 

**sel.last**

> Refers to the last selected character in the item. If the selection is not in this item then this form is illegal. 

*@x,y*

> Refers to the character or coordinate at the point given by x and y, where x and y are specified in the coordinate system of the canvas. If x and y lie outside the coordinates covered by the text item, then they refer to the first or last character in the line that is closest to the given point. 

<a name="TRANSFORMATIONS"></a>
### TRANSFORMATIONS

Normally the origin of the canvas coordinate system is at the upper-left corner of the window containing the canvas. It is possible to adjust the origin of the canvas coordinate system relative to the origin of the window using the **xview** and **yview** widget commands; this is typically used for scrolling. Canvases do not support scaling or rotation of the canvas coordinate system relative to the window coordinate system. 
Individual items may be moved or scaled using widget commands described below, but they may not be rotated. 

Note that the default origin of the canvas's visible area is coincident with the origin for the whole window as that makes bindings using the mouse position easier to work with; you only need to use the **canvasx** and **canvasy** widget commands if you adjust the origin of the visible area. However, this also means that any focus ring (as controlled by the **-highlightthickness** option) and window border (as controlled by the **-borderwidth** option) must be taken into account before you get to the visible area of the canvas. 

Each path item has a **-matrix** option which defines the local coordinate system for that item. It is defined as a double list {a b c d tx ty} where a simple scaling is {sx 0 0 sy 0 0}, a translation {1 0 0 1 tx ty}, and a rotation around origin with an angle 'a' is {cos(a) sin(a) -sin(a) cos(a) 0 0}. The simplest way to interpret this is to design an extra coordinate system according to the matrix, and then draw the item in that system.

Inheritance works differently for the **-matrix** option than for the other options which are just overwritten. Instead any set -matrix option starting from the root, via any number of group items, to the actual item being displayed, are nested. That is, any defined matrices from the root down define a sequence of coordinate transformations.

The following functions provide some basic matrix operations such as rotation, translation etc.. All function return a matrix which can be used as value for the *-matrix* option.


<a name="path::matrix-rotate"></a>
**path::matrix rotate** *angle ?cx? ?cy?*

> Return matrix with rotation of *angle* around *cx, cy*.

<a name="path::matrix-scale"></a>
**path::matrix scale** *sx ?sy?*

> Return scaling matrix. If *sy* is not provided use *sx* for x and y direction.

<a name="path::matrix-flip"></a>
**path::matrix flip** *?cx? ?cy? ?fx? ?fy?*

> Return matrix with translation of *cx, cy* and flip with *fx* and *fy*.

<a name="path::matrix-rotateflip"></a>
**path::matrix rotateflip** *?angle? ?cx? ?cy? ?fx? ?fy?*

> Return matrix with rotation of *angle* around *cx, cy* and flip with *fx* and *fy*.

<a name="path::matrix-skewx"></a>
**path::matrix skewx** *?angle?*

> Return matrix with skew in x-direction of *angle*

<a name="path::matrix-skewy"></a>
**path::matrix skewy** *?angle?*

> Return matrix with skew in y-direction of *angle*

<a name="path::matrix-move"></a>
**path::matrix move** *dx dy*

> Return matrix with translation of *dx* in x-direction and *dy* in y-direction.

<a name="path::matrix-mult"></a>
**path::matrix mult** *ma mb*

> Return product of matrix multiplication of *ma* and *mb*.

<a name="STYLES"></a>
### STYLES

Styles are created and configured using:

> <code>
    path::style command ?options?  
</code>

<a name="path::style-cget"></a>
**path::style cget** *token option*

> Returns the value of an option.

<a name="path::style-configure"></a>
**path::style configure** *token ?option? ?value option value...?*

> Configures the object in the usual tcl way.

<a name="path::style-create"></a>
**path::style create** *?fillOptions strokeOptions?*

> Creates a style object and returns its token.

<a name="path::style-delete"></a>
**path::style delete** *token*

> Deletes the object.

<a name="path::style-inuse"></a>
**path::style inuse** *token*

> If any item is configured with the style token 1 is returned, else 0.

<a name="path::style-names"></a>
**path::style names**

> Returns all existing tokens.

The same options as for the item are supported with the exception of **-style**, **-state**, and **-tags**.

<a name="GRADIENTS"></a>
### GRADIENTS

Gradients are created and configured using:

> <code>
    path::gradient command ?options?  
</code>

<a name="path::gradient-cget"></a>
**path::gradient cget** *token option*

> Returns the value of an option.

<a name="path::gradient-configure"></a>
**path::gradient configure** *token ?option? ?value option value...?*

> Configures the object in the usual tcl way.

<a name="path::gradient-create"></a>
**path::gradient create** *type ?-key value ...?*

> Creates a linear gradient object with type any of linear or radial and returns its token.

<a name="path::gradient-delete"></a>
**path::gradient delete** *token*

> Deletes the object.

<a name="path::gradient-inuse"></a>
**path::gradient inuse** *token*

> If any item is configured with the gradient token 1 is returned, else 0.

<a name="path::gradient-names"></a>
**path::gradient names**

> Returns all existing tokens.

<a name="path::gradient-type"></a>
**path::gradient type** *token*

> Returns the type (linear\|radial) of the gradient. The options for linear gradients are:

> **-method** pad\|repeat\|reflect

> > Partial implementation; defaults to pad

> **-stops** *{stopSpec ?stopSpec...?}*

> > Where *stopSpec* is a list {offset color ?opacity?}. All offsets must be ordered and run from 0 to 1.

> **-lineartransition** *{x1 y1 x2 y2}*

> > Specifies the transtion vector relative the items bounding box. Depending on **-units** it gets interpreted differently. If **-units** is 'bbox' coordinates run from 0 to 1 and are relative the items bounding box. If **-units** is 'userspace' then they are defined in absolute coordinates but in the space of the items coordinate system. It defaults to {0 0 1 0}, left to right.

> **-matrix** *{a b c d tx ty}*

> > Sets a specific transformation for the gradient pattern only. NB: not sure about the order transforms, see **-units**.

> **-units** bbox\|userspace

> > Sets the units of the transition coordinates. See above. Defaults to 'bbox'.

The options for radial gradients are the same as for linear gradients except that the **-lineartransition** is replaced by a **-radialtransition**:

> **-radialtransition** *{cx cy ?r? ?fx fy?}*

> > Specifies the transition circles relative the items bounding box and run from 0 to 1. They default to {0.5 0.5 0.5 0.5 0.5}. *cx,cy* is the center of the end circle and *fx,fy* the center of the start point.

> **path::gradientstopstyle** *name args*

> Currently is only 'rainbow' as name supported. The function illustrate the  definition of gradients.

<a name="SURFACE"></a>
### SURFACE

In memory drawing surface.

<a name="path::surface-names"></a>
**path::surface names**

> Lists the existing surface tokens.

<a name="path::surface-new"></a>
**path::surface new** *width height*

> Creates an in memory drawing surface. Its format is platform dependent. It returns a *surfaceToken* which is a new command.

The surface token commands are:

> *surfaceToken* **copy** *imageName*

> > Copies the surface to an existing image (photo) and returns the name of
the image so you can do:

> > <code>
    set image [$token copy [image create photo]]  
</code>

> > See [Tk_PhotoPutBlock][] for how it affects the existing image.

> > The boolean variable **path::premultiplyalpha** controls how the copy action handles surfaces with the alpha component premultiplied. If 1 the copy process correctly handles any format with premultiplied alpha. This gets the highest quality for antialiasing and correct results for partial transparency. It is also slower. If 0 the alpha values are not remultiplied and the result is wrong for transparent regions, and gives poor antialiasing effects. But it is faster. The default is 1.

> *surfaceTtoken* **create** *type coords ?options?*

> > Draws the item of type to the surface. All item types except the group and the corresponding options as described above are supported, except the canvas specific **-tags** and **-state**.

> *surfaceToken* **destroy**

> > Destroys surface.

> *surfaceToken* **erase** *x y width height*

> > Erases the indicated area to transparent.

> *surfaceToken* **height**

> > Returns height.

> *surfaceToken* **width**

> > Returns width.

> Note that the surface behaves different from the canvas widget. When you have put an item there there is no way to configure it or to remove it. If you have done a mistake then you have to erase the complete surface and start all over. Better to experiment on the canvas and then reproduce your drawing to a surface when you are satisfied with it.

> NB: gdi+ seems unable to produce antialiasing effects here but there seems to be no gdi+ specific way of drawing in memory bitmaps but had to call CreateDIBSection() which is a Win32 GDI API.

<a name="WIDGET COMMAND"></a>
## WIDGET COMMAND

<a name="pathName-addtag"></a>
*pathName* **addtag** *tag searchSpec ?arg arg ...?*

> For each item that meets the constraints specified by *searchSpec* and the *args*, add *tag* to the list of tags associated with the item if it is not already present on that list. It is possible that no items will satisfy the constraints given by searchSpec and args, in which case the command has no effect. This command returns an empty string as result. *SearchSpec* and *arg'*s may take any of the following forms: 

> **above** *tagOrId*
	
> > Selects the item just after (above) the one given by *tagOrId* in the display list. If *tagOrId* denotes more than one item, then the last (topmost) of these items in the display list is used. The command is constrained to siblings.

> **all**

> > Selects all the items in the canvas. 

> **below** *tagOrId*

> > Selects the item just before (below) the one given by *tagOrId* in the display list. If *tagOrId* denotes more than one item, then the first (lowest) of these items in the display list is used. The command is constrained to siblings.

> **closest** *x y ?halo? ?start?*

> > Selects the item closest to the point given by *x* and *y*. If more than one item is at the same closest distance (e.g. two items overlap the point), then the topmost of these items (the last one in the display list) is used. If *halo* is specified, then it must be a non-negative value. Any item closer than *halo* to the point is considered to overlap it. The *start* argument may be used to step circularly through all the closest items. If *start* is specified, it names an item using a tag or id (if by tag, it selects the first item in the display list with the given tag). Instead of selecting the topmost closest item, this form will select the topmost closest item that is below start in the display list; if no such item exists, then the selection behaves as if the start argument had not been specified. 

> **enclosed** *x1 y1 x2 y2*

> > Selects all the items completely enclosed within the rectangular region given by *x1, y1, x2, and y2*. *X1* must be no greater then *x2* and *y1* must be no greater than *y2*. 

> **overlapping** *x1 y1 x2 y2*

> > Selects all the items that overlap or are enclosed within the rectangular region given by *x1, y1, x2,* and *y2*. *X1* must be no greater then *x2* and *y1* must be no greater than *y2*. 

> **withtag** *tagOrId*

> > Selects all the items given by *tagOrId*. 

<a name="pathName-ancestors"></a>
*pathName* **ancestors** *tagOrId*

> Returns a list of item id's of the first item matching *tagOrId* starting with the root item with id 0.

*pathName* **bbox** *tagOrId ?tagOrId tagOrId ...?*

> Returns a list with four elements giving an approximate bounding box for all the items named by the *tagOrId* arguments. The list has the form *x1 y1 x2 y2* such that the drawn areas of all the named elements are within the region bounded by *x1* on the left, *x2* on the right, *y1* on the top, and *y2* on the bottom. The return value may overestimate the actual bounding box by a few pixels. If no items match any of the *tagOrId* arguments or if the matching items have empty bounding boxes (i.e. they have nothing to display) then an empty string is returned. 

<a name="pathName-bind"></a>
*pathName* **bind** *tagOrId ?sequence? ?command?*

> This command associates *command* with all the items given by *tagOrId* such that whenever the event sequence given by *sequence* occurs for one of the items the command will be invoked. This widget command is similar to the [bind][] command except that it operates on items in a canvas rather than entire widgets. See the [bind][] manual entry for complete details on the syntax of sequence and the substitutions performed on command before invoking it. If all arguments are specified then a new binding is created, replacing any existing binding for the same *sequence* and *tagOrId* (if the first character of *command* is “+” then *command* augments an existing binding rather than replacing it). In this case the return value is an empty string. If *command* is omitted then the command returns the *command* associated with *tagOrId* and *sequence* (an error occurs if there is no such binding). If both *command* and *sequence* are omitted then the command returns a list of all the sequences for which bindings have been defined for *tagOrId*. 

> The only events for which bindings may be specified are those related to the mouse and keyboard (such as **Enter**, **Leave**, **ButtonPress**, **Motion**, and **KeyPress**) or virtual events. The handling of events in canvases uses the current item defined in [ITEM IDS AND TAGS][] above. **Enter** and **Leave** events trigger for an item when it becomes the current item or ceases to be the current item; note that these events are different than **Enter** and **Leave** events for windows. Mouse-related events are directed to the current item, if any. Keyboard-related events are directed to the focus item, if any (see the **focus** widget command below for more on this). If a virtual event is used in a binding, that binding can trigger only if the virtual event is defined by an underlying mouse-related or keyboard-related event. 

> It is possible for multiple bindings to match a particular event. This could occur, for example, if one binding is associated with the item's id and another is associated with one of the item's tags. When this occurs, all of the matching bindings are invoked. A binding associated with the **all** tag is invoked first, followed by one binding for each of the item's tags (in order), followed by a binding associated with the item's id. If there are multiple matching bindings for a single tag, then only the most specific binding is invoked. A [continue][] command in a binding script terminates that script, and a [break][] command terminates that script and skips any remaining scripts for the event, just as for the [bind][] command. 

> If bindings have been created for a canvas window using the [bind][] command, then they are invoked in addition to bindings created for the canvas's items using the **bind** widget command. The bindings for items will be invoked before any of the bindings for the window as a whole. 

<a name="pathName-canvasx"></a>
*pathName* **canvasx** *screenx ?gridspacing?*

> Given a window x-coordinate in the canvas *screenx*, this command returns the canvas x-coordinate that is displayed at that location. If *gridspacing* is specified, then the canvas coordinate is rounded to the nearest multiple of *gridspacing* units. 

<a name="pathName-canvasy"></a>
*pathName* **canvasy** *screeny ?gridspacing?*

> Given a window y-coordinate in the canvas *screeny*, this command returns the canvas y-coordinate that is displayed at that location. If *gridspacing* is specified, then the canvas coordinate is rounded to the nearest multiple of *gridspacing* units. 

<a name="pathName-cget"></a>
*pathName* **cget** *option*

> Returns the current value of the configuration option given by *option*. *Option* may have any of the values accepted by the **path** command. 

<a name="pathName-children"></a>
*pathName* **children** *tagOrId*

> Lists all children of the first item matching *tagOrId*.

<a name="pathName-configure"></a>
*pathName* **configure** *?option? ?value? ?option value ...?*

> Query or modify the configuration options of the widget. If no *option* is specified, returns a list describing all of the available options for pathName (see [Tk_ConfigureInfo][] for information on the format of this list). If *option* is specified with no *value*, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more *option-value* pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. *Option* may have any of the values accepted by the **path** command. 

<a name="pathName-coords"></a>
*pathName* **coords** *tagOrId ?x0 y0 ...?*

*pathName* **coords** *tagOrId ?coordList?*

> Query or modify the coordinates that define an item. If no coordinates are specified, this command returns a list whose elements are the coordinates of the item named by *tagOrId*. If coordinates are specified, then they replace the current coordinates for the named item. If *tagOrId* refers to multiple items, then the first one in the display list is used. 

<a name="pathName-create"></a>
*pathName* **create** *type x y ?x y ...? ?option value ...?*

*pathName* **create** *type coordList ?option value ...?*

> Create a new item in pathName of type *type*. The exact format of the arguments after type depends on *type*, but usually they consist of the coordinates for one or more points, followed by specifications for zero or more item options. See the subsections on individual item types below for more on the syntax of this command. This command returns the id for the new item. 

> For further informations about useable items see section [ITEM TYPES](#ITEM-TYPES).

<a name="pathName-dchars"></a>
*pathName* **dchars** *tagOrId first ?last?*

> For each item given by *tagOrId*, delete the characters, or coordinates, in the range given by *first* and *last*, inclusive. If some of the items given by *tagOrId* do not support indexing operations then they ignore this operation. Text items interpret *first* and *last* as indices to a character, line and polygon items interpret them as indices to a coordinate (an x,y pair). Indices are described in [INDICES][] above. If *last* is omitted, it defaults to *first*. This command returns an empty string. 

<a name="pathName-delete"></a>
*pathName* **delete** *?*tagOrId* *tagOrId* ...?*

> Delete each of the items given by each *tagOrId*, and return an empty string. 

<a name="pathName-depth"></a>
*pathName* **depth** *tagOrId*

> Returns the depth in the tree hierarchy of the first item matching *tagOrId*. The root item has depth 0 and children of the root has depth 1 and so on.

<a name="pathName-distance"></a>
*pathName* **distance** *tagOrId x y*

> Returns the closest distance between the point (*x, y*) and the first item matching *tagOrId*.

<a name="pathName-dtag"></a>
*pathName* **dtag** *tagOrId ?tagToDelete?*

> For each of the items given by *tagOrId*, delete the tag given by *tagToDelete* from the list of those associated with the item. If an item does not have the tag *tagToDelete* then the item is unaffected by the command. If *tagToDelete* is omitted then it defaults to *tagOrId*. This command returns an empty string. 

<a name="pathName-find"></a>
*pathName* **find** *searchCommand ?arg arg ...?*

> This command returns a list consisting of all the items that meet the constraints specified by *searchCommand* and *arg'*s. *SearchCommand* and *args* have any of the forms accepted by the **addtag** command. The items are returned in stacking order, with the lowest item first. 

<a name="pathName-firstchild"></a>
*pathName* **firstchild** *tagOrId*

> Returns the first child item of the first item matching *tagOrId*. Applies only for groups.

<a name="pathName-focus"></a>
*pathName* **focus** *?*tagOrId*?*

> Set the keyboard focus for the canvas widget to the item given by *tagOrId*. If *tagOrId* refers to several items, then the focus is set to the first such item in the display list that supports the insertion cursor. If *tagOrId* does not refer to any items, or if none of them support the insertion cursor, then the focus is not changed. If *tagOrId* is an empty string, then the focus item is reset so that no item has the focus. If *tagOrId* is not specified then the command returns the id for the item that currently has the focus, or an empty string if no item has the focus. 

> Once the focus has been set to an item, the item will display the insertion cursor and all keyboard events will be directed to that item. The focus item within a canvas and the focus window on the screen (set with the focus command) are totally independent: a given item does not actually have the input focus unless (a) its canvas is the focus window and (b) the item is the focus item within the canvas. In most cases it is advisable to follow the focus widget command with the focus command to set the focus window to the canvas (if it was not there already). 

<a name="pathName-gettags"></a>
*pathName* **gettags** *tagOrId*

> Return a list whose elements are the tags associated with the item given by *tagOrId*. If *tagOrId* refers to more than one item, then the tags are returned from the first such item in the display list. If *tagOrId* does not refer to any items, or if the item contains no tags, then an empty string is returned. 

<a name="pathName-gradient"></a>
*pathName* **gradient** *command ?options?*

> See [GRADIENTS][] for the commands. The gradients created with this command are local to the canvas instance. Only gradients defined this way can be used.

<a name="pathName-icursor"></a>
*pathName* **icursor** *tagOrId index*

> Set the position of the insertion cursor for the item(s) given by *tagOrId* to just before the character whose position is given by *index*. If some or all of the items given by *tagOrId* do not support an insertion cursor then this command has no effect on them. See INDICES above for a description of the legal forms for *index*. Note: the insertion cursor is only displayed in an item if that item currently has the keyboard focus (see the focus widget command, above), but the cursor position may be set even when the item does not have the focus. This command returns an empty string. 

<a name="pathName-imove"></a>
*pathName* **imove** *tagOrId index x y*

> This command causes the *index*'th coordinate of each of the items indicated by *tagOrId* to be relocated to the location (*x,y*). Each item interprets *index *independently according to the rules described in [INDICES][] above. Out of the standard set of items, only line and polygon items may have their coordinates relocated this way. 

> If you apply move on a group item it will apply this to all its descendants, also to child group items in a recursive way.

<a name="pathName-index"></a>
*pathName* **index** *tagOrId index*

> This command returns a decimal string giving the numerical index within *tagOrId* corresponding to *index*. Index gives a textual description of the desired position as described in INDICES above. Text items interpret *index* as an index to a character, line and polygon items interpret it as an index to a coordinate (an x,y pair). The return value is guaranteed to lie between 0 and the number of characters, or coordinates, within the item, inclusive. If *tagOrId* refers to multiple items, then the *index* is processed in the first of these items that supports indexing operations (in display list order). 

<a name="pathName-insert"></a>
*pathName* **insert** *tagOrId beforeThis string*

> For each of the items given by *tagOrId*, if the item supports text or coordinate, insertion then string is inserted into the item's text just before the character, or coordinate, whose index is *beforeThis*. Text items interpret *beforeThis* as an index to a character, line and polygon items interpret it as an index to a coordinate (an x,y pair). For lines and polygons the string must be a valid coordinate sequence. See INDICES above for information about the forms allowed for *beforeThis*. This command returns an empty string. 

<a name="pathName-itemcget"></a>
*pathName* **itemcget** *tagOrId option*

> Returns the current value of the configuration option for the item given by *tagOrId* whose name is *option*. This command is similar to the **cget** widget command except that it applies to a particular item rather than the widget as a whole. *Option* may have any of the values accepted by the **create** widget command when the item was created. If *tagOrId* is a tag that refers to more than one item, the first (lowest) such item is used. 

<a name="pathName-itemconfigure"></a>
*pathName* **itemconfigure** *tagOrId ?option? ?value? ?option value ...?*

> This command is similar to the **configure** widget command except that it modifies item-specific options for the items given by *tagOrId* instead of modifying options for the overall canvas widget. If no *option* is specified, returns a list describing all of the available options for the first item given by *tagOrId* (see [Tk_ConfigureInfo][] for information on the format of this list). If *option* is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no *option* is specified). If one or more *option-value* pairs are specified, then the command modifies the given widget option(s) to have the given value(s) in each of the items given by *tagOrId*; in this case the command returns an empty string. The *options* and *values* are the same as those permissible in the **create** widget command when the item(s) were created; see the sections describing individual item types below for details on the legal options. 

<a name="pathName-itempdf"></a>
*pathName* **itempdf** *tagOrId ?extgsProc objProc gradProc?*

> The command return pdf code describing the given *tagOrId*. The function is optimised to work with [pdf4tcl][]. To create pdf from a **path** just call the **canvas** method from the pdf object p.e.:

    $pdf canvas $pathName -bbox [$pathName bbox] -x 0 -y 0

> See function `CanvasDoTkpathItem` in [pdf4tcl][] for details.

> If *extgsProc* is given and item has special graphic state *extgsProc* is called.

> If *objProc* is given and item has special object info *objProc* is called.

> If *gradProc* is given and the item uses a gradient the *gradProc* is called.

<a name="pathName-lastchild"></a>
*pathName* **lastchild** *tagOrId*

> Returns the last child item of the first item matching *tagOrId*. Applies only for groups.

<a name="pathName-lower"></a>
*pathName* **lower** *tagOrId ?belowThis?*

> Move all of the items given by *tagOrId* to a new position in the display list just before the item given by *belowThis*. If *tagOrId* refers to more than one item then all are moved but the relative order of the moved items will not be changed. *BelowThis* is a tag or id; if it refers to more than one item then the first (lowest) of these items in the display list is used as the destination location for the moved items. Note: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by the [raise][] command and [lower][] command, not the **raise** widget command and **lower** widget command for canvases. This command returns an empty string.

> Movement is constrained to siblings. If reference *tagOrId* not given it defaults to first/last item of the root items children. Items which are not siblings to the reference *tagOrId* are silently ignored.

<a name="pathName-move"></a>
*pathName* **move** *tagOrId xAmount yAmount*

> Move each of the items given by *tagOrId* in the canvas coordinate space by adding *xAmount* to the x-coordinate of each point associated with the item and *yAmount* to the y-coordinate of each point associated with the item. This command returns an empty string. 

<a name="pathName-moveto"></a>
*pathName* **moveto** *tagOrId xPos yPos*

Move the items given by *tagOrId* in the canvas coordinate space so that the first coordinate pair of the bottommost item with tag *tagOrId* is located at position (*xPos,yPos*). *xPos* and *yPos* may be the empty string, in which case the corresponding coordinate will be unchanged. All items matching *tagOrId* remain in the same positions relative to each other. This command returns an empty string. 

<a name="pathName-nextsibling"></a>
*pathName* **nextsibling** *tagOrId*

> Returns the next sibling item of the first item matching *tagOrId*. If *tagOrId* is the last child we return empty.

<a name="pathName-parent"></a>
*pathName* **parent** *tagOrId*

> Returns the parent item of the first item matching *tagOrId*. This command works for all items, also for the standard ones. It is therefore better to use this than `cget id -parent` which is only supported for the new path items.

<a name="pathName-prevsibling"></a>
*pathName* **prevsibling** *tagOrId*

> Returns the previous sibling item of the first item matching *tagOrId*. If *tagOrId* is the first child we return empty.

<a name="pathName-raise"></a>
*pathName* **raise** *tagOrId ?aboveThis?*

> Move all of the items given by *tagOrId* to a new position in the display list just after the item given by aboveThis. If *tagOrId* refers to more than one item then all are moved but the relative order of the moved items will not be changed. AboveThis is a tag or id; if it refers to more than one item then the last (topmost) of these items in the display list is used as the destination location for the moved items. This command returns an empty string. 

> Movement is constrained to siblings. If reference *tagOrId* not given it defaults to first/last item of the root items children. Items which are not siblings to the reference *tagOrId* are silently ignored.

> Note: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by the raise command and lower command, not the raise widget command and lower widget command for canvases. 

<a name="pathName-rchars"></a>
*pathName* **rchars** *tagOrId first last string*

> This command causes the text or coordinates between *first* and *last* for each of the items indicated by *tagOrId* to be replaced by string. Each item interprets *first* and *last* independently according to the rules described in [INDICES][] above. Out of the standard set of items, text items support this operation by altering their text as directed, and line and polygon items support this operation by altering their coordinate list (in which case string should be a list of coordinates to use as a replacement). The other items ignore this operation. 

<a name="pathName-scale"></a>
*pathName* **scale** *tagOrId xOrigin yOrigin xScale yScale*

> Rescale the coordinates of all of the items given by *tagOrId* in canvas coordinate space. *XOrigin* and *yOrigin* identify the origin for the scaling operation and *xScale* and *yScale* identify the scale factors for x- and y-coordinates, respectively (a scale factor of 1.0 implies no change to that coordinate). For each of the points defining each item, the x-coordinate is adjusted to change the distance from *xOrigin* by a factor of *xScale*. Similarly, each y-coordinate is adjusted to change the distance from *yOrigin* by a factor of *yScale*. This command returns an empty string. 

> Note that some items have only a single pair of coordinates (e.g. windows) and so scaling of them by this command can only move them around.

> If you apply scale on a group item it will apply this to all its descendants, also to child group items in a recursive way. 

<a name="pathName-scan"></a>
*pathName* **scan** *option args*

> This command is used to implement scanning on canvases. It has two forms, depending on option: 

> *pathName* **scan mark** *x y*

> > Records *x* and *y* and the canvas's current view; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget and *x* and *y* are the coordinates of the mouse. It returns an empty string. 

> *pathName* **scan dragto** *x y ?gain?*

> > This command computes the difference between its *x* and *y* arguments (which are typically mouse coordinates) and the x and y arguments to the last scan mark command for the widget. It then adjusts the view by *gain* times the difference in coordinates, where *gain* defaults to 10. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the canvas at high speed through its window. The return value is an empty string. 

<a name="pathName-select"></a>
*pathName* **select** *option ?*tagOrId* arg?*

> Manipulates the selection in one of several ways, depending on *option*. The command may take any of the forms described below. In all of the descriptions below, *tagOrId* must refer to an item that supports indexing and selection; if it refers to multiple items then the first of these that supports indexing and the selection is used. Index gives a textual description of a position within *tagOrId*, as described in [INDICES][] above. 

> *pathName* **select adjust** *tagOrId index*

> > Locate the end of the selection in *tagOrId* nearest to the character given by *index*, and adjust that end of the selection to be at *index* (i.e. including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection is not currently in *tagOrId* then this command behaves the same as the select to widget command. Returns an empty string. 

> *pathName* **select clear**

> > Clear the selection if it is in this widget. If the selection is not in this widget then the command has no effect. Returns an empty string. 

> *pathName* **select from** *tagOrId index*

> > Set the selection anchor point for the widget to be just before the character given by *index* in the item given by *tagOrId*. This command does not change the selection; it just sets the fixed end of the selection for future select to commands. Returns an empty string. 

>  *pathName* **select item**

> > Returns the id of the selected item, if the selection is in an item in this canvas. If the selection is not in this canvas then an empty string is returned. 

> *pathName* **select to** *tagOrId index*

> > Set the selection to consist of those characters of *tagOrId* between the selection anchor point and *index*. The new selection will include the character given by *index*; it will include the character given by the anchor point only if *index* is greater than or equal to the anchor point. The anchor point is determined by the most recent select adjust or select from command for this widget. If the selection anchor point for the widget is not currently in *tagOrId*, then it is set to the same character given by *index*. Returns an empty string. 

<a name="pathName-style"></a>
*pathName* **style** *cmd ?options?*

> See [STYLES](#STYLES) for the commands. The styles created with this command are local to the canvas instance. Only styles defined this way can be used.

> The styleToken is a style created with 'pathName style create'. It's options take precedence over any other options set directly. This is how SVG works (bad?). Currently all a style's options ever set are recorded in a cumulative way using a mask. Even if an option is set to its default it takes precedence over an items option.

<a name="pathName-type"></a>
*pathName* **type** *tagOrId*

> Returns the type of the item given by *tagOrId*, such as rectangle or text. If *tagOrId* refers to more than one item, then the type of the first item in the display list is returned. If *tagOrId* does not refer to any items at all then an empty string is returned. 

<a name="pathName-types"></a>
*pathName* **types**

> List all item types defined in canvas.

<a name=*pathName-xview"></a>
*pathName* **xview** *?args?*

> This command is used to query and change the horizontal position of the information displayed in the canvas's window. It can take any of the following forms: 

> *pathName* **xview**

> > Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the canvas's area (as defined by the **-scrollregion** option) is off-screen to the left, the middle 40% is visible in the window, and 40% of the canvas is off-screen to the right. These are the same values passed to scrollbars via the **-xscrollcommand** option. 

> *pathName* **xview moveto** *fraction*

> > Adjusts the view in the window so that *fraction* of the total width of the canvas is off-screen to the left. *Fraction* must be a fraction between 0 and 1. 

> *pathName* **xview scroll** *number what*

> > This command shifts the view in the window left or right according to *number* and *what*. *Number* must be an integer. *What* must be either **units** or **pages** or an abbreviation of one of these. If *what* is units, the view adjusts left or right in **units** of the **xScrollIncrement** option, if it is greater than zero, or in units of one-tenth the window's width otherwise. If what is **pages** then the view adjusts in units of nine-tenths the window's width. If *number* is negative then information farther to the left becomes visible; if it is positive then information farther to the right becomes visible. 

<a name="pathName-yview"></a>
*pathName* **yview** *?args?*

> This command is used to query and change the vertical position of the information displayed in the canvas's window. It can take any of the following forms: 

> *pathName* **yview**

> > Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the vertical span that is visible in the window. For example, if the first element is .6 and the second element is 1.0, the lowest 40% of the canvas's area (as defined by the **-scrollregion** option) is visible in the window. These are the same values passed to scrollbars via the **-yscrollcommand** option. 

> *pathName* **yview moveto** *fraction*

> > Adjusts the view in the window so that *fraction* of the canvas's area is off-screen to the top. *Fraction* is a fraction between 0 and 1. 

> *pathName* **yview scroll** *number what*

> > This command adjusts the view in the window up or down according to *number* and *what*. *Number* must be an integer. *What* must be either **units** or **pages**. If *what* is **units**, the view adjusts up or down in units of the **yScrollIncrement** option, if it is greater than zero, or in units of one-tenth the window's height otherwise. If what is pages then the view adjusts in units of nine-tenths the window's height. If *number* is negative then higher information becomes visible; if it is positive then lower information becomes visible. 

<a name="ITEM-TYPES"></a>
## ITEM TYPES

The sections below describe the various types of items supported by canvas widgets. Each item type is characterized by two things: first, the form of the **create** command used to create instances of the type; and second, a set of configuration options for items of that type, which may be used in the **create** and **itemconfigure** widget commands. Most items do not support indexing or selection or the commands related to them, such as **index** and **insert**. Where items do support these facilities, it is noted explicitly in the descriptions below. At present, text, line and polygon items provide this support. For lines and polygons the indexing facility is used to manipulate the coordinates of the item. 

<a name="COMMON-ITEM-OPTIONS"></a>
### COMMON ITEM OPTIONS

The options can be separated into a few groups depending on the nature of an item for which they apply. Not all are implemented.

Arrow options accepted by line, polyline and path objects. Arrows are not
implemented on surfaces (see path::surface).

Options set in a group are inherited by its children but they never override
options explicitly set in children. This also applies to group items configured
with a -style.

    .c create group ?fillOptions strokeOptions genericOptions?

<a name="ITEM-fill"></a>
**-fill** *color\|gradientToken*

> This is either a usual tk color or the name of a gradient.

<a name="ITEM-fillopacity"></a>
**-fillopacity** *value*

> The given *value* is a float value between 0.0 and 1.0

<a name="ITEM-fillrule"></a>
**-fillrule** *nonzero\|evenodd*

<a name="ITEM-stroke"></a>
**-stroke** *color*

<a name="ITEM-strokedasharray"></a>
**-strokedasharray** *dashArray*

> The *dashArray* is a list of integers. Each element represents the number of pixels of a line segment. Only the odd segments are drawn using the "outline" color. The other segments are drawn transparent. 

<a name="ITEM-strokelinecap"></a>
**-strokelinecap** *butt\|round\|square*

<a name="ITEM-strokelinejoin"></a>
**-strokelinejoin** *miter\|round\|bevel*

<a name="ITEM-strokemiterlimit"></a>
**-strokemiterlimit** *float*

<a name="ITEM-strokeopacity"></a>
**-strokeopacity** *value*

> The given *value* is a float value between 0.0 and 1.0

<a name="ITEM-strokewidth"></a>
**-strokewidth** *float*

<a name="ITEM-matrix"></a>
**-matrix** *{a b c d tx ty}*

<a name="ITEM-parent"></a>
**-parent** *tagOrId*

<a name="ITEM-state"></a>
**-state** *active\|disabled\|normal\|hidden*

<a name="ITEM-style"></a>
**-style** *styleToken*

<a name="ITEM-tags"></a>
**-tags** *tagList*

<a name="ITEM-startarrow"></a>
**-startarrow** *boolean*

> Arrowhead on/off; the default value is off.

<a name="ITEM-startarrowlength"></a>
**-startarrowlength** *float*

> Length of the arrowhead.
  * 0.0 is special and draws '|-----'
  * negative values draw '>----'

<a name="ITEM-startarrowwidth"></a>
**-startarrowwidth** *float*

> Arrow width; must be positive.

<a name="ITEM-startarrowfill"></a>
**-startarrowfill** *float*

> Relative to startarrowlength; for example:
  * 0.0: do not fill arrowhead, arrowhead will be two lines
  * 1.0: '<|-------'
  * 2.0: '<>-------'

<a name="ITEM-endarrow"></a>
**-endarrow** *boolean*

> See **-startarrow**.

<a name="ITEM-endarrowlength"></a>
**-endarrowlength** *float*

> See **-startarrowlength**.

<a name="ITEM-endarrowwidth"></a>
**-endarrowwidth** *float*

> See **-startarrowwidth**.

<a name="ITEM-endarrowfill"></a>
**-endarrowfill** *float*

> See **-startarrowfill**.

<a name="GROUP-ITEM"></a>
### GROUP ITEM

<a name="pathName-create-group"></a>
*pathName* **create group** *?fillOptions strokeOptions genericOptions?*

A group item is merely a placeholder for other items, similar to how a
frame widget is a container for other widgets. It is a building block for
the tree structure. Unlike other items, and unlike frame widgets, it
doesn't display anything. It has no coordinates which is an additional
difference. The root item is a special group item with id 0 and tags
equal to "root". The root group can be configured like other items, but
its -tags and -parent options are read only.
Options set in a group are inherited by its children but they never override
options explicitly set in children. This also applies to group items configured
with a -style.

<a name="PATH-ITEM"></a>
### PATH ITEM

<a name="pathName-create-path"></a>
*pathName* **create path** *pathSpec ?fillOptions strokeOptions arrowOptions genericOptions?*

The path specification must be a single list and not concateneted with the rest of the command:

    pathName create path {M 10 10 h 10 v 10 h -10 z} -fill blue
    pathName create path M 10 10 h 10 v 10 h -10 z -fill blue    ;# Error

Furthermore, coordinates are pixel coordinates and nothing else.
SVG: It implements the complete syntax of the path elements d attribute with
one major difference: all separators must be whitespace, no commas, no
implicit assumptions; all instructions and numbers must form a tcl list.

All path specifications are normalized initially to the fundamental atoms
M, L, A, Q, and C, all upper case. When you use the canvas 'coords' command
it is the normalized path spec that is returned. Bad?

Visualize this as a pen which always has a current coordinate after
the first M. Coordinates are floats:

* M x y

> Put the pen on the paper at specified coordinate. Must be the first atom but can appear any time later. The pen doesn't draw anything when moved to this point.

* L x y

> Draw a straight line to the given coordinate. 

* H x

> Draw a horizontal line to the given x coordinate.

* V y

> Draw a vertical line to the given y coordinate.

* A rx ry phi largeArc sweep x y

> Draw an elliptical arc from the current point to (x, y). The points are on an ellipse with x-radius rx and y-radius ry. The ellipse is rotated by phi degrees. If the arc is less than 180 degrees, largeArc is zero, else it is one. If the arc is to be drawn in cw direction, sweep is one, and zero for the ccw direction.

> NB: the start and end points may not coincide else the result  is undefined. If you want to make a circle just do two 180 degree arcs.

* Q x1 y1 x y

> Draw a qadratic Bezier curve from the current point to (x, y) using control point (x1, y1).

* T x y

> Draw a qadratic Bezier curve from the current point to (x, y) The control point will be the reflection of the previous Q atoms control point. This makes smooth paths.

* C x1 y1 x2 y2 x y

> Draw a cubic Bezier curve from the current point to (x, y) using control points (x1, y1) and (x2, y2).

* S x2 y2 x y

> Draw a cubic Bezier curve from the current point to (x, y), using (x2, y2) as the control point for this new endpoint. The first control point will be the reflection of the previous C atoms ending control point. This makes smooth paths.

* Z
   
> Close path by drawing from the current point to the preceeding M point.

You may use lower case characters for all atoms which then means that all
coordinates, where relevant, are interpreted as coordinates relative the
current point.

Helper function for making path definitions:

> **path::path ellipse** *x y rx ry*

> > The function return a path definition of an ellipse with a middle point at *x* and *y* and a radius in x-disrection of *rx* and a radius in y-direction of *ry*.

> **path::path circle** *x y r*

> > The function return a path definition of an circle with a middle point at *x* and *y* and a radius of *r*.

<a name="LINE-ITEM"></a>
### LINE ITEM

<a name="pathName-create-line"></a>
*pathName* **create line** *x1 y1 x2 y2 ?strokeOptions arrowOptions genericOptions?*

Makes a single-segment straight line.

<a name="POLYLINE-ITEM"></a>
### POLYLINE ITEM

<a name="pathName-create-polyline"></a>
*pathName* **create polyline** *x1 y1 x2 y2 .... ?strokeOptions arrowOptions genericOptions?*

Makes a multi-segment line with open ends.

<a name="POLYGON-ITEM"></a>
### POLYGON ITEM

<a name="pathName-create-polygon"></a>
*pathName* **create polygon** *x1 y1 x2 y2 .... ?fillOptions strokeOptions genericOptions?*

Makes a closed polygon.

<a name="RECT-ITEM"></a>
### RECT ITEM

<a name="pathName-create-rect"></a>
*pathName* **create rect** *x1 y1 x2 y2 ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*

This is a rectangle item with optionally rounded corners.
Item specific options:

**-rx** *value*

> Corner x-radius, or if -ry not given it sets the uniform radius.

**-ry** *value*

> Corner y-radius

<a name="CIRCLE-ITEM"></a>
### CIRCLE ITEM

<a name="pathName-create-circle"></a>
*pathName* **create circle** *cx cy ?-r fillOptions strokeOptions genericOptions?*

A plain circle item. Item specific options:

**-r** *value*

> Its radius; defaults to zero

<a name="ELLIPSE-ITEM"></a>
### ELLIPSE ITEM

<a name="pathName-create-ellipse"></a>
*pathName* **create ellipse** *cx cy ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*

An ellipse item. Item specific options:

**-rx** *value*

> Its x-radius

**-ry** *value*

> Its y-radius


<a name="IMAGE-ITEM"></a>
### IMAGE ITEM

<a name="pathName-create-image"></a>
*pathName* **create image** *x y ?-image -width -height genericOptions?*

This displays an image in the canvas anchored nw. If -width or -height is
nonzero then the image is scaled to this size prior to any affine transform.

image extra options:

**-anchor** *n\|w\|s\|e\|nw\|ne\|sw\|se\|c*

> Default value is nw

**-tintcolor** *color*

> Tint color; the default value is "" which means no tinting

**-tintamount** *value*

*Value* is amount for tinting between 0. and 1.

**-interpolation** *mode*

> Image interpolation *mode* is one of **none, fast** or **best**

**-srcregion** *{x1 y1 x2 y2}*

> Shows only the specified region of image; if x2 or y2 are larger than the image bounds, then the image will be repeated (tiling)

These options are not implemented on surfaces (see path::surface).

<a name="TEXT-ITEM"></a>
### TEXT ITEM

<a name="pathName-create-text"></a>
*pathName* **create text** *x y ?-text string? ?-textanchor start\|middle\|end\|n\|w\|s\|e\|nw\|ne\|sw\|se\|c? ?-fontfamily fontname -fontsize float? ?-fontslant normal\|italic\|oblique? ?-fontweight normal\|bold? ?fillOptions strokeOptions genericOptions? ?-filloverstroke BOOLEAN?*

Displays text as expected. Note that the x coordinate marks the baseline
of the text. Gradient fills are unsupported so far. Especially the font
handling and settings will likely be developed further.
Editing not implemented. The default font family and size is platform dependent.

text extra options:

**-textanchor** *n\|w\|s\|e\|nw\|ne\|sw\|se\|c\|start\|middle\|end*

> Textanchor extended with points of compass.

**-fontslant** *normal\|italic\|oblique*

> Default value is normal

**-fontweight** *normal\|bold*

> Default value is normal

**-filloverstroke** *boolean*

> Fill drawn over the stroke; default value is false

These options are not implemented on surface items (path::surface), except for

**-textanchor** *start\|middle\|end*

<a name="WINDOW-ITEM"></a>
### WINDOW ITEM

Items of type window cause a particular window to be displayed at a given position on the canvas. Window items are created with widget commands of the following form: 

<a name="pathName-create-window"></a>
*pathName* **create window** *x y ?option value ...?*

*pathName* **create window** *coordList ?option value ...?*

The arguments x and y or coordList (which must have two elements) specify the coordinates of a point used to position the window on the display, as controlled by the -anchor option. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. Theoretically, a window item becomes the current item when the mouse pointer is over any part of its bounding box, but in practice this typically does not happen because the mouse pointer ceases to be over the canvas at that point. 

The following standard options are supported by window items: 

> **-anchor**

> **-state**

> **-tags**

The following extra options are supported for window items: 

**-height** *pixels*

> Specifies the height to assign to the item's window. Pixels may have any of the forms described in the [COORDINATES][] section above. If this option is not specified, or if it is specified as zero, then the window is given whatever height it requests internally. 

**-width** *pixels*

> Specifies the width to assign to the item's window. Pixels may have any of the forms described in the [COORDINATES][] section above. If this option is not specified, or if it is specified as zero, then the window is given whatever width it requests internally. 

**-window** *pathName*

> Specifies the window to associate with this item. The window specified by pathName must either be a child of the canvas widget or a child of some ancestor of the canvas widget. PathName may not refer to a top-level window. 

Note: due to restrictions in the ways that windows are managed, it is not possible to draw other graphical items (such as lines and images) on top of window items. A window item always obscures any graphics that overlap it, regardless of their order in the display list. Also note that window items, unlike other canvas items, are not clipped for display by their containing canvas's border, and are instead clipped by the parent widget of the window specified by the -window option; when the parent widget is the canvas, this means that the window item can overlap the canvas's border. 

<a name="BINDINGS"></a>
## BINDINGS

In the current implementation, new canvases are not given any default behavior: you will have to execute explicit Tcl commands to give the canvas its behavior. 

<a name="CREDITS"></a>
## CREDITS

Tk's canvas widget is a blatant ripoff of ideas from Joel Bartlett's ezd program. Ezd provides structured graphics in a Scheme environment and preceded canvases by a year or two. Its simple mechanisms for placing and animating graphical objects inspired the functions of canvases.

[Tkpath][] was originally developed by Matts Bengtsson.

User visisble changes to the original [Tkpath][] code are:

- changed widget name in **path** and use of namespace **::path**
- -matrix is now a flat list
- tk canvas items removed, only exception is **window** item
- changed item names to match [SVG][] names:
  - **pimage** => **image**
  - **pline** => **line**
  - **ppolygon** => **polygon**
  - **prect** => **rect**
  - **ptext** => **text**
- no unique abbreviations of widget commands

<a name="KEYWORDS"></a>
## KEYWORDS

canvas, svg, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 2005-2008 Mats Bengtsson

&copy; 2015- Christian Werner <[email protected]>

&copy; 2016- René Zaumseil <[email protected]>

BSD style license.

<a name="SEE-ALSO"></a>
## SEE ALSO

[bind][], [font][], [image][], [scrollbar][], [pdf4tcl][], [SVG][], [Cairo][]

<a name="KEYWORDS"></a>
## KEYWORDS

canvas, pdf, svg, widget

[bind]: bind.htm
[break]: break.htm
[continue]: continue.htm
[font]: font.htm
[image]: image.htm
[options]: options.htm
[raise]: raise.htm
[scrollbar]: scrollbar.htm
[lower]: lower.htm
[Tk_ConfigureInfo]: ConfigWidg.htm
[Tkpath]: <https://sourceforge.net/projects/tclbitprint/>
[pdf4tcl]: <https://sourceforge.net/projects/pdf4tcl/>
[SVG]: <http://www.w3.org/TR/SVG11/>
[Cairo]: <http://cairographics.org>


Changes to doc/vector.n.md.

1
2
3
4
5
6
7
8
9
10
..
49
50
51
52
53
54
55

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
....
1021
1022
1023
1024
1025
1026
1027











1028
1029
1030
1031
1032
1033
1034
....
1035
1036
1037
1038
1039
1040
1041
1042

# vector(n) -- Vector data type for Tcl

*   [NAME]((#NAME)
*   [SYNOPSIS](#SYNOPSIS)
*   [DESCRIPTION](#DESCRIPTION)
*   [SYNTAX](#SYNTAX)
  * [graph::vector configure](#graph::vector-configure) *?option value?...*
  * [graph::vector create](#graph::vector-create) *vectorName?(...)? ?option value?...*
  * [graph::vector destroy](#graph::vector-destroy) *vectorName ?vectorName?...*
  * [graph::vector expression](#graph::vector-expression) *expression*
................................................................................
  * [vectorName split](#vectorName-split) *dstName ?dstName?...*
  * [vectorName variable](#vectorName-variable) *varName*
* [C LANGUAGE API](#C-LANGUAGE-API)
* [LIBRARY ROUTINES](#LIBRARY-ROUTINES)
* [C API EXAMPLE](#C-API-EXAMPLE)
* [INCOMPATIBILITIEA](#INCOMPATIBILITIES)
* [EXAMPLE](#EXAMPLE)

* [KEYWORDS](#KEYWORDS)
* [COPYRIGHT](#COPYRIGHT)

<a name="NAME"></a>
## NAME 

graph::vector - Vector data type for graph widgets

<a name="SYNOPSIS"></a>
## SYNOPSIS 

**[graph::vector configure](#graph::vector-configure)** *?option value? ...*

**[graph::vector create](#graph::vector-create)** *vectorName?(...)? ?option value?...*

................................................................................
graph::vector create B(10)  
graph::vector create S(10)  
graph::vector create T(10)  
graph::S expr A+B  
graph::T expr S+last; # Running total  
</code>












<a name="KEYWORDS"></a>
## KEYWORDS

vector, graph, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT
................................................................................

&copy; 1995-1997 Roger E. Critchlow Jr.

&copy; 2001 George A. Howlett.

&copy; 2018 René Zaumseil <[email protected]>



|

<







 







>



<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>







 







|
>
1
2

3
4
5
6
7
8
9
..
48
49
50
51
52
53
54
55
56
57
58





59
60
61
62
63
64
65
....
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
....
1041
1042
1043
1044
1045
1046
1047
1048
1049
# graph::vector(n) -- Vector data type for graph widgets


*   [SYNOPSIS](#SYNOPSIS)
*   [DESCRIPTION](#DESCRIPTION)
*   [SYNTAX](#SYNTAX)
  * [graph::vector configure](#graph::vector-configure) *?option value?...*
  * [graph::vector create](#graph::vector-create) *vectorName?(...)? ?option value?...*
  * [graph::vector destroy](#graph::vector-destroy) *vectorName ?vectorName?...*
  * [graph::vector expression](#graph::vector-expression) *expression*
................................................................................
  * [vectorName split](#vectorName-split) *dstName ?dstName?...*
  * [vectorName variable](#vectorName-variable) *varName*
* [C LANGUAGE API](#C-LANGUAGE-API)
* [LIBRARY ROUTINES](#LIBRARY-ROUTINES)
* [C API EXAMPLE](#C-API-EXAMPLE)
* [INCOMPATIBILITIEA](#INCOMPATIBILITIES)
* [EXAMPLE](#EXAMPLE)
* [CREDITS](#CREDITS)  
* [KEYWORDS](#KEYWORDS)
* [COPYRIGHT](#COPYRIGHT)






<a name="SYNOPSIS"></a>
## SYNOPSIS 

**[graph::vector configure](#graph::vector-configure)** *?option value? ...*

**[graph::vector create](#graph::vector-create)** *vectorName?(...)? ?option value?...*

................................................................................
graph::vector create B(10)  
graph::vector create S(10)  
graph::vector create T(10)  
graph::S expr A+B  
graph::T expr S+last; # Running total  
</code>

<a name="CREDITS"></a>
## CREDITS

[BLT][] was originally develeoped by George A. Howlett. It can be found at <https://sourceforge.net/projects/blt/>.

Refactored [BLT][] Components ([Rbc][]), includes data vectors and graph widgets from the original [BLT][]. Both can be found at sourceforge.

User visible changes to the original [Rbc][] code are:

- command name is now **graph::vector**

<a name="KEYWORDS"></a>
## KEYWORDS

vector, graph, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT
................................................................................

&copy; 1995-1997 Roger E. Critchlow Jr.

&copy; 2001 George A. Howlett.

&copy; 2018 René Zaumseil <[email protected]>

[BLT]: <https://sourceforge.net/projects/blt/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>

Changes to generic/rbc/rbcGraph.c.

2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
{
    Tcl_Class clazz;
    Tcl_Object object;
    Tcl_Obj *objPtr;
    int i;
	static const char *initScript =
		"::oo::class create ::graph {"
		" self method unknown {args} {uplevel #0 ::graph create {*}$args; return [lindex $args 0]}\n"
        " self unexport new destroy\n"
        " unexport new create destroy\n"
        "}";

    rbcBarElementUid = (RbcUid) Tk_GetUid("BarElement");
    rbcLineElementUid = (RbcUid) Tk_GetUid("LineElement");
    rbcStripElementUid = (RbcUid) Tk_GetUid("StripElement");






|







2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
{
    Tcl_Class clazz;
    Tcl_Object object;
    Tcl_Obj *objPtr;
    int i;
	static const char *initScript =
		"::oo::class create ::graph {"
		" self method unknown {args} {uplevel #0 ::graph create args; return [lindex $args 0]}\n"
        " self unexport new destroy\n"
        " unexport new create destroy\n"
        "}";

    rbcBarElementUid = (RbcUid) Tk_GetUid("BarElement");
    rbcLineElementUid = (RbcUid) Tk_GetUid("LineElement");
    rbcStripElementUid = (RbcUid) Tk_GetUid("StripElement");

Added generic/rbc/tkMacOSXPath.c.














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
/*
 * tkMacOSXPath.c --
 *
 *	This file implements path drawing API's using CoreGraphics on Mac OS X.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 *
 */

/* This should go into configure.in but don't know how. */
#ifdef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#undef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#endif

#include "tkMacOSXInt.h"
#include "tkIntPath.h"

#if !__OBJC__
#error Objective-C compiler required
#endif

#import <Cocoa/Cocoa.h>


#define TINT_INT_CALCULATION

/* Seems to work for both Endians. */
#define BlueFloatFromXColorPtr(xc)   ((float) ((xc)->blue >> 8) / 255.0)
#define GreenFloatFromXColorPtr(xc)  ((float) ((xc)->green >> 8) / 255.0)
#define RedFloatFromXColorPtr(xc)    ((float) ((xc)->red >> 8) / 255.0)

#define Blue255FromXColorPtr(xc)   ((xc)->blue >> 8)
#define Green255FromXColorPtr(xc)  ((xc)->green >> 8)
#define Red255FromXColorPtr(xc)    ((xc)->red >> 8)


#ifndef FloatToFixed
#define FloatToFixed(a) ((Fixed)((float) (a) * fixed1))
#endif

extern int Tk_PathAntiAlias;
extern int Tk_PathSurfaceCopyPremultiplyAlpha;
extern int Tk_PathDepixelize;

const CGFloat kValidDomain[2] = {0, 1};
const CGFloat kValidRange[8] = {0, 1, 0, 1, 0, 1, 0, 1};

/*
 * This is used as a place holder for platform dependent stuff between each call.
 */
typedef struct TkPathContext_ {
    CGContextRef    c;
    int             saveCount;
    CGrafPtr        port;	/* QD graphics port, NULL for bitmaps. */
    char            *data;	/* bitmap data, NULL for windows. */
    int             widthCode;  /* Used to depixelize the strokes:
                                 * 0: not integer width
                                 * 1: odd integer width
                                 * 2: even integer width */

    /* fields from TK TkMacOSXDrawingContext: */
    NSView *view;
    HIShapeRef clipRgn;
    CGRect portBounds;
    int focusLocked;
    int xOff, yOff;
} TkPathContext_;

#define MAX_NL 32
typedef struct PathATSUIRecord {
    ATSUStyle       atsuStyle;
    ATSUTextLayout  atsuLayout;
    UniChar         *buffer;	/* @@@ Not sure this needs to be cached! */
    int             nlc;
    int             nl[MAX_NL + 1];
    ATSUTextMeasurement   dx[MAX_NL];
    ATSUTextMeasurement   dy[MAX_NL];
} PathATSUIRecord;

typedef struct FillInfo {
    double fillOpacity;
    GradientStopArray *stopArrPtr;
} FillInfo;

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDrawableView --
 *
 *      This function returns the NSView for a given X drawable.
 *
 * Results:
 *      A NSView* or nil.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

NSView*
TkMacOSXDrawableView(
    MacDrawable *macWin)
{
    NSView *result = nil;

    if (!macWin) {
        result = nil;
    } else if (!macWin->toplevel) {
        result = macWin->view;
    } else if (!(macWin->toplevel->flags & TK_EMBEDDED)) {
        result = macWin->toplevel->view;
    } else {
        TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);
        if (contWinPtr) {
            result = TkMacOSXDrawableView(contWinPtr->privatePtr);
        }
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpClipDrawableToRect --
 *
 *      Clip all drawing into the drawable d to the given rectangle.
 *      If width or height are negative, reset to no clipping.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Subsequent drawing into d is offset and clipped as specified.
 *
 *----------------------------------------------------------------------
 */

void
TkpClipDrawableToRect(
    Display *display,
    Drawable d,
    int x, int y,
    int width, int height)
{
    MacDrawable *macDraw = (MacDrawable *) d;
    NSView *view = TkMacOSXDrawableView(macDraw);

    if (macDraw->drawRgn) {
        CFRelease(macDraw->drawRgn);
        macDraw->drawRgn = NULL;
    }
    if (width >= 0 && height >= 0) {
        CGRect drawRect = CGRectMake(x + macDraw->xOff, y + macDraw->yOff,
                width, height);
        HIShapeRef drawRgn = HIShapeCreateWithRect(&drawRect);

        if (macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
            TkMacOSXUpdateClipRgn(macDraw->winPtr);
        }
        if (macDraw->visRgn) {
            macDraw->drawRgn = HIShapeCreateIntersection(macDraw->visRgn,
                    drawRgn);
            CFRelease(drawRgn);
        } else {
            macDraw->drawRgn = drawRgn;
        }
        if (view && view != [NSView focusView] && [view lockFocusIfCanDraw]) {
            drawRect.origin.y = [view bounds].size.height -
                    (drawRect.origin.y + drawRect.size.height);
            NSRectClip(NSRectFromCGRect(drawRect));
            macDraw->flags |= TK_FOCUSED_VIEW;
        }
    } else {
        if (view && (macDraw->flags & TK_FOCUSED_VIEW)) {
            [view unlockFocus];
            macDraw->flags &= ~TK_FOCUSED_VIEW;
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetClipRgn --
 *
 *	Get the clipping region needed to restrict drawing to the given
 *	drawable.
 *
 * Results:
 *	Clipping region. If non-NULL, CFRelease it when done.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

HIShapeRef
TkMacOSXGetClipRgn(
    Drawable drawable)		/* Drawable. */
{
    MacDrawable *macDraw = (MacDrawable *) drawable;
    HIShapeRef clipRgn = NULL;

    if (macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(macDraw->winPtr);
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s visRgn  ", macDraw->winPtr->pathName);
	TkMacOSXDebugFlashRegion(drawable, macDraw->visRgn);
#endif /* TK_MAC_DEBUG_DRAWING */
    }

    if (macDraw->drawRgn) {
        clipRgn = HIShapeCreateCopy(macDraw->drawRgn);
    } else if (macDraw->visRgn) {
        clipRgn = HIShapeCreateCopy(macDraw->visRgn);
    }

    return clipRgn;
}


/* copied from tk8.5.16/macosx/tkMacOSXSubwindows.c */
NSView*
TkpMacOSXDrawableView(
                     MacDrawable *macWin)
{
    NSView *result = nil;

    if (!macWin) {
	result = nil;
    } else if (!macWin->toplevel) {
	result = macWin->view;
    } else if (!(macWin->toplevel->flags & TK_EMBEDDED)) {
	result = macWin->toplevel->view;
    } else {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);
	if (contWinPtr) {
	    result = TkpMacOSXDrawableView(contWinPtr->privatePtr);
	}
    }
    return result;
}

void
PathSetUpCGContext(
        Drawable d,
        TkPathContext_ *dcPtr)
{
    CGrafPtr port;
    MacDrawable *macDraw = (MacDrawable *) d;
    int dontDraw = 0;

    dcPtr->c = NULL;
    dcPtr->view = NULL;
    dcPtr->clipRgn = NULL;
    dcPtr->focusLocked = 0;

    port = TkMacOSXGetDrawablePort(d);

    dcPtr->clipRgn = TkMacOSXGetClipRgn(d);
    if (!dontDraw) {
        dontDraw = dcPtr->clipRgn ? HIShapeIsEmpty(dcPtr->clipRgn) : 0;
    }
    if (dontDraw) {
        goto end;
    }

    NSView *view = TkpMacOSXDrawableView(macDraw);
    if (view) {
        NSView *fView = [NSView focusView];
        if (view != fView) {
            dcPtr->focusLocked = [view lockFocusIfCanDraw];
            dontDraw = !dcPtr->focusLocked;
        } else {
            dontDraw = ![view canDraw];
        }
        if (dontDraw) {
            goto end;
        }
        [[view window] disableFlushWindow];
        dcPtr->view = view;
        NSGraphicsContext *currentGraphicsContext = [NSGraphicsContext currentContext];
        dcPtr->c = (CGContextRef)[currentGraphicsContext graphicsPort];
        dcPtr->portBounds = NSRectToCGRect([view bounds]);
        if (dcPtr->clipRgn) {
        }
    } else {
        Tcl_Panic("PathSetUpCGContext(): "
                  "no NSView to draw into !");
    }

    /*
     * Core Graphics defines the origin to be the bottom left
     * corner of the CGContext and the positive y-axis points up.
     * Move the origin and flip the y-axis for all subsequent
     * Core Graphics drawing operations.
     */

    CGContextSaveGState(dcPtr->c);
    dcPtr->saveCount = 1;
    CGRect cgbounds = CGContextGetClipBoundingBox(dcPtr->c);
    dcPtr->portBounds = NSRectToCGRect([view bounds]);
    dcPtr->portBounds.origin.x += macDraw->xOff;
    dcPtr->portBounds.origin.y += macDraw->yOff;

    dcPtr->xOff = macDraw->xOff;
    dcPtr->yOff = macDraw->yOff;

end:
    if (dontDraw && dcPtr->clipRgn) {
        CFRelease(dcPtr->clipRgn);
        dcPtr->clipRgn = NULL;
    }
}

void
PathReleaseCGContext(
                     TkPathContext_ *dcPtr)
{
    if (dcPtr->c) {
        CGContextSynchronize(dcPtr->c);
        [[dcPtr->view window] setViewsNeedDisplay:YES];
        [[dcPtr->view window] enableFlushWindow];
        if (dcPtr->focusLocked)
        {
	    [dcPtr->view unlockFocus];
        }
	while (dcPtr->saveCount > 0) {
            CGContextRestoreGState(dcPtr->c);
	    dcPtr->saveCount--;
        }
    }
    if (dcPtr->clipRgn) {
        CFRelease(dcPtr->clipRgn);
        dcPtr->clipRgn = NULL;
    }
}

CGColorSpaceRef GetTheColorSpaceRef(void)
{
    static CGColorSpaceRef deviceRGB = NULL;
    if (deviceRGB == NULL) {
        deviceRGB = CGColorSpaceCreateDeviceRGB();
    }
    return deviceRGB;
}

static LookupTable LineCapStyleLookupTable[] = {
    {CapNotLast, 		kCGLineCapButt},
    {CapButt, 	 		kCGLineCapButt},
    {CapRound, 	 		kCGLineCapRound},
    {CapProjecting, 	kCGLineCapSquare}
};

static LookupTable LineJoinStyleLookupTable[] = {
    {JoinMiter, 	kCGLineJoinMiter},
    {JoinRound,		kCGLineJoinRound},
    {JoinBevel, 	kCGLineJoinBevel}
};

void
PathSetCGContextStyle(CGContextRef c, Tk_PathStyle *style)
{
    Tk_PathDash *dashPtr;
    int fill = 0, stroke = 0;

    /** Drawing attribute functions. **/

    /* Set the line width in the current graphics state to `width'. */
    CGContextSetLineWidth(c, style->strokeWidth);

    /* Set the line cap in the current graphics state to `cap'. */
    CGContextSetLineCap(c,
            TkPathTableLookup(LineCapStyleLookupTable, 4, style->capStyle));

    /* Set the line join in the current graphics state to `join'. */
    CGContextSetLineJoin(c,
            TkPathTableLookup(LineJoinStyleLookupTable, 3, style->joinStyle));

    /* Set the miter limit in the current graphics state to `limit'. */
    CGContextSetMiterLimit(c, style->miterLimit);

    /* Set the line dash patttern in the current graphics state. */
    dashPtr = style->dashPtr;
    if ((dashPtr != NULL) && (dashPtr->number != 0)) {
        CGFloat *dashes = (CGFloat *)ckalloc(dashPtr->number * sizeof(CGFloat));
        int i;

        for (i = 0; i < dashPtr->number; i++)
            dashes[i] = dashPtr->array[i] * style->strokeWidth;
        CGContextSetLineDash(c, 0.0, dashes, dashPtr->number);
        ckfree((char *)dashes);
    }

    /* Set the current fill colorspace in the context `c' to `DeviceRGB' and
     * set the components of the current fill color to `(red, green, blue,
     * alpha)'. */
    if (GetColorFromPathColor(style->fill) != NULL) {
        fill = 1;
        CGContextSetRGBFillColor(c,
                RedFloatFromXColorPtr(style->fill->color),
                GreenFloatFromXColorPtr(style->fill->color),
                BlueFloatFromXColorPtr(style->fill->color),
                style->fillOpacity);
    }

    /* Set the current stroke colorspace in the context `c' to `DeviceRGB' and
    * set the components of the current stroke color to `(red, green, blue,
    * alpha)'. */
    if (style->strokeColor != NULL) {
        stroke = 1;
        CGContextSetRGBStrokeColor(c,
                RedFloatFromXColorPtr(style->strokeColor),
                GreenFloatFromXColorPtr(style->strokeColor),
                BlueFloatFromXColorPtr(style->strokeColor),
                style->strokeOpacity);
    }
    if (stroke && fill) {
        CGContextSetTextDrawingMode(c, kCGTextFillStroke);
    } else if (stroke) {
        CGContextSetTextDrawingMode(c, kCGTextStroke);
    } else if (fill) {
        CGContextSetTextDrawingMode(c, kCGTextFill);
    }
}

/* Various ATSUI support functions. */

static OSStatus
CreateATSUIStyle(const char *fontFamily, float fontSize, Boolean isBold, Boolean isItalic, ATSUStyle *atsuStylePtr)
{
    OSStatus	err = noErr;
    ATSUStyle 	style;
    ATSUFontID	atsuFont;
    Fixed	atsuSize;
    Boolean	isUnderline = false;
    static const ATSUAttributeTag tags[] = { kATSUFontTag,       kATSUSizeTag,  kATSUQDBoldfaceTag,  kATSUQDItalicTag,  kATSUQDUnderlineTag };
    static const ByteCount sizes[] =       { sizeof(ATSUFontID), sizeof(Fixed), sizeof(Boolean),     sizeof(Boolean),   sizeof(Boolean) };
    const ATSUAttributeValuePtr values[] = { &atsuFont,          &atsuSize,     &isBold,             &isItalic,         &isUnderline };

    *atsuStylePtr = NULL;
    style = NULL;
    atsuFont = 0;
    atsuSize = FloatToFixed(fontSize);
    {
        err = ATSUFindFontFromName((Ptr) fontFamily, strlen(fontFamily), kFontFamilyName,
                kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, &atsuFont);
    }
    if (err != noErr) {
        return err;
    }
    err = ATSUCreateStyle(&style);
    if (err != noErr) {
        if (style) ATSUDisposeStyle(style);
        return err;
    }
    err = ATSUSetAttributes(style, sizeof(tags)/sizeof(tags[0]),
            tags, sizes, values);
    if (err != noErr) {
        if (style) ATSUDisposeStyle(style);
        return err;
    }
    *atsuStylePtr = style;
    return noErr;
}

static OSStatus
CreateLayoutForString(UniChar *buffer, CFIndex length, ATSUStyle atsuStyle, ATSUTextLayout *layoutPtr)
{
    ATSUTextLayout layout = NULL;
    OSStatus err = noErr;

    *layoutPtr = NULL;
    err = ATSUCreateTextLayoutWithTextPtr(buffer, 0,
            length, length, 1, (unsigned long *) &length, &atsuStyle, &layout);
    if (err == noErr) {
        *layoutPtr = layout;
    }
    ATSUSetTransientFontMatching(layout, true);
    return err;
}

TkPathContext
TkPathInit(Tk_Window tkwin, Drawable d)
{
    TkPathContext_ *context = (TkPathContext_ *) ckalloc(sizeof(TkPathContext_));
    bzero(context, sizeof(TkPathContext_));

    PathSetUpCGContext(d, context);
    context->port = TkMacOSXGetDrawablePort(d);
    context->data = NULL;
    context->widthCode = 0;
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(Display *display, int width, int height)
{
    CGContextRef cgContext;
    TkPathContext_ *context = (TkPathContext_ *) ckalloc((unsigned) (sizeof(TkPathContext_)));
    size_t bytesPerRow;
    char *data;

    /* Move up into own function */
    bzero(context, sizeof(TkPathContext_));
    bytesPerRow = 4*width;
    /* Round up to nearest multiple of 16 */
    bytesPerRow = (bytesPerRow + (16-1)) & ~(16-1);
    data = ckalloc(height*bytesPerRow);

    /* Make it RGBA with 32 bit depth. */
    cgContext = CGBitmapContextCreate(data, width, height, 8, bytesPerRow,
            GetTheColorSpaceRef(), kCGImageAlphaPremultipliedLast);
    if (cgContext == NULL) {
        ckfree((char *) context);
        return (TkPathContext) NULL;
    }
    CGContextClearRect(cgContext, CGRectMake(0, 0, width, height));
    CGContextTranslateCTM(cgContext, 0, height);
    CGContextScaleCTM(cgContext, 1, -1);
    context->c = cgContext;
    context->port = NULL;
    context->data = data;
    context->clipRgn = NULL;
    context->saveCount = 0;
    context->xOff = context->yOff = 0;
    return (TkPathContext) context;
}

void
TkPathPushTMatrix(TkPathContext ctx, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGAffineTransform transform;

    if (mPtr == NULL) {
        return;
    }
    /* Return the transform [ a b c d tx ty ]. */
    transform = CGAffineTransformMake(
            (float) mPtr->a, (float) mPtr->b,
            (float) mPtr->c, (float) mPtr->d,
            (float) mPtr->tx, (float) mPtr->ty);
    CGContextConcatCTM(context->c, transform);
}

void
TkPathResetTMatrix(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->widthCode = 0;
    while (context->saveCount > 0) {
	CGContextRestoreGState(context->c);
	context->saveCount--;
    }
    CGContextSaveGState(context->c);
    context->saveCount++;

    if (context->data != NULL) {
	/* surface bitmap */
	return;
    }

    CGAffineTransform t = { .a=1.0, .b=0.0, .c=0.0, .d=-1.0, .tx=0.0,
			    .ty=context->portBounds.size.height};
    CGContextConcatCTM(context->c, t);

    CGRect r;
    HIShapeGetBounds(context->clipRgn, &r);

    HIShapeReplacePathInCGContext(context->clipRgn, context->c);
    CGContextEOClip(context->c);

    CGContextTranslateCTM(context->c, context->xOff, context->yOff);

    CGContextSetShouldAntialias(context->c, Tk_PathAntiAlias);
    CGContextSetInterpolationQuality(context->c, kCGInterpolationHigh);
}

void
TkPathSaveState(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextSaveGState(context->c);
    context->saveCount++;
}

void
TkPathRestoreState(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (context->saveCount > 0) {
	CGContextRestoreGState(context->c);
	context->saveCount--;
    }
}

void
TkPathBeginPath(TkPathContext ctx, Tk_PathStyle *stylePtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    int nint;
    double width;
    CGContextBeginPath(context->c);
    PathSetCGContextStyle(context->c, stylePtr);
    if (stylePtr->strokeColor == NULL) {
        context->widthCode = 0;
    } else {
        width = stylePtr->strokeWidth;
        nint = (int) (width + 0.5);
        context->widthCode = fabs(width - nint) > 0.01 ? 0 : 2 - nint % 2;
    }
}

void
TkPathMoveTo(TkPathContext ctx, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextMoveToPoint(context->c, x, y);
}

void
TkPathLineTo(TkPathContext ctx, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddLineToPoint(context->c, x, y);
}

void
TkPathLinesTo(TkPathContext ctx, double *pts, int n)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Add a set of lines to the context's path. */
    /* CGContextAddLines(context->c, const CGPoint points[], size_t count); */
}

void
TkPathQuadBezier(TkPathContext ctx, double ctrlX, double ctrlY, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddQuadCurveToPoint(context->c, ctrlX, ctrlY, x, y);
}

void
TkPathCurveTo(TkPathContext ctx, double ctrlX1, double ctrlY1,
        double ctrlX2, double ctrlY2, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddCurveToPoint(context->c, ctrlX1, ctrlY1, ctrlX2, ctrlY2, x, y);
}

void
TkPathArcTo(TkPathContext ctx,
        double rx, double ry,
        double phiDegrees, 	/* The rotation angle in degrees! */
        char largeArcFlag, char sweepFlag, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    /* @@@ Should we try to use the native arc functions here? */
    if (Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    TkPathArcToUsingBezier(ctx, rx, ry, phiDegrees, largeArcFlag, sweepFlag, x, y);
}

void
TkPathRectangle(TkPathContext ctx, double x, double y, double width, double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect r;
    if (Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    r = CGRectMake(x, y, width, height);
    CGContextAddRect(context->c, r);
}

void
TkPathOval(TkPathContext ctx, double cx, double cy, double rx, double ry)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    CGRect r;
    r = CGRectMake(cx-rx, cy-ry, 2*rx, 2*ry);
    CGContextAddEllipseInRect(context->c, r);
}


CGInterpolationQuality convertInterpolationToCGInterpolation(int interpolation)
{
    switch (interpolation) {
        case kPathImageInterpolationNone:
            return kCGInterpolationNone;
        case kPathImageInterpolationFast:
            return kCGInterpolationLow;
        case kPathImageInterpolationBest:
            return kCGInterpolationHigh;
        default:
            return kCGInterpolationMedium;
    }
}

void
TkPathImage(TkPathContext ctx, Tk_Image image, Tk_PhotoHandle photo,
        double x, double y, double width0, double height0, double fillOpacity,
        XColor *tintColor, double tintAmount, int interpolation, PathRect *srcRegion)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGImageRef cgImage;
    CGDataProviderRef provider;
    CGColorSpaceRef colorspace;
    CGImageAlphaInfo alphaInfo;
    size_t size;
    Tk_PhotoImageBlock block;
    unsigned char *data = NULL;
    unsigned char *ptr = NULL;
    unsigned char *srcPtr, *dstPtr;
    int srcR, srcG, srcB, srcA;     /* The source pixel offsets. */
    int dstR, dstG, dstB, dstA;     /* The destination pixel offsets. */
    int pitch;
    int iwidth, iheight;
    int i, j;

    /* Return value? */
    Tk_PhotoGetImage(photo, &block);
    size = block.pitch * block.height;
    iheight = block.height;
    iwidth = block.width;
    pitch = block.pitch;
    double width = (width0 == 0.0) ? (double)iwidth : width0;
    double height = (height0 == 0.0) ? (double)iheight : height0;


    /*
     * The offset array contains the offsets from the address of a pixel to
     * the addresses of the bytes containing the red, green, blue and alpha
     * (transparency) components.  These are normally 0, 1, 2 and 3.
     * @@@ There are more cases to consider than these!
     */
    srcR = dstR = block.offset[0];
    srcG = dstG = block.offset[1];
    srcB = dstB = block.offset[2];
    srcA = dstA = block.offset[3];

    if (srcA == 3) {
        alphaInfo = kCGImageAlphaLast;
    } else if (srcA == 0) {
        alphaInfo = kCGImageAlphaFirst;
    } else {
        /* @@@ What to do here? */
        return;
    }

    if (block.pixelSize == 4) {
        if ((srcR == dstR) && (srcG == dstG) && (srcB == dstB) && (srcA == dstA) && fillOpacity >= 1.0 && (tintAmount <= 0.0 || tintColor == NULL)) {
            ptr = (unsigned char *) block.pixelPtr;
        } else {
            data = (unsigned char *) ckalloc(pitch*iheight);
            ptr = data;

            if (tintColor && tintAmount > 0.0) {
#ifdef TINT_INT_CALCULATION
                uint32_t tintR, tintG, tintB, uAmount, uRemain, uOpacity;

                if (tintAmount > 1.0)
                    tintAmount = 1.0;
                uAmount = (uint32_t)(tintAmount * 256.0);
                uRemain = 256 - uAmount;
                uOpacity = (uint32_t)(fillOpacity * 256.0);
                tintR = Red255FromXColorPtr(tintColor);
                tintG = Green255FromXColorPtr(tintColor);
                tintB = Blue255FromXColorPtr(tintColor);
                for (i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i*pitch;
                    dstPtr = ptr + i*pitch;
                    for (j = 0; j < iwidth; j++) {
                        /* extract */
                        uint32_t r = *(srcPtr+srcR);
                        uint32_t g = *(srcPtr+srcG);
                        uint32_t b = *(srcPtr+srcB);
                        uint32_t a = *(srcPtr+srcA);

                        /* transform */
                        uint32_t lumAmount = ((r * 6966 + g * 23436 + b * 2366) * uAmount) >> 23;  /* 0-256 */
                        r = (uRemain * r + lumAmount * tintR);
                        g = (uRemain * g + lumAmount * tintG);
                        b = (uRemain * b + lumAmount * tintB);

                        /* fix range */
                        r = r>0xFFFF ? 0xFFFF : r;
                        g = g>0xFFFF ? 0xFFFF : g;
                        b = b>0xFFFF ? 0xFFFF : b;

                        /* and put back */
                        *(dstPtr+dstR) = r >> 8;
                        *(dstPtr+dstG) = g >> 8;
                        *(dstPtr+dstB) = b >> 8;
                        *(dstPtr+dstA) = (a * uOpacity) >> 8;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
#else
                float tintR, tintG, tintB;

                if (tintAmount > 1.0)
                    tintAmount = 1.0;
                tintR = RedFloatFromXColorPtr(tintColor);
                tintG = GreenFloatFromXColorPtr(tintColor);
                tintB = BlueFloatFromXColorPtr(tintColor);
                for (i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i*pitch;
                    dstPtr = ptr + i*pitch;
                    for (j = 0; j < iwidth; j++) {
                        /* extract */
                        int r = *(srcPtr+srcR);
                        int g = *(srcPtr+srcG);
                        int b = *(srcPtr+srcB);

                        /* transform */
                        int lum = (int)(0.2126*r + 0.7152*g + 0.0722*b);
                        r = (int)((1.0-tintAmount)*r + tintAmount*lum*tintR);
                        g = (int)((1.0-tintAmount)*g + tintAmount*lum*tintG);
                        b = (int)((1.0-tintAmount)*b + tintAmount*lum*tintB);

                        /* fix range */
                        r = r<0 ? 0 : r>255 ? 255 : r;
                        g = g<0 ? 0 : g>255 ? 255 : g;
                        b = b<0 ? 0 : b>255 ? 255 : b;

                        /* and put back */
                        *(dstPtr+dstR) = r;
                        *(dstPtr+dstG) = g;
                        *(dstPtr+dstB) = b;
                        *(dstPtr+dstA) = *(srcPtr+srcA) * fillOpacity;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
#endif
            } else {
                for (i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i*pitch;
                    dstPtr = ptr + i*pitch;
                    for (j = 0; j < iwidth; j++) {
                        *(dstPtr+dstR) = *(srcPtr+srcR);
                        *(dstPtr+dstG) = *(srcPtr+srcG);
                        *(dstPtr+dstB) = *(srcPtr+srcB);
                        *(dstPtr+dstA) = *(srcPtr+srcA) * fillOpacity;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
            }
        }
    } else {
        ptr = (unsigned char *) block.pixelPtr;
        return;
    }
    provider = CGDataProviderCreateWithData(NULL, ptr, size, NULL);
    colorspace = CGColorSpaceCreateDeviceRGB();
    cgImage = CGImageCreate(block.width, block.height,
            8, 						/* bitsPerComponent */
            block.pixelSize*8,	 	/* bitsPerPixel */
            block.pitch, 			/* bytesPerRow */
            colorspace,				/* colorspace */
            alphaInfo,				/* alphaInfo */
            provider, NULL,
            interpolation > 0 ? 1 : 0,  /* shouldInterpolate */
            kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorspace);
    if (width == 0.0) {
        width = (double) block.width;
    }
    if (height == 0.0) {
        height = (double) block.height;
    }

    CGContextSaveGState(context->c);
    context->saveCount++;

    if (srcRegion != NULL) {
        width = (width0 == 0.0) ? srcRegion->x2 - srcRegion->x1 : width0;
        height = (height0 == 0.0) ? srcRegion->y2 - srcRegion->y1 : height0;
        double xscale = width / (srcRegion->x2 - srcRegion->x1);
        double yscale = height / (srcRegion->y2 - srcRegion->y1);
        CGContextSetInterpolationQuality(context->c, convertInterpolationToCGInterpolation(interpolation));
        CGContextTranslateCTM(context->c, x, y+height);
        CGContextScaleCTM(context->c, xscale, -yscale);
        CGContextClipToRect(context->c, CGRectMake(0.0, 0.0, width/xscale, height/yscale));
        CGContextDrawTiledImage(context->c,
                CGRectMake(srcRegion->x1, fmod(srcRegion->y2, iheight), iwidth, iheight),
                cgImage);
    } else {
        /* Flip back to an upright coordinate system since CGContextDrawImage expect this. */
        CGContextSetInterpolationQuality(context->c, convertInterpolationToCGInterpolation(interpolation));
        CGContextTranslateCTM(context->c, x, y+height);
        CGContextScaleCTM(context->c, 1, -1);
        CGContextDrawImage(context->c, CGRectMake(0.0, 0.0, width, height), cgImage);
    }
    CGImageRelease(cgImage);
    CGContextRestoreGState(context->c);
    context->saveCount--;
    if (data) {
        ckfree((char *)data);
    }
}

void
TkPathClosePath(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextClosePath(context->c);
}

/*
 * @@@ Problems: don't want Tcl_Interp, finding matching font not while processing options.
 * Separate font style from layout???
 */

Boolean isItalic(enum FontSlant slant)
{
    switch(slant) {
        case PATH_TEXT_SLANT_NORMAL: return false;
        case PATH_TEXT_SLANT_ITALIC: return true;
        case PATH_TEXT_SLANT_OBLIQUE: return true;
        default: return false;
    }
}

Boolean
isBold(enum FontWeight weight)
{
    switch(weight) {
        case PATH_TEXT_WEIGHT_NORMAL: return false;
        case PATH_TEXT_WEIGHT_BOLD: return true;
        default: return false;
    }
}

int
TkPathTextConfig(Tcl_Interp *interp, Tk_PathTextStyle *textStylePtr, char *utf8, void **customPtr)
{
    PathATSUIRecord	*recordPtr;
    ATSUStyle 		atsuStyle = NULL;
    ATSUTextLayout 	atsuLayout = NULL;
    CFStringRef 	cf;
    UniChar 		*buffer;
    CFRange 		range;
    CFIndex 		length;
    OSStatus 		err;
    Tcl_Encoding	enc;
    Tcl_DString		ds;

    if (utf8 == NULL) {
        return TCL_OK;
    }
    TkPathTextFree(textStylePtr, *customPtr);

    enc = Tcl_GetEncoding(NULL, "utf-8");
    Tcl_DStringInit(&ds);
    Tcl_UtfToExternalDString(enc, utf8, -1, &ds);
    Tcl_FreeEncoding(enc);
    cf = CFStringCreateWithCString(NULL, Tcl_DStringValue(&ds), kCFStringEncodingUTF8);
    Tcl_DStringFree(&ds);
    length = CFStringGetLength(cf);
    if (length == 0) {
        return TCL_OK;
    }
    range = CFRangeMake(0, length);
    err = CreateATSUIStyle(textStylePtr->fontFamily, textStylePtr->fontSize, isBold(textStylePtr->fontWeight), isItalic(textStylePtr->fontSlant), &atsuStyle);
    if (err != noErr) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("font style couldn't be created", -1));
        return TCL_ERROR;
    }
    buffer = (UniChar *) ckalloc(length * sizeof(UniChar));
    CFStringGetCharacters(cf, range, buffer);
    err = CreateLayoutForString(buffer, length, atsuStyle, &atsuLayout);
    CFRelease(cf);
    if (err != noErr) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("text layout couldn't be created", -1));
        ckfree((char *)buffer);
        return TCL_ERROR;
    }
    recordPtr = (PathATSUIRecord *) ckalloc(sizeof(PathATSUIRecord));
    recordPtr->atsuStyle = atsuStyle;
    recordPtr->atsuLayout = atsuLayout;
    recordPtr->buffer = buffer;
    int i, j;
    recordPtr->nl[0] = 0;
    for (i = 0, j = 1; i < length; i++) {
        if ((j < MAX_NL) && (buffer[i] == '\n')) {
            recordPtr->nl[j++] = i + 1;
            buffer[i] = 0x2028;
        }
    }
    recordPtr->nl[j] = i + 1;
    recordPtr->nlc = j;
    *customPtr = (PathATSUIRecord *) recordPtr;
    return TCL_OK;
}

static void drawMultilineText(PathATSUIRecord *recordPtr)
{
    int i;

    for (i = 0; i < recordPtr->nlc; i++) {
        ATSUDrawText(recordPtr->atsuLayout, recordPtr->nl[i], recordPtr->nl[i+1] - recordPtr->nl[i] - 1, recordPtr->dx[i], recordPtr->dy[i]);
    }
}

void
TkPathTextDraw(TkPathContext ctx, Tk_PathStyle *style, Tk_PathTextStyle *textStylePtr,
        double x, double y, int fillOverStroke, char *utf8, void *custom)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    ByteCount iSize = sizeof(CGContextRef);
    ATSUAttributeTag iTag = kATSUCGContextTag;
    ATSUAttributeValuePtr iValuePtr = &(context->c);

    ATSUSetLayoutControls(recordPtr->atsuLayout, 1, &iTag, &iSize, &iValuePtr);
    CGContextSaveGState(context->c);
    context->saveCount++;
    CGContextTranslateCTM(context->c, x, y);
    CGContextScaleCTM(context->c, 1, -1);
    if ((style->strokeColor != NULL) && (GetColorFromPathColor(style->fill) != NULL)) {
        CGContextSetTextDrawingMode(context->c, fillOverStroke ? kCGTextStroke : kCGTextFill);
        drawMultilineText(recordPtr);
        CGContextSetTextDrawingMode(context->c, fillOverStroke ? kCGTextFill : kCGTextStroke);
        drawMultilineText(recordPtr);
    } else {
        drawMultilineText(recordPtr);
    }
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathTextFree(Tk_PathTextStyle *textStylePtr, void *custom)
{
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    if (recordPtr) {
        if (recordPtr->atsuStyle) {
            ATSUDisposeStyle(recordPtr->atsuStyle);
        }
        if (recordPtr->atsuLayout) {
            ATSUDisposeTextLayout(recordPtr->atsuLayout);
        }
        if (recordPtr->buffer) {
            ckfree((char *) recordPtr->buffer);
        }
    }
}

PathRect
TkPathTextMeasureBbox(Display *display, Tk_PathTextStyle *textStylePtr, char *utf8, double *lineSpacing, void *custom)
{
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    PathRect r,ri;
    int i;
    ATSTrapezoid b;
    ItemCount numBounds;
    double x = 0.0;
    double y = 0.0;
    double baseX = 0.0;
    double lineSp = 0;

    for (i = 0; i < recordPtr->nlc; i++) {
        b.upperRight.x = b.upperLeft.x = 0;

        ATSUGetGlyphBounds(recordPtr->atsuLayout, 0, 0,
                recordPtr->nl[i], recordPtr->nl[i+1] - recordPtr->nl[i] - 1,
                kATSUseFractionalOrigins, 1, &b, &numBounds);
        ri.x1 = MIN(Fix2X(b.upperLeft.x), Fix2X(b.lowerLeft.x));
        ri.y1 = MIN(Fix2X(b.upperLeft.y), Fix2X(b.upperRight.y));
        ri.x2 = MAX(Fix2X(b.upperRight.x), Fix2X(b.lowerRight.x));
        ri.y2 = MAX(Fix2X(b.lowerLeft.y), Fix2X(b.lowerRight.y));
        if (i == 0) {
            baseX = ri.x1;
            r.x1 = ri.x1;
            r.y1 = ri.y1;
            r.x2 = ri.x2;
            r.y2 = ri.y2;
        } else {
            x = ri.x1 - baseX;
            ri.x1 -= x;
            ri.y1 += y;
            ri.x2 -= x;
            ri.y2 += y;
            if (r.x1 > ri.x1) r.x1 = ri.x1;
            if (r.y1 > ri.y1) r.y1 = ri.y1;
            if (r.x2 < ri.x2) r.x2 = ri.x2;
            if (r.y2 < ri.y2) r.y2 = ri.y2;
        }
        recordPtr->dx[i] = X2Fix(-x);
        recordPtr->dy[i] = X2Fix(-y);
        y = r.y2 - r.y1;
	lineSp += y;
    }

    if (lineSpacing != NULL && i > 0) {
	*lineSpacing = lineSp / i;
    }

    return r;
}

void
TkPathSurfaceErase(TkPathContext ctx, double x, double y, double width, double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextClearRect(context->c, CGRectMake(x, y, width, height));
}

void
TkPathSurfaceToPhoto(Tcl_Interp *interp, TkPathContext ctx, Tk_PhotoHandle photo)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextRef c = context->c;
    Tk_PhotoImageBlock block;
    unsigned char *data;
    unsigned char *pixel;
    int width, height;
    int bytesPerRow;

    width = CGBitmapContextGetWidth(c);
    height = CGBitmapContextGetHeight(c);
    data = CGBitmapContextGetData(c);
    bytesPerRow = CGBitmapContextGetBytesPerRow(c);

    Tk_PhotoGetImage(photo, &block);
    pixel = (unsigned char *) attemptckalloc(height*bytesPerRow);
    if (pixel == NULL) {
        return;
    }
    if (Tk_PathSurfaceCopyPremultiplyAlpha) {
        TkPathCopyBitsPremultipliedAlphaRGBA(data, pixel, width, height, bytesPerRow);
    } else {
        memcpy(pixel, data, height*bytesPerRow);
    }
    block.pixelPtr = pixel;
    block.width = width;
    block.height = height;
    block.pitch = bytesPerRow;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    /* Should change this to check for errors... */
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, width, height, TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *) pixel);
}

void
TkPathClipToPath(TkPathContext ctx, int fillRule)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    /* If you need to grow the clipping path after it’s shrunk, you must save the
     * graphics state before you clip, then restore the graphics state to restore the current
     * clipping path. */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if (fillRule == WindingRule) {
        CGContextClip(context->c);
    } else if (fillRule == EvenOddRule) {
        CGContextEOClip(context->c);
    }
}

void
TkPathReleaseClipToPath(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathStroke(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextStrokePath(context->c);
}

void
TkPathFill(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (style->fillRule == WindingRule) {
        CGContextFillPath(context->c);
    } else if (style->fillRule == EvenOddRule) {
        CGContextEOFillPath(context->c);
    }
}

void
TkPathFillAndStroke(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if (style->fillRule == WindingRule) {
        CGContextDrawPath(context->c, kCGPathFillStroke);
    } else if (style->fillRule == EvenOddRule) {
        CGContextDrawPath(context->c, kCGPathEOFillStroke);
    }
}

void
TkPathEndPath(TkPathContext ctx)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Empty ??? */
}

void
TkPathFree(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    PathReleaseCGContext(context);
    if (context->data) {
        ckfree(context->data);
    }
    ckfree((char *) ctx);
}

int
TkPathDrawingDestroysPath(void)
{
    return 1;
}

int
TkPathPixelAlign(void)
{
    return 0;
}

/* TkPathGetCurrentPosition --
 *
 * 		Returns the current pen position in untransformed coordinates!
 */

int
TkPathGetCurrentPosition(TkPathContext ctx, PathPoint *ptPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGPoint cgpt;

    cgpt = CGContextGetPathCurrentPoint(context->c);
    ptPtr->x = cgpt.x;
    ptPtr->y = cgpt.y;
    return TCL_OK;
}

int
TkPathBoundingBox(TkPathContext ctx, PathRect *rPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect cgRect;

    /* This one is not very useful since it includes the control points. */
    cgRect = CGContextGetPathBoundingBox(context->c);
    rPtr->x1 = cgRect.origin.x;
    rPtr->y1 = cgRect.origin.y;
    rPtr->x2 = cgRect.origin.x + cgRect.size.width;
    rPtr->y2 = cgRect.origin.y + cgRect.size.height;
    return TCL_OK;
}

/*
 * Using CGShading for fill gradients.
 */

static void
ShadeEvaluate(void *info, const CGFloat *in, CGFloat *out)
{
    FillInfo            *fillInfo = (FillInfo *)info;
    GradientStopArray 	*stopArrPtr = fillInfo->stopArrPtr;
    double              fillOpacity = fillInfo->fillOpacity;
    GradientStop        **stopPtrPtr = stopArrPtr->stops;
    GradientStop		*stop1 = NULL, *stop2 = NULL;
    int					nstops = stopArrPtr->nstops;
    int					i = 0;
    float 				par = *in;
    float				f1, f2;

    /* Find the two stops for this point. Tricky! */
    while ((i < nstops) && ((*stopPtrPtr)->offset < par)) {
        stopPtrPtr++, i++;
    }
    if (i == 0) {
        /* First stop > 0. */
        stop1 = *stopPtrPtr;
        stop2 = stop1;
    } else if (i == nstops) {
        /* We have stepped beyond the last stop; step back! */
        stop1 = *(stopPtrPtr - 1);
        stop2 = stop1;
    } else {
        stop1 = *(stopPtrPtr - 1);
        stop2 = *stopPtrPtr;
    }
    /* Interpolate between the two stops.
     * "If two gradient stops have the same offset value,
     * then the latter gradient stop controls the color value at the
     * overlap point."
     */
    if (fabs(stop2->offset - stop1->offset) < 1e-6) {
        *out++ = RedFloatFromXColorPtr(stop2->color);
        *out++ = GreenFloatFromXColorPtr(stop2->color);
        *out++ = BlueFloatFromXColorPtr(stop2->color);
        *out++ = stop2->opacity * fillOpacity;
    } else {
        f1 = (stop2->offset - par)/(stop2->offset - stop1->offset);
        f2 = (par - stop1->offset)/(stop2->offset - stop1->offset);
        *out++ = f1 * RedFloatFromXColorPtr(stop1->color) +
                f2 * RedFloatFromXColorPtr(stop2->color);
        *out++ = f1 * GreenFloatFromXColorPtr(stop1->color) +
                f2 * GreenFloatFromXColorPtr(stop2->color);
        *out++ = f1 * BlueFloatFromXColorPtr(stop1->color) +
                f2 * BlueFloatFromXColorPtr(stop2->color);
        *out++ = (f1 * stop1->opacity + f2 * stop2->opacity) * fillOpacity;
    }
}

static void
ShadeRelease(void *info)
{
    /* Not sure if anything to do here. */
}

void
TkPathPaintLinearGradient(TkPathContext ctx, PathRect *bbox, LinearGradientFill *fillPtr, int fillRule, double fillOpacity, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef 		shading;
    CGPoint 			start, end;
    CGColorSpaceRef 	colorSpaceRef;
    CGFunctionRef 		function;
    CGFunctionCallbacks callbacks;
    PathRect 			*trans = fillPtr->transitionPtr;		/* The transition line. */
    FillInfo            fillInfo;

    fillInfo.fillOpacity = fillOpacity;
    fillInfo.stopArrPtr = fillPtr->stopArrPtr;

    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
        CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function = CGFunctionCreate((void *) &fillInfo, 1, kValidDomain, 4, kValidRange, &callbacks);
    start = CGPointMake(trans->x1, trans->y1);
    end   = CGPointMake(trans->x2, trans->y2);
    shading = CGShadingCreateAxial(colorSpaceRef, start, end, function, 1, 1);
    if (mPtr) {
        /* @@@ I'm not completely sure of the order of transforms here! */
        TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGContextRestoreGState(context->c);
    context->saveCount--;
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
}

void
TkPathPaintRadialGradient(TkPathContext ctx, PathRect *bbox, RadialGradientFill *fillPtr, int fillRule, double fillOpacity, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef 		shading;
    CGPoint 			start, end;
    CGColorSpaceRef 	colorSpaceRef;
    CGFunctionRef 		function;
    CGFunctionCallbacks callbacks;
    RadialTransition    *tPtr = fillPtr->radialPtr;
    FillInfo            fillInfo;

    fillInfo.fillOpacity = fillOpacity;
    fillInfo.stopArrPtr = fillPtr->stopArrPtr;

    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextSaveGState(context->c);
	context->saveCount++;
        CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
        CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function = CGFunctionCreate((void *) &fillInfo, 1, kValidDomain, 4, kValidRange, &callbacks);
    start = CGPointMake(tPtr->focalX, tPtr->focalY);
    end   = CGPointMake(tPtr->centerX, tPtr->centerY);
    shading = CGShadingCreateRadial(colorSpaceRef, start, 0.0, end, tPtr->radius, function, 1, 1);
    if (mPtr) {
        /* @@@ I'm not completely sure of the order of transforms here! */
        TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextRestoreGState(context->c);
	context->saveCount--;
    }
}

int
TkPathSetup(Tcl_Interp *interp)
{
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */

Added generic/rbc/tkPathCanvArrow.c.






























































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
 * tkCanvArrow.c --
 *
 *    This file implements arrow heads
 *
 * Copyright (c) 2014 OpenSim Ltd., author:Zoltan Bojthe
 *
 * $Id$
 */

#include "tkPathInt.h"

#ifdef _MSC_VER
#ifndef isnan
#define isnan(x) ((x) != (x))
#endif
#endif

/*
 * Points in an arrowHead:
 */
#define PTS_IN_ARROW 6
#define DRAWABLE_PTS_IN_ARROW 5
#define ORIG_PT_IN_ARROW 2
#define LINE_PT_IN_ARROW 5


static const double zero = 0.0; // just for NaN
#define NaN (zero/zero)

TkPathAtom *
TkPathMakePathAtomsFromArrow(TkPathArrowDescr *arrowDescr)
{
    TkPathPoint *coords = arrowDescr->arrowPointsPtr;
    TkPathAtom *atomPtr = NULL, *ret = NULL;
    if (coords)
    {
        int i = 0;
        if (isnan(coords[0].x) || isnan(coords[0].y)) {
            i = 1;
        }
        ret = atomPtr = TkPathNewMoveToAtom(coords[i].x, coords[i].y);
        for (i++ ; i < DRAWABLE_PTS_IN_ARROW; i++) {
            if (isnan(coords[i].x) || isnan(coords[i].y))
                continue;
            atomPtr->nextPtr = TkPathNewLineToAtom(coords[i].x, coords[i].y);
            atomPtr = atomPtr->nextPtr;
        }
    }
    return ret;
}

void
TkPathDisplayArrow(Tk_PathCanvas canvas, TkPathArrowDescr *arrowDescr,
        Tk_PathStyle *const style, TkPathMatrix *mPtr, TkPathRect *bboxPtr)
{
    if (arrowDescr->arrowEnabled && arrowDescr->arrowPointsPtr != NULL) {
        Tk_PathStyle arrowStyle = *style;
        TkPathColor fc;
        TkPathAtom *atomPtr;

    TkPathResetTMatrix(ContextOfCanvas(canvas));
        if (arrowDescr->arrowFillRatio > 0.0 &&
        arrowDescr->arrowLength != 0.0) {
            arrowStyle.strokeWidth = 0.0;
            fc.color = arrowStyle.strokeColor;
            fc.gradientInstPtr = NULL;
            arrowStyle.fill = &fc;
            arrowStyle.fillOpacity = arrowStyle.strokeOpacity;
        } else {
            arrowStyle.fill = NULL;
            arrowStyle.fillOpacity = 1.0;
            arrowStyle.joinStyle = 1;
            arrowStyle.dashPtr = NULL;
        }
        atomPtr = TkPathMakePathAtomsFromArrow(arrowDescr);
        TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &arrowStyle,
        mPtr, bboxPtr);
        TkPathFreeAtoms(atomPtr);
    }
}

void
TkPathPaintArrow(TkPathContext context, TkPathArrowDescr *arrowDescr,
       Tk_PathStyle *const style, TkPathRect *bboxPtr)
{
    if (arrowDescr->arrowEnabled && arrowDescr->arrowPointsPtr != NULL) {
        Tk_PathStyle arrowStyle = *style;
        TkPathColor fc;
        TkPathAtom *atomPtr;

        arrowStyle.matrixPtr = NULL;
        if (arrowDescr->arrowFillRatio > 0.0 &&
        arrowDescr->arrowLength != 0.0) {
            arrowStyle.strokeWidth = 0.0;
            fc.color = arrowStyle.strokeColor;
            fc.gradientInstPtr = NULL;
            arrowStyle.fill = &fc;
            arrowStyle.fillOpacity = arrowStyle.strokeOpacity;
        } else {
            arrowStyle.fill = NULL;
            arrowStyle.fillOpacity = 1.0;
            arrowStyle.joinStyle = 1;
            arrowStyle.dashPtr = NULL;
        }
        atomPtr = TkPathMakePathAtomsFromArrow(arrowDescr);
    if (TkPathMakePath(context, atomPtr, &arrowStyle) == TCL_OK) {
        TkPathPaintPath(context, atomPtr, &arrowStyle, bboxPtr);
    }
        TkPathFreeAtoms(atomPtr);
    }
}

void
TkPathArrowDescrInit(TkPathArrowDescr *descrPtr)
{
    descrPtr->arrowEnabled = TK_PATH_ARROWS_OFF;
    descrPtr->arrowLength = (float)8.0;
    descrPtr->arrowWidth = (float)4.0;
    descrPtr->arrowFillRatio = (float)1.0;
    descrPtr->arrowPointsPtr = NULL;
}

void
TkPathIncludeArrowPointsInRect(TkPathRect *bbox, TkPathArrowDescr *arrowDescrPtr)
{
    if (arrowDescrPtr->arrowEnabled && arrowDescrPtr->arrowPointsPtr) {
        int i;

        for (i = 0; i < PTS_IN_ARROW; i++)
            if (!isnan(arrowDescrPtr->arrowPointsPtr[i].x) &&
        !isnan(arrowDescrPtr->arrowPointsPtr[i].y))
                TkPathIncludePointInRect(bbox, arrowDescrPtr->arrowPointsPtr[i].x,
                   arrowDescrPtr->arrowPointsPtr[i].y);
    }
}

void
TkPathIncludeArrowPoints(Tk_PathItem *itemPtr, TkPathArrowDescr *arrowDescrPtr)
{
    if (arrowDescrPtr->arrowEnabled) {
        int i;

        for (i = 0; i < PTS_IN_ARROW; i++)
            if (!isnan(arrowDescrPtr->arrowPointsPtr[i].x) &&
        !isnan(arrowDescrPtr->arrowPointsPtr[i].y))
                TkPathIncludePoint(itemPtr,
                   (double *)&arrowDescrPtr->arrowPointsPtr[i]);
    }
}

void
TkPathPreconfigureArrow(TkPathPoint *pf, TkPathArrowDescr *arrowDescr)
{
    if (arrowDescr->arrowPointsPtr == NULL) {
        if (arrowDescr->arrowEnabled) {
            arrowDescr->arrowPointsPtr = (TkPathPoint *)
        ckalloc((unsigned)(PTS_IN_ARROW * sizeof(TkPathPoint)));
            arrowDescr->arrowPointsPtr[LINE_PT_IN_ARROW] = *pf;
            arrowDescr->arrowPointsPtr[ORIG_PT_IN_ARROW] = *pf;
        }
    } else {
        if (pf->x == arrowDescr->arrowPointsPtr[LINE_PT_IN_ARROW].x &&
        pf->y == arrowDescr->arrowPointsPtr[LINE_PT_IN_ARROW].y) {
            *pf = arrowDescr->arrowPointsPtr[ORIG_PT_IN_ARROW];
        }
        if (!arrowDescr->arrowEnabled) {
            ckfree((char *)arrowDescr->arrowPointsPtr);
            arrowDescr->arrowPointsPtr = NULL;
        }
    }
}

TkPathPoint
TkPathConfigureArrow(TkPathPoint pf, TkPathPoint pl, TkPathArrowDescr *arrowDescr,
        Tk_PathStyle *lineStyle, int updateFirstPoint)
{
    if (arrowDescr->arrowEnabled) {
        TkPathPoint p0;
        double lineWidth = lineStyle->strokeWidth;
        double shapeLength = arrowDescr->arrowLength;
        double shapeWidth = arrowDescr->arrowWidth;
        double shapeFill = arrowDescr->arrowFillRatio;
        double dx, dy, length, sinTheta, cosTheta;
        double backup;          /* Distance to backup end points so the line
                                 * ends in the middle of the arrowhead. */
        double minsShapeFill;
        TkPathPoint *poly = arrowDescr->arrowPointsPtr;
        int capStyle = lineStyle->capStyle;
        /*  CapButt, CapProjecting, or CapRound. */

        if (!poly) {
            Tcl_Panic("Internal error: TkPathPoint list is NULL pointer\n");
        }
        if (shapeWidth < lineWidth) {
            shapeWidth = lineWidth;
        }
        minsShapeFill = lineWidth*shapeLength/shapeWidth;
        if (shapeFill > 0.0 &&
        fabs(shapeLength*shapeFill) < fabs(minsShapeFill))
            shapeFill = 1.1*minsShapeFill / shapeLength;

        backup = 0.0;
        if (lineWidth > 1.0) {
            backup = (capStyle == CapProjecting) ? 0.5 * lineWidth : 0.0;
            if (shapeFill > 0.0 && shapeLength != 0.0) {
                backup += 0.5 * lineWidth * shapeLength / shapeWidth;
            }
        }

        dx = pf.x - pl.x;
        dy = pf.y - pl.y;
        length = hypot(dx, dy);
        if (length == 0) {
            sinTheta = cosTheta = 0.0;
        } else {
            sinTheta = dy/length;
            cosTheta = dx/length;
        }

        p0.x = pf.x - shapeLength * cosTheta;
        p0.y = pf.y - shapeLength * sinTheta;
        if (shapeFill > 0.0 && shapeLength != 0.0) {
            poly[0].x = pf.x - shapeLength * shapeFill * cosTheta;
            poly[0].y = pf.y - shapeLength * shapeFill * sinTheta;
            poly[4] = poly[0];
        } else {
            poly[0].x = poly[0].y = poly[4].x = poly[4].y = NaN;
        }
        poly[1].x = p0.x - shapeWidth * sinTheta;
        poly[1].y = p0.y + shapeWidth * cosTheta;
        poly[2].x = pf.x;
        poly[2].y = pf.y;
        poly[3].x = p0.x + shapeWidth * sinTheta;
        poly[3].y = p0.y - shapeWidth * cosTheta;
        /*
         * Polygon done. Now move the first point towards the second so that
         * the corners at the end of the line are inside the arrowhead.
         */

        poly[LINE_PT_IN_ARROW] = poly[ORIG_PT_IN_ARROW];
        if (updateFirstPoint) {
            poly[LINE_PT_IN_ARROW].x -= backup*cosTheta;
            poly[LINE_PT_IN_ARROW].y -= backup*sinTheta;
        }

        return poly[LINE_PT_IN_ARROW];
    }
    return pf;
}

void
TkPathTranslateArrow(TkPathArrowDescr *arrowDescr, double deltaX, double deltaY)
{
    if (arrowDescr->arrowPointsPtr != NULL) {
        int i;
        for (i = 0; i < PTS_IN_ARROW; i++) {
            arrowDescr->arrowPointsPtr[i].x += deltaX;
            arrowDescr->arrowPointsPtr[i].y += deltaY;
        }
    }
}

void
TkPathScaleArrow(TkPathArrowDescr *arrowDescr, double originX, double originY,
         double scaleX, double scaleY)
{
    if (arrowDescr->arrowPointsPtr != NULL) {
        int i;
        TkPathPoint *pt;
        for (i = 0, pt = arrowDescr->arrowPointsPtr;
         i < PTS_IN_ARROW; i++, pt++) {
            pt->x = originX + scaleX*(pt->x - originX);
            pt->y = originX + scaleX*(pt->y - originX);
        }
    }
}

void
TkPathFreeArrow(TkPathArrowDescr *arrowDescr)
{
    if (arrowDescr->arrowPointsPtr != NULL) {
        ckfree((char *)arrowDescr->arrowPointsPtr);
        arrowDescr->arrowPointsPtr = NULL;
    }
}

typedef TkPathPoint *PathPointPtr;

int
TkPathGetSegmentsFromPathAtomList(TkPathAtom *firstAtom,
        TkPathPoint **firstPt, TkPathPoint *secondPt,
        TkPathPoint *penultPt, TkPathPoint **lastPt)
{
    TkPathAtom *atom;
    int i;

    *firstPt = *lastPt = NULL;
    secondPt->x = secondPt->y = penultPt->x = penultPt->y = NaN;

    if (firstAtom && firstAtom->type != TK_PATH_ATOM_M) {
        Tcl_Panic("Invalid path! Path must start with M(move) atom");
    }
    for (i = 0, atom = firstAtom; atom; atom = atom->nextPtr) {
        switch (atom->type) {
            case TK_PATH_ATOM_M:
            {
                TkMoveToAtom *moveto = (TkMoveToAtom *)atom;
                if (i == 0) {
                    *firstPt = (PathPointPtr)&moveto->x;
                    i++;
                } else if (i == 1) {
                    secondPt->x = moveto->x;
                    secondPt->y = moveto->y;
                    i++;
                }
                penultPt->x = penultPt->y = NaN;
                *lastPt = (PathPointPtr)&moveto->x;
                break;
            }
            case TK_PATH_ATOM_L:
            {
                TkLineToAtom *lineto = (TkLineToAtom *)atom;
                if (i == 1) {
                    secondPt->x = lineto->x;
                    secondPt->y = lineto->y;
                    i++;
                }
                *penultPt = **lastPt;
                *lastPt = (PathPointPtr)&lineto->x;
                break;
            }
            case TK_PATH_ATOM_A: {
                TkArcAtom *arc = (TkArcAtom *) atom;

                /*
         * Draw an elliptical arc from the current point to (x, y).
         * The points are on an ellipse with x-radius <radX> and
         * y-radius <radY>. The ellipse is rotated by <angle> degrees.
         * If the arc is less than 180 degrees, <largeArcFlag> is
         * zero, else it is one. If the arc is to be drawn in cw
         * direction, sweepFlag is one, and zero for the ccw
         * direction.
         * NB: the start and end points may not coincide else the
         * result is undefined. If you want to make a circle just
         * do two 180 degree arcs.
                 */
                int result;
                double cx, cy, rx, ry;
                double theta1, dtheta;
                TkPathPoint startPt = **lastPt;
                double phi = DEGREES_TO_RADIANS * arc->angle;

                result = TkPathEndpointToCentralArcParameters(
                        startPt.x, startPt.y,
                        arc->x, arc->y, arc->radX, arc->radY,
                        phi,
                        arc->largeArcFlag, arc->sweepFlag,
                        &cx, &cy, &rx, &ry,
                        &theta1, &dtheta);
                if (result == TK_PATH_ARC_OK) {
                    double sinTheta2, cosTheta2;
                    double sinPhi = sin(phi);
                    double cosPhi = cos(phi);
                    double theta2 = theta1 + dtheta;

                    if (dtheta > 0.0) {
                        theta1 += M_PI*0.01;
                        theta2 -= M_PI*0.01;
                    } else {
                        theta1 -= M_PI*0.01;
                        theta2 += M_PI*0.01;
                    }

                    sinTheta2 = sin(theta2);
                    cosTheta2 = cos(theta2);

                    if (i == 1) {
                        double sinTheta1 = sin(theta1);
                        double cosTheta1 = cos(theta1);
                        /* auxiliary point 1 */
                        secondPt->x = cx + rx * cosTheta1 * cosPhi -
                ry * sinTheta1 * sinPhi;
                        secondPt->y = cy + rx * cosTheta1 * sinPhi +
                ry * sinTheta1 * cosPhi;
                        i++;
                    }
                    /* auxiliary point 2 */
                    penultPt->x = cx + rx * cosTheta2 * cosPhi -
            ry * sinTheta2 * sinPhi;
                    penultPt->y = cy + rx * cosTheta2 * sinPhi +
            ry * sinTheta2 * cosPhi;
                } else {
                    /* arc is line */
                    if (i == 1) {
                        secondPt->x = arc->x;
                        secondPt->y = arc->y;
                        i++;
                    }
                    *penultPt = **lastPt;
                }

                *lastPt = (PathPointPtr)&arc->x;
                break;
            }
            case TK_PATH_ATOM_Q: {
                TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atom;
                if (i == 1) {
                    secondPt->x = quad->ctrlX;
                    secondPt->y = quad->ctrlY;
                    i++;
                }
                penultPt->x = quad->ctrlX;
                penultPt->y = quad->ctrlY;
                *lastPt = (PathPointPtr)&quad->anchorX;
                break;
            }
            case TK_PATH_ATOM_C: {
                TkCurveToAtom *curve = (TkCurveToAtom *) atom;
                if (i == 1) {
                    secondPt->x = curve->ctrlX1;
                    secondPt->y = curve->ctrlY1;
                    i++;
                }
                penultPt->x = curve->ctrlX2;
                penultPt->y = curve->ctrlY2;
                *lastPt = (PathPointPtr)&curve->anchorX;
                break;
            }
            case TK_PATH_ATOM_Z: {
                TkCloseAtom *closeAtom = (TkCloseAtom *) atom;
                *penultPt = **lastPt;
                *lastPt = (PathPointPtr)&closeAtom->x;
                break;
            }
            case TK_PATH_ATOM_ELLIPSE:
            case TK_PATH_ATOM_RECT: {
                /* Empty. */
                break;
            }
            default:
                break;
        }
    }
    return (i >= 2) ? TCL_OK : TCL_ERROR;
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvEllipse.c.


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/*
 * tkCanvEllipse.c --
 *
 *    This file implements the circle and ellipse canvas items modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

/*
 * The structure below defines the record for each circle and ellipse item.
 */

typedef struct EllipseItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                             * path types.  MUST BE FIRST IN STRUCTURE. */
    char type;            /* Circle or ellipse. */
    double center[2];        /* Center coord. */
    double rx;            /* Radius. Circle uses rx for overall radius. */
    double ry;
} EllipseItem;

enum {
    kOvalTypeCircle,
    kOvalTypeEllipse
};

/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputeEllipseBbox(Tk_PathCanvas canvas, EllipseItem *ellPtr);
static int    ConfigureEllipse(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int flags);
static int    CreateAny(Tcl_Interp *interp, Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[], char type);
static int    CreateCircle(Tcl_Interp *interp,
            Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static int    CreateEllipse(Tcl_Interp *interp,
            Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static void    DeleteEllipse(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display);
static void    DisplayEllipse(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display, Drawable drawable,
            int x, int y, int width, int height);
static void    EllipseBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int mask);
static int    EllipseCoords(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static int    EllipseToArea(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *rectPtr);
static int    EllipseToPdf(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int prepass);
static double    EllipseToPoint(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *coordPtr);
static void    ScaleEllipse(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslateEllipse(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);


enum {
    ELLIPSE_OPTION_INDEX_RX            = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 0)),
    ELLIPSE_OPTION_INDEX_RY            = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
    ELLIPSE_OPTION_INDEX_R            = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 2)),
};

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_FILL
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

#define TK_PATH_OPTION_SPEC_R(typeName)            \
    {TK_OPTION_DOUBLE, "-rx", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, rx),        \
    0, 0, ELLIPSE_OPTION_INDEX_R}

#define TK_PATH_OPTION_SPEC_RX(typeName)            \
    {TK_OPTION_DOUBLE, "-rx", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, rx),        \
    0, 0, ELLIPSE_OPTION_INDEX_RX}

#define TK_PATH_OPTION_SPEC_RY(typeName)            \
    {TK_OPTION_DOUBLE, "-ry", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, ry),        \
    0, 0, ELLIPSE_OPTION_INDEX_RY}

static Tk_OptionSpec optionSpecsCircle[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_R(EllipseItem),
    TK_PATH_OPTION_SPEC_END
};

static Tk_OptionSpec optionSpecsEllipse[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_RX(EllipseItem),
    TK_PATH_OPTION_SPEC_RY(EllipseItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below define the 'circle' and 'ellipse' item types by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeCircle = {
    "circle",                /* name */
    sizeof(EllipseItem),        /* itemSize */
    CreateCircle,            /* createProc */
    optionSpecsCircle,            /* optionSpecs */
    ConfigureEllipse,            /* configureProc */
    EllipseCoords,            /* coordProc */
    DeleteEllipse,            /* deleteProc */
    DisplayEllipse,            /* displayProc */
    0,                    /* flags */
    EllipseBbox,            /* bboxProc */
    EllipseToPoint,            /* pointProc */
    EllipseToArea,            /* areaProc */
    EllipseToPdf,            /* pdfProc */
    ScaleEllipse,            /* scaleProc */
    TranslateEllipse,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

Tk_PathItemType tkPathTypeEllipse = {
    "ellipse",                /* name */
    sizeof(EllipseItem),        /* itemSize */
    CreateEllipse,            /* createProc */
    optionSpecsEllipse,            /* optionSpecs */
    ConfigureEllipse,            /* configureProc */
    EllipseCoords,            /* coordProc */
    DeleteEllipse,            /* deleteProc */
    DisplayEllipse,            /* displayProc */
    0,                    /* flags */
    EllipseBbox,            /* bboxProc */
    EllipseToPoint,            /* pointProc */
    EllipseToArea,            /* areaProc */
    EllipseToPdf,            /* pdfProc */
    ScaleEllipse,            /* scaleProc */
    TranslateEllipse,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

static int
CreateCircle(Tcl_Interp *interp, Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kOvalTypeCircle);
}

static int
CreateEllipse(Tcl_Interp *interp, Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kOvalTypeEllipse);
}

static int
CreateAny(Tcl_Interp *interp, Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[], char type)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
    Tk_OptionTable optionTable;
    int    i;

    if (objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    ellPtr->type = type;

    if (ellPtr->type == kOvalTypeCircle) {
    optionTable = Tk_CreateOptionTable(interp, optionSpecsCircle);
    } else {
    optionTable = Tk_CreateOptionTable(interp, optionSpecsEllipse);
    }
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) ellPtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for (i = 1; i < objc; i++) {
        char *arg = Tcl_GetString(objv[i]);
        if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if (TkPathCoordsForPointItems(interp, canvas, ellPtr->center, i, objv) != TCL_OK) {
        goto error;
    }
    if (ConfigureEllipse(interp, canvas, itemPtr, objc-i, objv+i, 0) == TCL_OK) {
        return TCL_OK;
    }

    error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeleteEllipse(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
EllipseCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    int result;

    result = TkPathCoordsForPointItems(interp, canvas, ellPtr->center, objc, objv);
    if ((result == TCL_OK) && ((objc == 1) || (objc == 2))) {
        ComputeEllipseBbox(canvas, ellPtr);
    }
    return result;
}

static TkPathRect
GetBareBbox(EllipseItem *ellPtr)
{
    TkPathRect bbox;

    bbox.x1 = ellPtr->center[0] - ellPtr->rx;
    bbox.y1 = ellPtr->center[1] - ellPtr->ry;
    bbox.x2 = ellPtr->center[0] + ellPtr->rx;
    bbox.y2 = ellPtr->center[1] + ellPtr->ry;
    return bbox;
}

static void
ComputeEllipseBbox(Tk_PathCanvas canvas, EllipseItem *ellPtr)
{
    Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
    Tk_PathItem *itemPtr = &itemExPtr->header;
    Tk_PathStyle style;
    Tk_PathState state = itemExPtr->header.state;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if (state == TK_PATHSTATE_HIDDEN) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    itemPtr->bbox = GetBareBbox(ellPtr);
    itemPtr->totalBbox = TkPathGetGenericPathTotalBboxFromBare(NULL, &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr, &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigureEllipse(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[], int flags)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int mask, error;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) ellPtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }
    if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr, mask) != TCL_OK) {
        continue;
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    stylePtr->mask |= mask;
    }

    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity   = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));
    ellPtr->rx = MAX(0.0, ellPtr->rx);
    ellPtr->ry = MAX(0.0, ellPtr->ry);
    if (ellPtr->type == kOvalTypeCircle) {
        /* Practical. */
        ellPtr->ry = ellPtr->rx;
    }
    if (error) {
    Tcl_SetObjResult(interp, errorResult);
    Tcl_DecrRefCount(errorResult);
    return TCL_ERROR;
    } else {
    ComputeEllipseBbox(canvas, ellPtr);
    return TCL_OK;
    }
}

static void
DeleteEllipse(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    if (stylePtr->fill != NULL) {
    TkPathFreePathColor(stylePtr->fill);
    }
    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    Tk_FreeConfigOptions((char *) itemPtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

static void
DisplayEllipse(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display, Drawable drawable,
        int x, int y, int width, int height)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
#if 0
    TkPathRect bbox;
#endif
    TkPathAtom *atomPtr;
    TkEllipseAtom ellAtom;
    Tk_PathStyle style;

    /*
     * We create the atom on the fly to save some memory.
     */
    atomPtr = (TkPathAtom *)&ellAtom;
    atomPtr->nextPtr = NULL;
    atomPtr->type = TK_PATH_ATOM_ELLIPSE;
    ellAtom.cx = ellPtr->center[0];
    ellAtom.cy = ellPtr->center[1];
    ellAtom.rx = ellPtr->rx;
    ellAtom.ry = ellPtr->ry;

    itemPtr->bbox = GetBareBbox(ellPtr);
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &style,
        &m, &itemPtr->bbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
EllipseBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    ComputeEllipseBbox(canvas, ellPtr);
}

static double
EllipseToPoint(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *pointPtr)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathStyle style;
    TkPathMatrix *mPtr;
    double bareOval[4];
    double width, dist;
    int rectiLinear = 0;
    int haveDist = 0;
    int filled;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    filled = HaveAnyFillFromPathColor(style.fill);
    width = 0.0;
    if (style.strokeColor != NULL) {
        width = style.strokeWidth;
    }
    mPtr = style.matrixPtr;
    if (mPtr == NULL) {
        rectiLinear = 1;
        bareOval[0] = ellPtr->center[0] - ellPtr->rx;
        bareOval[1] = ellPtr->center[1] - ellPtr->ry;
        bareOval[2] = ellPtr->center[0] + ellPtr->rx;
        bareOval[3] = ellPtr->center[1] + ellPtr->ry;

        /* For tiny points make it simple. */
        if ((ellPtr->rx <= 2.0) && (ellPtr->ry <= 2.0)) {
            dist = hypot(ellPtr->center[0] - pointPtr[0], ellPtr->center[1] - pointPtr[1]);
            dist = MAX(0.0, dist - (ellPtr->rx + ellPtr->ry)/2.0);
            haveDist = 1;
        }
    } else if ((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {
        double rx, ry;

        /* This is a situation we can treat in a simplified way. Apply the transform here. */
        rectiLinear = 1;
        bareOval[0] = mPtr->a * (ellPtr->center[0] - ellPtr->rx) + mPtr->tx;
        bareOval[1] = mPtr->d * (ellPtr->center[1] - ellPtr->ry) + mPtr->ty;
        bareOval[2] = mPtr->a * (ellPtr->center[0] + ellPtr->rx) + mPtr->tx;
        bareOval[3] = mPtr->d * (ellPtr->center[1] + ellPtr->ry) + mPtr->ty;

        /* For tiny points make it simple. */
        rx = fabs(bareOval[0] - bareOval[2])/2.0;
        ry = fabs(bareOval[1] - bareOval[3])/2.0;
        if ((rx <= 2.0) && (ry <= 2.0)) {
            dist = hypot((bareOval[0] + bareOval[2]/2.0) - pointPtr[0],
                    (bareOval[1] + bareOval[3]/2.0) - pointPtr[1]);
            dist = MAX(0.0, dist - (rx + ry)/2.0);
            haveDist = 1;
        }
    }
    if (!haveDist) {
        if (rectiLinear) {
            dist = TkOvalToPoint(bareOval, width, filled, pointPtr);
        } else {
            TkPathAtom *atomPtr;
            TkEllipseAtom ellAtom;

            /*
             * We create the atom on the fly to save some memory.
             */
            atomPtr = (TkPathAtom *)&ellAtom;
            atomPtr->nextPtr = NULL;
            atomPtr->type = TK_PATH_ATOM_ELLIPSE;
            ellAtom.cx = ellPtr->center[0];
            ellAtom.cy = ellPtr->center[1];
            ellAtom.rx = ellPtr->rx;
            ellAtom.ry = ellPtr->ry;
            dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, atomPtr,
                    TK_PATH_NUMSEGEMENTS_Ellipse+1, pointPtr);
        }
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
EllipseToArea(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *areaPtr)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathStyle style;
    TkPathMatrix *mPtr;
    double center[2], bareOval[4], halfWidth;
    int rectiLinear = 0;
    int result;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    halfWidth = 0.0;
    center[0] = ellPtr->center[0];
    center[1] = ellPtr->center[1];
    if (style.strokeColor != NULL) {
        halfWidth = style.strokeWidth/2.0;
    }
    mPtr = style.matrixPtr;
    if (mPtr == NULL) {
        rectiLinear = 1;
        bareOval[0] = center[0] - ellPtr->rx;
        bareOval[1] = center[1] - ellPtr->ry;
        bareOval[2] = center[0] + ellPtr->rx;
        bareOval[3] = center[1] + ellPtr->ry;
    } else if ((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {
        /*
     * This is a situation we can treat in a simplified way.
     * Apply the transform here.
     */
        rectiLinear = 1;
        bareOval[0] = mPtr->a * (center[0] - ellPtr->rx) + mPtr->tx;
        bareOval[1] = mPtr->d * (center[1] - ellPtr->ry) + mPtr->ty;
        bareOval[2] = mPtr->a * (center[0] + ellPtr->rx) + mPtr->tx;
        bareOval[3] = mPtr->d * (center[1] + ellPtr->ry) + mPtr->ty;
    center[0] = mPtr->a * center[0] + mPtr->tx;
    center[1] = mPtr->d * center[1] + mPtr->ty;
    }

    if (rectiLinear) {
        double oval[4];

        /* @@@ Assuming untransformed strokes */
        oval[0] = bareOval[0] - halfWidth;
        oval[1] = bareOval[1] - halfWidth;
        oval[2] = bareOval[2] + halfWidth;
        oval[3] = bareOval[3] + halfWidth;

        result = TkOvalToArea(oval, areaPtr);

        /*
         * If the rectangle appears to overlap the oval and the oval
         * isn't filled, do one more check to see if perhaps all four
         * of the rectangle's corners are totally inside the oval's
         * unfilled center, in which case we should return "outside".
         */
        if ((result == 0) && (style.strokeColor != NULL)
                && !HaveAnyFillFromPathColor(style.fill)) {
            double width, height;
            double xDelta1, yDelta1, xDelta2, yDelta2;

            width = (bareOval[2] - bareOval[0])/2.0 - halfWidth;
            height = (bareOval[3] - bareOval[1])/2.0 - halfWidth;
            if ((width <= 0.0) || (height <= 0.0)) {
                return 0;
            }
            xDelta1 = (areaPtr[0] - center[0])/width;
            xDelta1 *= xDelta1;
            yDelta1 = (areaPtr[1] - center[1])/height;
            yDelta1 *= yDelta1;
            xDelta2 = (areaPtr[2] - center[0])/width;
            xDelta2 *= xDelta2;
            yDelta2 = (areaPtr[3] - center[1])/height;
            yDelta2 *= yDelta2;
            if (((xDelta1 + yDelta1) < 1.0)
                    && ((xDelta1 + yDelta2) < 1.0)
                    && ((xDelta2 + yDelta1) < 1.0)
                    && ((xDelta2 + yDelta2) < 1.0)) {
                result = -1;
            }
        }
    } else {
        TkPathAtom *atomPtr;
        TkEllipseAtom ellAtom;

        /*
         * We create the atom on the fly to save some memory.
         */
        atomPtr = (TkPathAtom *)&ellAtom;
        atomPtr->nextPtr = NULL;
        atomPtr->type = TK_PATH_ATOM_ELLIPSE;
        ellAtom.cx = ellPtr->center[0];
        ellAtom.cy = ellPtr->center[1];
        ellAtom.rx = ellPtr->rx;
        ellAtom.ry = ellPtr->ry;
        result = TkPathGenericPathToArea(canvas, itemPtr, &style, atomPtr,
                TK_PATH_NUMSEGEMENTS_Ellipse+1, areaPtr);
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static int
EllipseToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    TkEllipseAtom atom;
    Tk_PathState state = itemPtr->state;
    int result;

    if (state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if (state == TK_PATHSTATE_HIDDEN) {
    return TCL_OK;
    }
    /* We create the atom on the fly to save some memory.  */
    atomPtr = (TkPathAtom *)&atom;
    atomPtr->nextPtr = NULL;
    atomPtr->type = TK_PATH_ATOM_ELLIPSE;
    atom.cx = ellPtr->center[0];
    atom.cy = ellPtr->center[1];
    atom.rx = ellPtr->rx;
    atom.ry = ellPtr->ry;
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    result = TkPathPdf(interp, atomPtr, &style, &itemPtr->bbox, objc, objv);
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScaleEllipse(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double originX, double originY, double scaleX, double scaleY)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX, &scaleY);

    ellPtr->center[0] = originX + scaleX*(ellPtr->center[0] - originX);
    ellPtr->center[1] = originY + scaleY*(ellPtr->center[1] - originY);
    ellPtr->rx *= scaleX;
    ellPtr->ry *= scaleY;
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslateEllipse(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double deltaX, double deltaY)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    ellPtr->center[0] += deltaX;
    ellPtr->center[1] += deltaY;
#if 0
    TkPathTranslatePathAtoms(ellPtr->atomPtr, deltaX, deltaY);
#endif
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvGroup.c.


































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
 * tkCanvGroup.c --
 *
 *    This file implements a line canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

enum {
    /* When childs update themself so they set all
     * its ancestors dirty bbox flag so they know
     * when they need to recompute its bbox. */
    GROUP_FLAG_DIRTY_BBOX        = (1L << 0)
};

/*
 * The structure below defines the record for each path item.
 */

typedef struct GroupItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                             * path types.  MUST BE FIRST IN STRUCTURE. */
    TkPathRect totalBbox;        /* Bounding box including stroke.
                 * Untransformed coordinates. */
    long flags;            /* Various flags, see enum. */
} GroupItem;


/*
 * Prototypes for procedures defined in this file:
 */

void        GroupUpdateBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr);
static int    ConfigureGroup(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int flags);
static int    CreateGroup(Tcl_Interp *interp,
            Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static void    DeleteGroup(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display);
static void    DisplayGroup(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display, Drawable drawable,
            int x, int y, int width, int height);
static void    GroupBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int flags);
static int    GroupCoords(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static int    GroupToArea(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *rectPtr);
static int    GroupToPdf(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int prepass);
static double    GroupToPoint(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *coordPtr);
static void    ScaleGroup(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslateGroup(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_FILL
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeGroup = {
    "group",                /* name */
    sizeof(GroupItem),            /* itemSize */
    CreateGroup,            /* createProc */
    optionSpecs,            /* optionSpecs */
    ConfigureGroup,            /* configureProc */
    GroupCoords,            /* coordProc */
    DeleteGroup,            /* deleteProc */
    DisplayGroup,            /* displayProc */
    0,                    /* flags */
    GroupBbox,                /* bboxProc */
    GroupToPoint,            /* pointProc */
    GroupToArea,            /* areaProc */
    GroupToPdf,                /* pdfProc */
    ScaleGroup,                /* scaleProc */
    TranslateGroup,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};


static int
CreateGroup(Tcl_Interp *interp,
    Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &groupPtr->headerEx;
    Tk_OptionTable optionTable;

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    groupPtr->totalBbox = TkPathNewEmptyPathRect();
    groupPtr->flags = 0L;
    itemExPtr->header.x1 = itemExPtr->header.x2 =
    itemExPtr->header.y1 = itemExPtr->header.y2 = -1;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) groupPtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }
    if (ConfigureGroup(interp, canvas, itemPtr, objc, objv, 0) == TCL_OK) {
        return TCL_OK;
    }

error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeleteGroup(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}


static int
ConfigureGroup(Tcl_Interp *interp, Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr, int objc,
        Tcl_Obj *const objv[], int flags)
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &groupPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) groupPtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }
    if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr, mask) != TCL_OK) {
        continue;
    }

    /*
     * Root item's -tags and -parent is read only.
     */
    if (itemPtr->id == 0) {
        if (mask & TK_PATH_CORE_OPTION_PARENT) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("root items -parent is not configurable", -1));
        continue;
        }
        if (mask & TK_PATH_CORE_OPTION_TAGS) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("root items -tags is not configurable", -1));
        continue;
        }
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    stylePtr->mask |= mask;
    }
    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity   = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));

    /*
     * We must notify all children to update themself
     * since they may inherit features.
     */
    if (!error) {
    TkPathGroupItemConfigured(canvas, itemPtr, mask);
    }
    if (error) {
    Tcl_SetObjResult(interp, errorResult);
    Tcl_DecrRefCount(errorResult);
    return TCL_ERROR;
    } else {
    return TCL_OK;
    }
}

static void
DeleteGroup(Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr, Display *display)
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &groupPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    if (stylePtr->fill != NULL) {
    TkPathFreePathColor(stylePtr->fill);
    }
    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    Tk_FreeConfigOptions((char *) itemPtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

static void
DisplayGroup(Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr, Display *display, Drawable drawable,
    int x, int y, int width, int height)
{
    /* Empty. */
}

static void
GroupBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int flags)
{
    /* Empty. */
}

static int
GroupCoords(Tcl_Interp *interp,
    Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[])
{
    Tcl_SetObjResult(interp,
        Tcl_NewStringObj("group items have no coords", -1));
    return TCL_ERROR;
}

static int
GroupToArea(Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr, double *rectPtr)
{
    /*
     * This says that the group is entirely outside any area.
     */
    return -1;
}

static double
GroupToPoint(Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr, double *coordPtr)
{
    /*
     * This says that the group is nowhere.
     */
    return DBL_MAX;
}

static int
GroupToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    return TCL_OK;
}

static void
ScaleGroup(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int compensate, double originX, double originY,
    double scaleX, double scaleY)
{
    TkPathCanvasScaleGroup(canvas, itemPtr, compensate,
    originX, originY, scaleX, scaleY);
    /* @@@ TODO: we could handle bbox ourselves? */
}

static void
TranslateGroup(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int compensate, double deltaX, double deltaY)
{
    TkPathCanvasTranslateGroup(canvas, itemPtr, compensate, deltaX, deltaY);
    /* @@@ TODO: we could handle bbox ourselves? */
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathCanvasSetGroupDirtyBbox --
 *
 *    This function is invoked by canvas code to tell us that one or
 *    more of our childrens have changed somehow so that our bbox
 *    need to be recomputed next time TkPathCanvasUpdateGroupBbox
 *    is called.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

void
TkPathCanvasSetGroupDirtyBbox(Tk_PathItem *itemPtr)
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;
    groupPtr->flags &= GROUP_FLAG_DIRTY_BBOX;
}

void
TkPathCanvasUpdateGroupBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr)
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;

    if (groupPtr->flags & GROUP_FLAG_DIRTY_BBOX) {
    TkPathCanvasGroupBbox(canvas, itemPtr,
        &itemPtr->x1, &itemPtr->y1, &itemPtr->x2, &itemPtr->y2);
    groupPtr->flags &= ~GROUP_FLAG_DIRTY_BBOX;
    }
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvImage.c.




























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
/*
 * tkCanvPimage.c --
 *
 *    This file implements an image canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

#define BBOX_OUT 2.0

/*
 * The structure below defines the record for each path item.
 */

typedef struct PimageItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                 * types.  MUST BE FIRST IN STRUCTURE. */
    Tk_PathCanvas canvas;   /* Canvas containing item. */
    double fillOpacity;
    TkPathMatrix *matrixPtr;        /*  a  b   default (NULL): 1 0
                c  d           0 1
                tx ty            0 0 */
    double coord[2];        /* nw coord. */
    Tcl_Obj *imageObj;        /* Object describing the -image option.
                 * NULL means no image right now. */
    Tk_Image image;        /* Image to display in window, or NULL if
                 * no image at present. */
    Tk_PhotoHandle photo;
    double width;        /* If 0 use natural width or height. */
    double height;
    Tk_Anchor anchor;       /* Where to anchor image relative to (x,y). */
    XColor *tintColor;
    double tintAmount;
    int interpolation;
    TkPathRect *srcRegionPtr;
} PimageItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputePimageBbox(Tk_PathCanvas canvas, PimageItem *pimagePtr);
static int    ConfigurePimage(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int flags);
static int    CreatePimage(Tcl_Interp *interp,
            Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static void    DeletePimage(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display);
static void    DisplayPimage(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display, Drawable drawable,
            int x, int y, int width, int height);
static void    PimageBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int mask);
static int    PimageCoords(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static int    PimageToArea(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *rectPtr);
static int    PimageToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *item, int objc, Tcl_Obj *const objv[],
            int prepass);
static double    PimageToPoint(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *coordPtr);
static void    ScalePimage(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslatePimage(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);
static void    ImageChangedProc(ClientData clientData,
            int x, int y, int width, int height, int imgWidth,
            int imgHeight);
static void    PimageStyleChangedProc(ClientData clientData, int flags);

enum {
    PIMAGE_OPTION_INDEX_FILLOPACITY =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
    PIMAGE_OPTION_INDEX_HEIGHT =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 2)),
    PIMAGE_OPTION_INDEX_IMAGE =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 3)),
    PIMAGE_OPTION_INDEX_MATRIX =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 4)),
    PIMAGE_OPTION_INDEX_WIDTH =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 5)),
    PIMAGE_OPTION_INDEX_ANCHOR =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 6)),
    PIMAGE_OPTION_INDEX_TINTCOLOR =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 7)),
    PIMAGE_OPTION_INDEX_TINTAMOUNT =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 8)),
    PIMAGE_OPTION_INDEX_INTERPOLATION =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 9)),
    PIMAGE_OPTION_INDEX_SRCREGION =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 10))
};

static const char *imageInterpolationST[] = {
    "none", "fast", "best", NULL
};

static int    PathRectSetOption(ClientData clientData, Tcl_Interp *interp,
            Tk_Window tkwin, Tcl_Obj **value, char *recordPtr,
            int internalOffset, char *oldInternalPtr, int flags);
static Tcl_Obj *PathRectGetOption(ClientData clientData, Tk_Window tkwin,
            char *recordPtr, int internalOffset);
static void    PathRectRestoreOption(ClientData clientData, Tk_Window tkwin,
            char *internalPtr, char *oldInternalPtr);
static void    PathRectFreeOption(ClientData clientData, Tk_Window tkwin,
            char *internalPtr);

#define TK_PATH_STYLE_CUSTOM_OPTION_PATHRECT    \
    static Tk_ObjCustomOption pathRectCO = {    \
    "pathrect",                \
    PathRectSetOption,            \
    PathRectGetOption,            \
    PathRectRestoreOption,            \
    PathRectFreeOption,            \
    (ClientData) NULL            \
    };

TK_PATH_STYLE_CUSTOM_OPTION_MATRIX
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_STATE
TK_PATH_STYLE_CUSTOM_OPTION_PATHRECT

#define TK_PATH_OPTION_SPEC_FILLOPACITY                \
    {TK_OPTION_DOUBLE, "-fillopacity", NULL, NULL,        \
    "1.0", -1, Tk_Offset(PimageItem, fillOpacity),        \
    0, 0, PIMAGE_OPTION_INDEX_FILLOPACITY}

#define TK_PATH_OPTION_SPEC_HEIGHT                    \
    {TK_OPTION_DOUBLE, "-height", NULL, NULL,            \
    "0", -1, Tk_Offset(PimageItem, height),            \
    0, 0, PIMAGE_OPTION_INDEX_HEIGHT}

#define TK_PATH_OPTION_SPEC_IMAGE                    \
    {TK_OPTION_STRING, "-image", NULL, NULL,            \
    NULL, Tk_Offset(PimageItem, imageObj), -1,        \
    TK_OPTION_NULL_OK, 0, PIMAGE_OPTION_INDEX_IMAGE}

#define TK_PATH_OPTION_SPEC_MATRIX                    \
    {TK_OPTION_CUSTOM, "-matrix", NULL, NULL,            \
    NULL, -1, Tk_Offset(PimageItem, matrixPtr),        \
    TK_OPTION_NULL_OK, (ClientData) &matrixCO,        \
    PIMAGE_OPTION_INDEX_MATRIX}

#define TK_PATH_OPTION_SPEC_WIDTH                    \
    {TK_OPTION_DOUBLE, "-width", NULL, NULL,            \
    "0", -1, Tk_Offset(PimageItem, width),            \
    0, 0, PIMAGE_OPTION_INDEX_WIDTH}

#define TK_PATH_OPTION_SPEC_ANCHOR                    \
    {TK_OPTION_ANCHOR, "-anchor", NULL, NULL,            \
    "nw", -1, Tk_Offset(PimageItem, anchor),        \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_TINTCOLOR                \
    {TK_OPTION_COLOR, "-tintcolor", NULL, NULL,            \
    NULL, -1, Tk_Offset(PimageItem, tintColor),        \
    TK_OPTION_NULL_OK, 0, PIMAGE_OPTION_INDEX_TINTCOLOR}

#define TK_PATH_OPTION_SPEC_TINTAMOUNT                \
    {TK_OPTION_DOUBLE, "-tintamount", NULL, NULL,        \
    "0.5", -1, Tk_Offset(PimageItem, tintAmount),        \
    0, 0, PIMAGE_OPTION_INDEX_TINTAMOUNT}

#define TK_PATH_OPTION_SPEC_INTERPOLATION                \
    {TK_OPTION_STRING_TABLE, "-interpolation", NULL, NULL,  \
    "fast", -1, Tk_Offset(PimageItem, interpolation),   \
    0, (ClientData) imageInterpolationST, 0}

#define TK_PATH_OPTION_SPEC_SRCREGION                \
    {TK_OPTION_CUSTOM, "-srcregion", NULL, NULL,        \
    NULL, -1, Tk_Offset(PimageItem, srcRegionPtr),        \
    TK_OPTION_NULL_OK, (ClientData) &pathRectCO,        \
    PIMAGE_OPTION_INDEX_SRCREGION}

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_MATRIX,
    TK_PATH_OPTION_SPEC_FILLOPACITY,
    TK_PATH_OPTION_SPEC_HEIGHT,
    TK_PATH_OPTION_SPEC_IMAGE,
    TK_PATH_OPTION_SPEC_WIDTH,
    TK_PATH_OPTION_SPEC_ANCHOR,
    TK_PATH_OPTION_SPEC_TINTCOLOR,
    TK_PATH_OPTION_SPEC_TINTAMOUNT,
    TK_PATH_OPTION_SPEC_INTERPOLATION,
    TK_PATH_OPTION_SPEC_SRCREGION,
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'image' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeImage = {
    "image",                /* name */
    sizeof(PimageItem),            /* itemSize */
    CreatePimage,            /* createProc */
    optionSpecs,            /* optionSpecs */
    ConfigurePimage,            /* configureProc */
    PimageCoords,            /* coordProc */
    DeletePimage,            /* deleteProc */
    DisplayPimage,            /* displayProc */
    0,                    /* flags */
    PimageBbox,                /* bboxProc */
    PimageToPoint,            /* pointProc */
    PimageToArea,            /* areaProc */
    PimageToPdf,            /* pdfProc */
    ScalePimage,            /* scaleProc */
    TranslatePimage,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

static int
CreatePimage(Tcl_Interp *interp, Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr, int objc, Tcl_Obj *const objv[])
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pimagePtr->headerEx;
    int    i;
    Tk_OptionTable optionTable;

    if (objc == 0) {
    Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    pimagePtr->fillOpacity = 1.0;
    pimagePtr->matrixPtr = NULL;
    pimagePtr->imageObj = NULL;
    pimagePtr->image = NULL;
    pimagePtr->photo = NULL;
    pimagePtr->height = 0;
    pimagePtr->width = 0;
    pimagePtr->anchor = TK_ANCHOR_NW;
    pimagePtr->tintColor = NULL;
    pimagePtr->tintAmount = 0.0;
    pimagePtr->interpolation = TK_PATH_IMAGEINTERPOLATION_Fast;
    pimagePtr->srcRegionPtr = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) pimagePtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
    goto error;
    }

    for (i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
    if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
        break;
    }
    }
    if (TkPathCoordsForPointItems(interp, canvas, pimagePtr->coord, i, objv)
    != TCL_OK) {
    goto error;
    }
    if (ConfigurePimage(interp, canvas, itemPtr, objc-i, objv+i, 0)
    == TCL_OK) {
    return TCL_OK;
    }

    error:
    /*
     * NB: We must unlink the item here since the ConfigurePimage()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePimage(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
PimageCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[])
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    int result;

    result = TkPathCoordsForPointItems(interp, canvas, pimagePtr->coord, objc, objv);
    if ((result == TCL_OK) && ((objc == 1) || (objc == 2))) {
    ComputePimageBbox(canvas, pimagePtr);
    }
    return result;
}

/*
 * This is just a convenience function to obtain any style matrix.
 */

static TkPathMatrix
GetTMatrix(PimageItem *pimagePtr)
{
    TkPathMatrix *matrixPtr;
    Tk_PathStyle *stylePtr;
    TkPathMatrix matrix = TkPathCanvasInheritTMatrix((Tk_PathItem *) pimagePtr);

    matrixPtr = pimagePtr->matrixPtr;
    if (pimagePtr->headerEx.styleInst != NULL) {
    stylePtr = pimagePtr->headerEx.styleInst->masterPtr;
    if (stylePtr->mask & TK_PATH_STYLE_OPTION_MATRIX) {
        matrixPtr = stylePtr->matrixPtr;
    }
    }
    if (matrixPtr != NULL) {
    TkPathMMulTMatrix(matrixPtr, &matrix);
    }
    return matrix;
}

void
ComputePimageBbox(Tk_PathCanvas canvas, PimageItem *pimagePtr)
{
    Tk_PathItem *itemPtr = (Tk_PathItem *)pimagePtr;
    Tk_PathState state = pimagePtr->headerEx.header.state;
    TkPathMatrix matrix;
    double width = 0.0, height = 0.0;
    TkPathRect bbox;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if (pimagePtr->image == NULL) {
    pimagePtr->headerEx.header.x1 = pimagePtr->headerEx.header.x2 =
    pimagePtr->headerEx.header.y1 = pimagePtr->headerEx.header.y2 = -1;
    return;
    }
    if (pimagePtr->srcRegionPtr) {
    width  = pimagePtr->srcRegionPtr->x2 - pimagePtr->srcRegionPtr->x1;
    height = pimagePtr->srcRegionPtr->y2 - pimagePtr->srcRegionPtr->y1;
    } else {
    int iwidth = 0, iheight = 0;
    Tk_SizeOfImage(pimagePtr->image, &iwidth, &iheight);
    width = iwidth;
    height = iheight;
    }
    if (pimagePtr->width > 0.0) {
    width = pimagePtr->width + 1.0;
    }
    if (pimagePtr->height > 0.0) {
    height = pimagePtr->height + 1.0;
    }

    switch (pimagePtr->anchor) {
    case TK_ANCHOR_NW:
    case TK_ANCHOR_W:
    case TK_ANCHOR_SW:
        bbox.x1 = pimagePtr->coord[0];
        break;

    case TK_ANCHOR_N:
    case TK_ANCHOR_CENTER:
    case TK_ANCHOR_S:
        bbox.x1 = pimagePtr->coord[0] - width / 2.0;
        break;

    case TK_ANCHOR_NE:
    case TK_ANCHOR_E:
    case TK_ANCHOR_SE:
        bbox.x1 = pimagePtr->coord[0] - width;
        break;
    }
    bbox.x2 = bbox.x1 + width;

    switch (pimagePtr->anchor) {
    case TK_ANCHOR_NW:
    case TK_ANCHOR_N:
    case TK_ANCHOR_NE:
        bbox.y1 = pimagePtr->coord[1];
        break;

    case TK_ANCHOR_W:
    case TK_ANCHOR_CENTER:
    case TK_ANCHOR_E:
        bbox.y1 = pimagePtr->coord[1] - height / 2.0;
        break;

    case TK_ANCHOR_SW:
    case TK_ANCHOR_S:
    case TK_ANCHOR_SE:
        bbox.y1 = pimagePtr->coord[1] - height;
        break;
    }
    bbox.y2 = bbox.y1 + height;

    bbox.x1 -= BBOX_OUT;
    bbox.x2 += BBOX_OUT;
    bbox.y1 -= BBOX_OUT;
    bbox.y2 += BBOX_OUT;

    itemPtr->bbox = bbox;
    itemPtr->totalBbox = itemPtr->bbox;    /* FIXME */
    matrix = GetTMatrix(pimagePtr);
    TkPathSetGenericPathHeaderBbox(&pimagePtr->headerEx.header, &matrix, &bbox);
}

static int
ConfigurePimage(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int flags)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    Tk_Window tkwin;
    Tk_Image image;
    Tk_PhotoHandle photo;
    Tk_SavedOptions savedOptions;
    Tk_PathItem *parentPtr;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) pimagePtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
	    if (errorResult != NULL) {
            Tcl_DecrRefCount(errorResult);
	    }
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }

    /*
     * Take each custom option, not handled in Tk_SetOptions, in turn.
     */
    if (mask & TK_PATH_CORE_OPTION_PARENT) {
        if (TkPathCanvasFindGroup(interp, canvas, itemPtr->parentObj,
                      &parentPtr) != TCL_OK) {
        continue;
        }
        TkPathCanvasSetParent(parentPtr, itemPtr);
    } else if ((itemPtr->id != 0) && (itemPtr->parentPtr == NULL)) {
        /*
         * If item not root and parent not set we must set it
         * to root by default.
         */
        TkPathCanvasSetParentToRoot(itemPtr);
    }

    /*
     * If we have got a style name it's options take precedence
     * over the actual path configuration options. This is how SVG does it.
     * Good or bad?
     */
    if (mask & TK_PATH_CORE_OPTION_STYLENAME) {
        TkPathStyleInst *styleInst = NULL;

        if (pimagePtr->headerEx.styleObj != NULL) {
        styleInst = TkPathGetStyle(interp,
            Tcl_GetString(pimagePtr->headerEx.styleObj),
            TkPathCanvasStyleTable(canvas), PimageStyleChangedProc,
            (ClientData) itemPtr);
        if (styleInst == NULL) {
            continue;
        }
        } else {
        styleInst = NULL;
        }
        if (pimagePtr->headerEx.styleInst != NULL) {
        TkPathFreeStyle(pimagePtr->headerEx.styleInst);
        }
        pimagePtr->headerEx.styleInst = styleInst;
    }

    /*
     * Create the image.  Save the old image around and don't free it
     * until after the new one is allocated.  This keeps the reference
     * count from going to zero so the image doesn't have to be recreated
     * if it hasn't changed.
     */
    if (!error && (mask & PIMAGE_OPTION_INDEX_IMAGE)) {
        if (pimagePtr->imageObj != NULL) {
        const char *name = Tcl_GetString(pimagePtr->imageObj);

        image = Tk_GetImage(interp, tkwin, name,
            ImageChangedProc, (ClientData) pimagePtr);
        if (image == NULL) {
            continue;
        }
        photo = Tk_FindPhoto(interp, name);
        if (photo == NULL) {
		    Tk_FreeImage(image);
		    Tcl_SetObjResult(interp,
			Tcl_NewStringObj("no photo with the given name", -1));
            continue;
        }
        } else {
        image = NULL;
        photo = NULL;
        }
        if (pimagePtr->image != NULL) {
        Tk_FreeImage(pimagePtr->image);
        }
        pimagePtr->image = image;
        pimagePtr->photo = photo;
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    }
    pimagePtr->fillOpacity = MAX(0.0, MIN(1.0, pimagePtr->fillOpacity));

    if (errorResult != NULL) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    }
    /*
     * Recompute bounding box for path.
     */
    ComputePimageBbox(canvas, pimagePtr);
    return TCL_OK;
}

static void
DeletePimage(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;

    if (pimagePtr->headerEx.styleInst != NULL) {
    TkPathFreeStyle(pimagePtr->headerEx.styleInst);
    }
    if (pimagePtr->image != NULL) {
    Tk_FreeImage(pimagePtr->image);
    }
    Tk_FreeConfigOptions((char *) pimagePtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPimage(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display,
    Drawable drawable,
    int x, int y, int width, int height)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathContext ctx;

    ctx = ContextOfCanvas(canvas);
    TkPathPushTMatrix(ctx, &m);
    m = GetTMatrix(pimagePtr);
    TkPathPushTMatrix(ctx, &m);
    /* @@@ Maybe we should taking care of x, y etc.? */
    TkPathImage(ctx, pimagePtr->image, pimagePtr->photo,
        itemPtr->bbox.x1+BBOX_OUT, itemPtr->bbox.y1+BBOX_OUT,
        pimagePtr->width, pimagePtr->height, pimagePtr->fillOpacity,
        pimagePtr->tintColor, pimagePtr->tintAmount,
        pimagePtr->interpolation,
        pimagePtr->srcRegionPtr);
}

static void
PimageBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    ComputePimageBbox(canvas, pimagePtr);
}

static double
PimageToPoint(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *pointPtr)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    TkPathMatrix m = GetTMatrix(pimagePtr);
    return TkPathRectToPointWithMatrix(itemPtr->bbox, &m, pointPtr);
}

static int
PimageToArea(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *areaPtr)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    TkPathMatrix m = GetTMatrix(pimagePtr);
    return TkPathRectToAreaWithMatrix(itemPtr->bbox, &m, areaPtr);
}

static int
PimageToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    Tk_PathStyle style;
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    Tcl_Obj *ret, *obj;
    TkPathMatrix matrix = { 1., 0., 0., 1., 0., 0.};
    Tk_PathState state = itemPtr->state;
    Tk_PhotoImageBlock block;
    int x, y;
    unsigned char *p;
    double tintR, tintG, tintB, tintAmount;
    TkPathRect srcRegion, bbox;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if ((pimagePtr->photo == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
    return TCL_OK;    /* nothing to display */
    }
    Tk_PhotoGetImage(pimagePtr->photo, &block);
    if ((block.width <= 0) || (block.height <= 0)) {
    return TCL_OK;    /* nothing to display */
    }
    if (pimagePtr->srcRegionPtr == NULL) {
    srcRegion.x1 = 0;
    srcRegion.y1 = 0;
    srcRegion.x2 = block.width;
    srcRegion.y2 = block.height;
    } else {
    srcRegion = *pimagePtr->srcRegionPtr;
    }
    bbox = itemPtr->bbox;
    /* undo effect of BBOX_OUT */
    bbox.x1 += BBOX_OUT - 1;
    bbox.x2 -= BBOX_OUT + 1;
    bbox.y1 += BBOX_OUT - 1;
    bbox.y2 -= BBOX_OUT + 1;

    if (objc > 0) {
    long id;
    int retc, opacity, tx, ty;
    int zLen;
    double scaleX, scaleY, dx, dy;
    Tcl_Obj *pixObj, *nameObj, **retv;

    /*
     * Callback provided, first make alpha mask.
     */
    opacity = (int)(pimagePtr->fillOpacity * 256);
    if (opacity > 256) {
        opacity = 256;
    } else if (opacity < 0) {
        opacity = 0;
    }
    pixObj = Tcl_NewObj();
    p = Tcl_SetByteArrayLength(pixObj, block.width * block.height);
    for (y = 0; y < block.height; y++) {
        unsigned char *q = block.pixelPtr + y * block.pitch;

        for (x = 0; x < block.width; x++) {
        *p++ = ((int) q[block.offset[3]] * opacity) >> 8;
        q += block.pixelSize;
        }
    }
    zLen = 0;
    if (Tcl_ZlibDeflate(interp, TCL_ZLIB_FORMAT_ZLIB,
            pixObj, 9, NULL) == TCL_OK) {
    p = Tcl_GetByteArrayFromObj(Tcl_GetObjResult(interp), &zLen);
    if (zLen > 0) {
        Tcl_DecrRefCount(pixObj);
        pixObj = Tcl_GetObjResult(interp);
    }
    Tcl_IncrRefCount(pixObj);
    }
    Tcl_ResetResult(interp);
    obj = Tcl_NewObj();
    Tcl_AppendPrintfToObj(obj, "<<\n/Type /XObject\n/Subtype /Image\n"
                  "/ColorSpace /DeviceGray\n/BitsPerComponent 8\n"
                  "/Width %d\n/Height %d\n",
                  block.width, block.height);
    if (zLen > 0) {
        Tcl_AppendPrintfToObj(obj, "/Filter /FlateDecode\n"
                  "/Length %d\n>>\nstream\n", zLen);
    } else
    {
        Tcl_AppendPrintfToObj(obj, "/Length %d\n>>\nstream\n",
                  block.width * block.height);
    }
    Tcl_AppendObjToObj(obj, pixObj);
    Tcl_DecrRefCount(pixObj);
    Tcl_AppendToObj(obj, "\nendstream\n", 11);
    ret = Tcl_DuplicateObj(objv[0]);
    Tcl_IncrRefCount(ret);
    if ((Tcl_ListObjAppendElement(interp, ret,
                      Tcl_NewIntObj(block.width)) != TCL_OK) ||
        (Tcl_ListObjAppendElement(interp, ret,
                      Tcl_NewIntObj(block.height)) != TCL_OK) ||
        (Tcl_ListObjAppendElement(interp, ret, obj) != TCL_OK)) {
        Tcl_DecrRefCount(ret);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if (Tcl_EvalObjEx(interp, ret, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(ret);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(ret);
    /*
     * Remember result information (object id of alpha channel).
     */
    if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                   &retc, &retv) != TCL_OK) {
        return TCL_ERROR;
    }
    if (retc < 1) {
        Tcl_SetResult(interp, (char *) "missing PDF id", TCL_STATIC);
        return TCL_ERROR;
    }
    Tcl_GetLongFromObj(NULL, retv[0], &id);
    /*
     * Make RGB image.
     */
    tintAmount = pimagePtr->tintAmount;
    if ((pimagePtr->tintColor != NULL) && (tintAmount > 0.0)) {
        if (tintAmount > 1.0) {
        tintAmount = 1.0;
        }
        tintR = (double) (pimagePtr->tintColor->red >> 8) / 0xff;
        tintG = (double) (pimagePtr->tintColor->green >> 8) / 0xff;
        tintB = (double) (pimagePtr->tintColor->blue >> 8) / 0xff;
    } else {
        tintAmount = 0.0;
        tintR = 0.0;
        tintG = 0.0;
        tintB = 0.0;
    }
    pixObj = Tcl_NewObj();
    p = Tcl_SetByteArrayLength(pixObj, block.width * block.height * 3);
    for (y = 0; y < block.height; y++) {
        unsigned char R, G, B;
        unsigned char *q = block.pixelPtr + y * block.pitch;

        for (x = 0; x < block.width; x++) {
        R = q[block.offset[0]];
        G = q[block.offset[1]];
        B = q[block.offset[2]];
        if (tintAmount > 0.0) {
            int RR, GG, BB;

            RR = (int)( (1.0 - tintAmount) * R +
            (tintAmount * tintR * 0.2126 * R +
             tintAmount * tintR * 0.7152 * G +
             tintAmount * tintR * 0.0722 * B));
            GG = (int)((1.0 - tintAmount) * G +
            (tintAmount * tintG * 0.2126 * R +
             tintAmount * tintG * 0.7152 * G +
             tintAmount * tintG * 0.0722 * B));
            BB = (int)((1.0 - tintAmount) * B +
            (tintAmount * tintB * 0.2126 * R +
             tintAmount * tintB * 0.7152 * G +
             tintAmount * tintB * 0.0722 * B));
            R = (RR > 0xff) ? 0xff : RR;
            G = (GG > 0xff) ? 0xff : GG;
            B = (BB > 0xff) ? 0xff : BB;
        }
        *p++ = R;
        *p++ = G;
        *p++ = B;
        q += block.pixelSize;
        }
    }
    zLen = 0;
    if (Tcl_ZlibDeflate(interp, TCL_ZLIB_FORMAT_ZLIB,
            pixObj, 9, NULL) == TCL_OK) {
    p = Tcl_GetByteArrayFromObj(Tcl_GetObjResult(interp), &zLen);
    if (zLen > 0) {
        Tcl_DecrRefCount(pixObj);
        pixObj = Tcl_GetObjResult(interp);
    }
    Tcl_IncrRefCount(pixObj);
    }
    Tcl_ResetResult(interp);
    obj = Tcl_NewObj();
    Tcl_AppendPrintfToObj(obj, "<<\n/Type /XObject\n/Subtype /Image\n"
                  "/ColorSpace /DeviceRGB\n/BitsPerComponent 8\n"
                  "/Width %d\n/Height %d\n/SMask %ld 0 R\n",
                  block.width, block.height, id);
    if ((pimagePtr->interpolation == TK_PATH_IMAGEINTERPOLATION_Fast) ||
        (pimagePtr->interpolation == TK_PATH_IMAGEINTERPOLATION_Best)) {
        Tcl_AppendToObj(obj, "/Interpolate true\n", 18);
    }
    if (zLen > 0) {
        Tcl_AppendPrintfToObj(obj, "/Filter /FlateDecode\n"
                  "/Length %d\n>>\nstream\n", zLen);
    } else
    {
        Tcl_AppendPrintfToObj(obj, "/Length %d\n>>\nstream\n",
                  block.width * block.height * 3);
    }
    Tcl_AppendObjToObj(obj, pixObj);
    Tcl_DecrRefCount(pixObj);
    Tcl_AppendToObj(obj, "\nendstream\n", 11);
    ret = Tcl_DuplicateObj(objv[0]);
    Tcl_IncrRefCount(ret);
    if ((Tcl_ListObjAppendElement(interp, ret,
                      Tcl_NewIntObj(block.width)) != TCL_OK) ||
        (Tcl_ListObjAppendElement(interp, ret,
                      Tcl_NewIntObj(block.height)) != TCL_OK) ||
        (Tcl_ListObjAppendElement(interp, ret, obj) != TCL_OK)) {
        Tcl_DecrRefCount(ret);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if (Tcl_EvalObjEx(interp, ret, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(ret);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(ret);
    /*
     * Remember result information (name of RGB image).
     */
    if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                   &retc, &retv) != TCL_OK) {
        return TCL_ERROR;
    }
    if (retc < 2) {
        Tcl_SetResult(interp, (char *) "missing PDF id/name", TCL_STATIC);
        return TCL_ERROR;
    }
    nameObj = retv[1];
    Tcl_IncrRefCount(nameObj);
    /*
     * Print image object(s).
     */
    ret = Tcl_NewObj();
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    matrix = GetTMatrix(pimagePtr);
    /* TkPathMatrix */
    TkPathPdfNumber(ret, 6, matrix.a, " ");
    TkPathPdfNumber(ret, 6, matrix.b, " ");
    TkPathPdfNumber(ret, 6, matrix.c, " ");
    TkPathPdfNumber(ret, 6, matrix.d, " ");
    TkPathPdfNumber(ret, 3, matrix.tx, " ");
    TkPathPdfNumber(ret, 3, matrix.ty, " cm\n");
    /* translate */
    Tcl_AppendToObj(ret, "1 0 0 1 ", 8);
    TkPathPdfNumber(ret, 3, bbox.x1, " ");
    TkPathPdfNumber(ret, 3, bbox.y2, " cm\n");
    /* clipping */
    Tcl_AppendToObj(ret, "0 0 m ", 6);
    TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " 0 l ");
    TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " ");
    TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l 0 ");
    TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l W n\n");
    tx = ty = 1;
    dx = srcRegion.x2 - srcRegion.x1;
    if (dx > block.width) {
        tx += (int)((srcRegion.x2 - srcRegion.x1) / block.width);
    } else {
        srcRegion.x1 = fmod(srcRegion.x1, (double) block.width);
        srcRegion.x2 = srcRegion.x1 + dx;
        if (srcRegion.x1 != 0) {
        tx++;
        }
    }
    dy = srcRegion.y2 - srcRegion.y1;
    if (dy > block.height) {
        ty += (int)((srcRegion.y2 - srcRegion.y1) / block.height);
    } else {
        srcRegion.y1 = fmod(srcRegion.y1, (double) block.height);
        srcRegion.y2 = srcRegion.y1 + dy;
        if (srcRegion.y1 != 0) {
        ty++;
        }
    }
    if (pimagePtr->width > 0) {
        scaleX = pimagePtr->width / (double) block.width;
        scaleX /= (srcRegion.x2 - srcRegion.x1) / block.width;
    } else {
        scaleX = 1.0;
    }
    if (pimagePtr->height > 0) {
        scaleY = pimagePtr->height / (double) block.height;
        scaleY /= (srcRegion.y2 - srcRegion.y1) / block.height;
    } else {
        scaleY = 1.0;
    }
    for (x = 0; x < tx; x++) {
        for (y = 0; y < ty; y++) {
        /* translate */
        Tcl_AppendToObj(ret, "q\n1 0 0 1 ", 10);
        TkPathPdfNumber(ret, 6,    (x * block.width - srcRegion.x1) *
                scaleX, " ");
        TkPathPdfNumber(ret, 6,    -(srcRegion.y2 - (ty - y) *
                      block.height) * scaleY, " cm\n");
        /* scale to requested image size */
        TkPathPdfNumber(ret, 6,    scaleX * block.width, " 0 0 ");
        TkPathPdfNumber(ret, 6,    -scaleY * block.height, " 0 0 cm\n");
        /* print it */
        Tcl_AppendPrintfToObj(ret, "/%s Do\nQ\n",
            Tcl_GetString(nameObj));
        }
    }
    Tcl_DecrRefCount(nameObj);
    Tcl_SetObjResult(interp, ret);
    TkPathCanvasFreeInheritedStyle(&style);
    } else {
    /*
     * No callback, make direct RGB image without alpha mask.
     */
    ret = Tcl_NewObj();
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    matrix = GetTMatrix(pimagePtr);
    /* TkPathMatrix */
    TkPathPdfNumber(ret, 6, matrix.a, " ");
    TkPathPdfNumber(ret, 6, matrix.b, " ");
    TkPathPdfNumber(ret, 6, matrix.c, " ");
    TkPathPdfNumber(ret, 6, matrix.d, " ");
    TkPathPdfNumber(ret, 3, matrix.tx, " ");
    TkPathPdfNumber(ret, 3, matrix.ty, " cm\n");
    /* translate */
    Tcl_AppendToObj(ret, "1 0 0 1 ", 8);
    TkPathPdfNumber(ret, 3, bbox.x1, " ");
    TkPathPdfNumber(ret, 3, bbox.y2, " cm\n");
    /* clipping */
    Tcl_AppendToObj(ret, "0 0 m ", 6);
    TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " 0 l ");
    TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " ");
    TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l 0 ");
    TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l W n\n");
    /* scale to requested image size, no cropping/tiling */
    TkPathPdfNumber(ret, 6,    (pimagePtr->width > 0) ? pimagePtr->width :
            (double) block.width, " 0 0 ");
    TkPathPdfNumber(ret, 6,    (pimagePtr->height > 0) ? pimagePtr->height :
            (double) -block.height, " 0 0 cm\n");
    Tcl_AppendToObj(ret, "BI\n", 3);
    Tcl_AppendPrintfToObj(ret, "/W %d\n/H %d\n", block.width, block.height);
    Tcl_AppendToObj(ret, "/CS /RGB\n/BPC 8\nID\n", 19);
    tintAmount = pimagePtr->tintAmount;
    if ((pimagePtr->tintColor != NULL) && (tintAmount > 0.0)) {
        if (tintAmount > 1.0) {
        tintAmount = 1.0;
        }
        tintR = (double) (pimagePtr->tintColor->red >> 8) / 0xff;
        tintG = (double) (pimagePtr->tintColor->green >> 8) / 0xff;
        tintB = (double) (pimagePtr->tintColor->blue >> 8) / 0xff;
    } else {
        tintAmount = 0.0;
        tintR = 0.0;
        tintG = 0.0;
        tintB = 0.0;
    }
    obj = Tcl_NewObj();
    p = Tcl_SetByteArrayLength(obj, block.width * block.height * 3);
    for (y = 0; y < block.height; y++) {
        unsigned char R, G, B;
        unsigned char *q = block.pixelPtr + y * block.pitch;

        for (x = 0; x < block.width; x++) {
        R = q[block.offset[0]];
        G = q[block.offset[1]];
        B = q[block.offset[2]];
        if (tintAmount > 0.0) {
            int RR, GG, BB;

            RR = (int)((1.0 - tintAmount) * R +
            (tintAmount * tintR * 0.2126 * R +
             tintAmount * tintR * 0.7152 * G +
             tintAmount * tintR * 0.0722 * B));
            GG = (int)((1.0 - tintAmount) * G +
            (tintAmount * tintG * 0.2126 * R +
             tintAmount * tintG * 0.7152 * G +
             tintAmount * tintG * 0.0722 * B));
            BB = (int)((1.0 - tintAmount) * B +
            (tintAmount * tintB * 0.2126 * R +
             tintAmount * tintB * 0.7152 * G +
             tintAmount * tintB * 0.0722 * B));
            R = (RR > 0xff) ? 0xff : RR;
            G = (GG > 0xff) ? 0xff : GG;
            B = (BB > 0xff) ? 0xff : BB;
        }
        *p++ = R;
        *p++ = G;
        *p++ = B;
        q += block.pixelSize;
        }
    }
    Tcl_AppendObjToObj(ret, obj);
    Tcl_DecrRefCount(obj);
    Tcl_AppendToObj(ret, "\nEI\n", 4);
    Tcl_SetObjResult(interp, ret);
    TkPathCanvasFreeInheritedStyle(&style);
    }
    return TCL_OK;
}

static void
ScalePimage(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int compensate, double originX, double originY,
    double scaleX, double scaleY)
{
    /* Skip? */
}

static void
TranslatePimage(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double deltaX, double deltaY)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    /* Translate coordinates. */
    pimagePtr->coord[0] += deltaX;
    pimagePtr->coord[1] += deltaY;
    /* Recompute bounding box. */
    ComputePimageBbox(canvas, pimagePtr);
}

static void
ImageChangedProc(
    ClientData clientData,    /* Pointer to canvas item for image. */
    int x, int y,        /* Upper left pixel (within image)
                 * that must be redisplayed. */
    int width, int height,    /* Dimensions of area to redisplay
                 * (may be <= 0). */
    int imgWidth, int imgHeight)/* New dimensions of image. */
{
    PimageItem *pimagePtr = (PimageItem *) clientData;

    /*
     * If the image's size changed and it's not anchored at its
     * northwest corner then just redisplay the entire area of the
     * image.  This is a bit over-conservative, but we need to do
     * something because a size change also means a position change.
     */

    /* @@@ MUST consider our own width and height settings as well and TMatrix. */

    if (((pimagePtr->headerEx.header.x2 - pimagePtr->headerEx.header.x1) !=
     imgWidth)
    || ((pimagePtr->headerEx.header.y2 - pimagePtr->headerEx.header.y1) !=
        imgHeight)) {
    x = y = 0;
    width = imgWidth;
    height = imgHeight;
    Tk_PathCanvasEventuallyRedraw(pimagePtr->headerEx.canvas,
        pimagePtr->headerEx.header.x1, pimagePtr->headerEx.header.y1,
        pimagePtr->headerEx.header.x2, pimagePtr->headerEx.header.y2);
    }
    ComputePimageBbox(pimagePtr->headerEx.canvas, pimagePtr);
    Tk_PathCanvasEventuallyRedraw(pimagePtr->headerEx.canvas,
        pimagePtr->headerEx.header.x1 + x,
        pimagePtr->headerEx.header.y1 + y,
        (int) (pimagePtr->headerEx.header.x1 + x + width),
        (int) (pimagePtr->headerEx.header.y1 + y + height));
}

static void
PimageStyleChangedProc(ClientData clientData, int flags)
{
    Tk_PathItem *itemPtr = (Tk_PathItem *) clientData;
    PimageItem *pimagePtr = (PimageItem *) itemPtr;

    if (flags) {
    if (flags & TK_PATH_STYLE_FLAG_DELETE) {
        TkPathFreeStyle(pimagePtr->headerEx.styleInst);
        pimagePtr->headerEx.styleInst = NULL;
        Tcl_DecrRefCount(pimagePtr->headerEx.styleObj);
        pimagePtr->headerEx.styleObj = NULL;
    }
    Tk_PathCanvasEventuallyRedraw(pimagePtr->headerEx.canvas,
        itemPtr->x1, itemPtr->y1,
        itemPtr->x2, itemPtr->y2);
    }
}

static int
PathGetPathRect(
    Tcl_Interp* interp,
    const char *list,   /* Object containg the lists for the matrix. */
    TkPathRect *rectPtr) /* Where to store TkPathMatrix corresponding
                 * to list. Must be allocated! */
{
    const char **argv = NULL;
    int i, argc;
    int result = TCL_OK;
    double tmp[4];

    /* Check matrix consistency. */
    if (Tcl_SplitList(interp, list, &argc, &argv) != TCL_OK) {
    result = TCL_ERROR;
    goto bail;
    }
    if (argc != 4) {
    Tcl_AppendResult(interp, "rect \"", list, "\" is inconsistent",
        (char *) NULL);
    result = TCL_ERROR;
    goto bail;
    }

    /* Take each row in turn. */
    for (i = 0; i < 4; i++) {
    if (Tcl_GetDouble(interp, argv[i], &(tmp[i])) != TCL_OK) {
        Tcl_AppendResult(interp, "rect \"", list, "\" is inconsistent", (char *) NULL);
        result = TCL_ERROR;
        goto bail;
    }
    }

    /* TkPathRect. */
    rectPtr->x1  = tmp[0];
    rectPtr->y1  = tmp[1];
    rectPtr->x2  = tmp[2];
    rectPtr->y2  = tmp[3];

bail:
    if (argv != NULL) {
    Tcl_Free((char *) argv);
    }
    return result;
}

static int
PathGetTclObjFromPathRect(
    Tcl_Interp* interp,
    TkPathRect *rectPtr,
    Tcl_Obj **listObjPtrPtr)
{
    Tcl_Obj     *listObj;

    /* @@@ Error handling remains. */

    listObj = Tcl_NewListObj( 0, (Tcl_Obj **) NULL );
    if (rectPtr != NULL) {
    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(rectPtr->x1));
    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(rectPtr->y1));
    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(rectPtr->x2));
    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(rectPtr->y2));
    }
    *listObjPtrPtr = listObj;
    return TCL_OK;
}

/*
 * The -srcregion custom option.
 */

static int
PathRectSetOption(
    ClientData clientData,
    Tcl_Interp *interp,     /* Current interp; may be used for errors. */
    Tk_Window tkwin,        /* Window for which option is being set. */
    Tcl_Obj **value,        /* Pointer to the pointer to the value object.
                 * We use a pointer to the pointer because
                 * we may need to return a value (NULL). */
    char *recordPtr,        /* Pointer to storage for the widget record. */
    int internalOffset,     /* Offset within *recordPtr at which the
                   internal value is to be stored. */
    char *oldInternalPtr,   /* Pointer to storage for the old value. */
    int flags)          /* Flags for the option, set Tk_SetOptions. */
{
    char *internalPtr;      /* Points to location in record where
                 * internal representation of value should
                 * be stored, or NULL. */
    char *list;
    int length;
    Tcl_Obj *valuePtr;
    TkPathRect *newPtr;

    valuePtr = *value;
    if (internalOffset >= 0) {
    internalPtr = recordPtr + internalOffset;
    } else {
    internalPtr = NULL;
    }
    if ((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
    valuePtr = NULL;
    }
    if (internalPtr != NULL) {
    if (valuePtr != NULL) {
        list = Tcl_GetStringFromObj(valuePtr, &length);
        newPtr = (TkPathRect *) ckalloc(sizeof(TkPathRect));
        if (PathGetPathRect(interp, list, newPtr) != TCL_OK) {
        ckfree((char *) newPtr);
        return TCL_ERROR;
        }
    } else {
        newPtr = NULL;
    }
    *((TkPathRect **) oldInternalPtr) = *((TkPathRect **) internalPtr);
    *((TkPathRect **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

static Tcl_Obj *
PathRectGetOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,        /* Pointer to widget record. */
    int internalOffset)     /* Offset within *recordPtr containing the
                 * value. */
{
    char    *internalPtr;
    TkPathRect     *pathRectPtr;
    Tcl_Obj     *listObj;

    /* @@@ An alternative to this could be to have an objOffset in option table. */
    internalPtr = recordPtr + internalOffset;
    pathRectPtr = *((TkPathRect **) internalPtr);
    PathGetTclObjFromPathRect(NULL, pathRectPtr, &listObj);
    return listObj;
}

static void
PathRectRestoreOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,      /* Pointer to storage for value. */
    char *oldInternalPtr)   /* Pointer to old value. */
{
    *(TkPathRect **)internalPtr = *(TkPathRect **)oldInternalPtr;
}

static void
PathRectFreeOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)      /* Pointer to storage for value. */
{
    if (*((char **) internalPtr) != NULL) {
    ckfree(*((char **) internalPtr));
    *((char **) internalPtr) = NULL;
    }
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvLine.c.
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/*
 * tkCanvPline.c --
 *
 *    This file implements a line canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PlineItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                             * path types.  MUST BE FIRST IN STRUCTURE. */
    TkPathRect coords;        /* Coordinates (unorders bare bbox). */
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
} PlineItem;


/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputePlineBbox(Tk_PathCanvas canvas, PlineItem *plinePtr);
static int    ConfigurePline(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc,
                    Tcl_Obj *const objv[], int flags);
static int    CreatePline(Tcl_Interp *interp,
                    Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static void    DeletePline(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display);
static void    DisplayPline(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display, Drawable drawable,
            int x, int y, int width, int height);
static void    PlineBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask);
static int    ProcessCoords(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc, Tcl_Obj *const objv[]);
static int    PlineCoords(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static int    PlineToArea(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *rectPtr);
static int    PlineToPdf(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int prepass);
static double    PlineToPoint(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *coordPtr);
static void    ScalePline(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslatePline(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);
static TkPathAtom * MakePathAtoms(PlineItem *plinePtr);
static int      ConfigureArrows(Tk_PathCanvas canvas, PlineItem *linePtr);


TK_PATH_STYLE_CUSTOM_OPTION_MATRIX
TK_PATH_STYLE_CUSTOM_OPTION_DASH
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(PlineItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(PlineItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeLine = {
    "line",                /* name */
    sizeof(PlineItem),            /* itemSize */
    CreatePline,            /* createProc */
    optionSpecs,            /* optionSpecs */
    ConfigurePline,            /* configureProc */
    PlineCoords,            /* coordProc */
    DeletePline,            /* deleteProc */
    DisplayPline,            /* displayProc */
    0,                    /* flags */
    PlineBbox,                /* bboxProc */
    PlineToPoint,            /* pointProc */
    PlineToArea,            /* areaProc */
    PlineToPdf,                /* pdfProc */
    ScalePline,                /* scaleProc */
    TranslatePline,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

static int
CreatePline(Tcl_Interp *interp, Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;
    int    i;
    Tk_OptionTable optionTable;

    if (objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    TkPathArrowDescrInit(&plinePtr->startarrow);
    TkPathArrowDescrInit(&plinePtr->endarrow);

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) plinePtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for (i = 1; i < objc; i++) {
        char *arg = Tcl_GetString(objv[i]);
        if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if (ProcessCoords(interp, canvas, itemPtr, i, objv) != TCL_OK) {
        goto error;
    }
    if (ConfigurePline(interp, canvas, itemPtr, objc-i, objv+i, 0) == TCL_OK) {
        return TCL_OK;
    }

    error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePline(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
ProcessCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    TkPathRect *p = &plinePtr->coords;

    if (objc == 0) {
        Tcl_Obj *obj = Tcl_NewObj();
        Tcl_Obj *subobj = Tcl_NewDoubleObj(p->x1);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(p->y1);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(p->x2);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(p->y2);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if ((objc == 1) || (objc == 4)) {
        if (objc==1) {
            if (Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) &objv) != TCL_OK) {
                return TCL_ERROR;
            } else if (objc != 4) {
                Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # coordinates: expected 0 or 4", -1));
                return TCL_ERROR;
            }
        }
        if ((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0], &p->x1) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1], &p->y1) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[2], &p->x2) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[3], &p->y2) != TCL_OK)) {
            return TCL_ERROR;
        }
    } else {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # coordinates: expected 0 or 4", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

static int
PlineCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    int result;

    result = ProcessCoords(interp, canvas, itemPtr, objc, objv);
    if ((result == TCL_OK) && ((objc == 1) || (objc == 4))) {
        ConfigureArrows(canvas, plinePtr);
    ComputePlineBbox(canvas, plinePtr);
    }
    return result;
}

static void
ComputePlineBbox(Tk_PathCanvas canvas, PlineItem *plinePtr)
{
    Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;
    Tk_PathItem *itemPtr = &itemExPtr->header;
    Tk_PathStyle style;
    Tk_PathState state = itemExPtr->header.state;
    TkPathRect r;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if (state == TK_PATHSTATE_HIDDEN) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    r.x1 = MIN(plinePtr->coords.x1, plinePtr->coords.x2);
    r.x2 = MAX(plinePtr->coords.x1, plinePtr->coords.x2);
    r.y1 = MIN(plinePtr->coords.y1, plinePtr->coords.y2);
    r.y2 = MAX(plinePtr->coords.y1, plinePtr->coords.y2);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->startarrow);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->endarrow);
    itemPtr->bbox = r;
    itemPtr->totalBbox = TkPathGetGenericPathTotalBboxFromBare(NULL, &style, &r);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr, &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigurePline(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[], int flags)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error;
    int mask = 0;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
        if (!error) {
            if (Tk_SetOptions(interp, (char *) plinePtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr, mask) != TCL_OK) {
            continue;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if (!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }

    /*
     * Setup arrowheads, if needed. If arrowheads are turned off, restore the
     * line's endpoints (they were shortened when the arrowheads were added).
     */
    ConfigureArrows(canvas, plinePtr);

    if (error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputePlineBbox(canvas, plinePtr);
        return TCL_OK;
    }
}

static TkPathAtom *
MakePathAtoms(PlineItem *plinePtr)
{
    TkPathAtom *atomPtr;

    atomPtr = TkPathNewMoveToAtom(plinePtr->coords.x1, plinePtr->coords.y1);
    atomPtr->nextPtr = TkPathNewLineToAtom(plinePtr->coords.x2, plinePtr->coords.y2);
    return atomPtr;
}

static void
DeletePline(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;

    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    TkPathFreeArrow(&plinePtr->startarrow);
    TkPathFreeArrow(&plinePtr->endarrow);
    Tk_FreeConfigOptions((char *) itemPtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPline(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display, Drawable drawable,
        int x, int y, int width, int height)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathRect r;
    TkPathAtom *atomPtr;
    Tk_PathStyle style;

    r.x1 = MIN(plinePtr->coords.x1, plinePtr->coords.x2);
    r.x2 = MAX(plinePtr->coords.x1, plinePtr->coords.x2);
    r.y1 = MIN(plinePtr->coords.y1, plinePtr->coords.y2);
    r.y2 = MAX(plinePtr->coords.y1, plinePtr->coords.y2);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->startarrow);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->endarrow);

    atomPtr = MakePathAtoms(plinePtr);
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &style, &m, &r);
    TkPathFreeAtoms(atomPtr);

    /*
     * Display arrowheads, if they are wanted.
     */
    TkPathDisplayArrow(canvas, &plinePtr->startarrow, &style, &m, &r);
    TkPathDisplayArrow(canvas, &plinePtr->endarrow, &style, &m, &r);

    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PlineBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    ComputePlineBbox(canvas, plinePtr);
}

static double
PlineToPoint(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *pointPtr)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    double point;

    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);

    /* @@@ Perhaps we should do a simplified treatment here instead of the generic. */
    atomPtr = MakePathAtoms(plinePtr);
    point = TkPathGenericPathToPoint(canvas, itemPtr, &style,
            atomPtr, 2, pointPtr);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return point;
}

static int
PlineToArea(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *areaPtr)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    int area;

    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);

    /* @@@ Perhaps we should do a simplified treatment here instead of the generic. */
    atomPtr = MakePathAtoms(plinePtr);
    area = TkPathGenericPathToArea(canvas, itemPtr, &style,
            atomPtr, 2, areaPtr);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

static int
PlineToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathState state = itemPtr->state;
    int result;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if (state == TK_PATHSTATE_HIDDEN) {
    return TCL_OK;
    }
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    atomPtr = TkPathNewMoveToAtom(plinePtr->coords.x1, plinePtr->coords.y1);
    atomPtr->nextPtr = TkPathNewLineToAtom(plinePtr->coords.x2, plinePtr->coords.y2);
    result = TkPathPdf(interp, atomPtr, &style, &itemPtr->bbox, objc, objv);
    if (result == TCL_OK) {
    result = TkPathPdfArrow(interp, &plinePtr->startarrow, &style);
    if (result == TCL_OK) {
        result = TkPathPdfArrow(interp, &plinePtr->endarrow, &style);
    }
    }
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScalePline(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double originX, double originY, double scaleX, double scaleY)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX, &scaleY);

    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScalePathRect(&plinePtr->coords, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&plinePtr->startarrow, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&plinePtr->endarrow, originX, originY, scaleX, scaleY);
    ConfigureArrows(canvas, plinePtr);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePline(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double deltaX, double deltaY)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    /* Just translate the bbox as well. */
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslatePathRect(&plinePtr->coords, deltaX, deltaY);
    TkPathTranslateArrow(&plinePtr->startarrow, deltaX, deltaY);
    TkPathTranslateArrow(&plinePtr->endarrow, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/*--------------------------------------------------------------
 *
 * ConfigureArrows --
 *
 *  If arrowheads have been requested for a line, this function makes
 *  arrangements for the arrowheads.
 *
 * Results:
 *  Always returns TCL_OK.
 *
 * Side effects:
 *  Information in linePtr is set up for one or two arrowheads. The
 *  startarrowPtr and endarrowPtr polygons are allocated and initialized,
 *  if need be, and the end points of the line are adjusted so that a
 *  thick line doesn't stick out past the arrowheads.
 *
 *--------------------------------------------------------------
 */

static int
ConfigureArrows(
    Tk_PathCanvas canvas,       /* Canvas in which arrows will be displayed
                             * (interp and tkwin fields are needed). */
    PlineItem *linePtr)      /* Item to configure for arrows. */
{
    TkPathPoint pf, pl,newp;
    Tk_PathStyle *lineStyle = &linePtr->headerEx.style;
    int dontFill = lineStyle->fill == NULL;
    Tk_PathState state = linePtr->headerEx.header.state;

    if (state == TK_PATHSTATE_NULL) {
        state = ((TkPathCanvas *)canvas)->canvas_state;
    }

    pf.x = linePtr->coords.x1;
    pf.y = linePtr->coords.y1;
    pl.x = linePtr->coords.x2;
    pl.y = linePtr->coords.y2;

    TkPathPreconfigureArrow(&pf, &linePtr->startarrow);
    TkPathPreconfigureArrow(&pl, &linePtr->endarrow);

    newp = TkPathConfigureArrow(pf, pl, &linePtr->startarrow, lineStyle, dontFill);
    linePtr->coords.x1 = newp.x;
    linePtr->coords.y1 = newp.y;

    newp = TkPathConfigureArrow(pl, pf, &linePtr->endarrow, lineStyle, dontFill);
    linePtr->coords.x2 = newp.x;
    linePtr->coords.y2 = newp.y;

    return TCL_OK;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvPath.c.


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/*
 * tkCanvPath.c --
 *
 *  This file implements a path canvas item modelled after its
 *  SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

/* Values for the PathItem's flag. */

enum {
    kPathItemNeedNewNormalizedPath                     = (1L << 0)
};

/*
 * The structure below defines the record for each path item.
 */

typedef struct PathItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                             * path types.  MUST BE FIRST IN STRUCTURE. */
    Tcl_Obj *pathObjPtr;    /* The object containing the path definition. */
    int pathLen;
    Tcl_Obj *normPathObjPtr;/* The object containing the normalized path. */
    TkPathAtom *atomPtr;
    int maxNumSegments;     /* Max number of straight segments (for subpath)
                             * needed for Area and Point functions. */
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
    long flags;             /* Various flags, see enum. */
} PathItem;


/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputePathBbox(Tk_PathCanvas canvas, PathItem *pathPtr);
static int    ConfigurePath(Tcl_Interp *interp, Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, int objc,
                        Tcl_Obj *const objv[], int flags);
static int    CreatePath(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static int    ProcessPath(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static int    PathCoords(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static void    DeletePath(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, Display *display);
static void    DisplayPath(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, Display *display, Drawable dst,
                        int x, int y, int width, int height);
static void    PathBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int mask);
static int    PathToArea(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, double *areaPtr);
static int    PathToPdf(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int prepass);
static double    PathToPoint(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, double *coordPtr);
static void    ScalePath(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslatePath(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);
static int      ConfigureArrows(Tk_PathCanvas canvas, PathItem *pathPtr);

/* Support functions. */

static int        GetSubpathMaxNumSegments(TkPathAtom *atomPtr);


TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_FILL
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(PathItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(PathItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'path' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypePath = {
    "path",            /* name */
    sizeof(PathItem),        /* itemSize */
    CreatePath,            /* createProc */
    optionSpecs,        /* optionSpecs */
    ConfigurePath,        /* configureProc */
    PathCoords,            /* coordProc */
    DeletePath,            /* deleteProc */
    DisplayPath,        /* displayProc */
    0,                          /* flags */
    PathBbox,                   /* bboxProc */
    PathToPoint,        /* pointProc */
    PathToArea,            /* areaProc */
    PathToPdf,            /* pdfProc */
    ScalePath,            /* scaleProc */
    TranslatePath,        /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                /* isPathType */
};

/* Be sure rect is not empty (see above) before doing this. */
static void
NormalizePathRect(TkPathRect *r)
{
    double min, max;

    min = MIN(r->x1, r->x2);
    max = MAX(r->x1, r->x2);
    r->x1 = min;
    r->x2 = max;
    min = MIN(r->y1, r->y2);
    max = MAX(r->y1, r->y2);
    r->y1 = min;
    r->y2 = max;
}

/*
 +++ This starts the canvas item part +++
 */

/*
 *--------------------------------------------------------------
 *
 * CreatePath --
 *
 *    This procedure is invoked to create a new line item in
 *    a canvas.
 *
 * Results:
 *    A standard Tcl return value.  If an error occurred in
 *    creating the item, then an error message is left in
 *    the interp's result;  in this case itemPtr is left uninitialized,
 *    so it can be safely freed by the caller.
 *
 * Side effects:
 *    A new line item is created.
 *
 *--------------------------------------------------------------
 */

static int
CreatePath(
    Tcl_Interp *interp,     /* Used for error reporting. */
    Tk_PathCanvas canvas,     /* Canvas containing item. */
    Tk_PathItem *itemPtr,     /* Item to create. */
    int objc,                   /* Number of elements in objv.  */
    Tcl_Obj *const objv[])    /* Arguments describing the item. */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
    Tk_OptionTable optionTable;

    if (objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    pathPtr->pathObjPtr = NULL;
    pathPtr->pathLen = 0;
    pathPtr->normPathObjPtr = NULL;
    pathPtr->atomPtr = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    pathPtr->maxNumSegments = 0;
    TkPathArrowDescrInit(&pathPtr->startarrow);
    TkPathArrowDescrInit(&pathPtr->endarrow);
    pathPtr->flags = 0L;

    /* Forces a computation of the normalized path in PathCoords. */
    pathPtr->flags |= kPathItemNeedNewNormalizedPath;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) pathPtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    /*
     * The first argument must be the path definition list.
     */

    if (ProcessPath(interp, canvas, itemPtr, 1, objv) != TCL_OK) {
        goto error;
    }
    if (ConfigurePath(interp, canvas, itemPtr, objc-1, objv+1, 0) == TCL_OK) {
        return TCL_OK;
    }

    error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePath(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

/*
 *--------------------------------------------------------------
 *
 * ProcessPath --
 *
 *    Does the main job of processing the drawing path in 'PathCoords'
 *      but doesn't do the bbox calculation since this cannot be done
 *      before we have callaed 'ConfigurePath' because we need
 *      the inherited style.
 *
 * Results:
 *    Returns TCL_OK or TCL_ERROR, and sets the interp's result.
 *
 * Side effects:
 *    The coordinates for the given item may be changed.
 *
 *--------------------------------------------------------------
 */

static int
ProcessPath(
    Tcl_Interp *interp,     /* Used for error reporting. */
    Tk_PathCanvas canvas,   /* Canvas containing item. */
    Tk_PathItem *itemPtr,   /* Item whose coordinates are to be
                             * read or modified. */
    int objc,               /*  */
    Tcl_Obj *const objv[])  /*  */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = NULL;
    int result, len;

    if (objc == 0) {
        /* @@@ We have an option here if to return the normalized or original path. */
#if 0
        Tcl_SetObjResult(interp, pathPtr->pathObjPtr);
#endif

        /* We may need to recompute the normalized path from the atoms. */
        if (pathPtr->flags & kPathItemNeedNewNormalizedPath) {
            if (pathPtr->normPathObjPtr != NULL) {
                Tcl_DecrRefCount(pathPtr->normPathObjPtr);
            }
            TkPathNormalize(interp, pathPtr->atomPtr, &(pathPtr->normPathObjPtr));
            Tcl_IncrRefCount(pathPtr->normPathObjPtr);
            pathPtr->flags &= ~kPathItemNeedNewNormalizedPath;
        }
        Tcl_SetObjResult(interp, pathPtr->normPathObjPtr);
        return TCL_OK;
    } else if (objc == 1) {
        result = TkPathParseToAtoms(interp, objv[0], &atomPtr, &len);
        if (result == TCL_OK) {

            /* Free any old atoms. */
            if (pathPtr->atomPtr != NULL) {
                TkPathFreeAtoms(pathPtr->atomPtr);
            }
            pathPtr->atomPtr = atomPtr;
            pathPtr->pathLen = len;
            if (pathPtr->pathObjPtr != NULL) {
        Tcl_DecrRefCount(pathPtr->pathObjPtr);
        }
            pathPtr->pathObjPtr = objv[0];
            pathPtr->maxNumSegments = GetSubpathMaxNumSegments(atomPtr);
            Tcl_IncrRefCount(pathPtr->pathObjPtr);
            pathPtr->flags |= kPathItemNeedNewNormalizedPath;
        }
        return result;
    } else {
        Tcl_WrongNumArgs(interp, 0, objv, "pathName coords id ?pathSpec?");
        return TCL_ERROR;
    }
}

/*
 *--------------------------------------------------------------
 *
 * PathCoords --
 *
 *    This procedure is invoked to process the "coords" widget
 *    command on lines.  See the user documentation for details
 *    on what it does.
 *
 * Results:
 *    Returns TCL_OK or TCL_ERROR, and sets the interp's result.
 *
 * Side effects:
 *    The coordinates for the given item may be changed.
 *
 *--------------------------------------------------------------
 */

static int
PathCoords(
    Tcl_Interp *interp,     /* Used for error reporting. */
    Tk_PathCanvas canvas,   /* Canvas containing item. */
    Tk_PathItem *itemPtr,   /* Item whose coordinates are to be
                             * read or modified. */
    int objc,               /*  */
    Tcl_Obj *const objv[])  /*  */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    int result;

    result = ProcessPath(interp, canvas, itemPtr, objc, objv);
    if ((result == TCL_OK) && (objc == 1)) {
        ConfigureArrows(canvas, pathPtr);
        ComputePathBbox(canvas, pathPtr);
    }
    return result;
}

/*
 *--------------------------------------------------------------
 *
 * ComputePathBbox --
 *
 *    This procedure is invoked to compute the bounding box of
 *    all the pixels that may be drawn as part of a path.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The fields x1, y1, x2, and y2 are updated in the header
 *    for itemPtr.
 *
 *--------------------------------------------------------------
 */

static void
ComputePathBbox(
    Tk_PathCanvas canvas,   /* Canvas that contains item. */
    PathItem *pathPtr)      /* Item whose bbox is to be
                             * recomputed. */
{
    Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
    Tk_PathItem *itemPtr = &itemExPtr->header;
    Tk_PathStyle style;
    Tk_PathState state = itemExPtr->header.state;

    if (state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if (pathPtr->pathObjPtr == NULL || (pathPtr->pathLen < 4) || (state == TK_PATHSTATE_HIDDEN)) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);

    /*
     * Get an approximation of the path's bounding box
     * assuming zero stroke width.
     */
    itemPtr->bbox = TkPathGetGenericBarePathBbox(pathPtr->atomPtr);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &pathPtr->startarrow);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &pathPtr->endarrow);
    itemPtr->totalBbox = TkPathGetGenericPathTotalBboxFromBare(pathPtr->atomPtr,
            &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr, &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigureArrows(
        Tk_PathCanvas canvas, PathItem *pathPtr)
{
    TkPathPoint *pfirstp;
    TkPathPoint psecond;
    TkPathPoint ppenult;
    TkPathPoint *plastp;

    int error = TkPathGetSegmentsFromPathAtomList(pathPtr->atomPtr, &pfirstp,
            &psecond, &ppenult, &plastp);

    if (error == TCL_OK) {
        TkPathPoint pfirst = *pfirstp;
        TkPathPoint plast = *plastp;
        Tk_PathStyle *lineStyle = &pathPtr->headerEx.style;
        int isOpen = lineStyle->fill==NULL &&
        ((pfirst.x != plast.x) || (pfirst.y != plast.y));

        TkPathPreconfigureArrow(&pfirst, &pathPtr->startarrow);
        TkPathPreconfigureArrow(&plast, &pathPtr->endarrow);

        *pfirstp = TkPathConfigureArrow(pfirst, psecond,
            &pathPtr->startarrow, lineStyle, isOpen);
        *plastp = TkPathConfigureArrow(plast, ppenult, &pathPtr->endarrow,
            lineStyle, isOpen);
    } else {
        TkPathFreeArrow(&pathPtr->startarrow);
        TkPathFreeArrow(&pathPtr->endarrow);
    }

    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ConfigurePath --
 *
 *    This procedure is invoked to configure various aspects
 *    of a line item such as its background color.
 *
 * Results:
 *    A standard Tcl result code.  If an error occurs, then
 *    an error message is left in the interp's result.
 *
 * Side effects:
 *    Configuration information, such as colors and stipple
 *    patterns, may be set for itemPtr.
 *
 *--------------------------------------------------------------
 */

static int
ConfigurePath(
    Tcl_Interp *interp,        /* Used for error reporting. */
    Tk_PathCanvas canvas,    /* Canvas containing itemPtr. */
    Tk_PathItem *itemPtr,    /* Line item to reconfigure. */
    int objc,            /* Number of elements in objv.  */
    Tcl_Obj *const objv[],    /* Arguments describing things to configure. */
    int flags)            /* Flags to pass to Tk_ConfigureWidget. */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int mask, error;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) pathPtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }
    if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr, mask) != TCL_OK) {
        continue;
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    stylePtr->mask |= mask;
    }

    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity   = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));

    ConfigureArrows(canvas, pathPtr);

    /*
     * Recompute bounding box for path.
     */
    if (error) {
    Tcl_SetObjResult(interp, errorResult);
    Tcl_DecrRefCount(errorResult);
    return TCL_ERROR;
    } else {
        ComputePathBbox(canvas, pathPtr);
    return TCL_OK;
    }
}

/*
 *--------------------------------------------------------------
 *
 * DeletePath --
 *
 *    This procedure is called to clean up the data structure
 *    associated with a line item.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Resources associated with itemPtr are released.
 *
 *--------------------------------------------------------------
 */

static void
DeletePath(
    Tk_PathCanvas canvas,   /* Info about overall canvas widget. */
    Tk_PathItem *itemPtr,   /* Item that is being deleted. */
    Display *display)       /* Display containing window for
                             * canvas. */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    if (stylePtr->fill != NULL) {
    TkPathFreePathColor(stylePtr->fill);
    }
    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    if (pathPtr->pathObjPtr != NULL) {
        Tcl_DecrRefCount(pathPtr->pathObjPtr);
    }
    if (pathPtr->normPathObjPtr != NULL) {
        Tcl_DecrRefCount(pathPtr->normPathObjPtr);
    }
    if (pathPtr->atomPtr != NULL) {
        TkPathFreeAtoms(pathPtr->atomPtr);
        pathPtr->atomPtr = NULL;
    }
    TkPathFreeArrow(&pathPtr->startarrow);
    TkPathFreeArrow(&pathPtr->endarrow);
    Tk_FreeConfigOptions((char *) pathPtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

/*
 *--------------------------------------------------------------
 *
 * DisplayPath --
 *
 *    This procedure is invoked to draw a line item in a given
 *    drawable.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    ItemPtr is drawn in drawable using the transformation
 *    information in canvas.
 *
 *--------------------------------------------------------------
 */

static void
DisplayPath(
    Tk_PathCanvas canvas,   /* Canvas that contains item. */
    Tk_PathItem *itemPtr,   /* Item to be displayed. */
    Display *display,       /* Display on which to draw item. */
    Drawable drawable,      /* Pixmap or window in which to draw
                             * item. */
    int x, int y,           /* Describes region of canvas that */
    int width, int height)  /* must be redisplayed (not used). */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    Tk_PathStyle style;

    if (pathPtr->pathLen > 2) {
        style = TkPathCanvasInheritStyle(itemPtr, 0);
        TkPathDrawPath(ContextOfCanvas(canvas), pathPtr->atomPtr, &style,
        &m, &itemPtr->bbox);
        /*
         * Display arrowheads, if they are wanted.
         */
        TkPathDisplayArrow(canvas, &pathPtr->startarrow, &style, &m, &itemPtr->bbox);
        TkPathDisplayArrow(canvas, &pathPtr->endarrow, &style, &m, &itemPtr->bbox);

        TkPathCanvasFreeInheritedStyle(&style);
    }
}

static void
PathBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    /*
     * Try to be economical here.
     */
    if ((mask & TK_PATH_STYLE_OPTION_MATRIX) ||
            (mask & TK_PATH_STYLE_OPTION_STROKE) ||
            (mask & TK_PATH_STYLE_OPTION_STROKE_WIDTH) ||
            (mask & TK_PATH_CORE_OPTION_PARENT) ||
            (mask & TK_PATH_CORE_OPTION_STYLENAME)) {
        ComputePathBbox(canvas, pathPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * PathToPoint --
 *
 *    Computes the distance from a given point to a given
 *    line, in canvas units.
 *
 * Results:
 *    The return value is 0 if the point whose x and y coordinates
 *    are pointPtr[0] and pointPtr[1] is inside the line.  If the
 *    point isn't inside the line then the return value is the
 *    distance from the point to the line.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static double
PathToPoint(
    Tk_PathCanvas canvas,    /* Canvas containing item. */
    Tk_PathItem *itemPtr,    /* Item to check against point. */
    double *pointPtr)        /* Pointer to x and y coordinates. */
{
    PathItem        *pathPtr = (PathItem *) itemPtr;
    TkPathAtom        *atomPtr = pathPtr->atomPtr;
    Tk_PathStyle style;
    double dist;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, atomPtr,
            pathPtr->maxNumSegments, pointPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

/*
 * Get maximum number of segments needed to describe path.
 * Needed to see if we can use static space or need to allocate more.
 */

static int
GetArcNumSegments(double currentX, double currentY, TkArcAtom *arc)
{
    int result;
    int ntheta, nlength;
    int numSteps;            /* Number of curve points to
                     * generate.  */
    double cx, cy, rx, ry;
    double theta1, dtheta;

    result = TkPathEndpointToCentralArcParameters(
            currentX, currentY,
            arc->x, arc->y, arc->radX, arc->radY,
            DEGREES_TO_RADIANS * arc->angle,
            arc->largeArcFlag, arc->sweepFlag,
            &cx, &cy, &rx, &ry,
            &theta1, &dtheta);
    if (result == TK_PATH_ARC_Line) {
        return 2;
    } else if (result == TK_PATH_ARC_Skip) {
        return 0;
    }

    /* Estimate the number of steps needed.
     * Max 10 degrees or length 50.
     */
    ntheta = (int) (dtheta/5.0 + 0.5);
    nlength = (int) (0.5*(rx + ry)*dtheta/50 + 0.5);
    numSteps = MAX(4, MAX(ntheta, nlength));;
    return numSteps;
}

static int
GetSubpathMaxNumSegments(TkPathAtom *atomPtr)
{
    int            num;
    int         maxNumSegments;
    double         currentX = 0.0, currentY = 0.0;
    double         startX = 0.0, startY = 0.0;
    TkMoveToAtom     *move;
    TkLineToAtom     *line;
    TkArcAtom     *arc;
    TkQuadBezierAtom *quad;
    TkCurveToAtom *curve;

    num = 0;
    maxNumSegments = 0;

    while (atomPtr != NULL) {

        switch (atomPtr->type) {
            case TK_PATH_ATOM_M: {
                move = (TkMoveToAtom *) atomPtr;
                num = 1;
                currentX = move->x;
                currentY = move->y;
                startX = currentX;
                startY = currentY;
                break;
            }
            case TK_PATH_ATOM_L: {
                line = (TkLineToAtom *) atomPtr;
                num++;
                currentX = line->x;
                currentY = line->y;
                break;
            }
            case TK_PATH_ATOM_A: {
                arc = (TkArcAtom *) atomPtr;
                num += GetArcNumSegments(currentX, currentY, arc);
                currentX = arc->x;
                currentY = arc->y;
                break;
            }
            case TK_PATH_ATOM_Q: {
                quad = (TkQuadBezierAtom *) atomPtr;
                num += TK_PATH_NUMSEGEMENTS_QuadBezier;
                currentX = quad->anchorX;
                currentY = quad->anchorY;
                break;
            }
            case TK_PATH_ATOM_C: {
                curve = (TkCurveToAtom *) atomPtr;
                num += TK_PATH_NUMSEGEMENTS_CurveTo;
                currentX = curve->anchorX;
                currentY = curve->anchorY;
                break;
            }
            case TK_PATH_ATOM_Z: {
                num++;
                currentX = startX;
                currentY = startY;
                break;
            }
            case TK_PATH_ATOM_ELLIPSE:
            case TK_PATH_ATOM_RECT: {
                /* Empty. */
                break;
            }
        }
        if (num > maxNumSegments) {
            maxNumSegments = num;
        }
        atomPtr = atomPtr->nextPtr;
    }
    return maxNumSegments;
}

/*
 *--------------------------------------------------------------
 *
 * PathToArea --
 *
 *    This procedure is called to determine whether an item
 *    lies entirely inside, entirely outside, or overlapping
 *    a given rectangular area.
 *
 *    Each subpath is treated in turn. Generate straight line
 *    segments for each subpath and treat it as a polygon.
 *
 * Results:
 *    -1 is returned if the item is entirely outside the
 *    area, 0 if it overlaps, and 1 if it is entirely
 *    inside the given area.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
PathToArea(
    Tk_PathCanvas canvas,   /* Canvas containing item. */
    Tk_PathItem *itemPtr,   /* Item to check against line. */
    double *areaPtr)        /* Pointer to array of four coordinates
                             * (x1, y1, x2, y2) describing rectangular
                             * area.  */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathStyle style;
    int area;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    area = TkPathGenericPathToArea(canvas, itemPtr, &style,
            pathPtr->atomPtr, pathPtr->maxNumSegments, areaPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

/*
 *--------------------------------------------------------------
 *
 * ScalePath --
 *
 *    This procedure is invoked to rescale a path item.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The line referred to by itemPtr is rescaled so that the
 *    following transformation is applied to all point
 *    coordinates:
 *    x' = originX + scaleX*(x-originX)
 *    y' = originY + scaleY*(y-originY)
 *
 *--------------------------------------------------------------
 */

static void
ScalePath(
    Tk_PathCanvas canvas,           /* Canvas containing line. */
    Tk_PathItem *itemPtr,           /* Path to be scaled. */
    int compensate,            /* Compensate matrix. */
    double originX, double originY, /* Origin about which to scale rect. */
    double scaleX,                  /* Amount to scale in X direction. */
    double scaleY)                  /* Amount to scale in Y direction. */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = pathPtr->atomPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX, &scaleY);

    /* @@@ TODO: Arc atoms with nonzero rotation angle is WRONG! */

    TkPathScalePathAtoms(atomPtr, originX, originY, scaleX, scaleY);

    /*
     * Set flags bit so we know that PathCoords need to update the
     * normalized path before being used.
     */
    pathPtr->flags |= kPathItemNeedNewNormalizedPath;

    /* Just scale the bbox'es as well. */
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    NormalizePathRect(&itemPtr->bbox);

    TkPathScaleArrow(&pathPtr->startarrow, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&pathPtr->endarrow, originX, originY, scaleX, scaleY);
    ConfigureArrows(canvas, pathPtr);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

/*
 *--------------------------------------------------------------
 *
 * TranslatePath --
 *
 *    This procedure is called to move a path by a given amount.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The position of the line is offset by (xDelta, yDelta), and
 *    the bounding box is updated in the generic part of the item
 *    structure.
 *
 *--------------------------------------------------------------
 */

static void
TranslatePath(
    Tk_PathCanvas canvas,       /* Canvas containing item. */
    Tk_PathItem *itemPtr,     /* Item that is being moved. */
    int compensate,        /* Compensate matrix. */
    double deltaX,        /* Amount by which item is to be */
    double deltaY)              /* moved. */
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = pathPtr->atomPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    TkPathTranslatePathAtoms(atomPtr, deltaX, deltaY);

    /*
     * Set flags bit so we know that PathCoords need to update the
     * normalized path before being used.
     */
    pathPtr->flags |= kPathItemNeedNewNormalizedPath;

    /* Just translate the bbox'es as well. */
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateArrow(&pathPtr->startarrow, deltaX, deltaY);
    TkPathTranslateArrow(&pathPtr->endarrow, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/*
 *--------------------------------------------------------------
 *
 * PathToPdf --
 *
 *    This procedure is called to generate Pdf for
 *    path items.
 *
 * Results:
 *    The return value is a standard Tcl result.  If an error
 *    occurs in generating Pdf then an error message is
 *    left in the interp's result, replacing whatever used
 *    to be there.  If no error occurs, then Pdf for the
 *    item is appended to the result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
PathToPdf(
    Tcl_Interp *interp,     /* Leave Pdf or error message
                             * here. */
    Tk_PathCanvas canvas,   /* Information about overall canvas. */
    Tk_PathItem *itemPtr,   /* Item for which Pdf is
                             * wanted. */
    int objc,               /* Number of arguments. */
    Tcl_Obj *const objv[],  /* Argument list. */
    int prepass)            /* 1 means this is a prepass to
                             * collect font information;  0 means
                             * final Pdf is being created. */
{
    Tk_PathStyle style;
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathState state = itemPtr->state;
    int result = TCL_OK;

    if (state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if ((pathPtr->pathObjPtr == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
    return result;
    }
    if (pathPtr->pathLen > 2) {
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    result = TkPathPdf(interp, pathPtr->atomPtr, &style, &itemPtr->bbox,
               objc, objv);
    if (result == TCL_OK) {
        result = TkPathPdfArrow(interp, &pathPtr->startarrow, &style);
        if (result == TCL_OK) {
        result = TkPathPdfArrow(interp, &pathPtr->endarrow, &style);
        }
    }
    TkPathCanvasFreeInheritedStyle(&style);
    }
    return result;
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvPoly.c.










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
 * tkCanvPpolygon.c --
 *
 *    This file implements polygon and polyline canvas items modelled after its
 *  SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PpolyItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                             * path types.  MUST BE FIRST IN STRUCTURE. */
    char type;            /* Polyline or polygon. */
    TkPathAtom *atomPtr;
    int maxNumSegments;        /* Max number of straight segments (for subpath)
                 * needed for Area and Point functions. */
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
} PpolyItem;

enum {
    kPpolyTypePolyline,
    kPpolyTypePolygon
};


/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputePpolyBbox(Tk_PathCanvas canvas, PpolyItem *ppolyPtr);
static int    ConfigurePpoly(Tcl_Interp *interp, Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, int objc,
                        Tcl_Obj *const objv[], int flags);
static int    CoordsForPolygonline(Tcl_Interp *interp, Tk_PathCanvas canvas,
            int closed, int objc, Tcl_Obj *const objv[],
            TkPathAtom **atomPtrPtr, int *lenPtr);
static int    CreateAny(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[], char type);
static int    CreatePolyline(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static int    CreatePpolygon(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static void    DeletePpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display);
static void    DisplayPpoly(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, Display *display, Drawable drawable,
                        int x, int y, int width, int height);
static void    PpolyBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask);
static int    PpolyCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static int    PpolyToArea(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, double *rectPtr);
static int    PpolyToPdf(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[], int prepass);
static double    PpolyToPoint(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, double *coordPtr);
static void    ScalePpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslatePpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);
static int      ConfigureArrows(Tk_PathCanvas canvas, PpolyItem *ppolyPtr);

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_FILL
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

static Tk_OptionSpec optionSpecsPolyline[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(PpolyItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(PpolyItem),
    TK_PATH_OPTION_SPEC_END
};

static Tk_OptionSpec optionSpecsPpolygon[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'polyline' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypePolyline = {
    "polyline",                /* name */
    sizeof(PpolyItem),            /* itemSize */
    CreatePolyline,            /* createProc */
    optionSpecsPolyline,        /* OptionSpecs */
    ConfigurePpoly,            /* configureProc */
    PpolyCoords,            /* coordProc */
    DeletePpoly,            /* deleteProc */
    DisplayPpoly,            /* displayProc */
    0,                    /* flags */
    PpolyBbox,                /* bboxProc */
    PpolyToPoint,            /* pointProc */
    PpolyToArea,            /* areaProc */
    PpolyToPdf,                /* pdfProc */
    ScalePpoly,                /* scaleProc */
    TranslatePpoly,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

Tk_PathItemType tkPathTypePolygon = {
    "polygon",                /* name */
    sizeof(PpolyItem),            /* itemSize */
    CreatePpolygon,            /* createProc */
    optionSpecsPpolygon,        /* OptionSpecs */
    ConfigurePpoly,            /* configureProc */
    PpolyCoords,            /* coordProc */
    DeletePpoly,            /* deleteProc */
    DisplayPpoly,            /* displayProc */
    0,                    /* flags */
    PpolyBbox,                /* bboxProc */
    PpolyToPoint,            /* pointProc */
    PpolyToArea,            /* areaProc */
    PpolyToPdf,                /* pdfProc */
    ScalePpoly,                /* scaleProc */
    TranslatePpoly,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

static int
CreatePolyline(Tcl_Interp *interp, Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr, int objc, Tcl_Obj *const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kPpolyTypePolyline);
}

static int
CreatePpolygon(Tcl_Interp *interp, Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr, int objc, Tcl_Obj *const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kPpolyTypePolygon);
}

static int
CreateAny(Tcl_Interp *interp, Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], char type)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
    Tk_OptionTable optionTable;
    int    i, len;

    if (objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    ppolyPtr->atomPtr = NULL;
    ppolyPtr->type = type;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    ppolyPtr->maxNumSegments = 0;
    TkPathArrowDescrInit(&ppolyPtr->startarrow);
    TkPathArrowDescrInit(&ppolyPtr->endarrow);

    if (ppolyPtr->type == kPpolyTypePolyline) {
    optionTable = Tk_CreateOptionTable(interp, optionSpecsPolyline);
    } else {
    optionTable = Tk_CreateOptionTable(interp, optionSpecsPpolygon);
    }
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) ppolyPtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for (i = 1; i < objc; i++) {
        char *arg = Tcl_GetString(objv[i]);
        if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if (CoordsForPolygonline(interp, canvas,
        (ppolyPtr->type == kPpolyTypePolyline) ? 0 : 1,
        i, objv, &(ppolyPtr->atomPtr), &len) != TCL_OK) {
        goto error;
    }
    ppolyPtr->maxNumSegments = len;

    if (ConfigurePpoly(interp, canvas, itemPtr, objc-i, objv+i, 0) == TCL_OK) {
        return TCL_OK;
    }

    error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePpoly(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
PpolyCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[])
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    int len, closed;

    closed = (ppolyPtr->type == kPpolyTypePolyline) ? 0 : 1;
    if (CoordsForPolygonline(interp, canvas, closed, objc, objv,
            &(ppolyPtr->atomPtr), &len) != TCL_OK) {
        return TCL_ERROR;
    }
    if (objc > 0) {
        ppolyPtr->maxNumSegments = len;
        ConfigureArrows(canvas, ppolyPtr);
        ComputePpolyBbox(canvas, ppolyPtr);
    }
    return TCL_OK;
}

void
ComputePpolyBbox(Tk_PathCanvas canvas, PpolyItem *ppolyPtr)
{
    Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
    Tk_PathItem *itemPtr = &itemExPtr->header;
    Tk_PathStyle style;
    Tk_PathState state = itemExPtr->header.state;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if ((ppolyPtr->atomPtr == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    itemPtr->bbox = TkPathGetGenericBarePathBbox(ppolyPtr->atomPtr);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &ppolyPtr->startarrow);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &ppolyPtr->endarrow);
    itemPtr->totalBbox = TkPathGetGenericPathTotalBboxFromBare(ppolyPtr->atomPtr,
            &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr,
        &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

/*--------------------------------------------------------------
 *
 * ConfigureArrows --
 *
 *  If arrowheads have been requested for a line, this function makes
 *  arrangements for the arrowheads.
 *
 * Results:
 *  Always returns TCL_OK.
 *
 * Side effects:
 *  Information in ppolyPtr is set up for one or two arrowheads. The
 *  startarrowPtr and endarrowPtr polygons are allocated and initialized,
 *  if need be, and the end points of the line are adjusted so that a
 *  thick line doesn't stick out past the arrowheads.
 *
 *--------------------------------------------------------------
 */

static int
ConfigureArrows(Tk_PathCanvas canvas, PpolyItem *ppolyPtr)
{
    TkPathPoint *pfirstp;
    TkPathPoint psecond;
    TkPathPoint ppenult;
    TkPathPoint *plastp;

    int error = TkPathGetSegmentsFromPathAtomList(ppolyPtr->atomPtr,
            &pfirstp, &psecond, &ppenult, &plastp);

    if (error == TCL_OK) {
        TkPathPoint pfirst = *pfirstp;
        TkPathPoint plast = *plastp;
        Tk_PathStyle *lineStyle = &ppolyPtr->headerEx.style;
        int isOpen = lineStyle->fill==NULL &&
        ((pfirst.x != plast.x) || (pfirst.y != plast.y));

        TkPathPreconfigureArrow(&pfirst, &ppolyPtr->startarrow);
        TkPathPreconfigureArrow(&plast, &ppolyPtr->endarrow);

        *pfirstp = TkPathConfigureArrow(pfirst, psecond,
            &ppolyPtr->startarrow, lineStyle, isOpen);
        *plastp = TkPathConfigureArrow(plast, ppenult, &ppolyPtr->endarrow,
            lineStyle, isOpen);
    } else {
        TkPathFreeArrow(&ppolyPtr->startarrow);
        TkPathFreeArrow(&ppolyPtr->endarrow);
    }

    return TCL_OK;
}

static int
ConfigurePpoly(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int flags)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int mask, error;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) ppolyPtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }
    if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr, mask) != TCL_OK) {
        continue;
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    stylePtr->mask |= mask;
    }
    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));

    ConfigureArrows(canvas, ppolyPtr);

    if (error) {
    Tcl_SetObjResult(interp, errorResult);
    Tcl_DecrRefCount(errorResult);
    return TCL_ERROR;
    } else {
    ComputePpolyBbox(canvas, ppolyPtr);
    return TCL_OK;
    }
}

static void
DeletePpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    if (stylePtr->fill != NULL) {
    TkPathFreePathColor(stylePtr->fill);
    }
    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    if (ppolyPtr->atomPtr != NULL) {
        TkPathFreeAtoms(ppolyPtr->atomPtr);
        ppolyPtr->atomPtr = NULL;
    }
    TkPathFreeArrow(&ppolyPtr->startarrow);
    TkPathFreeArrow(&ppolyPtr->endarrow);
    Tk_FreeConfigOptions((char *) itemPtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display,
    Drawable drawable, int x, int y, int width, int height)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    Tk_PathStyle style;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    TkPathDrawPath(ContextOfCanvas(canvas), ppolyPtr->atomPtr, &style,
        &m, &itemPtr->bbox);
    /*
     * Display arrowheads, if they are wanted.
     */
    TkPathDisplayArrow(canvas, &ppolyPtr->startarrow, &style, &m, &itemPtr->bbox);
    TkPathDisplayArrow(canvas, &ppolyPtr->endarrow, &style, &m, &itemPtr->bbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PpolyBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    ComputePpolyBbox(canvas, ppolyPtr);
}

static double
PpolyToPoint(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *pointPtr)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathStyle style;
    double dist;
    long flags;

    flags = (ppolyPtr->type == kPpolyTypePolyline) ?
        TK_PATH_MERGESTYLE_NOTFILL : 0;
    style = TkPathCanvasInheritStyle(itemPtr, flags);
    dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, ppolyPtr->atomPtr,
            ppolyPtr->maxNumSegments, pointPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
PpolyToArea(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *areaPtr)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathStyle style;
    int area;
    long flags;

    flags = (ppolyPtr->type == kPpolyTypePolyline) ?
        TK_PATH_MERGESTYLE_NOTFILL : 0;
    style = TkPathCanvasInheritStyle(itemPtr, flags);
    area = TkPathGenericPathToArea(canvas, itemPtr, &style,
            ppolyPtr->atomPtr, ppolyPtr->maxNumSegments, areaPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

static int
PpolyToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    Tk_PathStyle style;
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathState state = itemPtr->state;
    int result;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if ((ppolyPtr->atomPtr == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
    return TCL_OK;
    }
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    result = TkPathPdf(interp, ppolyPtr->atomPtr, &style, &itemPtr->bbox,
               objc, objv);
    if (result == TCL_OK) {
    result = TkPathPdfArrow(interp, &ppolyPtr->startarrow, &style);
    if (result == TCL_OK) {
        result = TkPathPdfArrow(interp, &ppolyPtr->endarrow, &style);
    }
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScalePpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double originX, double originY, double scaleX, double scaleY)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX, &scaleY);

    TkPathScalePathAtoms(ppolyPtr->atomPtr, originX, originY, scaleX, scaleY);
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&ppolyPtr->startarrow, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&ppolyPtr->endarrow, originX, originY, scaleX, scaleY);
    ConfigureArrows(canvas, ppolyPtr);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePpoly(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double deltaX, double deltaY)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    TkPathTranslatePathAtoms(ppolyPtr->atomPtr, deltaX, deltaY);
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateArrow(&ppolyPtr->startarrow, deltaX, deltaY);
    TkPathTranslateArrow(&ppolyPtr->endarrow, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/*
 *--------------------------------------------------------------
 *
 * CoordsForPolygonline --
 *
 *        Used as coordProc for polyline and polygon items.
 *
 * Results:
 *        Standard tcl result.
 *
 * Side effects:
 *        May store new atoms in atomPtrPtr and max number of points
 *        in lenPtr.
 *
 *--------------------------------------------------------------
 */

int
CoordsForPolygonline(
    Tcl_Interp *interp,
    Tk_PathCanvas canvas,
    int closed,                /* Polyline (0) or polygon (1) */
    int objc,
    Tcl_Obj *const objv[],
    TkPathAtom **atomPtrPtr,
    int *lenPtr)
{
    TkPathAtom *atomPtr = *atomPtrPtr;

    if (objc == 0) {
        Tcl_Obj *obj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);

        while (atomPtr != NULL) {
            switch (atomPtr->type) {
                case TK_PATH_ATOM_M: {
                    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;
                    Tcl_ListObjAppendElement(interp, obj, Tcl_NewDoubleObj(move->x));
                    Tcl_ListObjAppendElement(interp, obj, Tcl_NewDoubleObj(move->y));
                    break;
                }
                case TK_PATH_ATOM_L: {
                    TkLineToAtom *line = (TkLineToAtom *) atomPtr;
                    Tcl_ListObjAppendElement(interp, obj, Tcl_NewDoubleObj(line->x));
                    Tcl_ListObjAppendElement(interp, obj, Tcl_NewDoubleObj(line->y));
                    break;
                }
                case TK_PATH_ATOM_Z: {

                    break;
                }
                default: {
                    /* empty */
                }
            }
            atomPtr = atomPtr->nextPtr;
        }
        Tcl_SetObjResult(interp, obj);
        *lenPtr = 0;
        return TCL_OK;
    }
    if (objc == 1) {
        if (Tcl_ListObjGetElements(interp, objv[0], &objc,
            (Tcl_Obj ***) &objv) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if (objc & 1) {
        char buf[64 + TCL_INTEGER_SPACE];
        sprintf(buf, "wrong # coordinates: expected an even number, got %d", objc);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        return TCL_ERROR;
    } else if (objc < 4) {
        char buf[64 + TCL_INTEGER_SPACE];
        sprintf(buf, "wrong # coordinates: expected at least 4, got %d", objc);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        return TCL_ERROR;
    } else {
        int     i;
        double    x, y;
        double    firstX = 0.0, firstY = 0.0;
        TkPathAtom *firstAtomPtr = NULL;

        /*
        * Free any old stuff.
        */
        if (atomPtr != NULL) {
            TkPathFreeAtoms(atomPtr);
            atomPtr = NULL;
        }
        for (i = 0; i < objc; i += 2) {
            if (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[i], &x) != TCL_OK) {
                /* @@@ error recovery? */
                return TCL_ERROR;
            }
            if (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[i+1], &y) != TCL_OK) {
                return TCL_ERROR;
            }
            if (i == 0) {
                firstX = x;
                firstY = y;
                atomPtr = TkPathNewMoveToAtom(x, y);
                firstAtomPtr = atomPtr;
            } else {
                atomPtr->nextPtr = TkPathNewLineToAtom(x, y);
                atomPtr = atomPtr->nextPtr;
            }
        }
        if (closed) {
            atomPtr->nextPtr = TkPathNewCloseAtom(firstX, firstY);
        }
        *atomPtrPtr = firstAtomPtr;
        *lenPtr = i/2 + 2;
    }
    return TCL_OK;
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvRect.c.


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/*
 * tkCanvPrect.c --
 *
 *    This file implements a rectangle canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PrectItem  {
    Tk_PathItemEx headerEx; /* Generic stuff that's the same for all
                             * path types.  MUST BE FIRST IN STRUCTURE. */
    double rx;            /* Radius of corners. */
    double ry;
    int maxNumSegments;        /* Max number of straight segments (for subpath)
                             * needed for Area and Point functions. */
} PrectItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputePrectBbox(Tk_PathCanvas canvas, PrectItem *prectPtr);
static int    ConfigurePrect(Tcl_Interp *interp, Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, int objc,
                        Tcl_Obj *const objv[], int flags);
static int    CreatePrect(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static void    DeletePrect(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, Display *display);
static void    DisplayPrect(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, Display *display, Drawable drawable,
                        int x, int y, int width, int height);
static void    PrectBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask);
static int    PrectCoords(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
                        int objc, Tcl_Obj *const objv[]);
static int    PrectToArea(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, double *rectPtr);
static int    PrectToPdf(Tcl_Interp *interp,
                        Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[], int prepass);
static double    PrectToPoint(Tk_PathCanvas canvas,
                        Tk_PathItem *itemPtr, double *coordPtr);
static void    ScalePrect(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslatePrect(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);
static TkPathAtom * MakePathAtoms(PrectItem *prectPtr);


enum {
    PRECT_OPTION_INDEX_RX   = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 0)),
    PRECT_OPTION_INDEX_RY   = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
};

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_FILL
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

#define TK_PATH_OPTION_SPEC_RX(typeName)            \
    {TK_OPTION_DOUBLE, "-rx", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, rx),        \
    0, 0, PRECT_OPTION_INDEX_RX}

#define TK_PATH_OPTION_SPEC_RY(typeName)            \
    {TK_OPTION_DOUBLE, "-ry", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, ry),        \
    0, 0, PRECT_OPTION_INDEX_RY}

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_RX(PrectItem),
    TK_PATH_OPTION_SPEC_RY(PrectItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeRect = {
    "rect",                /* name */
    sizeof(PrectItem),            /* itemSize */
    CreatePrect,            /* createProc */
    optionSpecs,            /* optionSpecs OBSOLTE !!! ??? */
    ConfigurePrect,            /* configureProc */
    PrectCoords,            /* coordProc */
    DeletePrect,            /* deleteProc */
    DisplayPrect,            /* displayProc */
    0,                    /* flags */
    PrectBbox,                /* bboxProc */
    PrectToPoint,            /* pointProc */
    PrectToArea,            /* areaProc */
    PrectToPdf,                /* pdfProc */
    ScalePrect,                /* scaleProc */
    TranslatePrect,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};


static int
CreatePrect(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    int    i;
    Tk_OptionTable optionTable;

    if (objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    prectPtr->maxNumSegments = 100;        /* Crude overestimate. */

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) prectPtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for (i = 1; i < objc; i++) {
        char *arg = Tcl_GetString(objv[i]);
        if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if (TkPathCoordsForRectangularItems(interp, canvas, &itemPtr->bbox, i, objv) != TCL_OK) {
        goto error;
    }
    if (ConfigurePrect(interp, canvas, itemPtr, objc-i, objv+i, 0) == TCL_OK) {
        return TCL_OK;
    }

    error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePrect(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
PrectCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[])
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    int result;

    result = TkPathCoordsForRectangularItems(interp, canvas, &itemPtr->bbox, objc, objv);
    if ((result == TCL_OK) && ((objc == 1) || (objc == 4))) {
    ComputePrectBbox(canvas, prectPtr);
    }
    return result;
}

void
ComputePrectBbox(Tk_PathCanvas canvas, PrectItem *prectPtr)
{
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    Tk_PathItem *itemPtr = &itemExPtr->header;
    Tk_PathStyle style;
    Tk_PathState state = itemExPtr->header.state;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if (state == TK_PATHSTATE_HIDDEN) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    itemPtr->totalBbox = TkPathGetGenericPathTotalBboxFromBare(NULL, &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr, &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigurePrect(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
        int objc, Tcl_Obj *const objv[], int flags)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) prectPtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }
    if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr, mask) != TCL_OK) {
        continue;
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    stylePtr->mask |= mask;
    }
    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity   = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));
    prectPtr->rx = MAX(0.0, prectPtr->rx);
    prectPtr->ry = MAX(0.0, prectPtr->ry);

    /*
     * Recompute bounding box for path.
     */
    if (error) {
    Tcl_SetObjResult(interp, errorResult);
    Tcl_DecrRefCount(errorResult);
    return TCL_ERROR;
    } else {
    ComputePrectBbox(canvas, prectPtr);
    return TCL_OK;
    }
}

static TkPathAtom *
MakePathAtoms(PrectItem *prectPtr)
{
    Tk_PathItem *itemPtr = (Tk_PathItem *) prectPtr;
    TkPathAtom *atomPtr;
    double points[4];

    points[0] = itemPtr->bbox.x1;
    points[1] = itemPtr->bbox.y1;
    points[2] = itemPtr->bbox.x2;
    points[3] = itemPtr->bbox.y2;
    TkPathMakePrectAtoms(points, prectPtr->rx, prectPtr->ry, &atomPtr);
    return atomPtr;
}

static void
DeletePrect(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    if (stylePtr->fill != NULL) {
    TkPathFreePathColor(stylePtr->fill);
    }
    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    Tk_FreeConfigOptions((char *) itemPtr, itemPtr->optionTable,
             Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPrect(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display, Drawable drawable,
        int x, int y, int width, int height)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathAtom *atomPtr;
    Tk_PathStyle style;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    atomPtr = MakePathAtoms(prectPtr);
    TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &style,
        &m, &itemPtr->bbox);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PrectBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    ComputePrectBbox(canvas, prectPtr);
}

static double
PrectToPoint(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *pointPtr)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathStyle style;
    TkPathMatrix *mPtr;
    TkPathRect *rectPtr = &itemPtr->bbox;
    double bareRect[4];
    double width, dist;
    int rectiLinear = 0;
    int filled;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    filled = HaveAnyFillFromPathColor(style.fill);
    width = 0.0;
    if (style.strokeColor != NULL) {
        width = style.strokeWidth;
    }
    mPtr = style.matrixPtr;

    /* Try to be economical about this for pure rectangles. */
    if ((prectPtr->rx <= 1.0) && (prectPtr->ry <= 1.0)) {
        if (mPtr == NULL) {
            rectiLinear = 1;
            bareRect[0] = rectPtr->x1;
            bareRect[1] = rectPtr->y1;
            bareRect[2] = rectPtr->x2;
            bareRect[3] = rectPtr->y2;
        } else if ((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {

            /* This is a situation we can treat in a simplified way. Apply the transform here. */
            rectiLinear = 1;
            bareRect[0] = mPtr->a * rectPtr->x1 + mPtr->tx;
            bareRect[1] = mPtr->d * rectPtr->y1 + mPtr->ty;
            bareRect[2] = mPtr->a * rectPtr->x2 + mPtr->tx;
            bareRect[3] = mPtr->d * rectPtr->y2 + mPtr->ty;
        }
    }
    if (rectiLinear) {
        dist = TkPathRectToPoint(bareRect, width, filled, pointPtr);
    } else {
    TkPathAtom *atomPtr = MakePathAtoms(prectPtr);
        dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, atomPtr,
            prectPtr->maxNumSegments, pointPtr);
    TkPathFreeAtoms(atomPtr);
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
PrectToArea(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *areaPtr)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    Tk_PathStyle style = itemExPtr->style;  /* NB: We *copy* the style for temp usage. */
    TkPathMatrix *mPtr;
    TkPathRect *rectPtr = &(itemPtr->bbox);
    double bareRect[4];
    double width;
    int rectiLinear = 0;
    int filled, area;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    filled = HaveAnyFillFromPathColor(style.fill);
    width = 0.0;
    if (style.strokeColor != NULL) {
        width = style.strokeWidth;
    }
    mPtr = style.matrixPtr;

    /* Try to be economical about this for pure rectangles. */
    if ((prectPtr->rx <= 1.0) && (prectPtr->ry <= 1.0)) {
        if (mPtr == NULL) {
            rectiLinear = 1;
            bareRect[0] = rectPtr->x1;
            bareRect[1] = rectPtr->y1;
            bareRect[2] = rectPtr->x2;
            bareRect[3] = rectPtr->y2;
        } else if ((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {

            /* This is a situation we can treat in a simplified way. Apply the transform here. */
            rectiLinear = 1;
            bareRect[0] = mPtr->a * rectPtr->x1 + mPtr->tx;
            bareRect[1] = mPtr->d * rectPtr->y1 + mPtr->ty;
            bareRect[2] = mPtr->a * rectPtr->x2 + mPtr->tx;
            bareRect[3] = mPtr->d * rectPtr->y2 + mPtr->ty;
        }
    }
    if (rectiLinear) {
        area = TkPathRectToArea(bareRect, width, filled, areaPtr);
    } else {
    TkPathAtom *atomPtr = MakePathAtoms(prectPtr);
        area = TkPathGenericPathToArea(canvas, itemPtr, &style,
                atomPtr, prectPtr->maxNumSegments, areaPtr);
    TkPathFreeAtoms(atomPtr);
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

static int
PrectToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    double points[4];
    Tk_PathState state = itemPtr->state;
    int result;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if (state == TK_PATHSTATE_HIDDEN) {
    return TCL_OK;
    }
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    points[0] = itemPtr->bbox.x1;
    points[1] = itemPtr->bbox.y1;
    points[2] = itemPtr->bbox.x2;
    points[3] = itemPtr->bbox.y2;
    TkPathMakePrectAtoms(points, prectPtr->rx, prectPtr->ry, &atomPtr);
    result = TkPathPdf(interp, atomPtr, &style, &itemPtr->bbox, objc, objv);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScalePrect(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double originX, double originY, double scaleX, double scaleY)
{
    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX, &scaleY);

    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePrect(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double deltaX, double deltaY)
{
    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    /* Just translate the bbox'es as well. */
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvText.c.






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
/*
 * tkCanvPtext.c --
 *
 *    This file implements a text canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkPathInt.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PtextItem  {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                 * path types.  MUST BE FIRST IN STRUCTURE. */
    Tk_PathTextStyle textStyle;
    int textAnchor;
    int fillOverStroke;        /* boolean parameter */
    double x;
    double y;
    double baseHeightRatio;
    double lineSpacing;
    Tcl_Obj *utf8Obj;        /* The actual text to display; UTF-8 */
    int numChars;        /* Length of text in characters. */
    int numBytes;        /* Length of text in bytes. */
    void *custom;        /* Place holder for platform dependent stuff. */
} PtextItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void    ComputePtextBbox(Tk_PathCanvas canvas, PtextItem *ptextPtr);
static int    ConfigurePtext(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int flags);
static int    CreatePtext(Tcl_Interp *interp,
            Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static void    DeletePtext(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display);
static void    DisplayPtext(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, Display *display, Drawable drawable,
            int x, int y, int width, int height);
static void    PtextBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask);
static int    PtextCoords(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int objc, Tcl_Obj *const objv[]);
static int    ProcessPtextCoords(Tcl_Interp *interp, Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, int objc, Tcl_Obj *const objv[]);
static int    PtextToArea(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *rectPtr);
static int    PtextToPdf(Tcl_Interp *interp,
            Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int objc,
            Tcl_Obj *const objv[], int prepass);
static double    PtextToPoint(Tk_PathCanvas canvas,
            Tk_PathItem *itemPtr, double *coordPtr);
static void    ScalePtext(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double originX, double originY,
            double scaleX, double scaleY);
static void    TranslatePtext(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int compensate, double deltaX, double deltaY);
#if 0
static void    PtextDeleteChars(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
            int first, int last);
#endif
static int    drawptext(Tcl_Interp *interp, PtextItem *ptextPtr,
            Tcl_Obj *ret, Tcl_Obj *cmdl);
static char *    linebreak(char *str, char **nextp);

enum {
    PRECT_OPTION_INDEX_FONTFAMILY =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 0)),
    PRECT_OPTION_INDEX_FONTSIZE =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
    PRECT_OPTION_INDEX_TEXT =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 2)),
    PRECT_OPTION_INDEX_TEXTANCHOR =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 3)),
    PRECT_OPTION_INDEX_FONTWEIGHT =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 4)),
    PRECT_OPTION_INDEX_FONTSLANT =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 5)),
    PRECT_OPTION_INDEX_FILLOVERSTROKE =
    (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 6)),
};

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
TK_PATH_CUSTOM_OPTION_TAGS
TK_PATH_OPTION_STRING_TABLES_FILL
TK_PATH_OPTION_STRING_TABLES_STROKE
TK_PATH_OPTION_STRING_TABLES_STATE

/*
 * Best would be to extract font information from the named font
 * "TkDefaultFont" but the option defaults need static strings.
 * Perhaps using NULL and extracting family and size dynamically?
 */
#if (defined(__WIN32__) || defined(_WIN32) || \
    defined(__CYGWIN__) || defined(__MINGW32__)) && !defined(PLATFORM_SDL)
#   define DEF_PATHCANVTEXT_FONTFAMILY         "Tahoma"
#   define DEF_PATHCANVTEXT_FONTSIZE         "8"
#else
#   if defined(MAC_OSX_TK)
#    define DEF_PATHCANVTEXT_FONTFAMILY     "Lucida Grande"
#    define DEF_PATHCANVTEXT_FONTSIZE     "13"
#   else
#    define DEF_PATHCANVTEXT_FONTFAMILY     "Helvetica"
#    define DEF_PATHCANVTEXT_FONTSIZE     "12"
#   endif
#endif
#define DEF_PATHCANVTEXT_FONTWEIGHT "normal"
#define DEF_PATHCANVTEXT_FONTSLANT  "normal"

/*
 * The enum TK_PATH_TEXTANCHOR_Start... MUST be kept in sync!
 */
static const char *textAnchorST[] = {
    "start", "middle", "end", "n", "w", "s", "e",
    "nw", "ne", "sw", "se", "c", NULL
};

static const char *fontWeightST[] = {
    "normal", "bold", NULL
};

static const char *fontSlantST[] = {
    "normal", "italic", "oblique", NULL
};

#define TK_PATH_OPTION_SPEC_FONTFAMILY                \
    {TK_OPTION_STRING, "-fontfamily", NULL, NULL,        \
        DEF_PATHCANVTEXT_FONTFAMILY, -1,            \
        Tk_Offset(PtextItem, textStyle.fontFamily),        \
        0, 0, PRECT_OPTION_INDEX_FONTFAMILY}

#define TK_PATH_OPTION_SPEC_FONTSIZE                \
    {TK_OPTION_DOUBLE, "-fontsize", NULL, NULL,            \
        DEF_PATHCANVTEXT_FONTSIZE, -1,            \
        Tk_Offset(PtextItem, textStyle.fontSize),        \
        0, 0, PRECT_OPTION_INDEX_FONTSIZE}

#define TK_PATH_OPTION_SPEC_TEXT                    \
    {TK_OPTION_STRING, "-text", NULL, NULL,            \
        NULL, Tk_Offset(PtextItem, utf8Obj), -1,        \
        TK_OPTION_NULL_OK, 0, PRECT_OPTION_INDEX_TEXT}

#define TK_PATH_OPTION_SPEC_TEXTANCHOR                \
    {TK_OPTION_STRING_TABLE, "-textanchor", NULL, NULL,        \
        "start", -1, Tk_Offset(PtextItem, textAnchor),    \
        0, (ClientData) textAnchorST, 0}

#define TK_PATH_OPTION_SPEC_FONTWEIGHT                \
    {TK_OPTION_STRING_TABLE, "-fontweight", NULL, NULL,        \
        DEF_PATHCANVTEXT_FONTWEIGHT, -1,            \
        Tk_Offset(PtextItem, textStyle.fontWeight),        \
        0, (ClientData) fontWeightST, PRECT_OPTION_INDEX_FONTWEIGHT}

#define TK_PATH_OPTION_SPEC_FONTSLANT                \
    {TK_OPTION_STRING_TABLE, "-fontslant", NULL, NULL,        \
        DEF_PATHCANVTEXT_FONTSLANT, -1,            \
        Tk_Offset(PtextItem, textStyle.fontSlant),        \
        0, (ClientData) fontSlantST, PRECT_OPTION_INDEX_FONTSLANT}

#define TK_PATH_OPTION_SPEC_FILLOVERSTROKE                \
    {TK_OPTION_BOOLEAN, "-filloverstroke", NULL, NULL,        \
        0, -1, Tk_Offset(PtextItem, fillOverStroke),    \
        0, 0, PRECT_OPTION_INDEX_FILLOVERSTROKE}

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_FONTFAMILY,
    TK_PATH_OPTION_SPEC_FONTSIZE,
    TK_PATH_OPTION_SPEC_FONTSLANT,
    TK_PATH_OPTION_SPEC_FONTWEIGHT,
    TK_PATH_OPTION_SPEC_TEXT,
    TK_PATH_OPTION_SPEC_TEXTANCHOR,
    TK_PATH_OPTION_SPEC_FILLOVERSTROKE,
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeText = {
    "text",                /* name */
    sizeof(PtextItem),            /* itemSize */
    CreatePtext,            /* createProc */
    optionSpecs,            /* configSpecs */
    ConfigurePtext,            /* configureProc */
    PtextCoords,            /* coordProc */
    DeletePtext,            /* deleteProc */
    DisplayPtext,            /* displayProc */
    0,                    /* flags */
    PtextBbox,                /* bboxProc */
    PtextToPoint,            /* pointProc */
    PtextToArea,            /* areaProc */
    PtextToPdf,                /* pdfProc */
    ScalePtext,                /* scaleProc */
    TranslatePtext,            /* translateProc */
    (Tk_PathItemIndexProc *) NULL,    /* indexProc */
    (Tk_PathItemCursorProc *) NULL,    /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,    /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,    /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,    /* dTextProc */
    (Tk_PathItemType *) NULL,        /* nextPtr */
    1,                    /* isPathType */
};

static int
CreatePtext(Tcl_Interp *interp, Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[])
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    int    i;
    Tk_OptionTable optionTable;

    if (objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    ptextPtr->utf8Obj = NULL;
    ptextPtr->numChars = 0;
    ptextPtr->numBytes = 0;
    ptextPtr->textAnchor = TK_PATH_TEXTANCHOR_Start;
    ptextPtr->textStyle.fontFamily = NULL;
    ptextPtr->textStyle.fontSize = 0.0;
    ptextPtr->fillOverStroke = 0;
    ptextPtr->custom = NULL;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) ptextPtr, optionTable,
        Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for (i = 1; i < objc; i++) {
        char *arg = Tcl_GetString(objv[i]);
        if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if (ProcessPtextCoords(interp, canvas, itemPtr, i, objv) != TCL_OK) {
        goto error;
    }
    if (ConfigurePtext(interp, canvas, itemPtr, objc-i, objv+i, 0) == TCL_OK) {
        return TCL_OK;
    }

error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePtext(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
ProcessPtextCoords(Tcl_Interp *interp, Tk_PathCanvas canvas,
    Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[])
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;

    if (objc == 0) {
        Tcl_Obj *obj = Tcl_NewObj();
        Tcl_Obj *subobj = Tcl_NewDoubleObj(ptextPtr->x);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(ptextPtr->y);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if (objc < 3) {
        if (objc == 1) {
            if (Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) &objv) != TCL_OK) {
                return TCL_ERROR;
            } else if (objc != 2) {
                Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coordinates: expected 0 or 2",
                     -1));
                return TCL_ERROR;
            }
        }
        if ((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0],
                      &ptextPtr->x) != TCL_OK) ||
        (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
                      &ptextPtr->y) != TCL_OK)) {
            return TCL_ERROR;
        }
    } else {
        Tcl_SetObjResult(interp,
        Tcl_NewStringObj("wrong # coordinates: expected 0 or 2", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

static int
PtextCoords(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[])
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    int result;

    result = ProcessPtextCoords(interp, canvas, itemPtr, objc, objv);
    if ((result == TCL_OK) && (objc > 0) && (objc < 3)) {
    ComputePtextBbox(canvas, ptextPtr);
    }
    return result;
}

void
ComputePtextBbox(Tk_PathCanvas canvas, PtextItem *ptextPtr)
{
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    Tk_PathItem *itemPtr = &itemExPtr->header;
    Tk_PathStyle style;
    Tk_PathState state = itemExPtr->header.state;
    Tk_Window tkwin = Tk_PathCanvasTkwin(canvas);
    double width;
    double height;
    double bheight;
    double lineSpacing;
    TkPathRect bbox, r;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if ((ptextPtr->utf8Obj == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    r = TkPathTextMeasureBbox(Tk_Display(tkwin), &ptextPtr->textStyle,
        Tcl_GetString(ptextPtr->utf8Obj), &lineSpacing,
        ptextPtr->custom);
    width = r.x2 - r.x1;
    height = r.y2 - r.y1;
    bheight = -r.y1;

    switch (ptextPtr->textAnchor) {
        case TK_PATH_TEXTANCHOR_Start:
        case TK_PATH_TEXTANCHOR_W:
        case TK_PATH_TEXTANCHOR_NW:
        case TK_PATH_TEXTANCHOR_SW:
            bbox.x1 = ptextPtr->x;
            bbox.x2 = bbox.x1 + width;
            break;
        case TK_PATH_TEXTANCHOR_Middle:
        case TK_PATH_TEXTANCHOR_N:
        case TK_PATH_TEXTANCHOR_S:
        case TK_PATH_TEXTANCHOR_C:
            bbox.x1 = ptextPtr->x - width/2;
            bbox.x2 = ptextPtr->x + width/2;
            break;
        case TK_PATH_TEXTANCHOR_End:
        case TK_PATH_TEXTANCHOR_E:
        case TK_PATH_TEXTANCHOR_NE:
        case TK_PATH_TEXTANCHOR_SE:
            bbox.x1 = ptextPtr->x - width;
            bbox.x2 = ptextPtr->x;
            break;
        default:
            break;
    }

    switch (ptextPtr->textAnchor) {
        case TK_PATH_TEXTANCHOR_Start:
        case TK_PATH_TEXTANCHOR_Middle:
        case TK_PATH_TEXTANCHOR_End:
            bbox.y1 = ptextPtr->y + r.y1;   /* r.y1 is negative! */
            bbox.y2 = ptextPtr->y + r.y2;
            break;
        case TK_PATH_TEXTANCHOR_N:
        case TK_PATH_TEXTANCHOR_NW:
        case TK_PATH_TEXTANCHOR_NE:
            bbox.y1 = ptextPtr->y;
            bbox.y2 = ptextPtr->y + height;
            break;
        case TK_PATH_TEXTANCHOR_W:
        case TK_PATH_TEXTANCHOR_E:
        case TK_PATH_TEXTANCHOR_C:
            bbox.y1 = ptextPtr->y - height/2;
            bbox.y2 = ptextPtr->y + height/2;
            break;
        case TK_PATH_TEXTANCHOR_S:
        case TK_PATH_TEXTANCHOR_SW:
        case TK_PATH_TEXTANCHOR_SE:
            bbox.y1 = ptextPtr->y - height;
            bbox.y2 = ptextPtr->y;
            break;
        default:
            break;
    }

    /* Fudge for antialiasing etc. */
    bbox.x1 -= 1.0;
    bbox.y1 -= 1.0;
    bbox.x2 += 1.0;
    bbox.y2 += 1.0;
    height += 2.0;
    bheight += 1.0;
    if (style.strokeColor) {
        double halfWidth = style.strokeWidth/2;
        bbox.x1 -= halfWidth;
        bbox.y1 -= halfWidth;
        bbox.x2 += halfWidth;
        bbox.x2 += halfWidth;
        height += style.strokeWidth;
        bheight += halfWidth;
    }
    itemPtr->bbox = bbox;
    ptextPtr->baseHeightRatio = bheight / height;
    ptextPtr->lineSpacing = lineSpacing;
    itemPtr->totalBbox = itemPtr->bbox;    /* FIXME */
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr, &bbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigurePtext(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int flags)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for (error = 0; error <= 1; error++) {
    if (!error) {
        if (Tk_SetOptions(interp, (char *) ptextPtr, itemPtr->optionTable,
            objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
        continue;
        }
    } else {
        errorResult = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(errorResult);
        Tk_RestoreSavedOptions(&savedOptions);
    }

    /*
     * Since we have -fill default equal to black we need to force
     * setting the fill member of the style.
     */
    if (TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                    mask | TK_PATH_STYLE_OPTION_FILL)
        != TCL_OK) {
        continue;
    }
    /* @@@ TkPathTextConfig needs to be reworked! */
    if (ptextPtr->utf8Obj != NULL) {
        void *custom = NULL;

        ptextPtr->textStyle.fontSize = fabs(ptextPtr->textStyle.fontSize);
        if (TkPathTextConfig(interp, &ptextPtr->textStyle,
            Tcl_GetString(ptextPtr->utf8Obj), &custom) != TCL_OK) {
        continue;
        }
        if (ptextPtr->custom != NULL) {
        TkPathTextFree(&ptextPtr->textStyle, ptextPtr->custom);
        }
        ptextPtr->custom = custom;
    }

    /*
     * If we reach this on the first pass we are OK and continue below.
     */
    break;
    }
    if (!error) {
    Tk_FreeSavedOptions(&savedOptions);
    stylePtr->mask |= mask;
    }

    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    if (ptextPtr->utf8Obj != NULL) {
        ptextPtr->numBytes = Tcl_GetCharLength(ptextPtr->utf8Obj);
        ptextPtr->numChars = Tcl_NumUtfChars(Tcl_GetString(ptextPtr->utf8Obj),
        ptextPtr->numBytes);
    } else {
        ptextPtr->numBytes = 0;
        ptextPtr->numChars = 0;
    }
    if (error) {
    Tcl_SetObjResult(interp, errorResult);
    Tcl_DecrRefCount(errorResult);
    return TCL_ERROR;
    } else {
    ComputePtextBbox(canvas, ptextPtr);
    return TCL_OK;
    }
}

static void
DeletePtext(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    if (stylePtr->fill != NULL) {
    TkPathFreePathColor(stylePtr->fill);
    }
    if (itemExPtr->styleInst != NULL) {
    TkPathFreeStyle(itemExPtr->styleInst);
    }
    TkPathTextFree(&ptextPtr->textStyle, ptextPtr->custom);
    ptextPtr->custom = NULL;
    Tk_FreeConfigOptions((char *) ptextPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPtext(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, Display *display,
    Drawable drawable, int x, int y, int width, int height)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    Tk_PathStyle style;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathContext ctx;

    if (ptextPtr->utf8Obj == NULL) {
        return;
    }

    /*
     * The defaults for -fill and -stroke differ for the ptext item.
     */
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    if (!(style.mask & TK_PATH_STYLE_OPTION_FILL)) {
    style.fill = itemExPtr->style.fill;
    }
    if (!(style.mask & TK_PATH_STYLE_OPTION_STROKE)) {
    style.strokeColor = itemExPtr->style.strokeColor;
    }

    ctx = ContextOfCanvas(canvas);
    TkPathPushTMatrix(ctx, &m);
    if (style.matrixPtr != NULL) {
        TkPathPushTMatrix(ctx, style.matrixPtr);
    }
    TkPathBeginPath(ctx, &style);
    /* @@@ We need to handle gradients as well here!
     *     Wait to see what the other APIs have to say.
     */
    TkPathTextDraw(ctx, &style, &ptextPtr->textStyle,
           itemPtr->bbox.x1,
           itemPtr->bbox.y1 + ptextPtr->baseHeightRatio *
           (itemPtr->bbox.y2 - itemPtr->bbox.y1),
           ptextPtr->fillOverStroke,
           Tcl_GetString(ptextPtr->utf8Obj), ptextPtr->custom);
    TkPathEndPath(ctx);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PtextBbox(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int mask)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    ComputePtextBbox(canvas, ptextPtr);
}

static double
PtextToPoint(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *pointPtr)
{
    Tk_PathStyle style;
    double dist;

    style = TkPathCanvasInheritStyle(itemPtr,
        TK_PATH_MERGESTYLE_NOTFILL | TK_PATH_MERGESTYLE_NOTSTROKE);
    dist = TkPathRectToPointWithMatrix(itemPtr->bbox, style.matrixPtr, pointPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
PtextToArea(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, double *areaPtr)
{
    Tk_PathStyle style;
    int area;

    style = TkPathCanvasInheritStyle(itemPtr,
        TK_PATH_MERGESTYLE_NOTFILL | TK_PATH_MERGESTYLE_NOTSTROKE);
    area = TkPathRectToAreaWithMatrix(itemPtr->bbox, style.matrixPtr, areaPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

/* From tkUnixCairoPath.c */
static char *
linebreak(char *str, char **nextp)
{
    char *ret;

    if (str == NULL) {
        str = *nextp;
    }
    str += strspn(str, "\r\n");
    if (*str == '\0') {
        return NULL;
    }
    ret = str;
    str += strcspn(str, "\r\n");
    if (*str) {
        int ch = *str;

        *str++ = '\0';
        if ((ch == '\r') && (*str == '\n')) {
            str++;
    }
    }
    *nextp = str;
    return ret;
}

static int
drawptext(Tcl_Interp *interp, PtextItem *ptextPtr, Tcl_Obj *ret, Tcl_Obj *cmdl)
{
    char *utf8, *token, *savep;
    Tcl_DString ds;
    int i, result = TCL_OK;

    savep = Tcl_GetStringFromObj(ptextPtr->utf8Obj, &i);
    utf8 = (char *) ckalloc((unsigned) i + 1);
    strcpy(utf8, savep);
    Tcl_DStringInit(&ds);
    for (token = linebreak(utf8, &savep); token != NULL;
     token = linebreak(NULL, &savep)) {
    if (cmdl != NULL) {
        Tcl_Obj *cmd;

        /*
         * Use provided callback for formatting/encoding text.
         */
        cmd = Tcl_DuplicateObj(cmdl);
        Tcl_IncrRefCount(cmd);
        if (Tcl_ListObjAppendElement(interp, cmd,
            Tcl_NewStringObj(token, strlen(token))) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        result = TCL_ERROR;
        break;
        }
        if (Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        result = TCL_ERROR;
        break;
        }
        Tcl_DecrRefCount(cmd);
        Tcl_AppendToObj(ret, "(", 1);
        Tcl_AppendObjToObj(ret, Tcl_GetObjResult(interp));
        Tcl_AppendToObj(ret, ") Tj\nT*\n", 8);
    } else {
        Tcl_DStringSetLength(&ds, 0);
        Tcl_DStringAppend(&ds, "(", 1);
        i = 0;
        while (token[i] != '\0') {
        switch (token[i]) {
        case '(':
        case ')':
        case '\\':
            Tcl_DStringAppend(&ds, "\\", 1);
        default:
            if ((token[i] < 0) || (token[i] >= ' ')) {
            Tcl_DStringAppend(&ds, token + i, 1);
            } else {
            char obuf[8];

            sprintf(obuf, "\\%03o", token[i]);
            Tcl_DStringAppend(&ds, obuf, -1);
            }
            break;
        case '\n':
            Tcl_DStringAppend(&ds, "\\n", 2);
            break;
        case '\r':
            Tcl_DStringAppend(&ds, "\\r", 2);
            break;
        case '\t':
            Tcl_DStringAppend(&ds, "\\t", 2);
            break;
        case '\b':
            Tcl_DStringAppend(&ds, "\\b", 2);
            break;
        case '\f':
            Tcl_DStringAppend(&ds, "\\f", 2);
            break;
        }
        i++;
        }
        Tcl_DStringAppend(&ds, ") Tj\nT*\n", -1);
        Tcl_AppendToObj(ret, Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
    }
    }
    Tcl_DStringFree(&ds);
    ckfree(utf8);
    return result;
}

static int
PtextToPdf(Tcl_Interp *interp, Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int objc, Tcl_Obj *const objv[], int prepass)
{
    Tk_PathStyle style;
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tcl_Obj *ret, *cmdl;
    TkPathMatrix matrix = { 1., 0., 0., 1., 0., 0. };
    TkPathMatrix tmp = {1., 0., 0., -1., 0., 0. };
    Tk_PathState state = itemPtr->state;
    TkPathRect bbox = itemPtr->bbox;
    int hasStroke;
    char *font;
    int result = TCL_OK;

    if (state == TK_PATHSTATE_NULL) {
    state = TkPathCanvasState(canvas);
    }
    if ((ptextPtr->utf8Obj == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
    return result;
    }
    ret = Tcl_NewObj();
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    if (style.matrixPtr != NULL) {
    matrix = *(style.matrixPtr);
    }
    tmp.tx = bbox.x1; /* value with anchoring applied */
    tmp.ty = ptextPtr->y; /* TODO */
    tmp.ty = bbox.y1 + ptextPtr->baseHeightRatio * (bbox.y2 - bbox.y1);
    TkPathMMulTMatrix(&tmp, &matrix);
    /*
     * The defaults for -fill and -stroke differ for the ptext item.
     */
    if (!(style.mask & TK_PATH_STYLE_OPTION_FILL)) {
    style.fill = ptextPtr->headerEx.style.fill;
    } else if (GetGradientMasterFromPathColor(style.fill) != NULL) {
    style.fill = NULL;
    }
    if (!(style.mask & TK_PATH_STYLE_OPTION_STROKE)) {
    style.strokeColor = ptextPtr->headerEx.style.strokeColor;
    }
    if (objc > 0) {
    int retc;
    Tcl_Obj *gs, *cmd, **retv;

    gs = TkPathExtGS(&style, NULL);
    if (gs != NULL) {
        cmd = Tcl_DuplicateObj(objv[0]);
        Tcl_IncrRefCount(cmd);
        if (Tcl_ListObjAppendElement(interp, cmd, gs) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(gs);
        result = TCL_ERROR;
        goto done;
        }
        if (Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        result = TCL_ERROR;
        goto done;
        }
        Tcl_DecrRefCount(cmd);
        /*
         * Get name of extended graphics state.
         */
        if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                       &retc, &retv) != TCL_OK) {
        result = TCL_ERROR;
        goto done;
        }
        if (retc < 2) {
        Tcl_SetResult(interp, (char *) "missing PDF id/name",
                  TCL_STATIC);
        result = TCL_ERROR;
        goto done;
        }
        Tcl_AppendPrintfToObj(ret, "/%s gs\n", Tcl_GetString(retv[1]));
    }
    }
    hasStroke = (style.strokeColor != NULL);
    cmdl = (objc > 1) ? objv[1] : NULL;
    font = (objc > 2) ? Tcl_GetString(objv[2]) : ptextPtr->textStyle.fontFamily;
    /*
     * TODO: ptextPtr->textStyle.fontSlant ptextPtr->textStyle.fontWeight
     */
    Tcl_AppendPrintfToObj(ret, "q\nBT\n/%s ", font);
    TkPathPdfNumber(ret, 3, ptextPtr->textStyle.fontSize, " Tf\n");
    TkPathPdfNumber(ret, 3, ptextPtr->lineSpacing, " TL\n");
    TkPathPdfNumber(ret, 6, matrix.a, " ");
    TkPathPdfNumber(ret, 6, matrix.b, " ");
    TkPathPdfNumber(ret, 6, matrix.c, " ");
    TkPathPdfNumber(ret, 6, matrix.d, " ");
    TkPathPdfNumber(ret, 3, matrix.tx, " ");
    TkPathPdfNumber(ret, 3, matrix.ty, " Tm\n");
    if (ptextPtr->fillOverStroke && hasStroke &&
    (style.fill != NULL) && (style.fill->color != NULL)) {
    /* first pass w/o fill */
    TkPathPdfColor(ret, style.strokeColor, "RG");
    Tcl_AppendToObj(ret, "1 Tr\n", 5);
    TkPathPdfNumber(ret, 3, style.strokeWidth, " w\n");
    result = drawptext(interp, ptextPtr, ret, cmdl);
    if (result == TCL_OK) {
        /* second pass w/o stroke */
        Tcl_AppendPrintfToObj(ret, "ET\nQ\nq\nBT\n/%s ", font);
        TkPathPdfNumber(ret, 3, ptextPtr->textStyle.fontSize, " Tf\n");
        TkPathPdfNumber(ret, 3, ptextPtr->textStyle.fontSize, " TL\n");
        TkPathPdfNumber(ret, 6, matrix.a, " ");
        TkPathPdfNumber(ret, 6, matrix.b, " ");
        TkPathPdfNumber(ret, 6, matrix.c, " ");
        TkPathPdfNumber(ret, 6, matrix.d, " ");
        TkPathPdfNumber(ret, 3, matrix.tx, " ");
        TkPathPdfNumber(ret, 3, matrix.ty, " Tm\n");
        TkPathPdfColor(ret, style.fill->color, "rg");
        Tcl_AppendToObj(ret, "0 Tr\n", 5);
        result = drawptext(interp, ptextPtr, ret, cmdl);
    }
    } else if ((style.fill != NULL) && (style.fill->color != NULL)) {
    TkPathPdfColor(ret, style.fill->color, "rg");
    if (hasStroke) {
        TkPathPdfColor(ret, style.strokeColor, "RG");
        Tcl_AppendToObj(ret, "2 Tr\n", 5);
        TkPathPdfNumber(ret, 3, style.strokeWidth, " w\n");
    } else {
        Tcl_AppendToObj(ret, "0 Tr\n", 5);
    }
    result = drawptext(interp, ptextPtr, ret, cmdl);
    } else if (hasStroke) {
    TkPathPdfColor(ret, style.strokeColor, "RG");
    Tcl_AppendToObj(ret, "1 Tr\n", 5);
    TkPathPdfNumber(ret, 3, style.strokeWidth, " w\n");
    result = drawptext(interp, ptextPtr, ret, cmdl);
    }
done:
    TkPathCanvasFreeInheritedStyle(&style);
    if (result == TCL_OK) {
    Tcl_AppendToObj(ret, "ET\nQ\n", 5);
    Tcl_SetObjResult(interp, ret);
    } else {
    Tcl_DecrRefCount(ret);
    }
    return result;
}

static void
ScalePtext(Tk_PathCanvas canvas, Tk_PathItem *itemPtr, int compensate,
    double originX, double originY, double scaleX, double scaleY)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX, &scaleY);

    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    ptextPtr->x = originX + scaleX*(ptextPtr->x - originX);
    ptextPtr->y = originY + scaleY*(ptextPtr->y - originY);
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePtext(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int compensate, double deltaX, double deltaY)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    ptextPtr->x += deltaX;
    ptextPtr->y += deltaY;
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

#if 0    /* TODO */
static void
PtextDeleteChars(Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
    int first, int last)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    int byteIndex, byteCount, charsRemoved;
    char *new, *text;

    text = ptextPtr->utf8;
    if (first < 0) {
        first = 0;
    }
    if (last >= ptextPtr->numChars) {
        last = ptextPtr->numChars - 1;
    }
    if (first > last) {
        return;
    }
    charsRemoved = last + 1 - first;

    byteIndex = Tcl_UtfAtIndex(text, first) - text;
    byteCount = Tcl_UtfAtIndex(text + byteIndex, charsRemoved)
    - (text + byteIndex);

    new = (char *) ckalloc((unsigned) (ptextPtr->numBytes + 1 - byteCount));
    memcpy(new, text, (size_t) byteIndex);
    strcpy(new + byteIndex, text + byteIndex + byteCount);

    ckfree(text);
    ptextPtr->utf8 = new;
    ptextPtr->numChars -= charsRemoved;
    ptextPtr->numBytes -= byteCount;

    /*
     * TkPathTextConfig(interp, &ptextPtr->textStyle,
     *                  ptextPtr->utf8, &ptextPtr->custom);
     */
    ComputePtextBbox(canvas, ptextPtr);
    return;
}
#endif
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */

Added generic/rbc/tkPathCanvWindow.c.










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
/*
 * tkpCanvWind.c --
 *
 *	This file implements window items for canvas widgets.
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#include "tkPathInt.h"

/*
 * The structure below defines the record for each window item.
 */

typedef struct WindowItem  {
    Tk_PathItem header;		/* Generic stuff that's the same for all
				 * types.  MUST BE FIRST IN STRUCTURE. */
    double x, y;		/* Coordinates of positioning point for
				 * window. */
    Tk_Window tkwin;		/* Window associated with item.  NULL means
				 * window has been destroyed. */
    int width;			/* Width to use for window (<= 0 means use
				 * window's requested width). */
    int height;			/* Width to use for window (<= 0 means use
				 * window's requested width). */
    Tk_Anchor anchor;		/* Where to anchor window relative to
				 * (x,y). */
    Tk_PathCanvas canvas;		/* Canvas containing this item. */
} WindowItem;

#define PATH_DEF_STATE "normal"

static CONST char *stateStrings[] = {
    "active", "disabled", "normal", "hidden", NULL
};

static Tk_ObjCustomOption tagsCO = {
    "tags",
    Tk_PathCanvasTagsOptionSetProc,
    Tk_PathCanvasTagsOptionGetProc,
    Tk_PathCanvasTagsOptionRestoreProc,
    Tk_PathCanvasTagsOptionFreeProc,
    (ClientData) NULL
};

static Tk_OptionSpec optionSpecs[] = {
    {TK_OPTION_ANCHOR, "-anchor", NULL, NULL,
	"center", -1, Tk_Offset(WindowItem, anchor), 0, 0, 0},
    {TK_OPTION_PIXELS, "-height", NULL, NULL,
        "0", -1, Tk_Offset(WindowItem, height), 0, 0, 0},
    {TK_OPTION_STRING_TABLE, "-state", NULL, NULL,
        PATH_DEF_STATE, -1, Tk_Offset(Tk_PathItem, state),
        0, (ClientData) stateStrings, 0},
    {TK_OPTION_CUSTOM, "-tags", NULL, NULL,
	NULL, -1, Tk_Offset(Tk_PathItem, pathTagsPtr),
	TK_OPTION_NULL_OK, (ClientData) &tagsCO, 0},
    {TK_OPTION_PIXELS, "-width", NULL, NULL,
        "0", -1, Tk_Offset(WindowItem, width), 0, 0, 0},
    {TK_OPTION_WINDOW, "-window", NULL, NULL,
	NULL, -1, Tk_Offset(WindowItem, tkwin),
	TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_END, NULL, NULL, NULL,
	NULL, 0, -1, 0, (ClientData) NULL, 0}
};

/*
 * Prototypes for functions defined in this file:
 */

static void		ComputeWindowBbox(Tk_PathCanvas canvas,
			    WindowItem *winItemPtr);
static int		ConfigureWinItem(Tcl_Interp *interp,
			    Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
			    int objc, Tcl_Obj *CONST objv[], int flags);
static int		CreateWinItem(Tcl_Interp *interp,
			    Tk_PathCanvas canvas, struct Tk_PathItem *itemPtr,
			    int objc, Tcl_Obj *CONST objv[]);
static void		DeleteWinItem(Tk_PathCanvas canvas,
			    Tk_PathItem *itemPtr, Display *display);
static void		DisplayWinItem(Tk_PathCanvas canvas,
			    Tk_PathItem *itemPtr, Display *display,
			    Drawable dst,
			    int x, int y, int width, int height);
static void		ScaleWinItem(Tk_PathCanvas canvas,
			    Tk_PathItem *itemPtr, int compensate,
			    double originX, double originY,
			    double scaleX, double scaleY);
static void		TranslateWinItem(Tk_PathCanvas canvas,
			    Tk_PathItem *itemPtr, int compensate,
			    double deltaX, double deltaY);
static int		WinItemCoords(Tcl_Interp *interp,
			    Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
			    int objc, Tcl_Obj *CONST objv[]);
static void		WinItemLostSlaveProc(ClientData clientData,
			    Tk_Window tkwin);
static void		WinItemRequestProc(ClientData clientData,
			    Tk_Window tkwin);
static void		WinItemStructureProc(ClientData clientData,
			    XEvent *eventPtr);
static int		WinItemToArea(Tk_PathCanvas canvas,
			    Tk_PathItem *itemPtr, double *rectPtr);
static int		WinItemToPdf(Tcl_Interp *interp,
			    Tk_PathCanvas canvas, Tk_PathItem *itemPtr,
			    int objc, Tcl_Obj *CONST objv[], int prepass);
static double		WinItemToPoint(Tk_PathCanvas canvas,
			    Tk_PathItem *itemPtr, double *pointPtr);
#ifdef X_GetImage
static int		xerrorhandler(ClientData clientData, XErrorEvent *e);
#endif

/*
 * The structure below defines the window item type by means of functions
 * that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeWindow = {
    "window",			/* name */
    sizeof(WindowItem),		/* itemSize */
    CreateWinItem,		/* createProc */
    optionSpecs,		/* optionSpecs */
    ConfigureWinItem,		/* configureProc */
    WinItemCoords,		/* coordProc */
    DeleteWinItem,		/* deleteProc */
    DisplayWinItem,		/* displayProc */
    1,				/* flags */
    NULL,			/* bboxProc */
    WinItemToPoint,		/* pointProc */
    WinItemToArea,		/* areaProc */
    WinItemToPdf,		/* pdfProc */
    ScaleWinItem,		/* scaleProc */
    TranslateWinItem,		/* translateProc */
    NULL,			/* indexProc */
    NULL,			/* cursorProc */
    NULL,			/* selectionProc */
    NULL,			/* insertProc */
    NULL,			/* dTextProc */
    NULL,			/* nextPtr */
    0,				/* isPathType */
};

/*
 * The structure below defines the official type record for the canvas (as
 * geometry manager):
 */

static const Tk_GeomMgr canvasGeomType = {
    "canvas",				/* name */
    WinItemRequestProc,			/* requestProc */
    WinItemLostSlaveProc,		/* lostSlaveProc */
};
 
/*
 *--------------------------------------------------------------
 *
 * CreateWinItem --
 *
 *	This function is invoked to create a new window item in a canvas.
 *
 * Results:
 *	A standard Tcl return value. If an error occurred in creating the
 *	item, then an error message is left in the interp's result; in this
 *	case itemPtr is left uninitialized, so it can be safely freed by the
 *	caller.
 *
 * Side effects:
 *	A new window item is created.
 *
 *--------------------------------------------------------------
 */

static int
CreateWinItem(
    Tcl_Interp *interp,		/* Interpreter for error reporting. */
    Tk_PathCanvas canvas,		/* Canvas to hold new item. */
    Tk_PathItem *itemPtr,		/* Record to hold new item; header has been
				 * initialized by caller. */
    int objc,			/* Number of arguments in objv. */
    Tcl_Obj *CONST objv[])	/* Arguments describing window. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    int i;
    Tk_OptionTable optionTable;

    if (objc == 0) {
	Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Initialize item's record.
     */

    winItemPtr->tkwin = NULL;
    winItemPtr->width = 0;
    winItemPtr->height = 0;
    winItemPtr->anchor = TK_ANCHOR_CENTER;
    winItemPtr->canvas = canvas;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if (Tk_InitOptions(interp, (char *) winItemPtr, optionTable,
	    Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    /*
     * Process the arguments to fill in the item record. Only 1 (list) or 2 (x
     * y) coords are allowed.
     */

    if (objc == 1) {
	i = 1;
    } else {
	char *arg = Tcl_GetString(objv[1]);
	i = 2;
	if ((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
	    i = 1;
	}
    }
    if (WinItemCoords(interp, canvas, itemPtr, i, objv) != TCL_OK) {
	goto error;
    }
    if (ConfigureWinItem(interp, canvas, itemPtr, objc-i, objv+i, 0)
	    == TCL_OK) {
	return TCL_OK;
    }

  error:
    DeleteWinItem(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}
 
/*
 *--------------------------------------------------------------
 *
 * WinItemCoords --
 *
 *	This function is invoked to process the "coords" widget command on
 *	window items. See the user documentation for details on what it does.
 *
 * Results:
 *	Returns TCL_OK or TCL_ERROR, and sets the interp's result.
 *
 * Side effects:
 *	The coordinates for the given item may be changed.
 *
 *--------------------------------------------------------------
 */

static int
WinItemCoords(
    Tcl_Interp *interp,		/* Used for error reporting. */
    Tk_PathCanvas canvas,		/* Canvas containing item. */
    Tk_PathItem *itemPtr,		/* Item whose coordinates are to be read or
				 * modified. */
    int objc,			/* Number of coordinates supplied in objv. */
    Tcl_Obj *CONST objv[])	/* Array of coordinates: x1, y1, x2, y2, ... */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    if (objc == 0) {
	Tcl_Obj *obj = Tcl_NewObj();
	Tcl_Obj *subobj = Tcl_NewDoubleObj(winItemPtr->x);
	Tcl_ListObjAppendElement(interp, obj, subobj);
	subobj = Tcl_NewDoubleObj(winItemPtr->y);
	Tcl_ListObjAppendElement(interp, obj, subobj);
	Tcl_SetObjResult(interp, obj);
    } else if (objc < 3) {
	if (objc==1) {
	    if (Tcl_ListObjGetElements(interp, objv[0], &objc,
		    (Tcl_Obj ***) &objv) != TCL_OK) {
		return TCL_ERROR;
	    } else if (objc != 2) {
		char buf[64 + TCL_INTEGER_SPACE];

		sprintf(buf, "wrong # coordinates: expected 2, got %d", objc);
		Tcl_SetResult(interp, buf, TCL_VOLATILE);
		return TCL_ERROR;
	    }
	}
	if ((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0], &winItemPtr->x)
		!= TCL_OK) || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
		&winItemPtr->y) != TCL_OK)) {
	    return TCL_ERROR;
	}
	ComputeWindowBbox(canvas, winItemPtr);
    } else {
	char buf[64 + TCL_INTEGER_SPACE];

	sprintf(buf, "wrong # coordinates: expected 0 or 2, got %d", objc);
	Tcl_SetResult(interp, buf, TCL_VOLATILE);
	return TCL_ERROR;
    }
    return TCL_OK;
}
 
/*
 *--------------------------------------------------------------
 *
 * ConfigureWinItem --
 *
 *	This function is invoked to configure various aspects of a window
 *	item, such as its anchor position.
 *
 * Results:
 *	A standard Tcl result code. If an error occurs, then an error message
 *	is left in the interp's result.
 *
 * Side effects:
 *	Configuration information may be set for itemPtr.
 *
 *--------------------------------------------------------------
 */

static int
ConfigureWinItem(
    Tcl_Interp *interp,		/* Used for error reporting. */
    Tk_PathCanvas canvas,	/* Canvas containing itemPtr. */
    Tk_PathItem *itemPtr,	/* Window item to reconfigure. */
    int objc,			/* Number of elements in objv.  */
    Tcl_Obj *CONST objv[],	/* Arguments describing things to configure. */
    int flags)			/* Flags to pass to Tk_ConfigureWidget. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    Tk_Window oldWindow;
    Tk_Window canvasTkwin;

    oldWindow = winItemPtr->tkwin;
    canvasTkwin = Tk_PathCanvasTkwin(canvas);
    if (TCL_OK != Tk_SetOptions(interp, (char *) winItemPtr,
	    itemPtr->optionTable,
	    objc, objv, canvasTkwin, NULL, NULL)) {
	return TCL_ERROR;
    }

    /*
     * A few of the options require additional processing.
     */

    if (oldWindow != winItemPtr->tkwin) {
	if (oldWindow != NULL) {
	    Tk_DeleteEventHandler(oldWindow, StructureNotifyMask,
		    WinItemStructureProc, (ClientData) winItemPtr);
	    Tk_ManageGeometry(oldWindow, NULL, (ClientData) NULL);
	    Tk_UnmaintainGeometry(oldWindow, canvasTkwin);
	    Tk_UnmapWindow(oldWindow);
	}
	if (winItemPtr->tkwin != NULL) {
	    Tk_Window ancestor, parent;

	    /*
	     * Make sure that the canvas is either the parent of the window
	     * associated with the item or a descendant of that parent. Also,
	     * don't allow a top-of-hierarchy window to be managed inside a
	     * canvas.
	     */

	    parent = Tk_Parent(winItemPtr->tkwin);
	    for (ancestor = canvasTkwin; ;
		    ancestor = Tk_Parent(ancestor)) {
		if (ancestor == parent) {
		    break;
		}
		if (((Tk_FakeWin *) (ancestor))->flags & TK_TOP_HIERARCHY) {
		badWindow:
		    Tcl_AppendResult(interp, "can't use ",
			    Tk_PathName(winItemPtr->tkwin),
			    " in a window item of this canvas", NULL);
		    winItemPtr->tkwin = NULL;
		    return TCL_ERROR;
		}
	    }
	    if (((Tk_FakeWin *) (winItemPtr->tkwin))->flags & TK_TOP_HIERARCHY) {
		goto badWindow;
	    }
	    if (winItemPtr->tkwin == canvasTkwin) {
		goto badWindow;
	    }
	    Tk_CreateEventHandler(winItemPtr->tkwin, StructureNotifyMask,
		    WinItemStructureProc, (ClientData) winItemPtr);
	    Tk_ManageGeometry(winItemPtr->tkwin, &canvasGeomType,
		    (ClientData) winItemPtr);
	}
    }
    if ((winItemPtr->tkwin != NULL)
	    && (itemPtr->state == TK_PATHSTATE_HIDDEN)) {
	if (canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
	    Tk_UnmapWindow(winItemPtr->tkwin);
	} else {
	    Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
	}
    }

    ComputeWindowBbox(canvas, winItemPtr);

    return TCL_OK;
}
 
/*
 *--------------------------------------------------------------
 *
 * DeleteWinItem --
 *
 *	This function is called to clean up the data structure associated with
 *	a window item.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Resources associated with itemPtr are released.
 *
 *--------------------------------------------------------------
 */

static void
DeleteWinItem(
    Tk_PathCanvas canvas,		/* Overall info about widget. */
    Tk_PathItem *itemPtr,		/* Item that is being deleted. */
    Display *display)		/* Display containing window for canvas. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    Tk_Window canvasTkwin = Tk_PathCanvasTkwin(canvas);

    if (winItemPtr->tkwin != NULL) {
	Tk_DeleteEventHandler(winItemPtr->tkwin, StructureNotifyMask,
		WinItemStructureProc, (ClientData) winItemPtr);
	Tk_ManageGeometry(winItemPtr->tkwin, NULL,
		(ClientData) NULL);
	if (canvasTkwin != Tk_Parent(winItemPtr->tkwin)) {
	    Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
	}
	Tk_UnmapWindow(winItemPtr->tkwin);
    }
    Tk_FreeConfigOptions((char *) itemPtr, itemPtr->optionTable,
			 Tk_PathCanvasTkwin(canvas));
}
 
/*
 *--------------------------------------------------------------
 *
 * ComputeWindowBbox --
 *
 *	This function is invoked to compute the bounding box of all the pixels
 *	that may be drawn as part of a window item. This function is where the
 *	child window's placement is computed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The fields x1, y1, x2, and y2 are updated in the header for itemPtr.
 *
 *--------------------------------------------------------------
 */

static void
ComputeWindowBbox(
    Tk_PathCanvas canvas,		/* Canvas that contains item. */
    WindowItem *winItemPtr)	/* Item whose bbox is to be recomputed. */
{
    int width, height, x, y;
    Tk_PathState state = winItemPtr->header.state;

    x = (int) (winItemPtr->x + ((winItemPtr->x >= 0) ? 0.5 : - 0.5));
    y = (int) (winItemPtr->y + ((winItemPtr->y >= 0) ? 0.5 : - 0.5));

    if (state == TK_PATHSTATE_NULL) {
	state = TkPathCanvasState(canvas);
    }
    if ((winItemPtr->tkwin == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
	/*
	 * There is no window for this item yet. Just give it a 1x1 bounding
	 * box. Don't give it a 0x0 bounding box; there are strange cases
	 * where this bounding box might be used as the dimensions of the
	 * window, and 0x0 causes problems under X.
	 */

	winItemPtr->header.x1 = x;
	winItemPtr->header.x2 = winItemPtr->header.x1 + 1;
	winItemPtr->header.y1 = y;
	winItemPtr->header.y2 = winItemPtr->header.y1 + 1;
	return;
    }

    /*
     * Compute dimensions of window.
     */

    width = winItemPtr->width;
    if (width <= 0) {
	width = Tk_ReqWidth(winItemPtr->tkwin);
	if (width <= 0) {
	    width = 1;
	}
    }
    height = winItemPtr->height;
    if (height <= 0) {
	height = Tk_ReqHeight(winItemPtr->tkwin);
	if (height <= 0) {
	    height = 1;
	}
    }

    /*
     * Compute location of window, using anchor information.
     */

    switch (winItemPtr->anchor) {
    case TK_ANCHOR_N:
	x -= width/2;
	break;
    case TK_ANCHOR_NE:
	x -= width;
	break;
    case TK_ANCHOR_E:
	x -= width;
	y -= height/2;
	break;
    case TK_ANCHOR_SE:
	x -= width;
	y -= height;
	break;
    case TK_ANCHOR_S:
	x -= width/2;
	y -= height;
	break;
    case TK_ANCHOR_SW:
	y -= height;
	break;
    case TK_ANCHOR_W:
	y -= height/2;
	break;
    case TK_ANCHOR_NW:
	break;
    case TK_ANCHOR_CENTER:
	x -= width/2;
	y -= height/2;
	break;
    }

    /*
     * Store the information in the item header.
     */

    winItemPtr->header.x1 = x;
    winItemPtr->header.y1 = y;
    winItemPtr->header.x2 = x + width;
    winItemPtr->header.y2 = y + height;
}
 
/*
 *--------------------------------------------------------------
 *
 * DisplayWinItem --
 *
 *	This function is invoked to "draw" a window item in a given drawable.
 *	Since the window draws itself, we needn't do any actual redisplay
 *	here. However, this function takes care of actually repositioning the
 *	child window so that it occupies the correct screen position.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The child window's position may get changed. Note: this function gets
 *	called both when a window needs to be displayed and when it ceases to
 *	be visible on the screen (e.g. it was scrolled or moved off-screen or
 *	the enclosing canvas is unmapped).
 *
 *--------------------------------------------------------------
 */

static void
DisplayWinItem(
    Tk_PathCanvas canvas,		/* Canvas that contains item. */
    Tk_PathItem *itemPtr,		/* Item to be displayed. */
    Display *display,		/* Display on which to draw item. */
    Drawable drawable,		/* Pixmap or window in which to draw item. */
    int regionX, int regionY, int regionWidth, int regionHeight)
				/* Describes region of canvas that must be
				 * redisplayed (not used). */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    int width, height;
    short x, y;
    Tk_Window canvasTkwin = Tk_PathCanvasTkwin(canvas);
    Tk_PathState state = itemPtr->state;

    if (winItemPtr->tkwin == NULL) {
	return;
    }
    if (state == TK_PATHSTATE_NULL) {
	state = TkPathCanvasState(canvas);
    }

    /*
     * A drawable of None is used by the canvas UnmapNotify handler
     * to indicate that we should no longer display ourselves.
     */
    if (state == TK_PATHSTATE_HIDDEN || drawable == None) {
	if (canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
	    Tk_UnmapWindow(winItemPtr->tkwin);
	} else {
	    Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
	}
	return;
    }
    Tk_PathCanvasWindowCoords(canvas, (double) winItemPtr->header.x1,
	    (double) winItemPtr->header.y1, &x, &y);
    width = winItemPtr->header.x2 - winItemPtr->header.x1;
    height = winItemPtr->header.y2 - winItemPtr->header.y1;

    /*
     * If the window is completely out of the visible area of the canvas then
     * unmap it. This code used not to be present (why unmap the window if it
     * isn't visible anyway?) but this could cause the window to suddenly
     * reappear if the canvas window got resized.
     */

    if (((x + width) <= 0) || ((y + height) <= 0)
	    || (x >= Tk_Width(canvasTkwin)) || (y >= Tk_Height(canvasTkwin))) {
	if (canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
	    Tk_UnmapWindow(winItemPtr->tkwin);
	} else {
	    Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
	}
	return;
    }

    /*
     * Reposition and map the window (but in different ways depending on
     * whether the canvas is the window's parent).
     */

    if (canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
	if ((x != Tk_X(winItemPtr->tkwin)) || (y != Tk_Y(winItemPtr->tkwin))
		|| (width != Tk_Width(winItemPtr->tkwin))
		|| (height != Tk_Height(winItemPtr->tkwin))) {
	    Tk_MoveResizeWindow(winItemPtr->tkwin, x, y, width, height);
	}
	Tk_MapWindow(winItemPtr->tkwin);
    } else {
	Tk_MaintainGeometry(winItemPtr->tkwin, canvasTkwin, x, y,
		width, height);
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * WinItemToPoint --
 *
 *	Computes the distance from a given point to a given window, in canvas
 *	units.
 *
 * Results:
 *	The return value is 0 if the point whose x and y coordinates are
 *	coordPtr[0] and coordPtr[1] is inside the window. If the point isn't
 *	inside the window then the return value is the distance from the point
 *	to the window.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static double
WinItemToPoint(
    Tk_PathCanvas canvas,	/* Canvas containing item. */
    Tk_PathItem *itemPtr,	/* Item to check against point. */
    double *pointPtr)		/* Pointer to x and y coordinates. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    double x1, x2, y1, y2, xDiff, yDiff;

    x1 = winItemPtr->header.x1;
    y1 = winItemPtr->header.y1;
    x2 = winItemPtr->header.x2;
    y2 = winItemPtr->header.y2;

    /*
     * Point is outside window.
     */

    if (pointPtr[0] < x1) {
	xDiff = x1 - pointPtr[0];
    } else if (pointPtr[0] >= x2)  {
	xDiff = pointPtr[0] + 1 - x2;
    } else {
	xDiff = 0;
    }

    if (pointPtr[1] < y1) {
	yDiff = y1 - pointPtr[1];
    } else if (pointPtr[1] >= y2)  {
	yDiff = pointPtr[1] + 1 - y2;
    } else {
	yDiff = 0;
    }

    return hypot(xDiff, yDiff);
}
 
/*
 *--------------------------------------------------------------
 *
 * WinItemToArea --
 *
 *	This function is called to determine whether an item lies entirely
 *	inside, entirely outside, or overlapping a given rectangle.
 *
 * Results:
 *	-1 is returned if the item is entirely outside the area given by
 *	rectPtr, 0 if it overlaps, and 1 if it is entirely inside the given
 *	area.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
WinItemToArea(
    Tk_PathCanvas canvas,		/* Canvas containing item. */
    Tk_PathItem *itemPtr,		/* Item to check against rectangle. */
    double *rectPtr)		/* Pointer to array of four coordinates
				 * (x1,y1,x2,y2) describing rectangular
				 * area.  */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    if ((rectPtr[2] <= winItemPtr->header.x1)
	    || (rectPtr[0] >= winItemPtr->header.x2)
	    || (rectPtr[3] <= winItemPtr->header.y1)
	    || (rectPtr[1] >= winItemPtr->header.y2)) {
	return -1;
    }
    if ((rectPtr[0] <= winItemPtr->header.x1)
	    && (rectPtr[1] <= winItemPtr->header.y1)
	    && (rectPtr[2] >= winItemPtr->header.x2)
	    && (rectPtr[3] >= winItemPtr->header.y2)) {
	return 1;
    }
    return 0;
}
 
/*
 *--------------------------------------------------------------
 *
 * xerrorhandler --
 *
 *	This is a dummy function to catch X11 errors during an attempt to
 *	print a canvas window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

#ifdef X_GetImage
static int
xerrorhandler(
    ClientData clientData,
    XErrorEvent *e)
{
    return 0;
}
#endif

 
/*
 *--------------------------------------------------------------
 *
 * WinItemToPdf --
 *
 *	This function is called to generate Pdf for window items.
 *
 * Results:
 *	The return value is a standard Tcl result. If an error occurs in
 *	generating Pdf then an error message is left in interp->result,
 *	replacing whatever used to be there. If no error occurs, then
 *	Pdf for the item is appended to the result.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
WinItemToPdf(
    Tcl_Interp *interp,		/* Leave Pdf or error message here. */
    Tk_PathCanvas canvas,	/* Information about overall canvas. */
    Tk_PathItem *itemPtr,	/* Item for which Pdf is wanted. */
    int objc,                   /* Number of arguments. */
    Tcl_Obj *CONST objv[],      /* Argument list. */
    int prepass)		/* 1 means this is a prepass to collect font
				 * information; 0 means final Pdf is
				 * being created. */
{
    return TCL_OK;
}
 
/*
 *--------------------------------------------------------------
 *
 * ScaleWinItem --
 *
 *	This function is invoked to rescale a window item.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The window referred to by itemPtr is rescaled so that the following
 *	transformation is applied to all point coordinates:
 *		x' = originX + scaleX*(x-originX)
 *		y' = originY + scaleY*(y-originY)
 *
 *--------------------------------------------------------------
 */

static void
ScaleWinItem(
    Tk_PathCanvas canvas,		/* Canvas containing window. */
    Tk_PathItem *itemPtr,		/* Window to be scaled. */
    int compensate,			/* Unused. */
    double originX, double originY,
				/* Origin about which to scale window. */
    double scaleX,		/* Amount to scale in X direction. */
    double scaleY)		/* Amount to scale in Y direction. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    winItemPtr->x = originX + scaleX*(winItemPtr->x - originX);
    winItemPtr->y = originY + scaleY*(winItemPtr->y - originY);
    if (winItemPtr->width > 0) {
	winItemPtr->width = (int) (scaleX*winItemPtr->width);
    }
    if (winItemPtr->height > 0) {
	winItemPtr->height = (int) (scaleY*winItemPtr->height);
    }
    ComputeWindowBbox(canvas, winItemPtr);
}
 
/*
 *--------------------------------------------------------------
 *
 * TranslateWinItem --
 *
 *	This function is called to move a window by a given amount.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The position of the window is offset by (xDelta, yDelta), and the
 *	bounding box is updated in the generic part of the item structure.
 *
 *--------------------------------------------------------------
 */

static void
TranslateWinItem(
    Tk_PathCanvas canvas,		/* Canvas containing item. */
    Tk_PathItem *itemPtr,		/* Item that is being moved. */
    int compensate,			/* Unused. */
    double deltaX, double deltaY)
				/* Amount by which item is to be moved. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    winItemPtr->x += deltaX;
    winItemPtr->y += deltaY;
    ComputeWindowBbox(canvas, winItemPtr);
}
 
/*
 *--------------------------------------------------------------
 *
 * WinItemStructureProc --
 *
 *	This function is invoked whenever StructureNotify events occur for a
 *	window that's managed as part of a canvas window item. This function's
 *	only purpose is to clean up when windows are deleted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The window is disassociated from the window item when it is deleted.
 *
 *--------------------------------------------------------------
 */

static void
WinItemStructureProc(
    ClientData clientData,	/* Pointer to record describing window item. */
    XEvent *eventPtr)		/* Describes what just happened. */
{
    WindowItem *winItemPtr = (WindowItem *) clientData;

    if (eventPtr->type == DestroyNotify) {
	winItemPtr->tkwin = NULL;
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * WinItemRequestProc --
 *
 *	This function is invoked whenever a window that's associated with a
 *	window canvas item changes its requested dimensions.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The size and location on the screen of the window may change,
 *	depending on the options specified for the window item.
 *
 *--------------------------------------------------------------
 */

static void
WinItemRequestProc(
    ClientData clientData,	/* Pointer to record for window item. */
    Tk_Window tkwin)		/* Window that changed its desired size. */
{
    WindowItem *winItemPtr = (WindowItem *) clientData;

    ComputeWindowBbox(winItemPtr->canvas, winItemPtr);

    /*
     * A drawable argument of None to DisplayWinItem is used by the canvas
     * UnmapNotify handler to indicate that we should no longer display
     * ourselves, so need to pass a (bogus) non-zero drawable value here.
     */
    DisplayWinItem(winItemPtr->canvas, (Tk_PathItem *) winItemPtr, NULL,
	    (Drawable) -1, 0, 0, 0, 0);
}
 
/*
 *--------------------------------------------------------------
 *
 * WinItemLostSlaveProc --
 *
 *	This function is invoked by Tk whenever some other geometry claims
 *	control over a slave that used to be managed by us.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Forgets all canvas-related information about the slave.
 *
 *--------------------------------------------------------------
 */

	/* ARGSUSED */
static void
WinItemLostSlaveProc(
    ClientData clientData,	/* WindowItem structure for slave window that
				 * was stolen away. */
    Tk_Window tkwin)		/* Tk's handle for the slave window. */
{
    WindowItem *winItemPtr = (WindowItem *) clientData;
    Tk_Window canvasTkwin = Tk_PathCanvasTkwin(winItemPtr->canvas);

    Tk_DeleteEventHandler(winItemPtr->tkwin, StructureNotifyMask,
	    WinItemStructureProc, (ClientData) winItemPtr);
    if (canvasTkwin != Tk_Parent(winItemPtr->tkwin)) {
	Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
    }
    Tk_UnmapWindow(winItemPtr->tkwin);
    winItemPtr->tkwin = NULL;
}
 
/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */

Added generic/rbc/tkPathCanvas.c.








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
/*
 * tkpCanvas.c --
 *
 *    This module implements canvas widgets for the Tk toolkit. A canvas
 *    displays a background and a collection of graphical objects such as
 *    rectangles, lines, and texts.
 *
 * Copyright (c) 1991-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 1998-1999 by Scriptics Corporation.
 * Copyright (c) 2008 Mats Bengtsson
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#ifdef MAC_OSX_TK
#define TK_PATH_NO_DOUBLE_BUFFERING
#endif

#include "tkPathInt.h"

int Tk_PathAntiAlias = 1;
int Tk_PathDepixelize = 1;
int Tk_PathSurfaceCopyPremultiplyAlpha = 1;

/*
 * Flag bits for canvases:
 *
 * REDRAW_PENDING -        1 means a DoWhenIdle handler has already been
 *                created to redraw some or all of the canvas.
 * REDRAW_BORDERS -         1 means that the borders need to be redrawn
 *                during the next redisplay operation.
 * REPICK_NEEDED -        1 means DisplayCanvas should pick a new
 *                current item before redrawing the canvas.
 * GOT_FOCUS -            1 means the focus is currently in this widget,
 *                so should draw the insertion cursor and
 *                traversal highlight.
 * CURSOR_ON -            1 means the insertion cursor is in the "on"
 *                phase of its blink cycle. 0 means either we
 *                don't have the focus or the cursor is in the
 *                "off" phase of its cycle.
 * UPDATE_SCROLLBARS -        1 means the scrollbars should get updated as
 *                part of the next display operation.
 * LEFT_GRABBED_ITEM -        1 means that the mouse left the current item
 *                while a grab was in effect, so we didn't
 *                change canvasPtr->currentItemPtr.
 * REPICK_IN_PROGRESS -        1 means PickCurrentItem is currently
 *                executing. If it should be called recursively,
 *                it should simply return immediately.
 * BBOX_NOT_EMPTY -        1 means that the bounding box of the area that
 *                should be redrawn is not empty.
 * CANVAS_DELETED -
 */

#define REDRAW_PENDING        (1 << 0)
#define REDRAW_BORDERS        (1 << 1)
#define REPICK_NEEDED        (1 << 2)
#define GOT_FOCUS        (1 << 3)
#define CURSOR_ON        (1 << 4)
#define UPDATE_SCROLLBARS    (1 << 5)
#define LEFT_GRABBED_ITEM    (1 << 6)
#define REPICK_IN_PROGRESS    (1 << 7)
#define BBOX_NOT_EMPTY        (1 << 8)
#define CANVAS_DELETED        (1 << 9)

/*
 * Flag bits for canvas items (redraw_flags):
 *
 * FORCE_REDRAW -        1 means that the new coordinates of some item
 *                are not yet registered using
 *                Tk_PathCanvasEventuallyRedraw(). It should still
 *                be done by the general canvas code.
 */

#define FORCE_REDRAW        8

/*
 * The structure defined below is used to keep track of a tag search in
 * progress. No field should be accessed by anyone other than TagSearchScan,
 * TagSearchFirst, TagSearchNext, TagSearchScanExpr, TagSearchEvalExpr,
 * TagSearchExprInit, TagSearchExprDestroy, TagSearchDestroy.
 * (
 *   Not quite accurate: the TagSearch structure is also accessed from:
 *    CanvasWidgetCmd, FindItems, RelinkItems
 *   The only instances of the structure are owned by:
 *    CanvasWidgetCmd
 *   CanvasWidgetCmd is the only function that calls:
 *    FindItems, RelinkItems
 *   CanvasWidgetCmd, FindItems, RelinkItems, are the only functions that call
 *    TagSearch*
 * )
 */

typedef struct TagSearch {
    TkPathCanvas *canvasPtr;    /* Canvas widget being searched. */
    Tk_PathItem *currentPtr;    /* Pointer to last item returned. */
    Tk_PathItem *lastPtr;    /* The item right before the currentPtr is
                 * tracked so if the currentPtr is deleted we
                 * don't have to start from the beginning. */
    int searchOver;        /* Non-zero means NextItem should always
                 * return NULL. */
    int type;            /* Search type (see #defs below) */
    int id;            /* Item id for searches by id */
    char *string;        /* Tag expression string */
    int stringIndex;        /* Current position in string scan */
    int stringLength;        /* Length of tag expression string */
    char *rewritebuffer;    /* Tag string (after removing escapes) */
    unsigned int rewritebufferAllocated;
                /* Available space for rewrites. */
    TkPathTagSearchExpr *expr;    /* Compiled tag expression. */
} TagSearch;

/*
 * Values for the TagSearch type field.
 */

#define SEARCH_TYPE_EMPTY    0    /* Looking for empty tag */
#define SEARCH_TYPE_ID        1    /* Looking for an item by id */
#define SEARCH_TYPE_ALL        2    /* Looking for all items */
#define SEARCH_TYPE_TAG        3    /* Looking for an item by simple tag */
#define SEARCH_TYPE_EXPR    4    /* Compound search */
#define SEARCH_TYPE_ROOT    5    /* Looking for the root item */

#define PATH_DEF_STATE "normal"

/* These MUST be kept in sync with enums! X.h */

static const char *stateStrings[] = {
    "active", "disabled", "normal", "hidden", NULL
};

static const char *tagStyleStrings[] = {
    "exact", "expr", "glob", NULL
};

static Tk_ObjCustomOption offsetCO = {
    "offset",
    TkPathOffsetOptionSetProc,
    TkPathOffsetOptionGetProc,
    TkPathOffsetOptionRestoreProc,
    TkPathOffsetOptionFreeProc,
    (ClientData) (TK_OFFSET_RELATIVE|TK_OFFSET_INDEX)
};

static Tk_OptionSpec optionSpecs[] = {
    {TK_OPTION_BORDER, "-background", "background", "Background",
    DEF_CANVAS_BG_COLOR, -1, Tk_Offset(TkPathCanvas, bgBorder),
    0, (ClientData) DEF_CANVAS_BG_MONO, 0},
    {TK_OPTION_SYNONYM, "-bd", NULL, NULL,
    NULL, 0, -1, 0, (ClientData) "-borderwidth", 0},
    {TK_OPTION_SYNONYM, "-bg", NULL, NULL,
    NULL, 0, -1, 0, (ClientData) "-background", 0},
    {TK_OPTION_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
    DEF_CANVAS_BORDER_WIDTH, Tk_Offset(TkPathCanvas, borderWidthPtr),
    Tk_Offset(TkPathCanvas, borderWidth), 0, 0, 0},
    {TK_OPTION_DOUBLE, "-closeenough", "closeEnough", "CloseEnough",
    DEF_CANVAS_CLOSE_ENOUGH, -1, Tk_Offset(TkPathCanvas, closeEnough),
    0, 0, 0},
    {TK_OPTION_BOOLEAN, "-confine", "confine", "Confine",
    DEF_CANVAS_CONFINE, -1, Tk_Offset(TkPathCanvas, confine),
    0, 0, 0},
    {TK_OPTION_CURSOR, "-cursor", "cursor", "Cursor",
    DEF_CANVAS_CURSOR, -1, Tk_Offset(TkPathCanvas, cursor),
    TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_PIXELS, "-height", "height", "Height",
    DEF_CANVAS_HEIGHT, -1, Tk_Offset(TkPathCanvas, height),
    0, 0, 0},
    {TK_OPTION_COLOR, "-highlightbackground", "highlightBackground",
    "HighlightBackground", DEF_CANVAS_HIGHLIGHT_BG,
    -1, Tk_Offset(TkPathCanvas, highlightBgColorPtr),
    0, 0, 0},
    {TK_OPTION_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
    DEF_CANVAS_HIGHLIGHT, -1, Tk_Offset(TkPathCanvas, highlightColorPtr),
    0, 0, 0},
    {TK_OPTION_PIXELS, "-highlightthickness", "highlightThickness",
    "HighlightThickness", DEF_CANVAS_HIGHLIGHT_WIDTH,
    Tk_Offset(TkPathCanvas, highlightWidthPtr),
    Tk_Offset(TkPathCanvas, highlightWidth), 0, 0, 0},
    {TK_OPTION_BORDER, "-insertbackground", "insertBackground", "Foreground",
    DEF_CANVAS_INSERT_BG, -1, Tk_Offset(TkPathCanvas, textInfo.insertBorder),
    0, 0, 0},
    {TK_OPTION_PIXELS, "-insertborderwidth", "insertBorderWidth",
    "BorderWidth", DEF_CANVAS_INSERT_BD_COLOR, -1,
    Tk_Offset(TkPathCanvas, textInfo.insertBorderWidth),
    0, (ClientData) DEF_CANVAS_INSERT_BD_MONO, 0},
    {TK_OPTION_INT, "-insertofftime", "insertOffTime", "OffTime",
    DEF_CANVAS_INSERT_OFF_TIME, -1, Tk_Offset(TkPathCanvas, insertOffTime),
    0, 0, 0},
    {TK_OPTION_INT, "-insertontime", "insertOnTime", "OnTime",
    DEF_CANVAS_INSERT_ON_TIME, -1, Tk_Offset(TkPathCanvas, insertOnTime),
    0, 0, 0},
    {TK_OPTION_PIXELS, "-insertwidth", "insertWidth", "InsertWidth",
    DEF_CANVAS_INSERT_WIDTH, -1, Tk_Offset(TkPathCanvas, textInfo.insertWidth),
    0, 0, 0},
    {TK_OPTION_CUSTOM, "-offset", "offset", "Offset",
    "0,0", -1, Tk_Offset(TkPathCanvas, tsoffsetPtr),
    0, &offsetCO, 0},
    {TK_OPTION_RELIEF, "-relief", "relief", "Relief",
    DEF_CANVAS_RELIEF, -1, Tk_Offset(TkPathCanvas, relief),
    0, 0, 0},
    {TK_OPTION_STRING, "-scrollregion", "scrollRegion", "ScrollRegion",
    DEF_CANVAS_SCROLL_REGION, -1, Tk_Offset(TkPathCanvas, regionString),
    TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_BORDER, "-selectbackground", "selectBackground", "Foreground",
    DEF_CANVAS_SELECT_COLOR, -1, Tk_Offset(TkPathCanvas, textInfo.selBorder),
    0, (ClientData) DEF_CANVAS_SELECT_MONO, 0},
    {TK_OPTION_PIXELS, "-selectborderwidth", "selectBorderWidth",
    "BorderWidth", DEF_CANVAS_SELECT_BD_COLOR, -1,
    Tk_Offset(TkPathCanvas, textInfo.selBorderWidth),
    0, (ClientData) DEF_CANVAS_SELECT_BD_MONO, 0},
    {TK_OPTION_COLOR, "-selectforeground", "selectForeground", "Background",
    DEF_CANVAS_SELECT_FG_COLOR, -1, Tk_Offset(TkPathCanvas, textInfo.selFgColorPtr),
    TK_OPTION_NULL_OK, (ClientData) DEF_CANVAS_SELECT_FG_MONO, 0},
    {TK_OPTION_STRING_TABLE, "-state", "state", "State",
    PATH_DEF_STATE, -1, Tk_Offset(TkPathCanvas, canvas_state),
    0, (ClientData) stateStrings, 0},
    {TK_OPTION_STRING_TABLE, "-tagstyle", NULL, NULL,
        "expr", -1, Tk_Offset(TkPathCanvas, tagStyle),
        0, (ClientData) tagStyleStrings, 0},
    {TK_OPTION_STRING, "-takefocus", "takeFocus", "TakeFocus",
    DEF_CANVAS_TAKE_FOCUS, -1, Tk_Offset(TkPathCanvas, takeFocus),
    TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_PIXELS, "-width", "width", "Width",
    DEF_CANVAS_WIDTH, -1, Tk_Offset(TkPathCanvas, width),
    0, 0, 0},
    {TK_OPTION_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
    DEF_CANVAS_X_SCROLL_CMD, -1, Tk_Offset(TkPathCanvas, xScrollCmd),
    TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_PIXELS, "-xscrollincrement", "xScrollIncrement",
    "ScrollIncrement",
    DEF_CANVAS_X_SCROLL_INCREMENT, -1, Tk_Offset(TkPathCanvas, xScrollIncrement),
    0, 0, 0},
    {TK_OPTION_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand",
    DEF_CANVAS_Y_SCROLL_CMD, -1, Tk_Offset(TkPathCanvas, yScrollCmd),
    TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_PIXELS, "-yscrollincrement", "yScrollIncrement",
    "ScrollIncrement",
    DEF_CANVAS_Y_SCROLL_INCREMENT, -1, Tk_Offset(TkPathCanvas, yScrollIncrement),
    0, 0, 0},
    {TK_OPTION_END, NULL, NULL, NULL,
    NULL, 0, -1, 0, (ClientData) NULL, 0}
};

/*
 * List of all the item types known at present.
 */

static Tk_PathItemType *typeList = NULL;/* NULL means initialization hasn't
                     * been done yet. */

/*
 * Uids for operands in compiled advanced tag search expressions.
 * Initialization is done by GetStaticUids()
 */

typedef struct {
    Tk_Uid allUid;        /* "all" */
    Tk_Uid currentUid;        /* "current" */
    Tk_Uid rootUid;        /* "root" */
    Tk_Uid andUid;
    Tk_Uid orUid;
    Tk_Uid xorUid;
    Tk_Uid parenUid;
    Tk_Uid negparenUid;
    Tk_Uid endparenUid;
    Tk_Uid tagvalUid;
    Tk_Uid negtagvalUid;
} SearchUids;

static Tcl_ThreadDataKey dataKey;
static SearchUids *    GetStaticUids(void);

/*
 * Prototypes for functions defined later in this file:
 */

static void        CanvasBindProc(ClientData clientData,
                XEvent *eventPtr);
static void        CanvasBlinkProc(ClientData clientData);
static void        CanvasCmdDeletedProc(ClientData clientData);
static void        CanvasDoEvent(TkPathCanvas *canvasPtr, XEvent *eventPtr);
static void        CanvasEventProc(ClientData clientData,
                XEvent *eventPtr);
static int        CanvasFetchSelection(ClientData clientData, int offset,
                char *buffer, int maxBytes);
static Tk_PathItem *    CanvasFindClosest(TkPathCanvas *canvasPtr,
                double coords[2]);
static void        CanvasFocusProc(TkPathCanvas *canvasPtr, int gotFocus);
static void        CanvasLostSelection(ClientData clientData);
static void        CanvasSelectTo(TkPathCanvas *canvasPtr,
                Tk_PathItem *itemPtr, int index);
static void        CanvasSetOrigin(TkPathCanvas *canvasPtr,
                int xOrigin, int yOrigin);
static void        CanvasUpdateScrollbars(TkPathCanvas *canvasPtr);
static int        CanvasWidgetCmd(ClientData clientData,
                Tcl_Interp *interp, int objc,
                Tcl_Obj *const *objv);
static void        PathCanvasWorldChanged(
                ClientData instanceData);
static int        ConfigureCanvas(Tcl_Interp *interp,
                TkPathCanvas *canvasPtr, int objc,
                Tcl_Obj *const *objv, int flags);
static void        DestroyCanvas(char *memPtr);
static void        DisplayCanvas(ClientData clientData);
static void        DoItem(Tcl_Interp *interp,
                Tk_PathItem *itemPtr, Tk_Uid tag);
static void        EventuallyRedrawItem(Tk_PathCanvas canvas,
                Tk_PathItem *itemPtr);
static void        EventuallyRedrawItemAndChildren(Tk_PathCanvas canvas,
                Tk_PathItem *itemPtr);

static Tcl_Obj *    UnshareObj(Tcl_Obj *objPtr);
#ifdef NOT_USED
static Tk_PathItem *    ItemIteratorSubNext(Tk_PathItem *itemPtr, Tk_PathItem *groupPtr);
#endif
static void        ItemAddToParent(Tk_PathItem *parentPtr, Tk_PathItem *itemPtr);
static void        ItemDelete(TkPathCanvas *canvasPtr, Tk_PathItem *itemPtr);
static int        ItemCreate(Tcl_Interp *interp, TkPathCanvas *canvasPtr,
                Tk_PathItemType *typePtr, int isRoot, Tk_PathItem **itemPtrPtr,
                int objc, Tcl_Obj *const objv[]);
static int        ItemGetNumTags(Tk_PathItem *itemPtr);
static void        SetAncestorsDirtyBbox(Tk_PathItem *itemPtr);

static void        DebugGetItemInfo(Tk_PathItem *itemPtr, char *s);

static int      FindItems(Tcl_Interp *interp, TkPathCanvas *canvasPtr,
    int objc, Tcl_Obj *const *objv,
    Tcl_Obj *newTagObj, int first,
    TagSearch **searchPtrPtr);
static int      FindArea(Tcl_Interp *interp, TkPathCanvas *canvasPtr,
    Tcl_Obj *const *objv, Tk_Uid uid, int enclosed);
static double   GridAlign(double coord, double spacing);
static const char** GetStringsFromObjs(int objc, Tcl_Obj *const *objv);
static void     PickCurrentItem(TkPathCanvas *canvasPtr, XEvent *eventPtr);
static Tcl_Obj  *ScrollFractions(int screen1, int screen2, int object1,
    int object2);
static int      RelinkItems(TkPathCanvas *canvasPtr, Tcl_Obj *tag,
    Tk_PathItem *prevPtr, TagSearch **searchPtrPtr);
static void     TagSearchExprInit(TkPathTagSearchExpr **exprPtrPtr);
static void     TagSearchExprDestroy(TkPathTagSearchExpr *expr);
static void     TagSearchDestroy(TagSearch *searchPtr);
static int      TagSearchScan(TkPathCanvas *canvasPtr, Tcl_Obj *tag,
    TagSearch **searchPtrPtr);
static int      TagSearchScanExpr(Tcl_Interp *interp, TagSearch *searchPtr,
    TkPathTagSearchExpr *expr);
static int      TagSearchEvalExpr(TkPathTagSearchExpr *expr,
       Tk_PathItem *itemPtr);
static Tk_PathItem  *TagSearchFirst(TagSearch *searchPtr);
static Tk_PathItem  *TagSearchNext(TagSearch *searchPtr);
static int      PathConstructor(ClientData clientData, Tcl_Interp *interp,
    Tcl_ObjectContext objectContext, int objc, Tcl_Obj *const objv[]);
static int      PathMethod(ClientData clientData, Tcl_Interp *interp,
    Tcl_ObjectContext objectContext, int objc, Tcl_Obj *const objv[]);
static void     PathMetaDelete(ClientData clientData);

static Tcl_MethodType pathMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT,NULL , PathConstructor    , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"addtag"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"ancestors"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"bbox"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"bind"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"canvasx"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"canvasy"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"cget"      , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"children" , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"cmove" , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"configure" , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"coords"     ,PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"create"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"cscale"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"configure"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"dchars"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"delete"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"depth"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"distance"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"dtag"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"find"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"firstchild"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"focus"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"gettags"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"gradient"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"icursor"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"index"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"insert"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"itemcget"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"itemconfigure"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"itempdf"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"lastchild"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"lower"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"move"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"nextsibling"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"parent"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"prevsibling"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"raise"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"scale"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"scan"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"select"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"style"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"type"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"types"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"xview"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"yview"       , PathMethod , NULL , NULL },
    {TCL_OO_METHOD_VERSION_CURRENT,"debugtree"       , PathMethod , NULL , NULL },
    { -1    , NULL          , NULL     , NULL , NULL }
};

static Tcl_ObjectMetadataType pathMeta = {
    TCL_OO_METADATA_VERSION_CURRENT,
    "PathMeta",
    PathMetaDelete,
    NULL
};

/*
 * The structure below defines canvas class behavior by means of functions
 * that can be invoked from generic window code.
 */
static Tk_ClassProcs canvasClass = {
    sizeof(Tk_ClassProcs),    /* size */
    PathCanvasWorldChanged,    /* worldChangedProc */
};

/*
 * Macros that significantly simplify all code that finds items.
 */

#define FIRST_CANVAS_ITEM_MATCHING(objPtr,searchPtrPtr,errorExitClause) \
    if ((result = TagSearchScan(canvasPtr,(objPtr),(searchPtrPtr))) != TCL_OK) { \
    errorExitClause; \
    } \
    itemPtr = TagSearchFirst(*(searchPtrPtr));

#define FOR_EVERY_CANVAS_ITEM_MATCHING(objPtr,searchPtrPtr,errorExitClause) \
    if ((result = TagSearchScan(canvasPtr,(objPtr),(searchPtrPtr))) != TCL_OK) { \
    errorExitClause; \
    } \
    for (itemPtr = TagSearchFirst(*(searchPtrPtr)); \
        itemPtr != NULL; itemPtr = TagSearchNext(*(searchPtrPtr)))
#if defined(_WIN32) && defined(AGG_CUSTOM_ALLOCATOR)
/* AGG custom allocator functions */
void *(*agg_custom_alloc)(unsigned int size) = NULL;
void (*agg_custom_free)(void *ptr) = NULL;
#endif

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathInit --
 *
 *        Initializer for the tkpath package.
 *
 * Results:
 *        A standard Tcl result.
 *
 * Side Effects:
 *       Tcl commands created
 *
 *----------------------------------------------------------------------
 */
int
Tk_PathInit(Tcl_Interp *interp)        /* Tcl interpreter. */
{
    Tcl_Class clazz;
    Tcl_Object object;
    Tcl_Obj *objPtr;
    int i;
    /* Create class like tk command and remove oo functions from widget commands */
	static const char *initScript =
		"::oo::class create ::path {"
		" self method unknown {args} {uplevel #0 ::path create $args; return [lindex $args 0]}\n"
		" self unexport new destroy\n"
		" unexport new create destroy\n"
		"}";
#if defined(_WIN32) && defined(AGG_CUSTOM_ALLOCATOR)
    agg_custom_alloc = (void *(*)(unsigned int)) Tcl_Alloc;
    agg_custom_free = (void (*)(void *)) Tcl_Free;
#endif

	/* Needed oo extension */
	if (Tcl_OOInitStubs(interp) == NULL) {
		return TCL_ERROR;
	}

	if (TkPathSetup(interp) == TCL_ERROR) {
        return TCL_ERROR;
    }

    if (Tcl_CreateNamespace(interp, TK_PATHCMD_CLASS, NULL, NULL) == NULL) {
        return TCL_ERROR;
    }

    /* Create widget class. */
    if (Tcl_Eval(interp, initScript) != TCL_OK) {
        return TCL_ERROR;
    }
    /* Get class object */
    objPtr = Tcl_NewStringObj(TK_PATHCMD_CLASS, -1);
    Tcl_IncrRefCount(objPtr);
    if ((object = Tcl_GetObjectFromObj(interp, objPtr)) == NULL) {
        Tcl_DecrRefCount(objPtr);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(objPtr);
    if ((clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /* Add methods */
    Tcl_ClassSetConstructor(interp, clazz, Tcl_NewMethod(interp, clazz, NULL, 1, &pathMethods[0], NULL));
    for (i = 1; pathMethods[i].name != NULL; i++) {
        Tcl_NewMethod(interp, clazz, Tcl_NewStringObj(pathMethods[i].name, -1), 1, &pathMethods[i], NULL);
    }

    /*
     * Link the variable to control antialiasing.
     */
    if (Tcl_LinkVar(interp, TK_PATHVAR_ANTIALIAS,
            (char *) &Tk_PathAntiAlias, TCL_LINK_BOOLEAN) != TCL_OK) {
        Tcl_ResetResult(interp);
    }

    /*
     * With Tk_PathSurfaceCopyPremultiplyAlpha true we ignore the "premultiply alpha"
     * and use RGB as is. Else we need to divide each RGB with alpha
     * to get "true" values.
     */
    if (Tcl_LinkVar(interp, TK_PATHVAR_PREMULTIPLYALPHA,
            (char *) &Tk_PathSurfaceCopyPremultiplyAlpha,
        TCL_LINK_BOOLEAN) != TCL_OK) {
        Tcl_ResetResult(interp);
    }
    if (Tcl_LinkVar(interp, TK_PATHVAR_DEPIXELIZE,
            (char *) &Tk_PathDepixelize, TCL_LINK_BOOLEAN) != TCL_OK) {
        Tcl_ResetResult(interp);
    }

	/*
	* Create additional Tcl commands
	*/
	Tcl_CreateObjCommand(interp, TK_PATHCMD_PIXELALIGN,
		TkPathPixelAlignObjCmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);

    /*
     * tkpath specific item types. Hopefully ordered by usage.
     */
    typeList = &tkPathTypeGroup;
    tkPathTypeGroup.nextPtr = &tkPathTypePath;
    tkPathTypePath.nextPtr = &tkPathTypeText;
    tkPathTypeText.nextPtr = &tkPathTypeLine;
    tkPathTypeLine.nextPtr = &tkPathTypePolyline;
    tkPathTypePolyline.nextPtr = &tkPathTypePolygon;
    tkPathTypePolygon.nextPtr = &tkPathTypeRect;
    tkPathTypeRect.nextPtr = &tkPathTypeCircle;
    tkPathTypeCircle.nextPtr = &tkPathTypeEllipse;
    tkPathTypeEllipse.nextPtr = &tkPathTypeImage;
    tkPathTypeImage.nextPtr = &tkPathTypeWindow;
    tkPathTypeWindow.nextPtr = NULL;

	/*
	* Make separate gradient objects, similar to SVG.
	*/
	TkPathGradientInit(interp);
	TkPathSurfaceInit(interp);

	/*
     * Style object.
     */
    TkPathStyleInit(interp);

    return TCL_OK;
}

/* Constructor */
static int PathConstructor(
    ClientData clientData,
    Tcl_Interp *interp,
    Tcl_ObjectContext objectContext,
    int objc,
    Tcl_Obj *const objv[])
{
    Tcl_Object object;
    TkPathCanvas *canvasPtr;
    Tk_Window tkWin;
    Tk_PathItem *rootItemPtr;
    Tk_OptionTable optionTable;
    Tcl_Obj *rootObj;

	/* Get current object. Should not fail? */
    if ((object = Tcl_ObjectContextObject(objectContext)) == NULL) {
        return TCL_ERROR;
    }
    /* Check calling args */
    if (objc < 3 || strcmp("create", Tcl_GetString(objv[1])) != 0) {
        Tcl_WrongNumArgs(interp, 1, objv, "pathName ?options?");
        return TCL_ERROR;
    }

    tkWin = Tk_CreateWindowFromPath(interp, Tk_MainWindow(interp), Tcl_GetString(objv[2]), NULL);
    if (tkWin == NULL) {
        return TCL_ERROR;
    }

    /*
     * Create the option table for this widget class. If it has already been
     * created, the cached pointer will be returned.
     */

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);

    /*
     * Initialize fields that won't be initialized by ConfigureCanvas, or
     * which ConfigureCanvas expects to have reasonable values (e.g. resource
     * pointers).
     */

    canvasPtr = (TkPathCanvas *) ckalloc(sizeof(TkPathCanvas));
    canvasPtr->optionTable = optionTable;
    canvasPtr->tkwin = tkWin;
    canvasPtr->display = Tk_Display(tkWin);
    canvasPtr->interp = interp;
	canvasPtr->widgetCmd = Tcl_GetObjectCommand(object);
    canvasPtr->rootItemPtr = NULL;  /* root item created below. */
    canvasPtr->borderWidthPtr = NULL;
    canvasPtr->borderWidth = 0;
    canvasPtr->bgBorder = NULL;
    canvasPtr->relief = TK_RELIEF_FLAT;
    canvasPtr->highlightWidthPtr = NULL;
    canvasPtr->highlightWidth = 0;
    canvasPtr->highlightBgColorPtr = NULL;
    canvasPtr->highlightColorPtr = NULL;
    canvasPtr->inset = 0;
    canvasPtr->pixmapGC = None;
    canvasPtr->width = None;
    canvasPtr->height = None;
    canvasPtr->confine = 0;
    canvasPtr->textInfo.selBorder = NULL;
    canvasPtr->textInfo.selBorderWidth = 0;
    canvasPtr->textInfo.selFgColorPtr = NULL;
    canvasPtr->textInfo.selItemPtr = NULL;
    canvasPtr->textInfo.selectFirst = -1;
    canvasPtr->textInfo.selectLast = -1;
    canvasPtr->textInfo.anchorItemPtr = NULL;
    canvasPtr->textInfo.selectAnchor = 0;
    canvasPtr->textInfo.insertBorder = NULL;
    canvasPtr->textInfo.insertWidth = 0;
    canvasPtr->textInfo.insertBorderWidth = 0;
    canvasPtr->textInfo.focusItemPtr = NULL;
    canvasPtr->textInfo.gotFocus = 0;
    canvasPtr->textInfo.cursorOn = 0;
    canvasPtr->insertOnTime = 0;
    canvasPtr->insertOffTime = 0;
    canvasPtr->insertBlinkHandler = (Tcl_TimerToken) NULL;
    canvasPtr->xOrigin = canvasPtr->yOrigin = 0;
    canvasPtr->drawableXOrigin = canvasPtr->drawableYOrigin = 0;
    canvasPtr->bindingTable = NULL;
    canvasPtr->currentItemPtr = NULL;
    canvasPtr->newCurrentPtr = NULL;
    canvasPtr->closeEnough = 0.0;
    canvasPtr->pickEvent.type = LeaveNotify;
    canvasPtr->pickEvent.xcrossing.x = 0;
    canvasPtr->pickEvent.xcrossing.y = 0;
    canvasPtr->state = 0;
    canvasPtr->xScrollCmd = NULL;
    canvasPtr->yScrollCmd = NULL;
    canvasPtr->scrollX1 = 0;
    canvasPtr->scrollY1 = 0;
    canvasPtr->scrollX2 = 0;
    canvasPtr->scrollY2 = 0;
    canvasPtr->regionString = NULL;
    canvasPtr->xScrollIncrement = 0;
    canvasPtr->yScrollIncrement = 0;
    canvasPtr->scanX = 0;
    canvasPtr->scanXOrigin = 0;
    canvasPtr->scanY = 0;
    canvasPtr->scanYOrigin = 0;
    canvasPtr->hotPtr = NULL;
    canvasPtr->hotPrevPtr = NULL;
    canvasPtr->cursor = None;
    canvasPtr->takeFocus = NULL;
    canvasPtr->context = NULL;

#ifdef PLATFORM_SDL
    {
    double dW, dH;

    dW = WidthOfScreen(Tk_Screen(tkWin));
    dW /= WidthMMOfScreen(Tk_Screen(tkWin));
    dH = HeightOfScreen(Tk_Screen(tkWin));
    dH /= HeightMMOfScreen(Tk_Screen(tkWin));
    canvasPtr->pixelsPerMM = (dH > dW) ? dH : dW;
    }
#else
    canvasPtr->pixelsPerMM = WidthOfScreen(Tk_Screen(tkWin));
    canvasPtr->pixelsPerMM /= WidthMMOfScreen(Tk_Screen(tkWin));
#endif
    canvasPtr->flags = 0;
    canvasPtr->nextId = 1;        /* id = 0 reserved for root item */
    canvasPtr->canvas_state = TK_PATHSTATE_NORMAL;
    canvasPtr->tsoffsetPtr = NULL;
    canvasPtr->styleUid = 0;
    canvasPtr->gradientUid = 0;
    canvasPtr->bindTagExprs = NULL;

    Tcl_InitHashTable(&canvasPtr->idTable, TCL_ONE_WORD_KEYS);
    Tcl_InitHashTable(&canvasPtr->styleTable, TCL_STRING_KEYS);
    Tcl_InitHashTable(&canvasPtr->gradientTable, TCL_STRING_KEYS);

    Tk_SetClass(canvasPtr->tkwin, "PathCanvas");
    Tk_SetClassProcs(canvasPtr->tkwin, &canvasClass, (ClientData) canvasPtr);
    Tk_CreateEventHandler(canvasPtr->tkwin,
        ExposureMask|StructureNotifyMask|FocusChangeMask,
        CanvasEventProc, (ClientData) canvasPtr);
    Tk_CreateEventHandler(canvasPtr->tkwin, KeyPressMask|KeyReleaseMask
        |ButtonPressMask|ButtonReleaseMask|EnterWindowMask
        |LeaveWindowMask|PointerMotionMask|VirtualEventMask,
        CanvasBindProc, (ClientData) canvasPtr);
    Tk_CreateSelHandler(canvasPtr->tkwin, XA_PRIMARY, XA_STRING,
        CanvasFetchSelection, (ClientData) canvasPtr, XA_STRING);

    Tcl_ObjectSetMetadata(object, &pathMeta, (ClientData)canvasPtr);

    if (Tk_InitOptions(interp, (char *)canvasPtr, optionTable, canvasPtr->tkwin) != TCL_OK
        || ConfigureCanvas(interp, canvasPtr, objc-3, objv+3, 0) != TCL_OK) {
        Tk_DestroyWindow(canvasPtr->tkwin);
        return TCL_ERROR;
    }

    /*
     * Create the root item as a group item.
     * Need to set the tag "root" by hand since its configProc
     * forbids this for the root item.
     */
    ItemCreate(interp, canvasPtr, &tkPathTypeGroup, 1, &rootItemPtr, 0, NULL);
    rootObj = Tcl_NewStringObj("root", -1);
    Tcl_IncrRefCount(rootObj);
    rootItemPtr->pathTagsPtr = TkPathAllocTagsFromObj(NULL, rootObj);
    Tcl_DecrRefCount(rootObj);
    canvasPtr->rootItemPtr = rootItemPtr;

	/* No need to set return value. It will be ignored by "oo::class create" */
    return TCL_OK;
}

static int PathMethod(
    ClientData clientData,
    Tcl_Interp *interp,
    Tcl_ObjectContext objectContext,
    int objc,
    Tcl_Obj *const objv[])
{
    return CanvasWidgetCmd(Tcl_ObjectGetMetadata(Tcl_ObjectContextObject(objectContext), &pathMeta), interp, objc, objv);
}

static void
PathMetaDelete(ClientData clientData) {
    register TkPathCanvas *canvasPtr = clientData;

    /* Destroy window will calling DestroyCanvas() also. */
    if (canvasPtr && (!(canvasPtr->flags & CANVAS_DELETED))) {
        Tk_DestroyWindow(canvasPtr->tkwin);
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * CanvasWidgetCmd --
 *
 *    This function is invoked to process the Tcl command that corresponds
 *    to a widget managed by this module. See the user documentation for
 *    details on what it does.
 *
 * Results:
 *    A standard Tcl result.
 *
 * Side effects:
 *    See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
CanvasWidgetCmd(
    ClientData clientData,    /* Information about canvas widget. */
    Tcl_Interp *interp,        /* Current interpreter. */
    int objc,            /* Number of arguments. */
    Tcl_Obj *const objv[])    /* Argument objects. */
{
    TkPathCanvas *canvasPtr = (TkPathCanvas *) clientData;
    int c, result;
    Tcl_Obj *resultObjPtr;
    Tk_PathItem *itemPtr = NULL;/* Initialization needed only to prevent
                 * compiler warning. */
    TagSearch *searchPtr = NULL;/* Allocated by first TagSearchScan, freed by
                 * TagSearchDestroy */

    int index;
    static const char *optionStrings[] = {
    "addtag",    "ancestors",    "bbox",        "bind",
    "canvasx",    "canvasy",    "cget",        "children",
    "cmove",    "configure",    "coords",    "create",
    "cscale",    "dchars",
    "delete",    "depth",    "distance",    "dtag",
    "find",        "firstchild",    "focus",    "gettags",
    "gradient",    "icursor",    "index",    "insert",
    "itemcget",    "itemconfigure","itempdf",    "lastchild",
    "lower",    "move",        "nextsibling",    "parent",
    "prevsibling",    "raise",    "scale",
    "scan",        "select",    "style",    "type",
    "types",    "xview",    "yview",
#if 1
    "debugtree",
#endif
    NULL
    };
    enum options {
    CANV_ADDTAG,     CANV_ANCESTORS,    CANV_BBOX,        CANV_BIND,
    CANV_CANVASX,     CANV_CANVASY,        CANV_CGET,        CANV_CHILDREN,
    CANV_CMOVE,     CANV_CONFIGURE,    CANV_COORDS,    CANV_CREATE,
    CANV_CSCALE,     CANV_DCHARS,
    CANV_DELETE,     CANV_DEPTH,        CANV_DISTANCE,    CANV_DTAG,
    CANV_FIND,     CANV_FIRSTCHILD,   CANV_FOCUS,        CANV_GETTAGS,
    CANV_GRADIENT,     CANV_ICURSOR,        CANV_INDEX,        CANV_INSERT,
    CANV_ITEMCGET,     CANV_ITEMCONFIGURE,CANV_ITEMPDF,    CANV_LASTCHILD,
    CANV_LOWER,     CANV_MOVE,        CANV_NEXTSIBLING,    CANV_PARENT,
    CANV_PREVSIBLING,CANV_RAISE,        CANV_SCALE,
    CANV_SCAN,     CANV_SELECT,        CANV_STYLE,        CANV_TYPE,
    CANV_TYPES,     CANV_XVIEW,        CANV_YVIEW,
#if 1
    CANV_DEBUGTREE,
#endif
    };

    if (objc < 2) {
    Tcl_WrongNumArgs(interp, 1, objv, "option ?arg arg ...?");
    return TCL_ERROR;
    }
    if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0,
        &index) != TCL_OK) {
    return TCL_ERROR;
    }
    Tcl_Preserve((ClientData) canvasPtr);

    result = TCL_OK;
    switch ((enum options) index) {
    case CANV_ADDTAG: {
    if (objc < 4) {
        Tcl_WrongNumArgs(interp, 2, objv, "tag searchCommand ?arg arg ...?");
        result = TCL_ERROR;
        goto done;
    }
    result = FindItems(interp, canvasPtr, objc, objv, objv[2], 3, &searchPtr);
    break;
    }
    case CANV_ANCESTORS: {

    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        Tcl_Obj *listPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
        Tcl_Obj *obj;
        Tk_PathItem *walkPtr;

        walkPtr = itemPtr->parentPtr;
        while (walkPtr != NULL) {

        /*
         * Insert items higher in the tree first.
         */
        obj = Tcl_NewIntObj(walkPtr->id);
        Tcl_ListObjReplace(NULL, listPtr, 0, 0, 1, &obj);
        walkPtr = walkPtr->parentPtr;
        }
        Tcl_SetObjResult(interp, listPtr);
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_BBOX: {
    int i, gotAny;
    int x1 = 0, y1 = 0, x2 = 0, y2 = 0;    /* Initializations needed only
                         * to prevent overcautious
                         * compiler warnings. */

    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?tagOrId ...?");
        result = TCL_ERROR;
        goto done;
    }
    gotAny = 0;
    for (i = 2; i < objc; i++) {
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[i], &searchPtr, goto done) {

        /*
         * Groups bbox are only updated lazily, when needed.
         */
        if (itemPtr->firstChildPtr != NULL) {
            TkPathCanvasGroupBbox((Tk_PathCanvas) canvasPtr, itemPtr,
                &itemPtr->x1, &itemPtr->y1, &itemPtr->x2, &itemPtr->y2);
        }
        if ((itemPtr->x1 >= itemPtr->x2)
            || (itemPtr->y1 >= itemPtr->y2)) {
            continue;
        }
        if (!gotAny) {
            x1 = itemPtr->x1;
            y1 = itemPtr->y1;
            x2 = itemPtr->x2;
            y2 = itemPtr->y2;
            gotAny = 1;
        } else {
            if (itemPtr->x1 < x1) {
            x1 = itemPtr->x1;
            }
            if (itemPtr->y1 < y1) {
            y1 = itemPtr->y1;
            }
            if (itemPtr->x2 > x2) {
            x2 = itemPtr->x2;
            }
            if (itemPtr->y2 > y2) {
            y2 = itemPtr->y2;
            }
        }
        }
    }
    if (gotAny) {
        Tcl_Obj *listObj = Tcl_NewListObj(0, NULL);

        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(x1));
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(y1));
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(x2));
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(y2));
        Tcl_SetObjResult(interp, listObj);
    }
    break;
    }
    case CANV_BIND: {
    ClientData object;

    if ((objc < 3) || (objc > 5)) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?sequence? ?command?");
        result = TCL_ERROR;
        goto done;
    }

    /*
     * Figure out what object to use for the binding (individual item vs.
     * tag).
     */

    object = 0;
    result = TagSearchScan(canvasPtr, objv[2], &searchPtr);
    if (result != TCL_OK) {
        goto done;
    }
    if (searchPtr->type == SEARCH_TYPE_ID) {
        Tcl_HashEntry *entryPtr;

        entryPtr = Tcl_FindHashEntry(&canvasPtr->idTable,
            (char *) INT2PTR(searchPtr->id));
        if (entryPtr != NULL) {
        itemPtr = (Tk_PathItem *) Tcl_GetHashValue(entryPtr);
        object = (ClientData) itemPtr;
        }

        if (object == 0) {
        Tcl_AppendResult(interp, "item \"", Tcl_GetString(objv[2]),
            "\" doesn't exist", NULL);
        result = TCL_ERROR;
        goto done;
        }
    } else {
            object = (ClientData) searchPtr->expr->uid;
    }

    /*
     * Make a binding table if the canvas doesn't already have one.
     */

    if (canvasPtr->bindingTable == NULL) {
        canvasPtr->bindingTable = Tk_CreateBindingTable(interp);
    }

    if (objc == 5) {
        int append = 0;
        unsigned long mask;
        char* argv4 = Tcl_GetString(objv[4]);

        if (argv4[0] == 0) {
        result = Tk_DeleteBinding(interp, canvasPtr->bindingTable,
            object, Tcl_GetString(objv[3]));
        goto done;
        }
        if (searchPtr->type == SEARCH_TYPE_EXPR) {
        /*
         * If new tag expression, then insert in linked list.
         */

            TkPathTagSearchExpr *expr, **lastPtr;

        lastPtr = &(canvasPtr->bindTagExprs);
        while ((expr = *lastPtr) != NULL) {
            if (expr->uid == searchPtr->expr->uid) {
            break;
            }
            lastPtr = &(expr->next);
        }
        if (!expr) {
            /*
             * Transfer ownership of expr to bindTagExprs list.
             */

            *lastPtr = searchPtr->expr;
            searchPtr->expr->next = NULL;

            /*
             * Flag in TagSearch that expr has changed ownership so
             * that TagSearchDestroy doesn't try to free it.
             */

            searchPtr->expr = NULL;
        }
        }
        if (argv4[0] == '+') {
        argv4++;
        append = 1;
        }
        mask = Tk_CreateBinding(interp, canvasPtr->bindingTable,
            object, Tcl_GetString(objv[3]), argv4, append);
        if (mask == 0) {
        result = TCL_ERROR;
        goto done;
        }
        if (mask & (unsigned) ~(ButtonMotionMask|Button1MotionMask
            |Button2MotionMask|Button3MotionMask|Button4MotionMask
            |Button5MotionMask|ButtonPressMask|ButtonReleaseMask
            |EnterWindowMask|LeaveWindowMask|KeyPressMask
            |KeyReleaseMask|PointerMotionMask|VirtualEventMask)) {
        Tk_DeleteBinding(interp, canvasPtr->bindingTable,
            object, Tcl_GetString(objv[3]));
        Tcl_ResetResult(interp);
        Tcl_AppendResult(interp, "requested illegal events; ",
            "only key, button, motion, enter, leave, and virtual ",
            "events may be used", NULL);
        result = TCL_ERROR;
        goto done;
        }
    } else if (objc == 4) {
        const char *command;

        command = Tk_GetBinding(interp, canvasPtr->bindingTable,
            object, Tcl_GetString(objv[3]));
        if (command == NULL) {
        const char *string;

        string = Tcl_GetStringResult(interp);

        /*
         * Ignore missing binding errors. This is a special hack that
         * relies on the error message returned by FindSequence in
         * tkBind.c.
         */

        if (string[0] != '\0') {
            result = TCL_ERROR;
            goto done;
        } else {
            Tcl_ResetResult(interp);
        }
        } else {
        Tcl_SetResult(interp, (char *) command, TCL_STATIC);
        }
    } else {
        Tk_GetAllBindings(interp, canvasPtr->bindingTable, object);
    }
    break;
    }
    case CANV_CANVASX: {
    int x;
    double grid;
    char buf[TCL_DOUBLE_SPACE];

    if ((objc < 3) || (objc > 4)) {
        Tcl_WrongNumArgs(interp, 2, objv, "screenx ?gridspacing?");
        result = TCL_ERROR;
        goto done;
    }
    if (Tk_GetPixelsFromObj(interp, canvasPtr->tkwin, objv[2], &x) != TCL_OK) {
        result = TCL_ERROR;
        goto done;
    }
    if (objc == 4) {
        if (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) canvasPtr, objv[3],
            &grid) != TCL_OK) {
        result = TCL_ERROR;
        goto done;
        }
    } else {
        grid = 0.0;
    }
    x += canvasPtr->xOrigin;
    Tcl_PrintDouble(interp, GridAlign((double) x, grid), buf);
    Tcl_SetResult(interp, buf, TCL_VOLATILE);
    break;
    }
    case CANV_CANVASY: {
    int y;
    double grid;
    char buf[TCL_DOUBLE_SPACE];

    if ((objc < 3) || (objc > 4)) {
        Tcl_WrongNumArgs(interp, 2, objv, "screeny ?gridspacing?");
        result = TCL_ERROR;
        goto done;
    }
    if (Tk_GetPixelsFromObj(interp, canvasPtr->tkwin, objv[2], &y) != TCL_OK) {
        result = TCL_ERROR;
        goto done;
    }
    if (objc == 4) {
        if (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) canvasPtr,
            objv[3], &grid) != TCL_OK) {
        result = TCL_ERROR;
        goto done;
        }
    } else {
        grid = 0.0;
    }
    y += canvasPtr->yOrigin;
    Tcl_PrintDouble(interp, GridAlign((double) y, grid), buf);
    Tcl_SetResult(interp, buf, TCL_VOLATILE);
    break;
    }
    case CANV_CGET: {
    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "option");
        result = TCL_ERROR;
        goto done;
    }
    resultObjPtr = Tk_GetOptionValue(interp, (char *) canvasPtr,
        canvasPtr->optionTable, objv[2], canvasPtr->tkwin);
    if (resultObjPtr == NULL) {
        goto done;
    } else {
        Tcl_SetObjResult(interp, resultObjPtr);
    }
    break;
    }
    case CANV_CHILDREN: {
    Tcl_Obj *listObj;
    Tk_PathItem *childPtr;

    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        listObj = Tcl_NewListObj(0, NULL);
        childPtr = itemPtr->firstChildPtr;
        while (childPtr != NULL) {
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(childPtr->id));
        childPtr = childPtr->nextPtr;
        }
        Tcl_SetObjResult(interp, listObj);
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_CONFIGURE: {
    if (objc <= 3) {
        resultObjPtr = Tk_GetOptionInfo(interp, (char *) canvasPtr,
            canvasPtr->optionTable, (objc == 3) ? objv[2] : NULL,
            canvasPtr->tkwin);
        if (resultObjPtr == NULL) {
        result = TCL_ERROR;
        goto done;
        } else {
        Tcl_SetObjResult(interp, resultObjPtr);
        }
    } else {
        result = ConfigureCanvas(interp, canvasPtr, objc-2, objv+2,
            TK_CONFIG_ARGV_ONLY);
    }
    break;
    }
    case CANV_COORDS: {
    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?x y x y ...?");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        if (objc != 3) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        }
        if (itemPtr->typePtr->coordProc != NULL) {
        result = (*itemPtr->typePtr->coordProc)(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, objc-3, objv+3);
        }
        if (objc != 3) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        }
    }
    break;
    }
    case CANV_CREATE: {
    Tk_PathItemType *typePtr;
    Tk_PathItemType *matchPtr = NULL;
    Tk_PathItem *itemPtr;
    char *arg;
    int length;

    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "type coords ?arg arg ...?");
        result = TCL_ERROR;
        goto done;
    }
    arg = Tcl_GetStringFromObj(objv[2], &length);
    c = arg[0];
    for (typePtr = typeList; typePtr != NULL; typePtr = typePtr->nextPtr) {
        if ((c == typePtr->name[0])
            && (strncmp(arg, typePtr->name, (unsigned)length) == 0)) {
        if (matchPtr != NULL) {
        badType:
            Tcl_AppendResult(interp,
                "unknown or ambiguous item type \"",arg,"\"",NULL);
            result = TCL_ERROR;
            goto done;
        }
        matchPtr = typePtr;
        }
    }
    if (matchPtr == NULL) {
        goto badType;
    }
    if ((strncmp("group", matchPtr->name, (unsigned)length) != 0) &&
        (objc < 4)) {
        /*
         * Allow more specific error return. Groups have no coords.
         */
        Tcl_WrongNumArgs(interp, 3, objv, "coords ?arg arg ...?");
        result = TCL_ERROR;
        goto done;
    }
    typePtr = matchPtr;

    result = ItemCreate(interp, canvasPtr, typePtr, 0, &itemPtr, objc-3, objv+3);
    if (result != TCL_OK) {
        result = TCL_ERROR;
        goto done;
    }
    canvasPtr->hotPtr = itemPtr;
    canvasPtr->hotPrevPtr = itemPtr->prevPtr;

    EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
    canvasPtr->flags |= REPICK_NEEDED;
    Tcl_SetObjResult(interp, Tcl_NewIntObj(itemPtr->id));
    break;
    }
    case CANV_DCHARS: {
    int first, last;
    int x1,x2,y1,y2;

    if ((objc != 4) && (objc != 5)) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId first ?last?");
        result = TCL_ERROR;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        if ((itemPtr->typePtr->indexProc == NULL)
            || (itemPtr->typePtr->dCharsProc == NULL)) {
        continue;
        }
        result = itemPtr->typePtr->indexProc(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, (char *) objv[3],
            &first);
        if (result != TCL_OK) {
        goto done;
        }
        if (objc == 5) {
        result = itemPtr->typePtr->indexProc(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, (char *) objv[4],
            &last);
        if (result != TCL_OK) {
            goto done;
        }
        } else {
        last = first;
        }

        /*
         * Redraw both item's old and new areas: it's possible that a
         * delete could result in a new area larger than the old area.
         * Except if the insertProc sets the TK_ITEM_DONT_REDRAW flag,
         * nothing more needs to be done.
         */

        x1 = itemPtr->x1; y1 = itemPtr->y1;
        x2 = itemPtr->x2; y2 = itemPtr->y2;
        itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
        (*itemPtr->typePtr->dCharsProc)((Tk_PathCanvas) canvasPtr,
            itemPtr, first, last);
        if (!(itemPtr->redraw_flags & TK_ITEM_DONT_REDRAW)) {
        Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) canvasPtr,
            x1, y1, x2, y2);
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        }
        itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
    }
    break;
    }
    case CANV_DEBUGTREE: {
    Tk_PathItem *walkPtr, *tmpPtr;
    char tmp[256], info[256];
    const char *s;
    int depth;

    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
        result = TCL_ERROR;
        goto done;
    }
    for (walkPtr = canvasPtr->rootItemPtr; walkPtr != NULL;
        walkPtr = TkPathCanvasItemIteratorNext(walkPtr)) {
        depth = 0;
        tmpPtr = walkPtr;
        while (tmpPtr->parentPtr != NULL) {
        depth++;
        tmpPtr = tmpPtr->parentPtr;
        }
        if (walkPtr->firstChildPtr != NULL) {
        s = "----";
        } else {
        s = "";
        }
        info[0] = '\0';
        DebugGetItemInfo(walkPtr, info);
        sprintf(tmp, "%*d%s\t%s (itemPtr=%p)\n", 4*depth+3, walkPtr->id, s, info, walkPtr);
        Tcl_WriteChars(Tcl_GetChannel(interp, "stdout", NULL), tmp, -1);
    }
    break;
    }
    case CANV_DELETE: {
    int i;

    /*
     * Since deletinga group item implicitly deletes all its children
     * we may unintentionally try to delete an item more than once.
     * We therefore flatten (parent = root) all items first.
     */
    for (i = 2; i < objc; i++) {
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[i], &searchPtr, goto done) {

        /*
         * Silently ignoring the root item.
         */
        if (itemPtr->id == 0) continue;

        /*
         * This will also delete all its descendants by
         * recursive calls.
         */
        ItemDelete(canvasPtr, itemPtr);
        }
    }
    break;
    }
    case CANV_DEPTH: {
        if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
     if (itemPtr != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(TkPathCanvasGetDepth(itemPtr)));
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_DISTANCE: {
    double point[2], dist;

        if (objc != 5) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId x y");
        result = TCL_ERROR;
        goto done;
    }
    if ((Tcl_GetDoubleFromObj(interp, objv[3], &point[0]) != TCL_OK) ||
        (Tcl_GetDoubleFromObj(interp, objv[4], &point[1]) != TCL_OK)) {
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        dist = (*itemPtr->typePtr->pointProc)((Tk_PathCanvas) canvasPtr, itemPtr, point);
        Tcl_SetObjResult(interp, Tcl_NewDoubleObj(dist));
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_DTAG: {
    Tk_PathTags *ptagsPtr;
    Tk_Uid tag;
    int i;

    if ((objc != 3) && (objc != 4)) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?tagToDelete?");
        result = TCL_ERROR;
        goto done;
    }
    if (objc == 4) {
        tag = Tk_GetUid(Tcl_GetString(objv[3]));
    } else {
        tag = Tk_GetUid(Tcl_GetString(objv[2]));
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        ptagsPtr = itemPtr->pathTagsPtr;
        if (ptagsPtr != NULL) {
        for (i = ptagsPtr->numTags-1; i >= 0; i--) {
            if (ptagsPtr->tagPtr[i] == tag) {
            ptagsPtr->tagPtr[i] = ptagsPtr->tagPtr[ptagsPtr->numTags-1];
            ptagsPtr->numTags--;
            }
        }
        }
    }
    break;
    }
    case CANV_FIND: {
    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "searchCommand ?arg arg ...?");
        result = TCL_ERROR;
        goto done;
    }
    result = FindItems(interp, canvasPtr, objc, objv, NULL, 2,
        &searchPtr);
    break;
    }
    case CANV_FIRSTCHILD: {
    Tk_PathItem *childPtr;

    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        childPtr = itemPtr->firstChildPtr;
        if (childPtr != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(childPtr->id));
        }
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_FOCUS: {
    if (objc > 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "?tagOrId?");
        result = TCL_ERROR;
        goto done;
    }
    itemPtr = canvasPtr->textInfo.focusItemPtr;
    if (objc == 2) {
        if (itemPtr != NULL) {
        char buf[TCL_INTEGER_SPACE];

        sprintf(buf, "%d", itemPtr->id);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        }
        goto done;
    }
    if ((itemPtr != NULL) && (canvasPtr->textInfo.gotFocus)) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
    }
    if (Tcl_GetString(objv[2])[0] == 0) {
        canvasPtr->textInfo.focusItemPtr = NULL;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        if (itemPtr->typePtr->icursorProc != NULL) {
        break;
        }
    }
    if (itemPtr == NULL) {
        goto done;
    }
    canvasPtr->textInfo.focusItemPtr = itemPtr;
    if (canvasPtr->textInfo.gotFocus) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
    }
    break;
    }
    case CANV_GETTAGS: {
    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        int i;
        Tk_PathTags *ptagsPtr;

        ptagsPtr = itemPtr->pathTagsPtr;
        if (ptagsPtr != NULL) {
        for (i = 0; i < ptagsPtr->numTags; i++) {
            Tcl_AppendElement(interp, (char *) ptagsPtr->tagPtr[i]);
        }
        }
    }
    break;
    }
    case CANV_GRADIENT: {
    result = TkPathCanvasGradientObjCmd(interp, canvasPtr, objc, objv);
    break;
    }
    case CANV_ICURSOR: {
    int index;

    if (objc != 4) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId index");
        result = TCL_ERROR;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        if ((itemPtr->typePtr->indexProc == NULL)
            || (itemPtr->typePtr->icursorProc == NULL)) {
        goto done;
        }
        result = itemPtr->typePtr->indexProc(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, (char *) objv[3],
            &index);
        if (result != TCL_OK) {
        goto done;
        }
        (*itemPtr->typePtr->icursorProc)((Tk_PathCanvas) canvasPtr, itemPtr,
            index);
        if ((itemPtr == canvasPtr->textInfo.focusItemPtr)
            && (canvasPtr->textInfo.cursorOn)) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        }
    }
    break;
    }
    case CANV_INDEX: {
    int index;
    char buf[TCL_INTEGER_SPACE];

    if (objc != 4) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId string");
        result = TCL_ERROR;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        if (itemPtr->typePtr->indexProc != NULL) {
        break;
        }
    }
    if (itemPtr == NULL) {
        Tcl_AppendResult(interp, "can't find an indexable item \"",
            Tcl_GetString(objv[2]), "\"", NULL);
        result = TCL_ERROR;
        goto done;
    }
    result = itemPtr->typePtr->indexProc(interp, (Tk_PathCanvas) canvasPtr,
        itemPtr, (char *) objv[3], &index);
    if (result != TCL_OK) {
        goto done;
    }
    sprintf(buf, "%d", index);
    Tcl_SetResult(interp, buf, TCL_VOLATILE);
    break;
    }
    case CANV_INSERT: {
    int beforeThis;
    int x1,x2,y1,y2;

    if (objc != 5) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId beforeThis string");
        result = TCL_ERROR;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        if ((itemPtr->typePtr->indexProc == NULL)
            || (itemPtr->typePtr->insertProc == NULL)) {
        continue;
        }
        result = itemPtr->typePtr->indexProc(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, (char *) objv[3],
            &beforeThis);
        if (result != TCL_OK) {
        goto done;
        }

        /*
         * Redraw both item's old and new areas: it's possible that an
         * insertion could result in a new area either larger or smaller
         * than the old area. Except if the insertProc sets the
         * TK_ITEM_DONT_REDRAW flag, nothing more needs to be done.
         */

        x1 = itemPtr->x1; y1 = itemPtr->y1;
        x2 = itemPtr->x2; y2 = itemPtr->y2;
        itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
        (*itemPtr->typePtr->insertProc)((Tk_PathCanvas) canvasPtr,
            itemPtr, beforeThis, (char *) objv[4]);
        if (!(itemPtr->redraw_flags & TK_ITEM_DONT_REDRAW)) {
        Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) canvasPtr,
            x1, y1, x2, y2);
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        }
        itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
    }
    break;
    }
    case CANV_ITEMCGET: {
    if (objc != 4) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId option");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        resultObjPtr = Tk_GetOptionValue(canvasPtr->interp, (char *) itemPtr,
            itemPtr->optionTable, objv[3], canvasPtr->tkwin);
        if (resultObjPtr == NULL) {
        result = TCL_ERROR;
        goto done;
        } else {
        Tcl_SetObjResult(interp, resultObjPtr);
        }
    }
    break;
    }
    case CANV_ITEMCONFIGURE: {
    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?option value ...?");
        result = TCL_ERROR;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        if (objc <= 4) {
        resultObjPtr = Tk_GetOptionInfo(canvasPtr->interp, (char *) itemPtr,
            itemPtr->optionTable, (objc == 4) ? objv[3] : NULL,
            canvasPtr->tkwin);
        if (resultObjPtr == NULL) {
            result = TCL_ERROR;
            goto done;
        } else {
            Tcl_SetObjResult(interp, resultObjPtr);
        }
        } else {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        result = (*itemPtr->typePtr->configProc)(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, objc-3, objv+3,
            TK_CONFIG_ARGV_ONLY);
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        canvasPtr->flags |= REPICK_NEEDED;
        }
        if ((result != TCL_OK) || (objc < 5)) {
        break;
        }
    }
    break;
    }
    case CANV_ITEMPDF: {
    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ...");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        if (itemPtr->typePtr->pdfProc != NULL) {
        result = (*itemPtr->typePtr->pdfProc)(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, objc-3, objv+3, 0);
        }
    }
    break;
    }
    case CANV_LASTCHILD: {
    Tk_PathItem *childPtr;

    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        childPtr = itemPtr->lastChildPtr;
        if (childPtr != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(childPtr->id));
        }
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_LOWER: {
    Tk_PathItem *itemPtr;

    if ((objc != 3) && (objc != 4)) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?belowThis?");
        result = TCL_ERROR;
        goto done;
    }

    /*
     * First find the item just after which we'll insert the named items.
     */

    if (objc == 3) {
        itemPtr = NULL;
    } else {
        FIRST_CANVAS_ITEM_MATCHING(objv[3], &searchPtr, goto done);
        if (itemPtr == NULL) {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[3]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
        }
        itemPtr = itemPtr->prevPtr;
    }
    result = RelinkItems(canvasPtr, objv[2], itemPtr, &searchPtr);
    break;
    }
    case CANV_CMOVE:
    case CANV_MOVE: {
    int compensate = ((enum options) index) == CANV_CMOVE;
    double xAmount, yAmount;

    if (objc != 5) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId xAmount yAmount");
        result = TCL_ERROR;
        goto done;
    }
    if ((Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) canvasPtr, objv[3],
        &xAmount) != TCL_OK) || (Tk_PathCanvasGetCoordFromObj(interp,
        (Tk_PathCanvas) canvasPtr, objv[4], &yAmount) != TCL_OK)) {
        result = TCL_ERROR;
        goto done;
    }

        /* Round the deltas to the nearest integer to avoid round-off errors */
        xAmount = (double)((int)(xAmount + (xAmount > 0 ? 0.5 : -0.5)));
        yAmount = (double)((int)(yAmount + (yAmount > 0 ? 0.5 : -0.5)));

    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        (void) (*itemPtr->typePtr->translateProc)((Tk_PathCanvas) canvasPtr,
            itemPtr,  compensate, xAmount, yAmount);
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        canvasPtr->flags |= REPICK_NEEDED;
    }
    break;
    }
    case CANV_NEXTSIBLING: {
    Tk_PathItem *nextPtr;

    /* @@@ TODO: add optional argument like TreeCtrl has. */
    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        nextPtr = itemPtr->nextPtr;
        if (nextPtr != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(nextPtr->id));
        }
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_PARENT: {
    int id;

    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "id");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        if (itemPtr->id == 0) {
        id = -1;    /* @@@ TODO: What else to return? */
        } else {
        id = itemPtr->parentPtr->id;
        }
        Tcl_SetObjResult(interp, Tcl_NewIntObj(id));
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_PREVSIBLING: {
    Tk_PathItem *prevPtr;

    /* @@@ TODO: add optional argument like TreeCtrl has. */
    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        prevPtr = itemPtr->prevPtr;
        if (prevPtr != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(prevPtr->id));
        }
    } else {
        Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
    }
    break;
    }
    case CANV_RAISE: {
    Tk_PathItem *prevPtr;

    if ((objc != 3) && (objc != 4)) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?aboveThis?");
        result = TCL_ERROR;
        goto done;
    }

    /*
     * First find the item just after which we'll insert the named items.
     */

    if (objc == 3) {
        prevPtr = canvasPtr->rootItemPtr->lastChildPtr;
    } else {
        prevPtr = NULL;
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[3], &searchPtr, goto done) {
        prevPtr = itemPtr;
        }
        if (prevPtr == NULL) {
        Tcl_AppendResult(interp, "tagOrId \"", Tcl_GetString(objv[3]),
            "\" doesn't match any items", NULL);
        result = TCL_ERROR;
        goto done;
        }
    }
    result = RelinkItems(canvasPtr, objv[2], prevPtr, &searchPtr);
    break;
    }
    case CANV_CSCALE:
    case CANV_SCALE: {
    int compensate = ((enum options) index) == CANV_CSCALE;
    double xOrigin, yOrigin, xScale, yScale;

    if (objc != 7) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId xOrigin yOrigin xScale yScale");
        result = TCL_ERROR;
        goto done;
    }
    if ((Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) canvasPtr,
            objv[3], &xOrigin) != TCL_OK)
        || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) canvasPtr,
            objv[4], &yOrigin) != TCL_OK)
        || (Tcl_GetDoubleFromObj(interp, objv[5], &xScale) != TCL_OK)
        || (Tcl_GetDoubleFromObj(interp, objv[6], &yScale) != TCL_OK)) {
        result = TCL_ERROR;
        goto done;
    }
    if ((xScale == 0.0) || (yScale == 0.0)) {
        Tcl_SetResult(interp, (char *) "scale factor cannot be zero",
              TCL_STATIC);
        result = TCL_ERROR;
        goto done;
    }
    FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        (void) (*itemPtr->typePtr->scaleProc)((Tk_PathCanvas) canvasPtr,
            itemPtr, compensate, xOrigin, yOrigin, xScale, yScale);
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr, itemPtr);
        canvasPtr->flags |= REPICK_NEEDED;
    }
    break;
    }
    case CANV_SCAN: {
    int x, y;
#ifdef ANDROID
    int gain = 2;
#else
    int gain = 10;
#endif
    static const char *optionStrings[] = {
        "mark", "dragto", NULL
    };

    if (objc < 5) {
        Tcl_WrongNumArgs(interp, 2, objv, "mark|dragto x y ?dragGain?");
        result = TCL_ERROR;
    } else if (Tcl_GetIndexFromObj(interp, objv[2], optionStrings,
        "scan option", 0, &index) != TCL_OK) {
        result = TCL_ERROR;
    } else if ((objc != 5) && (objc != 5+index)) {
        Tcl_WrongNumArgs(interp, 3, objv, index?"x y ?gain?":"x y");
        result = TCL_ERROR;
    } else if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK)
        || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)){
        result = TCL_ERROR;
    } else if ((objc == 6) &&
        (Tcl_GetIntFromObj(interp, objv[5], &gain) != TCL_OK)) {
        result = TCL_ERROR;
    } else if (!index) {
        canvasPtr->scanX = x;
        canvasPtr->scanXOrigin = canvasPtr->xOrigin;
        canvasPtr->scanY = y;
        canvasPtr->scanYOrigin = canvasPtr->yOrigin;
    } else {
        int newXOrigin, newYOrigin, tmp;

        /*
         * Compute a new view origin for the canvas, amplifying the
         * mouse motion.
         */

        tmp = canvasPtr->scanXOrigin - gain*(x - canvasPtr->scanX)
            - canvasPtr->scrollX1;
        newXOrigin = canvasPtr->scrollX1 + tmp;
        tmp = canvasPtr->scanYOrigin - gain*(y - canvasPtr->scanY)
            - canvasPtr->scrollY1;
        newYOrigin = canvasPtr->scrollY1 + tmp;
        CanvasSetOrigin(canvasPtr, newXOrigin, newYOrigin);
    }
    break;
    }
    case CANV_SELECT: {
    int index, optionindex;
    static const char *optionStrings[] = {
        "adjust", "clear", "from", "item", "to", NULL
    };
    enum options {
        CANV_ADJUST, CANV_CLEAR, CANV_FROM, CANV_ITEM, CANV_TO
    };

    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "option ?tagOrId? ?arg?");
        result = TCL_ERROR;
        goto done;
    }
    if (objc >= 4) {
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[3], &searchPtr, goto done) {
        if ((itemPtr->typePtr->indexProc != NULL)
            && (itemPtr->typePtr->selectionProc != NULL)){
            break;
        }
        }
        if (itemPtr == NULL) {
        Tcl_AppendResult(interp,
            "can't find an indexable and selectable item \"",
            Tcl_GetString(objv[3]), "\"", NULL);
        result = TCL_ERROR;
        goto done;
        }
    }
    if (objc == 5) {
        result = itemPtr->typePtr->indexProc(interp,
            (Tk_PathCanvas) canvasPtr, itemPtr, (char *) objv[4],
            &index);
        if (result != TCL_OK) {
        goto done;
        }
    }
    if (Tcl_GetIndexFromObj(interp, objv[2], optionStrings,
        "select option", 0, &optionindex) != TCL_OK) {
        result = TCL_ERROR;
        goto done;
    }
    switch ((enum options) optionindex) {
    case CANV_ADJUST:
        if (objc != 5) {
        Tcl_WrongNumArgs(interp, 3, objv, "tagOrId index");
        result = TCL_ERROR;
        goto done;
        }
        if (canvasPtr->textInfo.selItemPtr == itemPtr) {
        if (index < (canvasPtr->textInfo.selectFirst
            + canvasPtr->textInfo.selectLast)/2) {
            canvasPtr->textInfo.selectAnchor =
                canvasPtr->textInfo.selectLast + 1;
        } else {
            canvasPtr->textInfo.selectAnchor =
                canvasPtr->textInfo.selectFirst;
        }
        }
        CanvasSelectTo(canvasPtr, itemPtr, index);
        break;
    case CANV_CLEAR:
        if (objc != 3) {
        Tcl_AppendResult(interp, 3, objv, NULL);
        result = TCL_ERROR;
        goto done;
        }
        if (canvasPtr->textInfo.selItemPtr != NULL) {
        EventuallyRedrawItem((Tk_PathCanvas) canvasPtr,
            canvasPtr->textInfo.selItemPtr);
        canvasPtr->textInfo.selItemPtr = NULL;
        }
        goto done;
        break;
    case CANV_FROM:
        if (objc != 5) {
        Tcl_WrongNumArgs(interp, 3, objv, "tagOrId index");
        result = TCL_ERROR;
        goto done;
        }
        canvasPtr->textInfo.anchorItemPtr = itemPtr;
        canvasPtr->textInfo.selectAnchor = index;
        break;
    case CANV_ITEM:
        if (objc != 3) {
        Tcl_WrongNumArgs(interp, 3, objv, NULL);
        result = TCL_ERROR;
        goto done;
        }
        if (canvasPtr->textInfo.selItemPtr != NULL) {
        Tcl_SetObjResult(interp,
            Tcl_NewIntObj(canvasPtr->textInfo.selItemPtr->id));
        }
        break;
    case CANV_TO:
        if (objc != 5) {
        Tcl_WrongNumArgs(interp, 2, objv, "tagOrId index");
        result = TCL_ERROR;
        goto done;
        }
        CanvasSelectTo(canvasPtr, itemPtr, index);
        break;
    }
    break;
    }
    case CANV_STYLE: {
    result = TkPathCanvasStyleObjCmd(interp, canvasPtr, objc, objv);
    break;
    }
    case CANV_TYPE: {
    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "tag");
        result = TCL_ERROR;
        goto done;
    }
    FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
    if (itemPtr != NULL) {
        Tcl_SetResult(interp, (char *) itemPtr->typePtr->name, TCL_STATIC);
    }
    break;
    }
    case CANV_TYPES: {
    Tk_PathItemType *typePtr;
        Tcl_Obj *listObj;

     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
        result = TCL_ERROR;
        goto done;
    }
    listObj = Tcl_NewListObj(0, NULL);
    for (typePtr = typeList; typePtr != NULL;
        typePtr = typePtr->nextPtr) {
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewStringObj(typePtr->name, -1));<