Modified the UGetCursor() routine to return a valid response if the
[xcircuit.git] / functions.c
blob3603466b5eeaf9f7682a041cc300051c32b5d093
1 /*-------------------------------------------------------------------------*/
2 /* functions.c */
3 /* Copyright (c) 2002 Tim Edwards, Johns Hopkins University */
4 /*-------------------------------------------------------------------------*/
6 /*-------------------------------------------------------------------------*/
7 /* written by Tim Edwards, 8/13/93 */
8 /*-------------------------------------------------------------------------*/
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <math.h>
14 #include <limits.h>
16 #ifndef _MSC_VER
17 #include <X11/Intrinsic.h>
18 #include <X11/StringDefs.h>
19 #endif
21 /*-------------------------------------------------------------------------*/
22 /* Local includes */
23 /*-------------------------------------------------------------------------*/
25 #ifdef TCL_WRAPPER
26 #include <tk.h>
27 #endif
29 #include "colordefs.h"
30 #include "xcircuit.h"
32 /*----------------------------------------------------------------------*/
33 /* Function prototype declarations */
34 /*----------------------------------------------------------------------*/
35 #include "prototypes.h"
37 /*-------------------------------------------------------------------------*/
38 /* External Variable definitions */
39 /*-------------------------------------------------------------------------*/
41 extern Display *dpy;
42 extern Pixmap STIPPLE[8];
43 extern XCWindowData *areawin;
44 extern Globaldata xobjs;
45 extern int number_colors;
46 extern colorindex *colorlist;
48 /*------------------------------------------------------------------------*/
49 /* find the squared length of a wire (or distance between two points in */
50 /* user space). */
51 /*------------------------------------------------------------------------*/
53 long sqwirelen(XPoint *userpt1, XPoint *userpt2)
55 long xdist, ydist;
57 xdist = (long)userpt2->x - (long)userpt1->x;
58 ydist = (long)userpt2->y - (long)userpt1->y;
59 return (xdist * xdist + ydist * ydist);
62 /*------------------------------------------------------------------------*/
63 /* floating-point version of the above */
64 /*------------------------------------------------------------------------*/
66 float fsqwirelen(XfPoint *userpt1, XfPoint *userpt2)
68 float xdist, ydist;
70 xdist = userpt2->x - userpt1->x;
71 ydist = userpt2->y - userpt1->y;
72 return (xdist * xdist + ydist * ydist);
75 /*------------------------------------------------------------------------*/
76 /* Find absolute distance between two points in user space */
77 /*------------------------------------------------------------------------*/
79 int wirelength(XPoint *userpt1, XPoint *userpt2)
81 u_long xdist, ydist;
83 xdist = (long)(userpt2->x) - (long)(userpt1->x);
84 ydist = (long)(userpt2->y) - (long)(userpt1->y);
85 return (int)sqrt((double)(xdist * xdist + ydist * ydist));
88 /*------------------------------------------------------------------------*/
89 /* Find the closest (squared) distance from a point to a line */
90 /*------------------------------------------------------------------------*/
92 long finddist(XPoint *linept1, XPoint *linept2, XPoint *userpt)
94 long a, b, c, frac;
95 float protod;
97 c = sqwirelen(linept1, linept2);
98 a = sqwirelen(linept1, userpt);
99 b = sqwirelen(linept2, userpt);
100 frac = a - b;
101 if (frac >= c) return b; /* "=" is important if c = 0 ! */
102 else if (-frac >= c) return a;
103 else {
104 protod = (float)(c + a - b);
105 return (a - (long)((protod * protod) / (float)(c << 2)));
109 /*----------------------------------------------------------------------*/
110 /* Decompose an arc segment into one to four bezier curves according */
111 /* the approximation algorithm lifted from the paper by L. Maisonobe */
112 /* (spaceroots.org). This decomposition is done when an arc in a path */
113 /* is read from an (older) xcircuit file, or when an arc is a selected */
114 /* item when a path is created. Because arcs are decomposed when */
115 /* encountered, we assume that the arc is the last element of the path. */
116 /*----------------------------------------------------------------------*/
118 void decomposearc(pathptr thepath, XPoint *startpoint)
120 float fnc, ang1, ang2;
121 short ncurves, i;
122 arcptr thearc;
123 genericptr *pgen;
124 splineptr *newspline;
125 polyptr *newpoly;
126 double nu1, nu2, lambda1, lambda2, alpha, tansq;
127 XfPoint E1, E2, Ep1, Ep2;
128 XPoint P1;
129 Boolean reverse = FALSE;
131 pgen = thepath->plist + thepath->parts - 1;
132 if (ELEMENTTYPE(*pgen) != ARC) return;
133 thearc = TOARC(pgen);
135 if (thearc->radius < 0) {
136 reverse = TRUE;
137 thearc->radius = -thearc->radius;
140 fnc = (thearc->angle2 - thearc->angle1) / 90.0;
141 ncurves = (short)fnc;
142 if (fnc - (float)((int)fnc) > 0.01) ncurves++;
144 thepath->parts--; /* Forget the arc */
146 for (i = 0; i < ncurves; i++) {
147 if (reverse) { /* arc path is reverse direction */
148 if (i == 0)
149 ang1 = thearc->angle2;
150 else
151 ang1 -= 90;
153 if (i == ncurves - 1)
154 ang2 = thearc->angle1;
155 else
156 ang2 = ang1 - 90;
158 else { /* arc path is forward direction */
159 if (i == 0)
160 ang1 = thearc->angle1;
161 else
162 ang1 += 90;
164 if (i == ncurves - 1)
165 ang2 = thearc->angle2;
166 else
167 ang2 = ang1 + 90;
170 lambda1 = (double)ang1 * RADFAC;
171 lambda2 = (double)ang2 * RADFAC;
173 nu1 = atan2(sin(lambda1) / (double)thearc->yaxis,
174 cos(lambda1) / (double)thearc->radius);
175 nu2 = atan2(sin(lambda2) / (double)thearc->yaxis,
176 cos(lambda2) / (double)thearc->radius);
177 E1.x = (float)thearc->position.x +
178 (float)thearc->radius * (float)cos(nu1);
179 E1.y = (float)thearc->position.y +
180 (float)thearc->yaxis * (float)sin(nu1);
181 E2.x = (float)thearc->position.x +
182 (float)thearc->radius * (float)cos(nu2);
183 E2.y = (float)thearc->position.y +
184 (float)thearc->yaxis * (float)sin(nu2);
185 Ep1.x = -(float)thearc->radius * (float)sin(nu1);
186 Ep1.y = (float)thearc->yaxis * (float)cos(nu1);
187 Ep2.x = -(float)thearc->radius * (float)sin(nu2);
188 Ep2.y = (float)thearc->yaxis * (float)cos(nu2);
190 P1.x = (int)(roundf(E1.x));
191 P1.y = (int)(roundf(E1.y));
193 tansq = tan((nu2 - nu1) / 2.0);
194 tansq *= tansq;
195 alpha = sin(nu2 - nu1) * 0.33333 * (sqrt(4 + (3 * tansq)) - 1);
197 /* If the arc 1st point is not the same as the previous path point,
198 * then add a straight line to the 1st arc point (mimics PostScript
199 * behavior).
202 if (startpoint && (i == 0)) {
203 if ((startpoint->x != P1.x) || (startpoint->y != P1.y)) {
204 NEW_POLY(newpoly, thepath);
205 polydefaults(*newpoly, 2, startpoint->x, startpoint->y);
206 (*newpoly)->style = thearc->style;
207 (*newpoly)->color = thearc->color;
208 (*newpoly)->width = thearc->width;
209 (*newpoly)->points[1].x = P1.x;
210 (*newpoly)->points[1].y = P1.y;
214 NEW_SPLINE(newspline, thepath);
215 splinedefaults(*newspline, 0, 0);
216 (*newspline)->style = thearc->style;
217 (*newspline)->color = thearc->color;
218 (*newspline)->width = thearc->width;
220 (*newspline)->ctrl[0].x = P1.x;
221 (*newspline)->ctrl[0].y = P1.y;
223 (*newspline)->ctrl[1].x = (int)(roundf(E1.x + alpha * Ep1.x));
224 (*newspline)->ctrl[1].y = (int)(roundf(E1.y + alpha * Ep1.y));
226 (*newspline)->ctrl[2].x = (int)(roundf(E2.x - alpha * Ep2.x));
227 (*newspline)->ctrl[2].y = (int)(roundf(E2.y - alpha * Ep2.y));
229 (*newspline)->ctrl[3].x = (int)(roundf(E2.x));
230 (*newspline)->ctrl[3].y = (int)(roundf(E2.y));
232 calcspline(*newspline);
235 /* Delete the arc */
236 free_single((genericptr)thearc);
239 /*----------------------------------------------------------------------*/
240 /* Calculate points for an arc */
241 /*----------------------------------------------------------------------*/
243 void calcarc(arcptr thearc)
245 short idx;
246 int sarc;
247 float theta, delta;
249 /* assume that angle2 > angle1 always: must be guaranteed by other routines */
251 sarc = (int)(thearc->angle2 - thearc->angle1) * RSTEPS;
252 thearc->number = (sarc / 360) + 1;
253 if (sarc % 360 != 0) thearc->number++;
255 delta = RADFAC * ((float)(thearc->angle2 - thearc->angle1) / (thearc->number - 1));
256 theta = thearc->angle1 * RADFAC;
258 for (idx = 0; idx < thearc->number - 1; idx++) {
259 thearc->points[idx].x = (float)thearc->position.x +
260 fabs((float)thearc->radius) * cos(theta);
261 thearc->points[idx].y = (float)thearc->position.y +
262 (float)thearc->yaxis * sin(theta);
263 theta += delta;
266 /* place last point exactly to avoid roundoff error */
268 theta = thearc->angle2 * RADFAC;
269 thearc->points[thearc->number - 1].x = (float)thearc->position.x +
270 fabs((float)thearc->radius) * cos(theta);
271 thearc->points[thearc->number - 1].y = (float)thearc->position.y +
272 (float)thearc->yaxis * sin(theta);
274 if (thearc->radius < 0) reversefpoints(thearc->points, thearc->number);
277 /*------------------------------------------------------------------------*/
278 /* Create a Bezier curve approximation from control points */
279 /* (using PostScript formula for Bezier cubic curve) */
280 /*------------------------------------------------------------------------*/
282 float par[INTSEGS];
283 float parsq[INTSEGS];
284 float parcb[INTSEGS];
286 void initsplines()
288 float t;
289 short idx;
291 for (idx = 0; idx < INTSEGS; idx++) {
292 t = (float)(idx + 1) / (INTSEGS + 1);
293 par[idx] = t;
294 parsq[idx] = t * t;
295 parcb[idx] = parsq[idx] * t;
299 /*------------------------------------------------------------------------*/
300 /* Compute spline coefficients */
301 /*------------------------------------------------------------------------*/
303 void computecoeffs(splineptr thespline, float *ax, float *bx, float *cx,
304 float *ay, float *by, float *cy)
306 *cx = 3.0 * (float)(thespline->ctrl[1].x - thespline->ctrl[0].x);
307 *bx = 3.0 * (float)(thespline->ctrl[2].x - thespline->ctrl[1].x) - *cx;
308 *ax = (float)(thespline->ctrl[3].x - thespline->ctrl[0].x) - *cx - *bx;
310 *cy = 3.0 * (float)(thespline->ctrl[1].y - thespline->ctrl[0].y);
311 *by = 3.0 * (float)(thespline->ctrl[2].y - thespline->ctrl[1].y) - *cy;
312 *ay = (float)(thespline->ctrl[3].y - thespline->ctrl[0].y) - *cy - *by;
315 /*------------------------------------------------------------------------*/
317 void calcspline(splineptr thespline)
319 float ax, bx, cx, ay, by, cy;
320 short idx;
322 computecoeffs(thespline, &ax, &bx, &cx, &ay, &by, &cy);
323 for (idx = 0; idx < INTSEGS; idx++) {
324 thespline->points[idx].x = ax * parcb[idx] + bx * parsq[idx] +
325 cx * par[idx] + (float)thespline->ctrl[0].x;
326 thespline->points[idx].y = ay * parcb[idx] + by * parsq[idx] +
327 cy * par[idx] + (float)thespline->ctrl[0].y;
331 /*------------------------------------------------------------------------*/
332 /* Find the (x,y) position and tangent rotation of a point on a spline */
333 /*------------------------------------------------------------------------*/
335 void findsplinepos(splineptr thespline, float t, XPoint *retpoint, float *retrot)
337 float ax, bx, cx, ay, by, cy;
338 float tsq = t * t;
339 float tcb = tsq * t;
340 double dxdt, dydt;
342 computecoeffs(thespline, &ax, &bx, &cx, &ay, &by, &cy);
343 retpoint->x = (short)(ax * tcb + bx * tsq + cx * t + (float)thespline->ctrl[0].x);
344 retpoint->y = (short)(ay * tcb + by * tsq + cy * t + (float)thespline->ctrl[0].y);
346 if (retrot != NULL) {
347 dxdt = (double)(3 * ax * tsq + 2 * bx * t + cx);
348 dydt = (double)(3 * ay * tsq + 2 * by * t + cy);
349 *retrot = INVRFAC * atan2(dxdt, dydt); /* reversed y, x */
350 if (*retrot < 0) *retrot += 360;
354 /*------------------------------------------------------------------------*/
355 /* floating-point version of the above */
356 /*------------------------------------------------------------------------*/
358 void ffindsplinepos(splineptr thespline, float t, XfPoint *retpoint)
360 float ax, bx, cx, ay, by, cy;
361 float tsq = t * t;
362 float tcb = tsq * t;
364 computecoeffs(thespline, &ax, &bx, &cx, &ay, &by, &cy);
365 retpoint->x = ax * tcb + bx * tsq + cx * t + (float)thespline->ctrl[0].x;
366 retpoint->y = ay * tcb + by * tsq + cy * t + (float)thespline->ctrl[0].y;
369 /*------------------------------------------------------------------------*/
370 /* Find the closest distance between a point and a spline and return the */
371 /* fractional distance along the spline of this point. */
372 /*------------------------------------------------------------------------*/
374 float findsplinemin(splineptr thespline, XPoint *upoint)
376 XfPoint *spt, flpt, newspt;
377 float minval = 1000000, tval, hval, ndist;
378 short j, ival;
380 flpt.x = (float)(upoint->x);
381 flpt.y = (float)(upoint->y);
383 /* get estimate from precalculated spline points */
385 for (spt = thespline->points; spt < thespline->points + INTSEGS;
386 spt++) {
387 ndist = fsqwirelen(spt, &flpt);
388 if (ndist < minval) {
389 minval = ndist;
390 ival = (short)(spt - thespline->points);
393 tval = (float)(ival + 1) / (INTSEGS + 1);
394 hval = 0.5 / (INTSEGS + 1);
396 /* short fixed iterative loop to converge on minimum t */
398 for (j = 0; j < 5; j++) {
399 tval += hval;
400 ffindsplinepos(thespline, tval, &newspt);
401 ndist = fsqwirelen(&newspt, &flpt);
402 if (ndist < minval) minval = ndist;
403 else {
404 tval -= hval * 2;
405 ffindsplinepos(thespline, tval, &newspt);
406 ndist = fsqwirelen(&newspt, &flpt);
407 if (ndist < minval) minval = ndist;
408 else tval += hval;
410 hval /= 2;
413 if (tval < 0.1) {
414 if ((float)sqwirelen(&(thespline->ctrl[0]), upoint) < minval) tval = 0;
416 else if (tval > 0.9) {
417 if ((float)sqwirelen(&(thespline->ctrl[3]), upoint) < minval) tval = 1;
419 return tval;
422 /*----------------------------------------------------------------------*/
423 /* Convert a polygon to a Bezier curve path */
424 /* Curve must be selected and there must be only one selection. */
425 /* */
426 /* Note that this routine will draw inside the perimeter of a convex */
427 /* hull. A routine that places spline endpoints on the polygon */
428 /* vertices will draw outside the perimeter of a convex hull. An */
429 /* optimal algorithm presumably zeros the total area between the curve */
430 /* and the polygon (positive and negative), but I haven't worked out */
431 /* what that solution is. The algorithm below seems good enough for */
432 /* most purposes. */
433 /*----------------------------------------------------------------------*/
435 void converttocurve()
437 genericptr *ggen;
438 splineptr *newspline;
439 polyptr thispoly;
440 pathptr *newpath;
441 short *newselect;
442 XPoint firstpoint, lastpoint, initpoint;
443 int i, numpoints;
445 if (areawin->selects != 1) return;
447 thispoly = TOPOLY(topobject->plist + (*areawin->selectlist));
448 if (ELEMENTTYPE(thispoly) != POLYGON) return;
449 if (thispoly->number < 3) return; /* Will not convert */
451 standard_element_delete(ERASE);
452 if ((thispoly->style & UNCLOSED) && (thispoly->number == 3)) {
453 NEW_SPLINE(newspline, topobject);
454 splinedefaults(*newspline, 0, 0);
455 (*newspline)->ctrl[0] = thispoly->points[0];
456 (*newspline)->ctrl[1] = thispoly->points[1];
457 (*newspline)->ctrl[2] = thispoly->points[1];
458 (*newspline)->ctrl[3] = thispoly->points[2];
460 else {
461 numpoints = thispoly->number;
463 /* If the polygon is closed but the first and last points */
464 /* overlap, treat the last point as if it doesn't exist. */
466 if (!(thispoly->style & UNCLOSED))
467 if ((thispoly->points[0].x == thispoly->points[thispoly->number - 1].x)
468 && (thispoly->points[0].y ==
469 thispoly->points[thispoly->number - 1].y))
470 numpoints--;
472 NEW_PATH(newpath, topobject);
473 pathdefaults(*newpath, 0, 0);
474 (*newpath)->style = thispoly->style;
476 if (!(thispoly->style & UNCLOSED)) {
477 lastpoint = thispoly->points[numpoints - 1];
478 initpoint.x = (lastpoint.x + thispoly->points[0].x) / 2;
479 initpoint.y = (lastpoint.y + thispoly->points[0].y) / 2;
480 firstpoint.x = (thispoly->points[0].x
481 + thispoly->points[1].x) / 2;
482 firstpoint.y = (thispoly->points[0].y
483 + thispoly->points[1].y) / 2;
485 NEW_SPLINE(newspline, (*newpath));
486 splinedefaults(*newspline, 0, 0);
487 (*newspline)->ctrl[0] = initpoint;
488 (*newspline)->ctrl[1] = thispoly->points[0];
489 (*newspline)->ctrl[2] = thispoly->points[0];
490 (*newspline)->ctrl[3] = firstpoint;
491 calcspline(*newspline);
493 else
494 firstpoint = thispoly->points[0];
496 for (i = 0; i < numpoints - ((!(thispoly->style & UNCLOSED)) ?
497 2 : 3); i++) {
498 lastpoint.x = (thispoly->points[i + 1].x
499 + thispoly->points[i + 2].x) / 2;
500 lastpoint.y = (thispoly->points[i + 1].y
501 + thispoly->points[i + 2].y) / 2;
503 NEW_SPLINE(newspline, (*newpath));
504 splinedefaults(*newspline, 0, 0);
505 (*newspline)->ctrl[0] = firstpoint;
506 (*newspline)->ctrl[1] = thispoly->points[i + 1];
507 (*newspline)->ctrl[2] = thispoly->points[i + 1];
508 (*newspline)->ctrl[3] = lastpoint;
509 firstpoint = lastpoint;
510 calcspline(*newspline);
512 if (!(thispoly->style & UNCLOSED))
513 lastpoint = initpoint;
514 else
515 lastpoint = thispoly->points[i + 2];
517 NEW_SPLINE(newspline, (*newpath));
518 splinedefaults(*newspline, 0, 0);
519 (*newspline)->ctrl[0] = firstpoint;
520 (*newspline)->ctrl[1] = thispoly->points[i + 1];
521 (*newspline)->ctrl[2] = thispoly->points[i + 1];
522 (*newspline)->ctrl[3] = lastpoint;
524 calcspline(*newspline);
525 calcbbox(areawin->topinstance);
526 setoptionmenu();
527 drawarea(NULL, NULL, NULL);
530 /*----------------------------------------------------------------------*/
531 /* Find closest point of a polygon to the cursor */
532 /*----------------------------------------------------------------------*/
534 short closepointdistance(polyptr curpoly, XPoint *cursloc, short *mindist)
536 short curdist;
537 XPoint *curpt, *savept;
539 curpt = savept = curpoly->points;
540 *mindist = wirelength(curpt, cursloc);
541 while (++curpt < curpoly->points + curpoly->number) {
542 curdist = wirelength(curpt, cursloc);
543 if (curdist < *mindist) {
544 *mindist = curdist;
545 savept = curpt;
548 return (short)(savept - curpoly->points);
551 /*----------------------------------------------------------------------------*/
552 /* Find closest point of a polygon to the cursor */
553 /*----------------------------------------------------------------------------*/
555 short closepoint(polyptr curpoly, XPoint *cursloc)
557 short mindist;
558 return closepointdistance(curpoly, cursloc, &mindist);
561 /*----------------------------------------------------------------------------*/
562 /* Find the distance to the closest point of a polygon to the cursor */
563 /*----------------------------------------------------------------------------*/
565 short closedistance(polyptr curpoly, XPoint *cursloc)
567 short mindist;
568 closepointdistance(curpoly, cursloc, &mindist);
569 return mindist;
572 /*----------------------------------------------------------------------------*/
573 /* Coordinate system transformations */
574 /*----------------------------------------------------------------------------*/
576 /*------------------------------------------------------------------------------*/
577 /* Check screen bounds: minimum, maximum scale and translation is determined */
578 /* by values which fit in an X11 type XPoint (short int). If the window */
579 /* extremes exceed type short when mapped to user space, or if the page */
580 /* bounds exceed type short when mapped to X11 window space, return error. */
581 /*------------------------------------------------------------------------------*/
583 short checkbounds()
585 long lval;
587 /* check window-to-user space */
589 lval = 2 * (long)((float) (areawin->width) / areawin->vscale) +
590 (long)areawin->pcorner.x;
591 if (lval != (long)((short)lval)) return -1;
592 lval = 2 * (long)((float) (areawin->height) / areawin->vscale) +
593 (long)areawin->pcorner.y;
594 if (lval != (long)((short)lval)) return -1;
596 /* check user-to-window space */
598 lval = (long)((float)(topobject->bbox.lowerleft.x - areawin->pcorner.x) *
599 areawin->vscale);
600 if (lval != (long)((short)lval)) return -1;
601 lval = (long)areawin->height - (long)((float)(topobject->bbox.lowerleft.y -
602 areawin->pcorner.y) * areawin->vscale);
603 if (lval != (long)((short)lval)) return -1;
605 lval = (long)((float)(topobject->bbox.lowerleft.x + topobject->bbox.width -
606 areawin->pcorner.x) * areawin->vscale);
607 if (lval != (long)((short)lval)) return -1;
608 lval = (long)areawin->height - (long)((float)(topobject->bbox.lowerleft.y +
609 topobject->bbox.height - areawin->pcorner.y) * areawin->vscale);
610 if (lval != (long)((short)lval)) return -1;
612 return 0;
615 /*------------------------------------------------------------------------*/
616 /* Transform X-window coordinate to xcircuit coordinate system */
617 /*------------------------------------------------------------------------*/
619 void window_to_user(short xw, short yw, XPoint *upt)
621 float tmpx, tmpy;
623 tmpx = (float)xw / areawin->vscale + (float)areawin->pcorner.x;
624 tmpy = (float)(areawin->height - yw) / areawin->vscale +
625 (float)areawin->pcorner.y;
627 tmpx += (tmpx > 0) ? 0.5 : -0.5;
628 tmpy += (tmpy > 0) ? 0.5 : -0.5;
630 upt->x = (short)tmpx;
631 upt->y = (short)tmpy;
634 /*------------------------------------------------------------------------*/
635 /* Transform xcircuit coordinate back to X-window coordinate system */
636 /*------------------------------------------------------------------------*/
638 void user_to_window(XPoint upt, XPoint *wpt)
640 float tmpx, tmpy;
642 tmpx = (float)(upt.x - areawin->pcorner.x) * areawin->vscale;
643 tmpy = (float)areawin->height - (float)(upt.y - areawin->pcorner.y)
644 * areawin->vscale;
646 tmpx += (tmpx > 0) ? 0.5 : -0.5;
647 tmpy += (tmpy > 0) ? 0.5 : -0.5;
649 wpt->x = (short)tmpx;
650 wpt->y = (short)tmpy;
653 /*----------------------------------------------------------------------*/
654 /* Transformations in the object hierarchy */
655 /*----------------------------------------------------------------------*/
657 /*----------------------------------------------------------------------*/
658 /* Return rotation relative to a specific CTM */
659 /*----------------------------------------------------------------------*/
661 float UGetCTMRotation(Matrix *ctm)
663 float rads = (float)atan2((double)(ctm->d), (double)(ctm->a));
664 return rads / RADFAC;
667 /*----------------------------------------------------------------------*/
668 /* Return rotation relative to the top level */
669 /* Note that UTopRotation() is also the rotation relative to the window */
670 /* since the top-level drawing page is always upright relative to the */
671 /* window. Thus, there is no routine UTopDrawingRotation(). */
672 /*----------------------------------------------------------------------*/
674 float UTopRotation()
676 return UGetCTMRotation(DCTM);
679 /*----------------------------------------------------------------------*/
680 /* Return scale relative to a specific CTM */
681 /*----------------------------------------------------------------------*/
683 float UGetCTMScale(Matrix *ctm)
685 return (float)(sqrt((double)(ctm->a * ctm->a + ctm->d * ctm->d)));
688 /*----------------------------------------------------------------------*/
689 /* Return scale relative to window */
690 /*----------------------------------------------------------------------*/
692 float UTopScale()
694 return UGetCTMScale(DCTM);
697 /*----------------------------------------------------------------------*/
698 /* Return scale multiplied by length */
699 /*----------------------------------------------------------------------*/
701 float UTopTransScale(float length)
703 return (float)(length * UTopScale());
706 /*----------------------------------------------------------------------*/
707 /* Return scale relative to the top-level schematic (not the window) */
708 /*----------------------------------------------------------------------*/
710 float UTopDrawingScale()
712 Matrix lctm, wctm;
713 UCopyCTM(DCTM, &lctm);
714 UResetCTM(&wctm);
715 UMakeWCTM(&wctm);
716 InvertCTM(&wctm);
717 UPreMultCTMbyMat(&wctm, &lctm);
718 return UGetCTMScale(&wctm);
721 /*----------------------------------------------------------------------*/
722 /* Return position offset relative to a specific CTM */
723 /*----------------------------------------------------------------------*/
725 void UGetCTMOffset(Matrix *ctm, int *offx, int *offy)
727 if (offx) *offx = (int)ctm->c;
728 if (offy) *offy = (int)ctm->f;
731 /*----------------------------------------------------------------------*/
732 /* Return position offset relative to top-level */
733 /*----------------------------------------------------------------------*/
735 void UTopOffset(int *offx, int *offy)
737 UGetCTMOffset(DCTM, offx, offy);
740 /*----------------------------------------------------------------------*/
741 /* Return postion relative to the top-level schematic (not the window) */
742 /*----------------------------------------------------------------------*/
744 void UTopDrawingOffset(int *offx, int *offy)
746 Matrix lctm, wctm;
747 UCopyCTM(DCTM, &lctm);
748 UResetCTM(&wctm);
749 UMakeWCTM(&wctm);
750 InvertCTM(&wctm);
751 UPreMultCTMbyMat(&wctm, &lctm);
752 UGetCTMOffset(&wctm, offx, offy);
755 /*----------------------------------------------------------------------*/
756 /* Get the cursor position */
757 /*----------------------------------------------------------------------*/
759 XPoint UGetCursor()
761 Window nullwin;
762 int nullint, xpos, ypos;
763 u_int nullui;
764 XPoint newpos;
766 if (areawin->area == NULL) {
767 newpos.x = newpos.y = 0;
768 return newpos;
771 #ifdef TCL_WRAPPER
772 /* Don't use areawin->window; if called from inside an object */
773 /* (e.g., "here" in a Tcl expression), areawin->window will be */
774 /* an off-screen pixmap, and cause a crash. */
776 if (Tk_WindowId(areawin->area) == (Window)NULL) {
777 newpos.x = newpos.y = 0;
778 return newpos;
781 #ifndef _MSC_VER
782 XQueryPointer(dpy, Tk_WindowId(areawin->area), &nullwin, &nullwin,
783 &nullint, &nullint, &xpos, &ypos, &nullui);
784 #else
785 XQueryPointer_TkW32(dpy, Tk_WindowId(areawin->area), &nullwin, &nullwin,
786 &nullint, &nullint, &xpos, &ypos, &nullui);
787 #endif
788 #else
789 XQueryPointer(dpy, areawin->window, &nullwin, &nullwin, &nullint,
790 &nullint, &xpos, &ypos, &nullui);
791 #endif
793 newpos.x = xpos;
794 newpos.y = ypos;
796 return newpos;
799 /*----------------------------------------------------------------------*/
800 /* Get the cursor position and translate to user coordinates */
801 /*----------------------------------------------------------------------*/
803 XPoint UGetCursorPos()
805 XPoint winpos, userpos;
807 if (areawin->area == NULL) {
808 winpos.x = winpos.y = 0;
810 else
811 winpos = UGetCursor();
813 window_to_user(winpos.x, winpos.y, &userpos);
815 return userpos;
818 /*----------------------------------------------------------------------*/
819 /* Translate a point to the nearest snap-to grid point */
820 /*----------------------------------------------------------------------*/
821 /* user coordinates to user coordinates version */
823 void u2u_snap(XPoint *uvalue)
825 float tmpx, tmpy;
826 float tmpix, tmpiy;
828 if (areawin->snapto) {
829 tmpx = (float)uvalue->x / xobjs.pagelist[areawin->page]->snapspace;
830 if (tmpx > 0)
831 tmpix = (float)((int)(tmpx + 0.5));
832 else
833 tmpix = (float)((int)(tmpx - 0.5));
835 tmpy = (float)uvalue->y / xobjs.pagelist[areawin->page]->snapspace;
836 if (tmpy > 0)
837 tmpiy = (float)((int)(tmpy + 0.5));
838 else
839 tmpiy = (float)((int)(tmpy - 0.5));
841 tmpix *= xobjs.pagelist[areawin->page]->snapspace;
842 tmpix += (tmpix > 0) ? 0.5 : -0.5;
843 tmpiy *= xobjs.pagelist[areawin->page]->snapspace;
844 tmpiy += (tmpiy > 0) ? 0.5 : -0.5;
846 uvalue->x = (int)tmpix;
847 uvalue->y = (int)tmpiy;
851 /*------------------------------------------------------------------------*/
852 /* window coordinates to user coordinates version */
853 /*------------------------------------------------------------------------*/
855 void snap(short valuex, short valuey, XPoint *returnpt)
857 window_to_user(valuex, valuey, returnpt);
858 u2u_snap(returnpt);
861 /*------------------------------------------------------------------------*/
862 /* Transform object coordinates through scale, translation, and rotation */
863 /* This routine attempts to match the PostScript definition of trans- */
864 /* formation matrices. */
865 /*------------------------------------------------------------------------*/
867 /*------------------------------------------------------------------------*/
868 /* Current transformation matrix manipulation routines */
869 /*------------------------------------------------------------------------*/
871 void UResetCTM(Matrix *ctm)
873 ctm->a = ctm->e = 1;
874 ctm->b = ctm->d = 0;
875 ctm->c = ctm->f = 0; /* 0.5 for nearest-int real->int conversion? */
877 #ifdef HAVE_CAIRO
878 if (ctm == DCTM && areawin->redraw_ongoing)
879 xc_cairo_set_matrix(ctm);
880 #endif /* HAVE_CAIRO */
883 /*------------------------------------------------------------------------*/
885 void InvertCTM(Matrix *ctm)
887 float det = ctm->a * ctm->e - ctm->b * ctm->d;
888 float tx = ctm->b * ctm->f - ctm->c * ctm->e;
889 float ty = ctm->d * ctm->c - ctm->a * ctm->f;
891 float tmpa = ctm->a;
893 ctm->b = -ctm->b / det;
894 ctm->d = -ctm->d / det;
896 ctm->a = ctm->e / det;
897 ctm->e = tmpa / det;
898 ctm->c = tx / det;
899 ctm->f = ty / det;
901 #ifdef HAVE_CAIRO
902 if (ctm == DCTM && areawin->redraw_ongoing)
903 xc_cairo_set_matrix(ctm);
904 #endif /* HAVE_CAIRO */
907 /*------------------------------------------------------------------------*/
909 void UCopyCTM(fctm, tctm)
910 Matrix *fctm, *tctm;
912 tctm->a = fctm->a;
913 tctm->b = fctm->b;
914 tctm->c = fctm->c;
915 tctm->d = fctm->d;
916 tctm->e = fctm->e;
917 tctm->f = fctm->f;
919 #ifdef HAVE_CAIRO
920 if (tctm == DCTM && areawin->redraw_ongoing)
921 xc_cairo_set_matrix(tctm);
922 #endif /* HAVE_CAIRO */
925 /*-------------------------------------------------------------------------*/
926 /* Multiply CTM by current screen position and scale to get transformation */
927 /* matrix from a user point to the X11 window */
928 /*-------------------------------------------------------------------------*/
930 void UMakeWCTM(Matrix *ctm)
932 ctm->a *= areawin->vscale;
933 ctm->b *= areawin->vscale;
934 ctm->c = (ctm->c - (float)areawin->pcorner.x) * areawin->vscale
935 + areawin->panx;
937 ctm->d *= -areawin->vscale;
938 ctm->e *= -areawin->vscale;
939 ctm->f = (float)areawin->height + ((float)areawin->pcorner.y - ctm->f) *
940 areawin->vscale + areawin->pany;
942 #ifdef HAVE_CAIRO
943 if (ctm == DCTM && areawin->redraw_ongoing)
944 xc_cairo_set_matrix(ctm);
945 #endif /* HAVE_CAIRO */
948 /*------------------------------------------------------------------------*/
950 void UMultCTM(Matrix *ctm, XPoint position, float scale, float rotate)
952 float tmpa, tmpb, tmpd, tmpe, yscale;
953 float mata, matb, matc;
954 double drot = (double)rotate * RADFAC;
956 yscale = abs(scale); /* -scale implies flip in x direction only */
958 tmpa = scale * cos(drot);
959 tmpb = yscale * sin(drot);
960 tmpd = -scale * sin(drot);
961 tmpe = yscale * cos(drot);
963 mata = ctm->a * tmpa + ctm->d * tmpb;
964 matb = ctm->b * tmpa + ctm->e * tmpb;
965 matc = ctm->c * tmpa + ctm->f * tmpb + position.x;
967 ctm->d = ctm->d * tmpe + ctm->a * tmpd;
968 ctm->e = ctm->e * tmpe + ctm->b * tmpd;
969 ctm->f = ctm->f * tmpe + ctm->c * tmpd + position.y;
971 ctm->a = mata;
972 ctm->b = matb;
973 ctm->c = matc;
975 #ifdef HAVE_CAIRO
976 if (ctm == DCTM && areawin->redraw_ongoing)
977 xc_cairo_set_matrix(ctm);
978 #endif /* HAVE_CAIRO */
981 /*----------------------------------------------------------------------*/
982 /* Slanting function x' = x + beta * y, y' = y */
983 /*----------------------------------------------------------------------*/
985 void USlantCTM(Matrix *ctm, float beta)
987 ctm->b += ctm->a * beta;
988 ctm->e += ctm->d * beta;
990 #ifdef HAVE_CAIRO
991 if (ctm == DCTM && areawin->redraw_ongoing)
992 xc_cairo_set_matrix(ctm);
993 #endif /* HAVE_CAIRO */
996 #define EPS 1e-9
997 /*----------------------------------------------------------------------*/
998 /* Transform text to make it right-side up within 90 degrees of page */
999 /* NOTE: This is not yet resolved, as xcircuit does not agree with */
1000 /* PostScript in a few cases! */
1001 /*----------------------------------------------------------------------*/
1003 void UPreScaleCTM(Matrix *ctm)
1005 /* negative X scale (-1, +1) */
1006 if ((ctm->a < -EPS) || ((ctm->a < EPS) && (ctm->a > -EPS) &&
1007 ((ctm->d * ctm->b) < 0))) {
1008 ctm->a = -ctm->a;
1009 ctm->d = -ctm->d;
1012 /* negative Y scale (+1, -1) */
1013 if (ctm->e > EPS) {
1014 ctm->e = -ctm->e;
1015 ctm->b = -ctm->b;
1018 /* At 90, 270 degrees need special attention to avoid discrepencies */
1019 /* with the PostScript output due to roundoff error. This code */
1020 /* matches what PostScript produces. */
1022 #ifdef HAVE_CAIRO
1023 if (ctm == DCTM && areawin->redraw_ongoing)
1024 xc_cairo_set_matrix(ctm);
1025 #endif /* HAVE_CAIRO */
1028 /*----------------------------------------------------------------------*/
1029 /* Adjust anchoring and CTM as necessary for flip invariance */
1030 /*----------------------------------------------------------------------*/
1032 short flipadjust(short anchor)
1034 short tmpanchor = anchor & (~FLIPINV);
1036 if (anchor & FLIPINV) {
1037 if (((DCTM)->a < -EPS) || (((DCTM)->a < EPS) && ((DCTM)->a > -EPS) &&
1038 (((DCTM)->d * (DCTM)->b) < 0))) {
1039 if ((tmpanchor & (RIGHT | NOTLEFT)) != NOTLEFT)
1040 tmpanchor ^= (RIGHT | NOTLEFT);
1042 /* NOTE: Justification does not change under flip invariance. */
1044 if ((DCTM)->e > EPS) {
1045 if ((tmpanchor & (TOP | NOTBOTTOM)) != NOTBOTTOM)
1046 tmpanchor ^= (TOP | NOTBOTTOM);
1048 UPreScaleCTM(DCTM);
1050 return tmpanchor;
1053 /*------------------------------------------------------------------------*/
1055 void UPreMultCTM(Matrix *ctm, XPoint position, float scale, float rotate)
1057 float tmpa, tmpb, tmpd, tmpe, yscale;
1058 float mata, matd;
1059 double drot = (double)rotate * RADFAC;
1061 yscale = abs(scale); /* negative scale value implies flip in x only */
1063 tmpa = scale * cos(drot);
1064 tmpb = yscale * sin(drot);
1065 tmpd = -scale * sin(drot);
1066 tmpe = yscale * cos(drot);
1068 ctm->c += ctm->a * position.x + ctm->b * position.y;
1069 ctm->f += ctm->d * position.x + ctm->e * position.y;
1071 mata = ctm->a * tmpa + ctm->b * tmpd;
1072 ctm->b = ctm->a * tmpb + ctm->b * tmpe;
1074 matd = ctm->d * tmpa + ctm->e * tmpd;
1075 ctm->e = ctm->d * tmpb + ctm->e * tmpe;
1077 ctm->a = mata;
1078 ctm->d = matd;
1080 #ifdef HAVE_CAIRO
1081 if (ctm == DCTM && areawin->redraw_ongoing)
1082 xc_cairo_set_matrix(ctm);
1083 #endif /* HAVE_CAIRO */
1086 /*----------------------------------------------------------------------*/
1087 /* Direct Matrix-Matrix multiplication */
1088 /*----------------------------------------------------------------------*/
1090 void UPreMultCTMbyMat(Matrix *ctm, Matrix *pre)
1092 float mata, matd;
1094 mata = pre->a * ctm->a + pre->d * ctm->b;
1095 ctm->c += pre->c * ctm->a + pre->f * ctm->b;
1096 ctm->b = pre->b * ctm->a + pre->e * ctm->b;
1097 ctm->a = mata;
1099 matd = pre->a * ctm->d + pre->d * ctm->e;
1100 ctm->f += pre->c * ctm->d + pre->f * ctm->e;
1101 ctm->e = pre->b * ctm->d + pre->e * ctm->e;
1102 ctm->d = matd;
1104 #ifdef HAVE_CAIRO
1105 if (ctm == DCTM && areawin->redraw_ongoing)
1106 xc_cairo_set_matrix(ctm);
1107 #endif /* HAVE_CAIRO */
1110 /*------------------------------------------------------------------------*/
1112 void UTransformbyCTM(Matrix *ctm, XPoint *ipoints, XPoint *points, short number)
1114 pointlist current, ptptr = points;
1115 float fx, fy;
1116 /* short tmpx; (jdk) */
1118 for (current = ipoints; current < ipoints + number; current++, ptptr++) {
1119 fx = ctm->a * (float)current->x + ctm->b * (float)current->y + ctm->c;
1120 fy = ctm->d * (float)current->x + ctm->e * (float)current->y + ctm->f;
1122 ptptr->x = (fx >= 0) ? (short)(fx + 0.5) : (short)(fx - 0.5);
1123 ptptr->y = (fy >= 0) ? (short)(fy + 0.5) : (short)(fy - 0.5);
1127 /*------------------------------------------------------------------------*/
1128 /* (same as above routine but using type (float) for point values; this */
1129 /* is for calculation of Bezier curve internal points. */
1130 /*------------------------------------------------------------------------*/
1132 void UfTransformbyCTM(Matrix *ctm, XfPoint *fpoints, XPoint *points, short number)
1134 fpointlist current;
1135 pointlist new = points;
1136 float fx, fy;
1138 for (current = fpoints; current < fpoints + number; current++, new++) {
1139 fx = ctm->a * current->x + ctm->b * current->y + ctm->c;
1140 fy = ctm->d * current->x + ctm->e * current->y + ctm->f;
1141 new->x = (fx >= 0) ? (short)(fx + 0.5) : (short)(fx - 0.5);
1142 new->y = (fy >= 0) ? (short)(fy + 0.5) : (short)(fy - 0.5);
1146 /*------------------------------------------------------------------------*/
1148 void UPopCTM()
1150 Matrixptr lastmatrix;
1152 if (areawin->MatStack == NULL) {
1153 Wprintf("Matrix stack pop error");
1154 return;
1156 lastmatrix = areawin->MatStack->nextmatrix;
1157 free(areawin->MatStack);
1158 areawin->MatStack = lastmatrix;
1160 #ifdef HAVE_CAIRO
1161 if (areawin->area) {
1162 xc_cairo_set_matrix(lastmatrix);
1164 #endif /* HAVE_CAIRO */
1167 /*------------------------------------------------------------------------*/
1169 void UPushCTM()
1171 Matrixptr nmatrix;
1173 nmatrix = (Matrixptr)malloc(sizeof(Matrix));
1174 if (areawin->MatStack == NULL)
1175 UResetCTM(nmatrix);
1176 else
1177 UCopyCTM(areawin->MatStack, nmatrix);
1178 nmatrix->nextmatrix = areawin->MatStack;
1179 areawin->MatStack = nmatrix;
1182 /*------------------------------------------------------------------------*/
1184 void UTransformPoints(XPoint *points, XPoint *newpoints, short number,
1185 XPoint atpt, float scale, float rotate)
1187 Matrix LCTM;
1189 UResetCTM(&LCTM);
1190 UMultCTM(&LCTM, atpt, scale, rotate);
1191 UTransformbyCTM(&LCTM, points, newpoints, number);
1194 /*----------------------------------------------------*/
1195 /* Transform points inward to next hierarchical level */
1196 /*----------------------------------------------------*/
1198 void InvTransformPoints(XPoint *points, XPoint *newpoints, short number,
1199 XPoint atpt, float scale, float rotate)
1201 Matrix LCTM;
1203 UResetCTM(&LCTM);
1204 UPreMultCTM(&LCTM, atpt, scale, rotate);
1205 InvertCTM(&LCTM);
1206 UTransformbyCTM(&LCTM, points, newpoints, number);
1209 /*----------------------------------------------------------------------*/
1210 /* Adjust wire coords to force a wire to a horizontal or vertical */
1211 /* position. */
1212 /* "pospt" is the target position for the point of interest. */
1213 /* "cycle" is the point number in the polygon of the point of interest. */
1214 /* cycle == -1 is equivalent to the last point of the polygon. */
1215 /* If "strict" is TRUE then single-segment wires are forced manhattan */
1216 /* even if that means that the endpoint drifts from the target point. */
1217 /* If "strict" is FALSE then single-segment wires will become non- */
1218 /* manhattan so that the target point is reached. */
1219 /* NOTE: It might be preferable to add a segment to maintain a */
1220 /* manhattan layout, except that we want to avoid merging nets */
1221 /* together. . . */
1222 /*----------------------------------------------------------------------*/
1224 void manhattanize(XPoint *pospt, polyptr newpoly, short cycle, Boolean strict)
1226 XPoint *curpt, *bpt, *bbpt, *fpt, *ffpt;
1227 int deltax, deltay;
1229 if (newpoly->number == 1) return; /* sanity check */
1231 if (cycle == -1 || cycle == newpoly->number - 1) {
1232 curpt = newpoly->points + newpoly->number - 1;
1233 bpt = newpoly->points + newpoly->number - 2;
1234 fpt = NULL;
1235 ffpt = NULL;
1236 if (newpoly->number > 2)
1237 bbpt = newpoly->points + newpoly->number - 3;
1238 else
1239 bbpt = NULL;
1241 else if (cycle == 0) {
1242 curpt = newpoly->points;
1243 fpt = newpoly->points + 1;
1244 bpt = NULL;
1245 bbpt = NULL;
1246 if (newpoly->number > 2)
1247 ffpt = newpoly->points + 2;
1248 else
1249 ffpt = NULL;
1251 else {
1252 curpt = newpoly->points + cycle;
1253 fpt = newpoly->points + cycle + 1;
1254 bpt = newpoly->points + cycle - 1;
1255 if (cycle > 1)
1256 bbpt = newpoly->points + cycle - 2;
1257 else
1258 bbpt = NULL;
1260 if (cycle < newpoly->number - 2)
1261 ffpt = newpoly->points + cycle + 2;
1262 else
1263 ffpt = NULL;
1266 /* enforce constraints on point behind cycle position */
1268 if (bpt != NULL) {
1269 if (bbpt != NULL) {
1270 if (bpt->x == bbpt->x) bpt->y = pospt->y;
1271 if (bpt->y == bbpt->y) bpt->x = pospt->x;
1273 else if (strict) {
1274 deltax = abs(bpt->x - pospt->x);
1275 deltay = abs(bpt->y - pospt->y);
1277 /* Only one segment---just make sure it's horizontal or vertical */
1278 if (deltay > deltax) pospt->x = bpt->x;
1279 else pospt->y = bpt->y;
1283 /* enforce constraints on point forward of cycle position */
1285 if (fpt != NULL) {
1286 if (ffpt != NULL) {
1287 if (fpt->x == ffpt->x) fpt->y = pospt->y;
1288 if (fpt->y == ffpt->y) fpt->x = pospt->x;
1290 else if (strict) {
1291 deltax = abs(fpt->x - pospt->x);
1292 deltay = abs(fpt->y - pospt->y);
1294 /* Only one segment---just make sure it's horizontal or vertical */
1295 if (deltay > deltax) pospt->x = fpt->x;
1296 else pospt->y = fpt->y;
1301 /*----------------------------------------------------------------------*/
1302 /* Bounding box calculation routines */
1303 /*----------------------------------------------------------------------*/
1305 void bboxcalc(short testval, short *lowerval, short *upperval)
1307 if (testval < *lowerval) *lowerval = testval;
1308 if (testval > *upperval) *upperval = testval;
1311 /*----------------------------------------------------------------------*/
1312 /* Bounding box calculation for elements which can be part of a path */
1313 /*----------------------------------------------------------------------*/
1315 void calcextents(genericptr *bboxgen, short *llx, short *lly,
1316 short *urx, short *ury)
1318 switch (ELEMENTTYPE(*bboxgen)) {
1319 case(POLYGON): {
1320 pointlist bboxpts;
1321 for (bboxpts = TOPOLY(bboxgen)->points; bboxpts < TOPOLY(bboxgen)->points
1322 + TOPOLY(bboxgen)->number; bboxpts++) {
1323 bboxcalc(bboxpts->x, llx, urx);
1324 bboxcalc(bboxpts->y, lly, ury);
1326 } break;
1328 case(SPLINE): {
1329 fpointlist bboxpts;
1330 bboxcalc(TOSPLINE(bboxgen)->ctrl[0].x, llx, urx);
1331 bboxcalc(TOSPLINE(bboxgen)->ctrl[0].y, lly, ury);
1332 bboxcalc(TOSPLINE(bboxgen)->ctrl[3].x, llx, urx);
1333 bboxcalc(TOSPLINE(bboxgen)->ctrl[3].y, lly, ury);
1334 for (bboxpts = TOSPLINE(bboxgen)->points; bboxpts <
1335 TOSPLINE(bboxgen)->points + INTSEGS; bboxpts++) {
1336 bboxcalc((short)(bboxpts->x), llx, urx);
1337 bboxcalc((short)(bboxpts->y), lly, ury);
1339 } break;
1341 case (ARC): {
1342 fpointlist bboxpts;
1343 for (bboxpts = TOARC(bboxgen)->points; bboxpts < TOARC(bboxgen)->points +
1344 TOARC(bboxgen)->number; bboxpts++) {
1345 bboxcalc((short)(bboxpts->x), llx, urx);
1346 bboxcalc((short)(bboxpts->y), lly, ury);
1348 } break;
1352 /*----------------------------------------------------------------------*/
1353 /* Calculate the bounding box of an object instance */
1354 /*----------------------------------------------------------------------*/
1356 void objinstbbox(objinstptr obbox, XPoint *npoints, int extend)
1358 XPoint points[4];
1360 points[0].x = points[1].x = obbox->bbox.lowerleft.x - extend;
1361 points[1].y = points[2].y = obbox->bbox.lowerleft.y + obbox->bbox.height
1362 + extend;
1363 points[2].x = points[3].x = obbox->bbox.lowerleft.x + obbox->bbox.width
1364 + extend;
1365 points[0].y = points[3].y = obbox->bbox.lowerleft.y - extend;
1367 UTransformPoints(points, npoints, 4, obbox->position,
1368 obbox->scale, obbox->rotation);
1371 /*----------------------------------------------------------------------*/
1372 /* Calculate the bounding box of a label */
1373 /*----------------------------------------------------------------------*/
1375 void labelbbox(labelptr labox, XPoint *npoints, objinstptr callinst)
1377 XPoint points[4];
1378 TextExtents tmpext;
1379 short j;
1381 tmpext = ULength(labox, callinst, NULL);
1382 points[0].x = points[1].x = (labox->anchor & NOTLEFT ?
1383 (labox->anchor & RIGHT ? -tmpext.maxwidth :
1384 -tmpext.maxwidth / 2) : 0);
1385 points[2].x = points[3].x = points[0].x + tmpext.maxwidth;
1386 points[0].y = points[3].y = (labox->anchor & NOTBOTTOM ?
1387 (labox->anchor & TOP ? -tmpext.ascent :
1388 -(tmpext.ascent + tmpext.base) / 2) : -tmpext.base)
1389 + tmpext.descent;
1390 points[1].y = points[2].y = points[0].y + tmpext.ascent - tmpext.descent;
1392 /* separate bounding box for pinlabels and infolabels */
1394 if (labox->pin)
1395 for (j = 0; j < 4; j++)
1396 pinadjust(labox->anchor, &points[j].x, &points[j].y, 1);
1398 UTransformPoints(points, npoints, 4, labox->position,
1399 labox->scale, labox->rotation);
1402 /*----------------------------------------------------------------------*/
1403 /* Calculate the bounding box of a graphic image */
1404 /*----------------------------------------------------------------------*/
1406 void graphicbbox(graphicptr gp, XPoint *npoints)
1408 XPoint points[4];
1409 int hw = xcImageGetWidth(gp->source) >> 1;
1410 int hh = xcImageGetHeight(gp->source) >> 1;
1412 points[1].x = points[2].x = hw;
1413 points[0].x = points[3].x = -hw;
1415 points[0].y = points[1].y = -hh;
1416 points[2].y = points[3].y = hh;
1418 UTransformPoints(points, npoints, 4, gp->position,
1419 gp->scale, gp->rotation);
1422 /*--------------------------------------------------------------*/
1423 /* Wrapper for single call to calcbboxsingle() in the netlister */
1424 /*--------------------------------------------------------------*/
1426 void calcinstbbox(genericptr *bboxgen, short *llx, short *lly, short *urx,
1427 short *ury)
1429 *llx = *lly = 32767;
1430 *urx = *ury = -32768;
1432 calcbboxsingle(bboxgen, areawin->topinstance, llx, lly, urx, ury);
1435 /*----------------------------------------------------------------------*/
1436 /* Bounding box calculation for a single generic element */
1437 /*----------------------------------------------------------------------*/
1439 void calcbboxsingle(genericptr *bboxgen, objinstptr thisinst,
1440 short *llx, short *lly, short *urx, short *ury)
1442 XPoint npoints[4];
1443 short j;
1445 /* For each screen element, compute the extents and revise bounding */
1446 /* box points, if necessary. */
1448 switch(ELEMENTTYPE(*bboxgen)) {
1450 case(OBJINST):
1451 objinstbbox(TOOBJINST(bboxgen), npoints, 0);
1453 for (j = 0; j < 4; j++) {
1454 bboxcalc(npoints[j].x, llx, urx);
1455 bboxcalc(npoints[j].y, lly, ury);
1457 break;
1459 case(LABEL):
1460 /* because a pin is offset from its position point, include */
1461 /* that point in the bounding box. */
1463 if (TOLABEL(bboxgen)->pin) {
1464 bboxcalc(TOLABEL(bboxgen)->position.x, llx, urx);
1465 bboxcalc(TOLABEL(bboxgen)->position.y, lly, ury);
1467 labelbbox(TOLABEL(bboxgen), npoints, thisinst);
1469 for (j = 0; j < 4; j++) {
1470 bboxcalc(npoints[j].x, llx, urx);
1471 bboxcalc(npoints[j].y, lly, ury);
1473 break;
1475 case(GRAPHIC):
1476 graphicbbox(TOGRAPHIC(bboxgen), npoints);
1477 for (j = 0; j < 4; j++) {
1478 bboxcalc(npoints[j].x, llx, urx);
1479 bboxcalc(npoints[j].y, lly, ury);
1481 break;
1483 case(PATH): {
1484 genericptr *pathc;
1485 for (pathc = TOPATH(bboxgen)->plist; pathc < TOPATH(bboxgen)->plist
1486 + TOPATH(bboxgen)->parts; pathc++)
1487 calcextents(pathc, llx, lly, urx, ury);
1488 } break;
1490 default:
1491 calcextents(bboxgen, llx, lly, urx, ury);
1495 /*------------------------------------------------------*/
1496 /* Find if an object is in the specified library */
1497 /*------------------------------------------------------*/
1499 Boolean object_in_library(short libnum, objectptr thisobject)
1501 short i;
1503 for (i = 0; i < xobjs.userlibs[libnum].number; i++) {
1504 if (*(xobjs.userlibs[libnum].library + i) == thisobject)
1505 return True;
1507 return False;
1510 /*-----------------------------------------------------------*/
1511 /* Find if an object is in the hierarchy of the given object */
1512 /* Returns the number (position in plist) or -1 if not found */
1513 /*-----------------------------------------------------------*/
1515 short find_object(objectptr pageobj, objectptr thisobject)
1517 short i, j;
1518 genericptr *pelem;
1520 for (i = 0; i < pageobj->parts; i++) {
1521 pelem = pageobj->plist + i;
1522 if (IS_OBJINST(*pelem)) {
1523 if ((TOOBJINST(pelem))->thisobject == thisobject)
1524 return i;
1525 else if ((j = find_object((TOOBJINST(pelem))->thisobject, thisobject)) >= 0)
1526 return i; /* was j---is this the right fix? */
1529 return -1;
1532 /*------------------------------------------------------*/
1533 /* Find all pages and libraries containing this object */
1534 /* and update accordingly. If this object is a page, */
1535 /* just update the page directory. */
1536 /*------------------------------------------------------*/
1538 void updatepagebounds(objectptr thisobject)
1540 short i, j;
1541 objectptr pageobj;
1543 if ((i = is_page(thisobject)) >= 0) {
1544 if (xobjs.pagelist[i]->background.name != (char *)NULL)
1545 backgroundbbox(i);
1546 updatepagelib(PAGELIB, i);
1548 else {
1549 for (i = 0; i < xobjs.pages; i++) {
1550 if (xobjs.pagelist[i]->pageinst != NULL) {
1551 pageobj = xobjs.pagelist[i]->pageinst->thisobject;
1552 if ((j = find_object(pageobj, thisobject)) >= 0) {
1553 calcbboxvalues(xobjs.pagelist[i]->pageinst,
1554 (genericptr *)(pageobj->plist + j));
1555 updatepagelib(PAGELIB, i);
1559 for (i = 0; i < xobjs.numlibs; i++)
1560 if (object_in_library(i, thisobject))
1561 composelib(i + LIBRARY);
1565 /*--------------------------------------------------------------*/
1566 /* Free memory for the schematic bounding box */
1567 /*--------------------------------------------------------------*/
1569 void invalidateschembbox(objinstptr thisinst)
1571 if (thisinst->schembbox != NULL) {
1572 free(thisinst->schembbox);
1573 thisinst->schembbox = NULL;
1577 /*--------------------------------------------------------------*/
1578 /* Calculate the bounding box for an object instance. Use the */
1579 /* existing bbox and finish calculation on all the elements */
1580 /* which have parameters not taking default values. */
1581 /* This finishes the calculation partially done by */
1582 /* calcbboxvalues(). */
1583 /*--------------------------------------------------------------*/
1585 void calcbboxinst(objinstptr thisinst)
1587 objectptr thisobj;
1588 genericptr *gelem;
1589 short llx, lly, urx, ury;
1591 short pllx, plly, purx, pury;
1592 Boolean hasschembbox = FALSE;
1593 Boolean didparamsubs = FALSE;
1595 if (thisinst == NULL) return;
1597 thisobj = thisinst->thisobject;
1599 llx = thisobj->bbox.lowerleft.x;
1600 lly = thisobj->bbox.lowerleft.y;
1601 urx = llx + thisobj->bbox.width;
1602 ury = lly + thisobj->bbox.height;
1604 pllx = plly = 32767;
1605 purx = pury = -32768;
1607 for (gelem = thisobj->plist; gelem < thisobj->plist + thisobj->parts;
1608 gelem++) {
1609 /* pins which do not appear outside of the object */
1610 /* contribute to the objects "schembbox". */
1612 if (IS_LABEL(*gelem)) {
1613 labelptr btext = TOLABEL(gelem);
1614 if (btext->pin && !(btext->anchor & PINVISIBLE)) {
1615 hasschembbox = TRUE;
1616 calcbboxsingle(gelem, thisinst, &pllx, &plly, &purx, &pury);
1617 continue;
1621 if (has_param(*gelem)) {
1622 if (didparamsubs == FALSE) {
1623 psubstitute(thisinst);
1624 didparamsubs = TRUE;
1626 calcbboxsingle(gelem, thisinst, &llx, &lly, &urx, &ury);
1629 /* If we have a clipmask, the clipmask is used to calculate the */
1630 /* bounding box, not the element it is masking. */
1632 switch(ELEMENTTYPE(*gelem)) {
1633 case POLYGON: case SPLINE: case ARC: case PATH:
1634 if (TOPOLY(gelem)->style & CLIPMASK) gelem++;
1635 break;
1639 thisinst->bbox.lowerleft.x = llx;
1640 thisinst->bbox.lowerleft.y = lly;
1641 thisinst->bbox.width = urx - llx;
1642 thisinst->bbox.height = ury - lly;
1644 if (hasschembbox) {
1645 if (thisinst->schembbox == NULL)
1646 thisinst->schembbox = (BBox *)malloc(sizeof(BBox));
1648 thisinst->schembbox->lowerleft.x = pllx;
1649 thisinst->schembbox->lowerleft.y = plly;
1650 thisinst->schembbox->width = purx - pllx;
1651 thisinst->schembbox->height = pury - plly;
1653 else
1654 invalidateschembbox(thisinst);
1657 /*--------------------------------------------------------------*/
1658 /* Update things based on a changed instance bounding box. */
1659 /* If the parameter was a single-instance */
1660 /* substitution, only the page should be updated. If the */
1661 /* parameter was a default value, the library should be updated */
1662 /* and any pages containing the object where the parameter */
1663 /* takes the default value. */
1664 /*--------------------------------------------------------------*/
1666 void updateinstparam(objectptr bobj)
1668 short i, j;
1669 objectptr pageobj;
1671 /* change bounds on pagelib and all pages */
1672 /* containing this *object* if and only if the object */
1673 /* instance takes the default value. Also update the */
1674 /* library page. */
1676 for (i = 0; i < xobjs.pages; i++)
1677 if (xobjs.pagelist[i]->pageinst != NULL) {
1678 pageobj = xobjs.pagelist[i]->pageinst->thisobject;
1679 if ((j = find_object(pageobj, topobject)) >= 0) {
1681 /* Really, we'd like to recalculate the bounding box only if the */
1682 /* parameter value is the default value which was just changed. */
1683 /* However, then any non-default values may contain the wrong */
1684 /* substitutions. */
1686 objinstptr cinst = TOOBJINST(pageobj->plist + j);
1687 if (cinst->thisobject->params == NULL) {
1688 calcbboxvalues(xobjs.pagelist[i]->pageinst, pageobj->plist + j);
1689 updatepagelib(PAGELIB, i);
1694 for (i = 0; i < xobjs.numlibs; i++)
1695 if (object_in_library(i, topobject))
1696 composelib(i + LIBRARY);
1699 /*--------------------------------------------------------------*/
1700 /* Calculate bbox on all elements of the given object */
1701 /*--------------------------------------------------------------*/
1703 void calcbbox(objinstptr binst)
1705 calcbboxvalues(binst, (genericptr *)NULL);
1706 if (binst == areawin->topinstance) {
1707 updatepagebounds(topobject);
1711 /*--------------------------------------------------------------*/
1712 /* Calculate bbox on the given element of the specified object. */
1713 /* This is a wrapper for calcbboxvalues() assuming that we're */
1714 /* on the top-level, and that page bounds need to be updated. */
1715 /*--------------------------------------------------------------*/
1717 void singlebbox(genericptr *gelem)
1719 calcbboxvalues(areawin->topinstance, (genericptr *)gelem);
1720 updatepagebounds(topobject);
1723 /*----------------------------------------------------------------------*/
1724 /* Extend bounding box based on selected elements only */
1725 /*----------------------------------------------------------------------*/
1727 void calcbboxselect()
1729 short *bsel;
1730 for (bsel = areawin->selectlist; bsel < areawin->selectlist +
1731 areawin->selects; bsel++)
1732 calcbboxvalues(areawin->topinstance, topobject->plist + *bsel);
1734 updatepagebounds(topobject);
1737 /*--------------------------------------------------------------*/
1738 /* Update Bounding box for an object. */
1739 /* If newelement == NULL, calculate bounding box from scratch. */
1740 /* Otherwise, expand bounding box to enclose newelement. */
1741 /*--------------------------------------------------------------*/
1743 void calcbboxvalues(objinstptr thisinst, genericptr *newelement)
1745 genericptr *bboxgen;
1746 short llx, lly, urx, ury;
1747 objectptr thisobj = thisinst->thisobject;
1749 /* no action if there are no elements */
1750 if (thisobj->parts == 0) return;
1752 /* If this object has parameters, then we will do a separate */
1753 /* bounding box calculation on parameterized parts. This */
1754 /* calculation ignores them, and the result is a base that the */
1755 /* instance bounding-box computation can use as a starting point. */
1757 /* set starting bounds as maximum bounds of screen */
1758 llx = lly = 32767;
1759 urx = ury = -32768;
1761 for (bboxgen = thisobj->plist; bboxgen < thisobj->plist +
1762 thisobj->parts; bboxgen++) {
1764 /* override the "for" loop if we're doing a single element */
1765 if (newelement != NULL) bboxgen = newelement;
1767 if ((thisobj->params == NULL) || (!has_param(*bboxgen))) {
1768 /* pins which do not appear outside of the object */
1769 /* are ignored now---will be computed per instance. */
1771 if (IS_LABEL(*bboxgen)) {
1772 labelptr btext = TOLABEL(bboxgen);
1773 if (btext->pin && !(btext->anchor & PINVISIBLE)) {
1774 goto nextgen;
1777 calcbboxsingle(bboxgen, thisinst, &llx, &lly, &urx, &ury);
1779 if (newelement == NULL)
1780 switch(ELEMENTTYPE(*bboxgen)) {
1781 case POLYGON: case SPLINE: case ARC: case PATH:
1782 if (TOPOLY(bboxgen)->style & CLIPMASK)
1783 bboxgen++;
1784 break;
1787 nextgen:
1788 if (newelement != NULL) break;
1791 /* if this is a single-element calculation and its bounding box */
1792 /* turned out to be smaller than the object's, then we need to */
1793 /* recompute the entire object's bounding box in case it got */
1794 /* smaller. This is not recursive, in spite of looks. */
1796 if (newelement != NULL) {
1797 if (llx > thisobj->bbox.lowerleft.x &&
1798 lly > thisobj->bbox.lowerleft.y &&
1799 urx < (thisobj->bbox.lowerleft.x + thisobj->bbox.width) &&
1800 ury < (thisobj->bbox.lowerleft.y + thisobj->bbox.height)) {
1801 calcbboxvalues(thisinst, NULL);
1802 return;
1804 else {
1805 bboxcalc(thisobj->bbox.lowerleft.x, &llx, &urx);
1806 bboxcalc(thisobj->bbox.lowerleft.y, &lly, &ury);
1807 bboxcalc(thisobj->bbox.lowerleft.x + thisobj->bbox.width, &llx, &urx);
1808 bboxcalc(thisobj->bbox.lowerleft.y + thisobj->bbox.height, &lly, &ury);
1812 /* Set the new bounding box. In pathological cases, such as a page */
1813 /* with only pin labels, the bounds may not have been changed from */
1814 /* their initial values. If so, then don't touch the bounding box. */
1816 if ((llx <= urx) && (lly <= ury)) {
1817 thisobj->bbox.lowerleft.x = llx;
1818 thisobj->bbox.lowerleft.y = lly;
1819 thisobj->bbox.width = urx - llx;
1820 thisobj->bbox.height = ury - lly;
1823 /* calculate instance-specific values */
1824 calcbboxinst(thisinst);
1827 /*------------------------------------------------------*/
1828 /* Center an object in the viewing window */
1829 /*------------------------------------------------------*/
1831 void centerview(objinstptr tinst)
1833 XPoint origin, corner;
1834 Dimension width, height;
1835 float fitwidth, fitheight;
1836 objectptr tobj = tinst->thisobject;
1838 origin = tinst->bbox.lowerleft;
1839 corner.x = origin.x + tinst->bbox.width;
1840 corner.y = origin.y + tinst->bbox.height;
1842 extendschembbox(tinst, &origin, &corner);
1844 width = corner.x - origin.x;
1845 height = corner.y - origin.y;
1847 fitwidth = (float)areawin->width / ((float)width + 2 * DEFAULTGRIDSPACE);
1848 fitheight = (float)areawin->height / ((float)height + 2 * DEFAULTGRIDSPACE);
1850 tobj->viewscale = (fitwidth < fitheight) ?
1851 min(MINAUTOSCALE, fitwidth) : min(MINAUTOSCALE, fitheight);
1853 tobj->pcorner.x = origin.x - (areawin->width
1854 / tobj->viewscale - width) / 2;
1855 tobj->pcorner.y = origin.y - (areawin->height
1856 / tobj->viewscale - height) / 2;
1858 /* Copy new position values to the current window */
1860 if ((areawin->topinstance != NULL) && (tobj == topobject)) {
1861 areawin->pcorner = tobj->pcorner;
1862 areawin->vscale = tobj->viewscale;
1866 /*-----------------------------------------------------------*/
1867 /* Refresh the window and scrollbars and write the page name */
1868 /*-----------------------------------------------------------*/
1870 void refresh(xcWidget bw, caddr_t clientdata, caddr_t calldata)
1872 areawin->redraw_needed = True;
1873 drawarea(NULL, NULL, NULL);
1874 if (areawin->scrollbarh)
1875 drawhbar(areawin->scrollbarh, NULL, NULL);
1876 if (areawin->scrollbarv)
1877 drawvbar(areawin->scrollbarv, NULL, NULL);
1878 printname(topobject);
1881 /*------------------------------------------------------*/
1882 /* Center the current page in the viewing window */
1883 /*------------------------------------------------------*/
1885 void zoomview(xcWidget w, caddr_t clientdata, caddr_t calldata)
1887 if (eventmode == NORMAL_MODE || eventmode == COPY_MODE ||
1888 eventmode == MOVE_MODE || eventmode == CATALOG_MODE ||
1889 eventmode == FONTCAT_MODE || eventmode == EFONTCAT_MODE ||
1890 eventmode == CATMOVE_MODE) {
1892 if (areawin->topinstance)
1893 centerview(areawin->topinstance);
1894 areawin->lastbackground = NULL;
1895 renderbackground();
1896 refresh(NULL, NULL, NULL);
1900 /*---------------------------------------------------------*/
1901 /* Basic X Graphics Routines in the User coordinate system */
1902 /*---------------------------------------------------------*/
1904 #ifndef HAVE_CAIRO
1905 void UDrawSimpleLine(XPoint *pt1, XPoint *pt2)
1907 XPoint newpt1, newpt2;
1909 if (!areawin->redraw_ongoing) {
1910 areawin->redraw_needed = True;
1911 return;
1914 UTransformbyCTM(DCTM, pt1, &newpt1, 1);
1915 UTransformbyCTM(DCTM, pt2, &newpt2, 1);
1917 DrawLine(dpy, areawin->window, areawin->gc,
1918 newpt1.x, newpt1.y, newpt2.x, newpt2.y);
1920 #endif /* !HAVE_CAIRO */
1922 /*-------------------------------------------------------------------------*/
1924 #ifndef HAVE_CAIRO
1925 void UDrawLine(XPoint *pt1, XPoint *pt2)
1927 float tmpwidth = UTopTransScale(xobjs.pagelist[areawin->page]->wirewidth);
1929 if (!areawin->redraw_ongoing) {
1930 areawin->redraw_needed = True;
1931 return;
1934 SetLineAttributes(dpy, areawin->gc, tmpwidth, LineSolid, CapRound, JoinBevel);
1935 UDrawSimpleLine(pt1, pt2);
1937 #endif /* !HAVE_CAIRO */
1939 /*----------------------------------------------------------------------*/
1940 /* Add circle at given point to indicate that the point is a parameter. */
1941 /* The circle is divided into quarters. For parameterized y-coordinate */
1942 /* the top and bottom quarters are drawn. For parameterized x- */
1943 /* coordinate, the left and right quarters are drawn. A full circle */
1944 /* indicates either both x- and y-coordinates are parameterized, or */
1945 /* else any other kind of parameterization (presently, not used). */
1946 /* */
1947 /* (note that the two angles in XDrawArc() are 1) the start angle, */
1948 /* measured in absolute 64th degrees from 0 (3 o'clock), and 2) the */
1949 /* path length, in relative 64th degrees (positive = counterclockwise, */
1950 /* negative = clockwise)). */
1951 /*----------------------------------------------------------------------*/
1953 #ifndef HAVE_CAIRO
1954 void UDrawCircle(XPoint *upt, u_char which)
1956 XPoint wpt;
1958 if (!areawin->redraw_ongoing) {
1959 areawin->redraw_needed = True;
1960 return;
1963 user_to_window(*upt, &wpt);
1964 SetThinLineAttributes(dpy, areawin->gc, 0, LineSolid, CapButt, JoinMiter);
1966 switch(which) {
1967 case P_POSITION_X:
1968 XDrawArc(dpy, areawin->window, areawin->gc, wpt.x - 4,
1969 wpt.y - 4, 8, 8, -(45 * 64), (90 * 64));
1970 XDrawArc(dpy, areawin->window, areawin->gc, wpt.x - 4,
1971 wpt.y - 4, 8, 8, (135 * 64), (90 * 64));
1972 break;
1973 case P_POSITION_Y:
1974 XDrawArc(dpy, areawin->window, areawin->gc, wpt.x - 4,
1975 wpt.y - 4, 8, 8, (45 * 64), (90 * 64));
1976 XDrawArc(dpy, areawin->window, areawin->gc, wpt.x - 4,
1977 wpt.y - 4, 8, 8, (225 * 64), (90 * 64));
1978 break;
1979 default:
1980 XDrawArc(dpy, areawin->window, areawin->gc, wpt.x - 4,
1981 wpt.y - 4, 8, 8, 0, (360 * 64));
1982 break;
1985 #endif /* !HAVE_CAIRO */
1987 /*----------------------------------------------------------------------*/
1988 /* Add "X" at string origin */
1989 /*----------------------------------------------------------------------*/
1991 #ifndef HAVE_CAIRO
1992 void UDrawXAt(XPoint *wpt)
1994 if (!areawin->redraw_ongoing) {
1995 areawin->redraw_needed = True;
1996 return;
1999 SetThinLineAttributes(dpy, areawin->gc, 0, LineSolid, CapButt, JoinMiter);
2000 DrawLine(dpy, areawin->window, areawin->gc, wpt->x - 3,
2001 wpt->y - 3, wpt->x + 3, wpt->y + 3);
2002 DrawLine(dpy, areawin->window, areawin->gc, wpt->x + 3,
2003 wpt->y - 3, wpt->x - 3, wpt->y + 3);
2005 #endif /* !HAVE_CAIRO */
2007 /*----------------------------------------------------------------------*/
2008 /* Draw "X" on current level */
2009 /*----------------------------------------------------------------------*/
2011 void UDrawX(labelptr curlabel)
2013 XPoint wpt;
2015 user_to_window(curlabel->position, &wpt);
2016 UDrawXAt(&wpt);
2019 /*----------------------------------------------------------------------*/
2020 /* Draw "X" on top level (only for LOCAL and GLOBAL pin labels) */
2021 /*----------------------------------------------------------------------*/
2023 void UDrawXDown(labelptr curlabel)
2025 XPoint wpt;
2027 UTransformbyCTM(DCTM, &curlabel->position, &wpt, 1);
2028 UDrawXAt(&wpt);
2031 /*----------------------------------------------------------------------*/
2032 /* Find the "real" width, height, and origin of an object including pin */
2033 /* labels and so forth that only show up on a schematic when it is the */
2034 /* top-level object. */
2035 /*----------------------------------------------------------------------*/
2037 int toplevelwidth(objinstptr bbinst, short *rllx)
2039 short llx, urx;
2040 short origin, corner;
2042 if (bbinst->schembbox == NULL) {
2043 if (rllx) *rllx = bbinst->bbox.lowerleft.x;
2044 return bbinst->bbox.width;
2047 origin = bbinst->bbox.lowerleft.x;
2048 corner = origin + bbinst->bbox.width;
2050 llx = bbinst->schembbox->lowerleft.x;
2051 urx = llx + bbinst->schembbox->width;
2053 bboxcalc(llx, &origin, &corner);
2054 bboxcalc(urx, &origin, &corner);
2056 if (rllx) *rllx = origin;
2057 return(corner - origin);
2060 /*----------------------------------------------------------------------*/
2062 int toplevelheight(objinstptr bbinst, short *rlly)
2064 short lly, ury;
2065 short origin, corner;
2067 if (bbinst->schembbox == NULL) {
2068 if (rlly) *rlly = bbinst->bbox.lowerleft.y;
2069 return bbinst->bbox.height;
2072 origin = bbinst->bbox.lowerleft.y;
2073 corner = origin + bbinst->bbox.height;
2075 lly = bbinst->schembbox->lowerleft.y;
2076 ury = lly + bbinst->schembbox->height;
2078 bboxcalc(lly, &origin, &corner);
2079 bboxcalc(ury, &origin, &corner);
2081 if (rlly) *rlly = origin;
2082 return(corner - origin);
2085 /*----------------------------------------------------------------------*/
2086 /* Add dimensions of schematic pins to an object's bounding box */
2087 /*----------------------------------------------------------------------*/
2089 void extendschembbox(objinstptr bbinst, XPoint *origin, XPoint *corner)
2091 short llx, lly, urx, ury;
2093 if ((bbinst == NULL) || (bbinst->schembbox == NULL)) return;
2095 llx = bbinst->schembbox->lowerleft.x;
2096 lly = bbinst->schembbox->lowerleft.y;
2097 urx = llx + bbinst->schembbox->width;
2098 ury = lly + bbinst->schembbox->height;
2100 bboxcalc(llx, &(origin->x), &(corner->x));
2101 bboxcalc(lly, &(origin->y), &(corner->y));
2102 bboxcalc(urx, &(origin->x), &(corner->x));
2103 bboxcalc(ury, &(origin->y), &(corner->y));
2106 /*----------------------------------------------------------------------*/
2107 /* Adjust a pinlabel position to account for pad spacing */
2108 /*----------------------------------------------------------------------*/
2110 void pinadjust (short anchor, short *xpoint, short *ypoint, short dir)
2112 int delx, dely;
2114 dely = (anchor & NOTBOTTOM) ?
2115 ((anchor & TOP) ? -PADSPACE : 0) : PADSPACE;
2116 delx = (anchor & NOTLEFT) ?
2117 ((anchor & RIGHT) ? -PADSPACE : 0) : PADSPACE;
2119 if (xpoint != NULL) *xpoint += (dir > 0) ? delx : -delx;
2120 if (ypoint != NULL) *ypoint += (dir > 0) ? dely : -dely;
2123 /*----------------------------------------------------------------------*/
2124 /* Draw line for editing text (position of cursor in string is given by */
2125 /* tpos (2nd parameter) */
2126 /*----------------------------------------------------------------------*/
2128 void UDrawTextLine(labelptr curlabel, short tpos)
2130 XPoint points[2]; /* top and bottom of text cursor line */
2131 short tmpanchor, xbase;
2132 int maxwidth;
2133 TextExtents tmpext;
2134 TextLinesInfo tlinfo;
2136 if (!areawin->redraw_ongoing) {
2137 areawin->redraw_needed = True;
2138 return;
2141 /* correct for position, rotation, scale, and flip invariance of text */
2143 UPushCTM();
2144 UPreMultCTM(DCTM, curlabel->position, curlabel->scale, curlabel->rotation);
2145 tmpanchor = flipadjust(curlabel->anchor);
2147 SetForeground(dpy, areawin->gc, AUXCOLOR);
2149 tlinfo.dostop = 0;
2150 tlinfo.tbreak = NULL;
2151 tlinfo.padding = NULL;
2153 tmpext = ULength(curlabel, areawin->topinstance, &tlinfo);
2154 maxwidth = tmpext.maxwidth;
2155 xbase = tmpext.base;
2156 tlinfo.dostop = tpos;
2157 tmpext = ULength(curlabel, areawin->topinstance, &tlinfo);
2159 points[0].x = (tmpanchor & NOTLEFT ?
2160 (tmpanchor & RIGHT ? -maxwidth : -maxwidth >> 1) : 0) + tmpext.width;
2161 if ((tmpanchor & JUSTIFYRIGHT) && tlinfo.padding)
2162 points[0].x += tlinfo.padding[tlinfo.line];
2163 else if ((tmpanchor & TEXTCENTERED) && tlinfo.padding)
2164 points[0].x += 0.5 * tlinfo.padding[tlinfo.line];
2165 points[0].y = (tmpanchor & NOTBOTTOM ?
2166 (tmpanchor & TOP ? -tmpext.ascent : -(tmpext.ascent + xbase) / 2)
2167 : -xbase) + tmpext.base - 3;
2168 points[1].x = points[0].x;
2169 points[1].y = points[0].y + TEXTHEIGHT + 6;
2171 if (curlabel->pin) {
2172 pinadjust(tmpanchor, &(points[0].x), &(points[0].y), 1);
2173 pinadjust(tmpanchor, &(points[1].x), &(points[1].y), 1);
2175 if (tlinfo.padding != NULL) free(tlinfo.padding);
2177 /* draw the line */
2179 UDrawLine(&points[0], &points[1]);
2180 UPopCTM();
2182 UDrawX(curlabel);
2185 /*-----------------------------------------------------------------*/
2186 /* Draw lines for editing text when multiple characters are chosen */
2187 /*-----------------------------------------------------------------*/
2189 void UDrawTLine(labelptr curlabel)
2191 UDrawTextLine(curlabel, areawin->textpos);
2192 if ((areawin->textend > 0) && (areawin->textend < areawin->textpos)) {
2193 UDrawTextLine(curlabel, areawin->textend);
2197 /*----------------------*/
2198 /* Draw an X */
2199 /*----------------------*/
2201 #ifndef HAVE_CAIRO
2202 void UDrawXLine(XPoint opt, XPoint cpt)
2204 XPoint upt, vpt;
2206 if (!areawin->redraw_ongoing) {
2207 areawin->redraw_needed = True;
2208 return;
2211 SetForeground(dpy, areawin->gc, AUXCOLOR);
2213 user_to_window(cpt, &upt);
2214 user_to_window(opt, &vpt);
2216 SetThinLineAttributes(dpy, areawin->gc, 0, LineOnOffDash, CapButt, JoinMiter);
2217 DrawLine(dpy, areawin->window, areawin->gc, vpt.x, vpt.y, upt.x, upt.y);
2219 SetThinLineAttributes(dpy, areawin->gc, 0, LineSolid, CapButt, JoinMiter);
2220 DrawLine(dpy, areawin->window, areawin->gc, upt.x - 3, upt.y - 3,
2221 upt.x + 3, upt.y + 3);
2222 DrawLine(dpy, areawin->window, areawin->gc, upt.x + 3, upt.y - 3,
2223 upt.x - 3, upt.y + 3);
2225 SetForeground(dpy, areawin->gc, areawin->gccolor);
2227 #endif /* HAVE_CAIRO */
2229 /*-------------------------------------------------------------------------*/
2231 #ifndef HAVE_CAIRO
2232 void UDrawBox(XPoint origin, XPoint corner)
2234 XPoint worig, wcorn;
2236 if (!areawin->redraw_ongoing) {
2237 areawin->redraw_needed = True;
2238 return;
2241 user_to_window(origin, &worig);
2242 user_to_window(corner, &wcorn);
2244 SetForeground(dpy, areawin->gc, AUXCOLOR);
2245 SetThinLineAttributes(dpy, areawin->gc, 0, LineSolid, CapRound, JoinBevel);
2246 DrawLine(dpy, areawin->window, areawin->gc, worig.x, worig.y,
2247 worig.x, wcorn.y);
2248 DrawLine(dpy, areawin->window, areawin->gc, worig.x, wcorn.y,
2249 wcorn.x, wcorn.y);
2250 DrawLine(dpy, areawin->window, areawin->gc, wcorn.x, wcorn.y,
2251 wcorn.x, worig.y);
2252 DrawLine(dpy, areawin->window, areawin->gc, wcorn.x, worig.y,
2253 worig.x, worig.y);
2255 #endif /* HAVE_CAIRO */
2257 /*----------------------------------------------------------------------*/
2258 /* Get a box indicating the dimensions of the edit element that most */
2259 /* closely reach the position "corner". */
2260 /*----------------------------------------------------------------------*/
2262 float UGetRescaleBox(XPoint *corner, XPoint *newpoints)
2264 genericptr rgen;
2265 float savescale, newscale;
2266 long mindist, testdist, refdist;
2267 labelptr rlab;
2268 graphicptr rgraph;
2269 objinstptr rinst;
2270 int i;
2272 if (!areawin->redraw_ongoing) {
2273 areawin->redraw_needed = True;
2274 // return 0.0;
2277 if (areawin->selects == 0) return 0.0;
2279 /* Use only the 1st selection as a reference to set the scale */
2281 rgen = SELTOGENERIC(areawin->selectlist);
2283 switch(ELEMENTTYPE(rgen)) {
2284 case LABEL:
2285 rlab = (labelptr)rgen;
2286 labelbbox(rlab, newpoints, areawin->topinstance);
2287 newpoints[4] = newpoints[0];
2288 mindist = LONG_MAX;
2289 for (i = 0; i < 4; i++) {
2290 testdist = finddist(&newpoints[i], &newpoints[i+1], corner);
2291 if (testdist < mindist)
2292 mindist = testdist;
2294 refdist = wirelength(corner, &(rlab->position));
2295 mindist = (int)sqrt(abs((double)mindist));
2296 savescale = rlab->scale;
2297 if (!test_insideness((int)corner->x, (int)corner->y, newpoints))
2298 mindist = -mindist;
2299 if (refdist == mindist) refdist = 1 - mindist;
2300 if (rlab->scale < 0) rlab->scale = -rlab->scale;
2301 newscale = fabs(rlab->scale * (float)refdist / (float)(refdist + mindist));
2302 if (newscale > 10 * rlab->scale) newscale = 10 * rlab->scale;
2303 if (areawin->snapto) {
2304 float snapstep = 2 * (float)xobjs.pagelist[areawin->page]->gridspace
2305 / (float)xobjs.pagelist[areawin->page]->snapspace;
2306 newscale = (float)((int)(newscale * snapstep)) / snapstep;
2307 if (newscale < (1.0 / snapstep)) newscale = (1.0 / snapstep);
2309 else if (newscale < 0.1 * rlab->scale) newscale = 0.1 * rlab->scale;
2310 rlab->scale = (savescale < 0) ? -newscale : newscale;
2311 labelbbox(rlab, newpoints, areawin->topinstance);
2312 rlab->scale = savescale;
2313 if (savescale < 0) newscale = -newscale;
2314 break;
2316 case GRAPHIC:
2317 rgraph = (graphicptr)rgen;
2318 graphicbbox(rgraph, newpoints);
2319 newpoints[4] = newpoints[0];
2320 mindist = LONG_MAX;
2321 for (i = 0; i < 4; i++) {
2322 testdist = finddist(&newpoints[i], &newpoints[i+1], corner);
2323 if (testdist < mindist)
2324 mindist = testdist;
2326 refdist = wirelength(corner, &(rgraph->position));
2327 mindist = (int)sqrt(abs((double)mindist));
2328 savescale = rgraph->scale;
2329 if (!test_insideness((int)corner->x, (int)corner->y, newpoints))
2330 mindist = -mindist;
2331 if (refdist == mindist) refdist = 1 - mindist; /* avoid inf result */
2332 if (rgraph->scale < 0) rgraph->scale = -rgraph->scale;
2333 newscale = fabs(rgraph->scale * (float)refdist / (float)(refdist + mindist));
2334 if (newscale > 10 * rgraph->scale) newscale = 10 * rgraph->scale;
2335 if (areawin->snapto) {
2336 float snapstep = 2 * (float)xobjs.pagelist[areawin->page]->gridspace
2337 / (float)xobjs.pagelist[areawin->page]->snapspace;
2338 newscale = (float)((int)(newscale * snapstep)) / snapstep;
2339 if (newscale < (1.0 / snapstep)) newscale = (1.0 / snapstep);
2341 else if (newscale < 0.1 * rgraph->scale) newscale = 0.1 * rgraph->scale;
2342 rgraph->scale = (savescale < 0) ? -newscale : newscale;
2343 graphicbbox(rgraph, newpoints);
2344 rgraph->scale = savescale;
2345 if (savescale < 0) newscale = -newscale;
2346 break;
2348 case OBJINST:
2349 rinst = (objinstptr)rgen;
2350 objinstbbox(rinst, newpoints, 0);
2351 newpoints[4] = newpoints[0];
2352 mindist = LONG_MAX;
2353 for (i = 0; i < 4; i++) {
2354 testdist = finddist(&newpoints[i], &newpoints[i+1], corner);
2355 if (testdist < mindist)
2356 mindist = testdist;
2358 refdist = wirelength(corner, &(rinst->position));
2359 mindist = (int)sqrt(abs((double)mindist));
2360 savescale = rinst->scale;
2361 if (!test_insideness((int)corner->x, (int)corner->y, newpoints))
2362 mindist = -mindist;
2363 if (refdist == mindist) refdist = 1 - mindist; /* avoid inf result */
2364 if (rinst->scale < 0) rinst->scale = -rinst->scale;
2365 newscale = fabs(rinst->scale * (float)refdist / (float)(refdist + mindist));
2366 if (newscale > 10 * rinst->scale) newscale = 10 * rinst->scale;
2367 if (areawin->snapto) {
2368 float snapstep = 2 * (float)xobjs.pagelist[areawin->page]->gridspace
2369 / (float)xobjs.pagelist[areawin->page]->snapspace;
2370 newscale = (float)((int)(newscale * snapstep)) / snapstep;
2371 if (newscale < (1.0 / snapstep)) newscale = (1.0 / snapstep);
2373 else if (newscale < 0.1 * rinst->scale) newscale = 0.1 * rinst->scale;
2374 rinst->scale = (savescale < 0) ? -newscale : newscale;
2375 objinstbbox(rinst, newpoints, 0);
2376 rinst->scale = savescale;
2377 if (savescale < 0) newscale = -newscale;
2378 break;
2381 return newscale;
2384 /*----------------------------------------------------------------------*/
2385 /* Draw a box indicating the dimensions of the edit element that most */
2386 /* closely reach the position "corner". */
2387 /*----------------------------------------------------------------------*/
2389 #ifndef HAVE_CAIRO
2390 void UDrawRescaleBox(XPoint *corner)
2392 XPoint origpoints[5], newpoints[5];
2394 if (!areawin->redraw_ongoing) {
2395 areawin->redraw_needed = True;
2396 return;
2399 if (areawin->selects == 0)
2400 return;
2402 UGetRescaleBox(corner, newpoints);
2404 SetForeground(dpy, areawin->gc, AUXCOLOR);
2405 SetThinLineAttributes(dpy, areawin->gc, 0, LineSolid, CapRound, JoinBevel);
2407 UTransformbyCTM(DCTM, newpoints, origpoints, 4);
2408 strokepath(origpoints, 4, 0, 1);
2410 #endif /* HAVE_CAIRO */
2412 /*-------------------------------------------------------------------------*/
2414 #ifndef HAVE_CAIRO
2415 void UDrawBBox()
2417 XPoint origin;
2418 XPoint worig, wcorn, corner;
2419 objinstptr bbinst = areawin->topinstance;
2421 if (!areawin->redraw_ongoing) {
2422 areawin->redraw_needed = True;
2423 return;
2426 if ((!areawin->bboxon) || (checkforbbox(topobject) != NULL)) return;
2428 origin = bbinst->bbox.lowerleft;
2429 corner.x = origin.x + bbinst->bbox.width;
2430 corner.y = origin.y + bbinst->bbox.height;
2432 /* Include any schematic labels in the bounding box. */
2433 extendschembbox(bbinst, &origin, &corner);
2435 user_to_window(origin, &worig);
2436 user_to_window(corner, &wcorn);
2438 SetForeground(dpy, areawin->gc, BBOXCOLOR);
2439 DrawLine(dpy, areawin->window, areawin->gc, worig.x, worig.y,
2440 worig.x, wcorn.y);
2441 DrawLine(dpy, areawin->window, areawin->gc, worig.x, wcorn.y,
2442 wcorn.x, wcorn.y);
2443 DrawLine(dpy, areawin->window, areawin->gc, wcorn.x, wcorn.y,
2444 wcorn.x, worig.y);
2445 DrawLine(dpy, areawin->window, areawin->gc, wcorn.x, worig.y,
2446 worig.x, worig.y);
2448 #endif /* !HAVE_CAIRO */
2450 /*----------------------------------------------------------------------*/
2451 /* Fill and/or draw a border around the stroking path */
2452 /*----------------------------------------------------------------------*/
2454 #ifndef HAVE_CAIRO
2455 void strokepath(XPoint *pathlist, short number, short style, float width)
2457 float tmpwidth;
2459 tmpwidth = UTopTransScale(width);
2461 if (!(style & CLIPMASK) || (areawin->showclipmasks == TRUE) ||
2462 (areawin->clipped < 0)) {
2463 if (style & FILLED || (!(style & FILLED) && style & OPAQUE)) {
2464 if ((style & FILLSOLID) == FILLSOLID)
2465 SetFillStyle(dpy, areawin->gc, FillSolid);
2466 else if (!(style & FILLED)) {
2467 SetFillStyle(dpy, areawin->gc, FillOpaqueStippled);
2468 SetStipple(dpy, areawin->gc, 7);
2470 else {
2471 if (style & OPAQUE)
2472 SetFillStyle(dpy, areawin->gc, FillOpaqueStippled);
2473 else
2474 SetFillStyle(dpy, areawin->gc, FillStippled);
2475 SetStipple(dpy, areawin->gc, ((style & FILLSOLID) >> 5));
2477 FillPolygon(dpy, areawin->window, areawin->gc, pathlist, number, Nonconvex,
2478 CoordModeOrigin);
2479 /* return to original state */
2480 SetFillStyle(dpy, areawin->gc, FillSolid);
2482 if (!(style & NOBORDER)) {
2483 if (style & (DASHED | DOTTED)) {
2484 /* Set up dots or dashes */
2485 char dashstring[2];
2486 /* prevent values greater than 255 from folding back into */
2487 /* type char. Limit to 63 (=255/4) to keep at least the */
2488 /* dot/gap ratio to scale when 'gap' is at its maximum */
2489 /* value. */
2490 unsigned char dotsize = min(63, max(1, (short)tmpwidth));
2491 if (style & DASHED)
2492 dashstring[0] = 4 * dotsize;
2493 else if (style & DOTTED)
2494 dashstring[0] = dotsize;
2495 dashstring[1] = 4 * dotsize;
2496 SetDashes(dpy, areawin->gc, 0, dashstring, 2);
2497 SetLineAttributes(dpy, areawin->gc, tmpwidth, LineOnOffDash,
2498 CapButt, (style & SQUARECAP) ? JoinMiter : JoinBevel);
2500 else
2501 SetLineAttributes(dpy, areawin->gc, tmpwidth, LineSolid,
2502 (style & SQUARECAP) ? CapProjecting : CapRound,
2503 (style & SQUARECAP) ? JoinMiter : JoinBevel);
2505 /* draw the spline and close off if so specified */
2506 DrawLines(dpy, areawin->window, areawin->gc, pathlist,
2507 number, CoordModeOrigin);
2508 if (!(style & UNCLOSED))
2509 DrawLine(dpy, areawin->window, areawin->gc, pathlist[0].x,
2510 pathlist[0].y, pathlist[number - 1].x, pathlist[number - 1].y);
2514 if (style & CLIPMASK) {
2515 if (areawin->clipped == 0) {
2516 XSetForeground(dpy, areawin->cmgc, 0);
2517 XFillRectangle(dpy, areawin->clipmask, areawin->cmgc, 0, 0,
2518 areawin->width, areawin->height);
2519 XSetForeground(dpy, areawin->cmgc, 1);
2520 FillPolygon(dpy, areawin->clipmask, areawin->cmgc, pathlist,
2521 number, Nonconvex, CoordModeOrigin);
2522 XSetClipMask(dpy, areawin->gc, areawin->clipmask);
2523 // printf("level 0: Clip to clipmask\n"); // Diagnostic
2524 areawin->clipped++;
2526 else if ((areawin->clipped > 0) && (areawin->clipped & 1) == 0) {
2527 if (areawin->pbuf == (Pixmap)NULL) {
2528 areawin->pbuf = XCreatePixmap (dpy, areawin->window,
2529 areawin->width, areawin->height, 1);
2531 XCopyArea(dpy, areawin->clipmask, areawin->pbuf, areawin->cmgc,
2532 0, 0, areawin->width, areawin->height, 0, 0);
2533 XSetForeground(dpy, areawin->cmgc, 0);
2534 XFillRectangle(dpy, areawin->clipmask, areawin->cmgc, 0, 0,
2535 areawin->width, areawin->height);
2536 XSetForeground(dpy, areawin->cmgc, 1);
2537 FillPolygon(dpy, areawin->clipmask, areawin->cmgc, pathlist,
2538 number, Nonconvex, CoordModeOrigin);
2539 XSetFunction(dpy, areawin->cmgc, GXand);
2540 XCopyArea(dpy, areawin->pbuf, areawin->clipmask, areawin->cmgc,
2541 0, 0, areawin->width, areawin->height, 0, 0);
2542 XSetFunction(dpy, areawin->cmgc, GXcopy);
2543 XSetClipMask(dpy, areawin->gc, areawin->clipmask);
2544 // printf("level X: Clip to clipmask\n"); // Diagnostic
2545 areawin->clipped++;
2549 #endif /* !HAVE_CAIRO */
2551 /*-------------------------------------------------------------------------*/
2553 void makesplinepath(splineptr thespline, XPoint *pathlist)
2555 XPoint *tmpptr = pathlist;
2557 UTransformbyCTM(DCTM, &(thespline->ctrl[0]), tmpptr, 1);
2558 UfTransformbyCTM(DCTM, thespline->points, ++tmpptr, INTSEGS);
2559 UTransformbyCTM(DCTM, &(thespline->ctrl[3]), tmpptr + INTSEGS, 1);
2562 /*-------------------------------------------------------------------------*/
2564 #ifndef HAVE_CAIRO
2565 void UDrawSpline(splineptr thespline, float passwidth)
2567 XPoint tmppoints[SPLINESEGS];
2568 float scaledwidth;
2570 if (!areawin->redraw_ongoing) {
2571 areawin->redraw_needed = True;
2572 return;
2575 scaledwidth = thespline->width * passwidth;
2577 makesplinepath(thespline, tmppoints);
2578 strokepath(tmppoints, SPLINESEGS, thespline->style, scaledwidth);
2580 #endif /* HAVE_CAIRO */
2582 /*-------------------------------------------------------------------------*/
2584 #ifndef HAVE_CAIRO
2585 void UDrawPolygon(polyptr thepoly, float passwidth)
2587 XPoint *tmppoints = (pointlist) malloc(thepoly->number * sizeof(XPoint));
2588 float scaledwidth;
2590 if (!areawin->redraw_ongoing) {
2591 areawin->redraw_needed = True;
2592 return;
2595 scaledwidth = thepoly->width * passwidth;
2597 UTransformbyCTM(DCTM, thepoly->points, tmppoints, thepoly->number);
2598 strokepath(tmppoints, thepoly->number, thepoly->style, scaledwidth);
2599 free(tmppoints);
2601 #endif /* HAVE_CAIRO */
2603 /*-------------------------------------------------------------------------*/
2605 #ifndef HAVE_CAIRO
2606 void UDrawArc(arcptr thearc, float passwidth)
2608 XPoint tmppoints[RSTEPS + 2];
2609 float scaledwidth;
2611 if (!areawin->redraw_ongoing) {
2612 areawin->redraw_needed = True;
2613 return;
2616 scaledwidth = thearc->width * passwidth;
2618 UfTransformbyCTM(DCTM, thearc->points, tmppoints, thearc->number);
2619 strokepath(tmppoints, thearc->number, thearc->style, scaledwidth);
2621 #endif /* HAVE_CAIRO */
2623 /*-------------------------------------------------------------------------*/
2625 #ifndef HAVE_CAIRO
2626 void UDrawPath(pathptr thepath, float passwidth)
2628 XPoint *tmppoints = (pointlist) malloc(sizeof(XPoint));
2629 genericptr *genpath;
2630 polyptr thepoly;
2631 splineptr thespline;
2632 int pathsegs = 0, curseg = 0;
2633 float scaledwidth;
2635 if (!areawin->redraw_ongoing) {
2636 areawin->redraw_needed = True;
2637 return;
2640 for (genpath = thepath->plist; genpath < thepath->plist + thepath->parts;
2641 genpath++) {
2642 switch(ELEMENTTYPE(*genpath)) {
2643 case POLYGON:
2644 thepoly = TOPOLY(genpath);
2645 pathsegs += thepoly->number;
2646 tmppoints = (pointlist) realloc(tmppoints, pathsegs * sizeof(XPoint));
2647 UTransformbyCTM(DCTM, thepoly->points, tmppoints + curseg, thepoly->number);
2648 curseg = pathsegs;
2649 break;
2650 case SPLINE:
2651 thespline = TOSPLINE(genpath);
2652 pathsegs += SPLINESEGS;
2653 tmppoints = (pointlist) realloc(tmppoints, pathsegs * sizeof(XPoint));
2654 makesplinepath(thespline, tmppoints + curseg);
2655 curseg = pathsegs;
2656 break;
2659 scaledwidth = thepath->width * passwidth;
2661 strokepath(tmppoints, pathsegs, thepath->style, scaledwidth);
2662 free(tmppoints);
2664 #endif /* HAVE_CAIRO */
2666 /*----------------------------------------------------------------------*/
2667 /* Main recursive object instance drawing routine. */
2668 /* context is the instance information passed down from above */
2669 /* theinstance is the object instance to be drawn */
2670 /* level is the level of recursion */
2671 /* passcolor is the inherited color value passed to object */
2672 /* passwidth is the inherited linewidth value passed to the object */
2673 /* stack contains graphics context information */
2674 /*----------------------------------------------------------------------*/
2676 #ifndef HAVE_CAIRO
2677 void UDrawObject(objinstptr theinstance, short level, int passcolor,
2678 float passwidth, pushlistptr *stack)
2680 genericptr *areagen;
2681 float tmpwidth;
2682 int defaultcolor = passcolor;
2683 int curcolor = passcolor;
2684 int thispart;
2685 short savesel;
2686 XPoint bboxin[2], bboxout[2];
2687 u_char xm, ym;
2688 objectptr theobject = theinstance->thisobject;
2690 if (!areawin->redraw_ongoing) {
2691 areawin->redraw_needed = True;
2692 return;
2695 /* Save the number of selections and set it to zero while we do the */
2696 /* object drawing. */
2698 savesel = areawin->selects;
2699 areawin->selects = 0;
2701 /* All parts are given in the coordinate system of the object, unless */
2702 /* this is the top-level object, in which they will be interpreted as */
2703 /* relative to the screen. */
2705 UPushCTM();
2707 if (stack) {
2708 /* Save the current clipping mask and push it on the stack */
2709 if (areawin->clipped > 0) {
2710 push_stack((pushlistptr *)stack, theinstance, (char *)areawin->clipmask);
2711 areawin->clipmask = XCreatePixmap(dpy, areawin->window, areawin->width,
2712 areawin->height, 1);
2713 XCopyArea(dpy, (Pixmap)(*stack)->clientdata, areawin->clipmask, areawin->cmgc,
2714 0, 0, areawin->width, areawin->height, 0, 0);
2716 else
2717 push_stack((pushlistptr *)stack, theinstance, (char *)NULL);
2719 if (level != 0)
2720 UPreMultCTM(DCTM, theinstance->position, theinstance->scale,
2721 theinstance->rotation);
2723 if (theinstance->style & LINE_INVARIANT)
2724 passwidth /= fabs(theinstance->scale);
2726 /* do a quick test for intersection with the display window */
2728 bboxin[0].x = theobject->bbox.lowerleft.x;
2729 bboxin[0].y = theobject->bbox.lowerleft.y;
2730 bboxin[1].x = theobject->bbox.lowerleft.x + theobject->bbox.width;
2731 bboxin[1].y = theobject->bbox.lowerleft.y + theobject->bbox.height;
2732 if (level == 0)
2733 extendschembbox(theinstance, &(bboxin[0]), &(bboxin[1]));
2734 UTransformbyCTM(DCTM, bboxin, bboxout, 2);
2736 xm = (bboxout[0].x < bboxout[1].x) ? 0 : 1;
2737 ym = (bboxout[0].y < bboxout[1].y) ? 0 : 1;
2739 if (bboxout[xm].x < areawin->width && bboxout[ym].y < areawin->height &&
2740 bboxout[1 - xm].x > 0 && bboxout[1 - ym].y > 0) {
2742 /* make parameter substitutions */
2743 psubstitute(theinstance);
2745 /* draw all of the elements */
2747 tmpwidth = UTopTransScale(passwidth);
2748 SetLineAttributes(dpy, areawin->gc, tmpwidth, LineSolid, CapRound,
2749 JoinBevel);
2751 /* guard against plist being regenerated during a redraw by the */
2752 /* expression parameter mechanism (should that be prohibited?) */
2754 for (thispart = 0; thispart < theobject->parts; thispart++) {
2755 areagen = theobject->plist + thispart;
2756 if ((*areagen)->type & DRAW_HIDE) continue;
2758 if (defaultcolor != DOFORALL) {
2759 Boolean clipcolor = FALSE;
2760 switch(ELEMENTTYPE(*areagen)) {
2761 case(POLYGON): case(SPLINE): case(ARC): case(PATH):
2762 if (TOPOLY(areagen)->style & CLIPMASK)
2763 clipcolor = TRUE;
2764 break;
2766 if (((*areagen)->color != curcolor) || (clipcolor == TRUE)) {
2767 if (clipcolor)
2768 curcolor = CLIPMASKCOLOR;
2769 else if ((*areagen)->color == DEFAULTCOLOR)
2770 curcolor = defaultcolor;
2771 else
2772 curcolor = (*areagen)->color;
2774 XcTopSetForeground(curcolor);
2778 switch(ELEMENTTYPE(*areagen)) {
2779 case(POLYGON):
2780 if (level == 0 || !((TOPOLY(areagen))->style & BBOX))
2781 UDrawPolygon(TOPOLY(areagen), passwidth);
2782 break;
2784 case(SPLINE):
2785 UDrawSpline(TOSPLINE(areagen), passwidth);
2786 break;
2788 case(ARC):
2789 UDrawArc(TOARC(areagen), passwidth);
2790 break;
2792 case(PATH):
2793 UDrawPath(TOPATH(areagen), passwidth);
2794 break;
2796 case(GRAPHIC):
2797 UDrawGraphic(TOGRAPHIC(areagen));
2798 break;
2800 case(OBJINST):
2801 if (areawin->editinplace && stack && (TOOBJINST(areagen)
2802 == areawin->topinstance)) {
2803 /* If stack matches areawin->stack, then don't draw */
2804 /* because it would be redundant. */
2805 pushlistptr alist = *stack, blist = areawin->stack;
2806 while (alist && blist) {
2807 if (alist->thisinst != blist->thisinst) break;
2808 alist = alist->next;
2809 blist = blist->next;
2811 if ((!alist) || (!blist)) break;
2813 if (areawin->clipped > 0) areawin->clipped += 2;
2814 UDrawObject(TOOBJINST(areagen), level + 1, curcolor, passwidth, stack);
2815 if (areawin->clipped > 0) areawin->clipped -= 2;
2816 break;
2818 case(LABEL):
2819 if (level == 0 || TOLABEL(areagen)->pin == False)
2820 UDrawString(TOLABEL(areagen), curcolor, theinstance);
2821 else if ((TOLABEL(areagen)->anchor & PINVISIBLE) && areawin->pinpointon)
2822 UDrawString(TOLABEL(areagen), curcolor, theinstance);
2823 else if (TOLABEL(areagen)->anchor & PINVISIBLE)
2824 UDrawStringNoX(TOLABEL(areagen), curcolor, theinstance);
2825 else if (level == 1 && TOLABEL(areagen)->pin &&
2826 TOLABEL(areagen)->pin != INFO && areawin->pinpointon)
2827 UDrawXDown(TOLABEL(areagen));
2828 break;
2830 if (areawin->clipped > 0) {
2831 if ((areawin->clipped & 3) == 1) {
2832 areawin->clipped++;
2834 else if ((areawin->clipped & 3) == 2) {
2835 areawin->clipped -= 2;
2836 if ((!stack) || ((*stack)->clientdata == (char *)NULL)) {
2837 XSetClipMask(dpy, areawin->gc, None);
2838 // printf("1: Clear clipmask\n"); // Diagnostic
2840 else {
2841 XSetClipMask(dpy, areawin->gc, (Pixmap)((*stack)->clientdata));
2842 // printf("1: Set to pushed clipmask\n"); // Diagnostic
2848 /* restore the color passed to the object, if different from current color */
2850 if ((defaultcolor != DOFORALL) && (passcolor != curcolor)) {
2851 XTopSetForeground(passcolor);
2853 if (areawin->clipped > 0) {
2854 if ((areawin->clipped & 3) != 3) {
2855 if ((!stack) || ((*stack)->clientdata == (char *)NULL)) {
2856 XSetClipMask(dpy, areawin->gc, None);
2857 // printf("2: Clear clipmask\n"); // Diagnostic
2859 else {
2860 XSetClipMask(dpy, areawin->gc, (Pixmap)((*stack)->clientdata));
2861 // printf("2: Set to pushed clipmask\n"); // Diagnostic
2864 areawin->clipped &= ~3;
2868 /* restore the selection list (if any) */
2869 areawin->selects = savesel;
2870 UPopCTM();
2871 if (stack) {
2872 if ((*stack) != NULL) {
2873 if ((*stack)->clientdata != (char *)NULL) {
2874 XFreePixmap(dpy, areawin->clipmask);
2875 areawin->clipmask = (Pixmap)(*stack)->clientdata;
2876 // printf("3: Restore clipmask\n"); // Diagnostic
2879 pop_stack(stack);
2882 #endif /* HAVE_CAIRO */
2884 /*----------------------------------------------------------------------*/
2885 /* Recursively run through the current page and find any labels which */
2886 /* are declared to be style LATEX. If "checkonly" is present, we set */
2887 /* it to TRUE or FALSE depending on whether or not LATEX labels have */
2888 /* been encountered. If NULL, then we write LATEX output appropriately */
2889 /* to a file named with the page filename + suffix ".tex". */
2890 /*----------------------------------------------------------------------*/
2892 void UDoLatex(objinstptr theinstance, short level, FILE *f,
2893 float scale, float scale2, int tx, int ty, Boolean *checkonly)
2895 XPoint lpos, xlpos;
2896 XfPoint xfpos;
2897 labelptr thislabel;
2898 genericptr *areagen;
2899 objectptr theobject = theinstance->thisobject;
2900 char *ltext;
2901 int lranchor, tbanchor;
2903 UPushCTM();
2904 if (level != 0)
2905 UPreMultCTM(DCTM, theinstance->position, theinstance->scale,
2906 theinstance->rotation);
2908 /* make parameter substitutions */
2909 psubstitute(theinstance);
2911 /* find all of the elements */
2913 for (areagen = theobject->plist; areagen < theobject->plist +
2914 theobject->parts; areagen++) {
2916 switch(ELEMENTTYPE(*areagen)) {
2917 case(OBJINST):
2918 UDoLatex(TOOBJINST(areagen), level + 1, f, scale, scale2, tx, ty, checkonly);
2919 break;
2921 case(LABEL):
2922 thislabel = TOLABEL(areagen);
2923 if (level == 0 || thislabel->pin == False ||
2924 (thislabel->anchor & PINVISIBLE))
2925 if (thislabel->anchor & LATEXLABEL) {
2926 if (checkonly) {
2927 *checkonly = TRUE;
2928 return;
2930 else {
2931 lpos.x = thislabel->position.x;
2932 lpos.y = thislabel->position.y;
2933 UTransformbyCTM(DCTM, &lpos, &xlpos, 1);
2934 xlpos.x += tx;
2935 xlpos.y += ty;
2936 xfpos.x = (float)xlpos.x * scale;
2937 xfpos.y = (float)xlpos.y * scale;
2938 xfpos.x /= 72.0;
2939 xfpos.y /= 72.0;
2940 xfpos.x -= 1.0;
2941 xfpos.y -= 1.0;
2942 xfpos.x += 0.056;
2943 xfpos.y += 0.056;
2944 xfpos.x /= scale2;
2945 xfpos.y /= scale2;
2946 ltext = textprinttex(thislabel->string, theinstance);
2947 tbanchor = thislabel->anchor & (NOTBOTTOM | TOP);
2948 lranchor = thislabel->anchor & (NOTLEFT | RIGHT);
2950 /* The 1.2 factor accounts for the difference between */
2951 /* Xcircuit's label scale of "1" and LaTeX's "normalsize" */
2953 fprintf(f, " \\putbox{%3.2fin}{%3.2fin}{%3.2f}{",
2954 xfpos.x, xfpos.y, 1.2 * thislabel->scale);
2955 if (thislabel->rotation != 0)
2956 fprintf(f, "\\rotatebox{-%d}{", thislabel->rotation);
2957 if (lranchor == (NOTLEFT | RIGHT)) fprintf(f, "\\rightbox{");
2958 else if (lranchor == NOTLEFT) fprintf(f, "\\centbox{");
2959 if (tbanchor == (NOTBOTTOM | TOP)) fprintf(f, "\\topbox{");
2960 else if (tbanchor == NOTBOTTOM) fprintf(f, "\\midbox{");
2961 fprintf(f, "%s", ltext);
2962 if (lranchor != NORMAL) fprintf(f, "}");
2963 if (tbanchor != NORMAL) fprintf(f, "}");
2964 if (thislabel->rotation != 0) fprintf(f, "}");
2965 fprintf(f, "}%%\n");
2966 free(ltext);
2969 break;
2972 UPopCTM();
2975 /*----------------------------------------------------------------------*/
2976 /* Top level routine for writing LATEX output. */
2977 /*----------------------------------------------------------------------*/
2979 void TopDoLatex()
2981 FILE *f;
2982 float psscale, outscale;
2983 int tx, ty, width, height;
2984 polyptr framebox;
2985 XPoint origin;
2986 Boolean checklatex = FALSE;
2987 char filename[100], extension[10], *dotptr;
2989 UDoLatex(areawin->topinstance, 0, NULL, 1.0, 1.0, 0, 0, &checklatex);
2991 if (checklatex == FALSE) return; /* No LaTeX labels to write */
2993 /* Handle cases where the file might have a ".eps" extension. */
2994 /* Thanks to Graham Sheward for pointing this out. */
2996 /* Modified file path routines: */
2997 /* Solved problems with incomplete paths, NULL file pointers, */
2998 /* added tilde and variable expansion by Agustín Campeny, April 2020 */
3000 sprintf(filename, "%s", xobjs.pagelist[areawin->page]->filename);
3002 xc_tilde_expand(filename, 100);
3003 while(xc_variable_expand(filename, 100));
3005 dotptr = strrchr(filename, '.');
3006 sprintf(extension, "%s", dotptr);
3007 filename[dotptr - filename] = '\0';
3008 sprintf(filename, "%s.tex", filename);
3010 f = fopen(filename, "w");
3012 if (!f) {
3013 Wprintf("Couldn't save .tex file. Check file path");
3014 return;
3017 *dotptr = '\0';
3019 fprintf(f, "%% XCircuit output \"%s.tex\" for LaTeX input from %s%s\n",
3020 filename, filename, extension);
3021 fprintf(f, "\\def\\putbox#1#2#3#4{\\makebox[0in][l]{\\makebox[#1][l]{}"
3022 "\\raisebox{\\baselineskip}[0in][0in]"
3023 "{\\raisebox{#2}[0in][0in]{\\scalebox{#3}{#4}}}}}\n");
3024 fprintf(f, "\\def\\rightbox#1{\\makebox[0in][r]{#1}}\n");
3025 fprintf(f, "\\def\\centbox#1{\\makebox[0in]{#1}}\n");
3026 fprintf(f, "\\def\\topbox#1{\\raisebox{-0.60\\baselineskip}[0in][0in]{#1}}\n");
3027 fprintf(f, "\\def\\midbox#1{\\raisebox{-0.20\\baselineskip}[0in][0in]{#1}}\n");
3029 /* Modified to use \scalebox and \parbox by Alex Tercete, June 2008 */
3031 // fprintf(f, "\\begin{center}\n");
3033 outscale = xobjs.pagelist[areawin->page]->outscale;
3034 psscale = getpsscale(outscale, areawin->page);
3036 width = toplevelwidth(areawin->topinstance, &origin.x);
3037 height = toplevelheight(areawin->topinstance, &origin.y);
3039 /* Added 10/19/10: If there is a specified bounding box, let it */
3040 /* determine the figure origin; otherwise, the labels will be */
3041 /* mismatched to the bounding box. */
3043 if ((framebox = checkforbbox(topobject)) != NULL) {
3044 int i, maxx, maxy;
3046 origin.x = maxx = framebox->points[0].x;
3047 origin.y = maxy = framebox->points[0].y;
3048 for (i = 1; i < framebox->number; i++) {
3049 if (framebox->points[i].x < origin.x) origin.x = framebox->points[i].x;
3050 if (framebox->points[i].x > maxx) maxx = framebox->points[i].x;
3051 if (framebox->points[i].y < origin.y) origin.y = framebox->points[i].y;
3052 if (framebox->points[i].y > maxy) maxy = framebox->points[i].y;
3054 origin.x -= ((width - maxx + origin.x) / 2);
3055 origin.y -= ((height - maxy + origin.y) / 2);
3058 tx = (int)(72 / psscale) - origin.x,
3059 ty = (int)(72 / psscale) - origin.y;
3061 fprintf(f, " \\scalebox{%g}{\n", outscale);
3062 fprintf(f, " \\normalsize\n");
3063 fprintf(f, " \\parbox{%gin}{\n", (((float)width * psscale) / 72.0) / outscale);
3064 fprintf(f, " \\includegraphics[scale=%g]{%s%s}\\\\\n", 1.0 / outscale,
3065 filename, extension);
3066 fprintf(f, " %% translate x=%d y=%d scale %3.2f\n", tx, ty, psscale);
3068 UPushCTM(); /* Save current state */
3069 UResetCTM(DCTM); /* Set to identity matrix */
3070 UDoLatex(areawin->topinstance, 0, f, psscale, outscale, tx, ty, NULL);
3071 UPopCTM(); /* Restore state */
3073 fprintf(f, " } %% close \'parbox\'\n");
3074 fprintf(f, " } %% close \'scalebox\'\n");
3075 fprintf(f, " \\vspace{-\\baselineskip} %% this is not"
3076 " necessary, but looks better\n");
3077 // fprintf(f, "\\end{center}\n");
3078 fclose(f);
3080 Wprintf("Wrote auxiliary file %s.tex", filename);