Subversion Repositories planix.SVN

Rev

Rev 2 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
/* Copyright (C) 1993, 1995, 1996, 1997, 1998, 1999 Aladdin Enterprises.  All rights reserved.
2
 
3
  This software is provided AS-IS with no warranty, either express or
4
  implied.
5
 
6
  This software is distributed under license and may not be copied,
7
  modified or distributed except as expressly authorized under the terms
8
  of the license contained in the file LICENSE in this distribution.
9
 
10
  For more information about licensing, please refer to
11
  http://www.ghostscript.com/licensing/. For information on
12
  commercial licensing, go to http://www.artifex.com/licensing/ or
13
  contact Artifex Software, Inc., 101 Lucas Valley Road #110,
14
  San Rafael, CA  94903, U.S.A., +1(415)492-9861.
15
*/
16
 
17
/* $Id: zmedia2.c,v 1.19 2005/08/30 06:38:44 igor Exp $ */
18
/* Media matching for setpagedevice */
19
#include "math_.h"
20
#include "memory_.h"
21
#include "ghost.h"
22
#include "gsmatrix.h"
23
#include "oper.h"
24
#include "idict.h"
25
#include "idparam.h"
26
#include "iname.h"
27
#include "store.h"
28
 
29
/* <pagedict> <attrdict> <policydict> <keys> .matchmedia <key> true */
30
/* <pagedict> <attrdict> <policydict> <keys> .matchmedia false */
31
/* <pagedict> null <policydict> <keys> .matchmedia null true */
32
private int zmatch_page_size(const gs_memory_t *mem,
33
			     const ref * pvreq, const ref * pvmed,
34
			     int policy, int orient, bool roll,
35
			     float *best_mismatch, gs_matrix * pmat,
36
			     gs_point * pmsize);
37
typedef struct match_record_s {
38
    ref best_key, match_key;
39
    uint priority, no_match_priority;
40
} match_record_t;
41
private void
42
reset_match(match_record_t *match)
43
{
44
    make_null(&match->best_key);
45
    make_null(&match->match_key);
46
    match->priority = match->no_match_priority;
47
}
48
private int
49
zmatchmedia(i_ctx_t *i_ctx_p)
50
{
51
    os_ptr op = osp;
52
    os_ptr preq = op - 3;
53
    os_ptr pattr = op - 2;
54
    os_ptr ppol = op - 1;
55
    os_ptr pkeys = op;		/* *const */
56
    int policy_default;
57
    float best_mismatch = (float)max_long;	/* adhoc */
58
    float mepos_penalty;
59
    float mbest = best_mismatch;
60
    match_record_t match;
61
    ref no_priority;
62
    ref *ppriority;
63
    int mepos, orient;
64
    bool roll;
65
    int code;
66
    int ai;
67
    struct mkd_ {
68
	ref key, dict;
69
    } aelt;
70
    if (r_has_type(pattr, t_null)) {
71
	check_op(4);
72
	make_null(op - 3);
73
	make_true(op - 2);
74
	pop(2);
75
	return 0;
76
    }
77
    check_type(*preq, t_dictionary);
78
    check_dict_read(*preq);
79
    check_type(*pattr, t_dictionary);
80
    check_dict_read(*pattr);
81
    check_type(*ppol, t_dictionary);
82
    check_dict_read(*ppol);
83
    check_array(*pkeys);
84
    check_read(*pkeys);
85
    switch (code = dict_int_null_param(preq, "MediaPosition", 0, 0x7fff,
86
				       0, &mepos)) {
87
	default:
88
	    return code;
89
	case 2:
90
	case 1:
91
	    mepos = -1;
92
	case 0:;
93
    }
94
    switch (code = dict_int_null_param(preq, "Orientation", 0, 3,
95
				       0, &orient)) {
96
	default:
97
	    return code;
98
	case 2:
99
	case 1:
100
	    orient = -1;
101
	case 0:;
102
    }
103
    code = dict_bool_param(preq, "RollFedMedia", false, &roll);
104
    if (code < 0)
105
	return code;
106
    code = dict_int_param(ppol, "PolicyNotFound", 0, 7, 0,
107
			  &policy_default);
108
    if (code < 0)
109
	return code;
110
    if (dict_find_string(pattr, "Priority", &ppriority) > 0) {
111
	check_array_only(*ppriority);
112
	check_read(*ppriority);
113
    } else {
114
	make_empty_array(&no_priority, a_readonly);
115
	ppriority = &no_priority;
116
    }
117
    match.no_match_priority = r_size(ppriority);
118
    reset_match(&match);
119
    for (ai = dict_first(pattr);
120
	 (ai = dict_next(pattr, ai, (ref * /*[2]*/)&aelt)) >= 0;
121
	 ) {
122
	if (r_has_type(&aelt.dict, t_dictionary) &&
123
	    r_has_attr(dict_access_ref(&aelt.dict), a_read) &&
124
	    r_has_type(&aelt.key, t_integer)
125
	    ) {
126
	    bool match_all;
127
	    uint ki, pi;
128
 
129
	    code = dict_bool_param(&aelt.dict, "MatchAll", false,
130
				   &match_all);
131
	    if (code < 0)
132
		return code;
133
	    for (ki = 0; ki < r_size(pkeys); ki++) {
134
		ref key;
135
		ref kstr;
136
		ref *prvalue;
137
		ref *pmvalue;
138
		ref *ppvalue;
139
		int policy;
140
 
141
		array_get(imemory, pkeys, ki, &key);
142
		if (dict_find(&aelt.dict, &key, &pmvalue) <= 0)
143
		    continue;
144
		if (dict_find(preq, &key, &prvalue) <= 0 ||
145
		    r_has_type(prvalue, t_null)
146
		    ) {
147
		    if (match_all)
148
			goto no;
149
		    else
150
			continue;
151
		}
152
		/* Look for the Policies entry for this key. */
153
		if (dict_find(ppol, &key, &ppvalue) > 0) {
154
		    check_type_only(*ppvalue, t_integer);
155
		    policy = ppvalue->value.intval;
156
		} else
157
		    policy = policy_default;
158
	/*
159
	 * Match a requested attribute value with the attribute value in the
160
	 * description of a medium.  For all attributes except PageSize,
161
	 * matching means equality.  PageSize is special; see match_page_size
162
	 * below.
163
	 */
164
		if (r_has_type(&key, t_name) &&
165
		    (name_string_ref(imemory, &key, &kstr),
166
		     r_size(&kstr) == 8 &&
167
		     !memcmp(kstr.value.bytes, "PageSize", 8))
168
		    ) {
169
		    gs_matrix ignore_mat;
170
		    gs_point ignore_msize;
171
 
172
		    if (zmatch_page_size(imemory, prvalue, pmvalue,
173
					 policy, orient, roll,
174
					 &best_mismatch,
175
					 &ignore_mat,
176
					 &ignore_msize)
177
			<= 0)
178
			goto no;
179
		} else if (!obj_eq(imemory, prvalue, pmvalue))
180
		    goto no;
181
	    }
182
 
183
	    mepos_penalty = (mepos < 0 || aelt.key.value.intval == mepos) ?
184
 
185
 
186
	    /* We have a match. Save the match in case no better match is found */
187
	    if (r_has_type(&match.match_key, t_null)) 
188
		match.match_key = aelt.key;
189
	    /*
190
	     * If it is a better match than the current best it supersedes it 
191
	     * regardless of priority. If the match is the same, then update 
192
	     * to the current only if the key value is lower.
193
	     */
194
	    if (best_mismatch + mepos_penalty <= mbest) {
195
		if (best_mismatch + mepos_penalty < mbest  ||
196
		    (r_has_type(&match.match_key, t_integer) &&
197
		     match.match_key.value.intval > aelt.key.value.intval)) {
198
		    reset_match(&match);
199
		    match.match_key = aelt.key;
200
		    mbest = best_mismatch + mepos_penalty;
201
		}
202
	    }
203
	    /* In case of a tie, see if the new match has priority. */
204
	    for (pi = match.priority; pi > 0;) {
205
		ref pri;
206
 
207
		pi--;
208
		array_get(imemory, ppriority, pi, &pri);
209
		if (obj_eq(imemory, &aelt.key, &pri)) {	/* Yes, higher priority. */
210
		    match.best_key = aelt.key;
211
		    match.priority = pi;
212
		    break;
213
		}
214
	    }
215
no:;
216
	}
217
    }
218
    if (r_has_type(&match.match_key, t_null)) {
219
	make_false(op - 3);
220
	pop(3);
221
    } else {
222
	if (r_has_type(&match.best_key, t_null))
223
	    op[-3] = match.match_key;
224
	else
225
	    op[-3] = match.best_key;
226
	make_true(op - 2);
227
	pop(2);
228
    }
229
    return 0;
230
}
231
 
232
/* [<req_x> <req_y>] [<med_x0> <med_y0> (<med_x1> <med_y1> | )]
233
 *     <policy> <orient|null> <roll> <matrix|null> .matchpagesize
234
 *   <matrix|null> <med_x> <med_y> true   -or-  false
235
 */
236
private int
237
zmatchpagesize(i_ctx_t *i_ctx_p)
238
{
239
    os_ptr op = osp;
240
    gs_matrix mat;
241
    float ignore_mismatch = (float)max_long;
242
    gs_point media_size;
243
    int orient;
244
    bool roll;
245
    int code;
246
 
247
    check_type(op[-3], t_integer);
248
    if (r_has_type(op - 2, t_null))
249
	orient = -1;
250
    else {
251
	check_int_leu(op[-2], 3);
252
	orient = (int)op[-2].value.intval;
253
    }
254
    check_type(op[-1], t_boolean);
255
    roll = op[-1].value.boolval;
256
    code = zmatch_page_size(imemory, 
257
			    op - 5, op - 4, (int)op[-3].value.intval,
258
			    orient, roll,
259
			    &ignore_mismatch, &mat, &media_size);
260
    switch (code) {
261
	default:
262
	    return code;
263
	case 0:
264
	    make_false(op - 5);
265
	    pop(5);
266
	    break;
267
	case 1:
268
	    code = write_matrix(op, &mat);
269
	    if (code < 0 && !r_has_type(op, t_null))
270
		return code;
271
	    op[-5] = *op;
272
	    make_real(op - 4, media_size.x);
273
	    make_real(op - 3, media_size.y);
274
	    make_true(op - 2);
275
	    pop(2);
276
	    break;
277
    }
278
    return 0;
279
}
280
/* Match the PageSize.  See below for details. */
281
private int
282
match_page_size(const gs_point * request,
283
			     const gs_rect * medium,
284
			     int policy, int orient, bool roll,
285
			     float *best_mismatch, gs_matrix * pmat,
286
			     gs_point * pmsize);
287
private int
288
zmatch_page_size(const gs_memory_t *mem, const ref * pvreq, const ref * pvmed,
289
		 int policy, int orient, bool roll,
290
		 float *best_mismatch, gs_matrix * pmat, gs_point * pmsize)
291
{
292
    uint nr, nm;
293
    int code;
294
    ref rv[6];
295
 
296
    /* array_get checks array types and size. */
297
    /* This allows normal or packed arrays to be used */
298
    if ((code = array_get(mem, pvreq, 1, &rv[1])) < 0)
299
        return_error(code);
300
    nr = r_size(pvreq);
301
    if ((code = array_get(mem, pvmed, 1, &rv[3])) < 0)
302
        return_error(code);
303
    nm = r_size(pvmed);
304
    if (!((nm == 2 || nm == 4) && (nr == 2 || nr == nm)))
305
	return_error(e_rangecheck);
306
    {
307
	uint i;
308
	double v[6];
309
	int code;
310
 
311
	array_get(mem, pvreq, 0, &rv[0]);
312
	for (i = 0; i < 4; ++i)
313
	    array_get(mem,pvmed, i % nm, &rv[i + 2]);
314
	if ((code = num_params(rv + 5, 6, v)) < 0)
315
	    return code;
316
	{
317
	    gs_point request;
318
	    gs_rect medium;
319
 
320
	    request.x = v[0], request.y = v[1];
321
	    medium.p.x = v[2], medium.p.y = v[3],
322
		medium.q.x = v[4], medium.q.y = v[5];
323
	    return match_page_size(&request, &medium, policy, orient,
324
				   roll, best_mismatch, pmat, pmsize);
325
	}
326
    }
327
}
328
/*
329
 * Match a requested PageSize with the PageSize of a medium.  The medium
330
 * may specify either a single value [mx my] or a range
331
 * [mxmin mymin mxmax mymax]; matching means equality or inclusion
332
 * to within a tolerance of 5, possibly swapping the requested X and Y.
333
 * Take the Policies value into account, keeping track of the discrepancy
334
 * if needed.  When a match is found, also return the matrix to be
335
 * concatenated after setting up the default matrix, and the actual
336
 * media size.
337
 *
338
 * NOTE: The algorithm here doesn't work properly for variable-size media
339
 * when the match isn't exact.  We'll fix it if we ever need to.
340
 */
341
private void make_adjustment_matrix(const gs_point * request,
342
				    const gs_rect * medium,
343
				    gs_matrix * pmat,
344
				    bool scale, int rotate);
345
private int
346
match_page_size(const gs_point * request, const gs_rect * medium, int policy,
347
		int orient, bool roll, float *best_mismatch, gs_matrix * pmat,
348
		gs_point * pmsize)
349
{
350
    double rx = request->x, ry = request->y;
351
 
352
    if ((rx <= 0) || (ry <= 0))
353
	return_error(e_rangecheck);
354
    if (policy == 7) {
355
		/* (Adobe) hack: just impose requested values */
356
	*best_mismatch = 0;
357
	gs_make_identity(pmat);
358
	*pmsize = *request;
359
    } else {
360
        int fit_direct  = rx - medium->p.x >= -5 && rx - medium->q.x <= 5 
361
                       && ry - medium->p.y >= -5 && ry - medium->q.y <= 5;
362
	int fit_rotated = rx - medium->p.y >= -5 && rx - medium->q.y <= 5 
363
                       && ry - medium->p.x >= -5 && ry - medium->q.x <= 5;
364
 
365
	/* Fudge matches from a non-standard page size match (4 element array) */
366
	/* as worse than an exact match from a standard (2 element array), but */
367
	/* better than for a rotated match to a standard pagesize. This should */
368
	/* prevent rotation unless we have to (particularly for raster file    */
369
	/* formats like TIFF, JPEG, PNG, PCX, BMP, etc. and also should allow  */
370
	/* exact page size specification when there is a range PageSize entry. */
371
	/* As the comment in gs_setpd.ps says "Devices that care will provide  */
372
	/* a real InputAttributes dictionary (most without a range pagesize)   */
373
        if ( fit_direct && fit_rotated) {
374
	    make_adjustment_matrix(request, medium, pmat, false, orient < 0 ? 0 : orient);
375
	    if (medium->p.x < medium->q.x || medium->p.y < medium->q.y)
376
		*best_mismatch = (float)0.001;		/* fudge a match to a range as a small number */
377
	    else	/* should be 0 for an exact match */
378
	        *best_mismatch = fabs((rx - medium->p.x) * (medium->q.x - rx)) +
379
	    			fabs((ry - medium->p.y) * (medium->q.y - ry));
380
        } else if ( fit_direct ) {
381
            int rotate = orient < 0 ? 0 : orient;
382
 
383
	    make_adjustment_matrix(request, medium, pmat, false, (rotate + 1) & 2);
384
	    *best_mismatch = fabs((medium->p.x - rx) * (medium->q.x - rx)) +
385
	    			fabs((medium->p.y - ry) * (medium->q.y - ry)) + 
386
            			    (pmat->xx == 0.0 || (rotate & 1) == 1 ? 0.01 : 0);	/* rotated */
387
        } else if ( fit_rotated ) {
388
            int rotate = (orient < 0 ? 1 : orient);
389
 
390
	    make_adjustment_matrix(request, medium, pmat, false, rotate | 1);
391
	    *best_mismatch = fabs((medium->p.y - rx) * (medium->q.y - rx)) +
392
	    			fabs((medium->p.x - ry) * (medium->q.x - ry)) + 
393
            			    (pmat->xx == 0.0 || (rotate & 1) == 1 ? 0.01 : 0);	/* rotated */
394
        } else {
395
	    int rotate =
396
		(orient >= 0 ? orient :
397
		 (rx < ry) ^ (medium->q.x < medium->q.y));
398
	    bool larger =
399
		(rotate & 1 ? medium->q.y >= rx && medium->q.x >= ry :
400
		 medium->q.x >= rx && medium->q.y >= ry);
401
	    bool adjust = false;
402
	    float mismatch = medium->q.x * medium->q.y - rx * ry;
403
 
404
	    switch (policy) {
405
	        default:		/* exact match only */
406
		    return 0;
407
	        case 3:		/* nearest match, adjust */
408
		    adjust = true;
409
	        case 5:		/* nearest match, don't adjust */
410
		    if (fabs(mismatch) >= fabs(*best_mismatch))
411
		        return 0;
412
		    break;
413
	        case 4:		/* next larger match, adjust */
414
		    adjust = true;
415
	        case 6:		/* next larger match, don't adjust */
416
		    if (!larger || mismatch >= *best_mismatch)
417
		        return 0;
418
		    break;
419
	    }
420
	    if (adjust)
421
	        make_adjustment_matrix(request, medium, pmat, !larger, rotate);
422
	    else {
423
	        gs_rect req_rect;
424
                if(rotate & 1) { 
425
                    req_rect.p.x = ry;
426
                    req_rect.p.y = rx;
427
                } else {
428
                    req_rect.p.x = rx;
429
                    req_rect.p.y = ry;
430
                }
431
	        req_rect.q = req_rect.p;
432
	        make_adjustment_matrix(request, &req_rect, pmat, false, rotate);
433
	    }
434
	    *best_mismatch = fabs(mismatch);
435
        }
436
        if (pmat->xx == 0) {	/* Swap request X and Y. */
437
	    double temp = rx;
438
 
439
	    rx = ry, ry = temp;
440
        }
441
#define ADJUST_INTO(req, mmin, mmax)\
442
      (req < mmin ? mmin : req > mmax ? mmax : req)
443
        pmsize->x = ADJUST_INTO(rx, medium->p.x, medium->q.x);
444
        pmsize->y = ADJUST_INTO(ry, medium->p.y, medium->q.y);
445
#undef ADJUST_INTO
446
    }
447
    return 1;
448
}
449
/*
450
 * Compute the adjustment matrix for scaling and/or rotating the page
451
 * to match the medium.  If the medium is completely flexible in a given
452
 * dimension (e.g., roll media in one dimension, or displays in both),
453
 * we must adjust its size in that dimension to match the request.
454
 * We recognize this by an unreasonably small medium->p.{x,y}.
455
 */
456
private void 
457
make_adjustment_matrix(const gs_point * request, const gs_rect * medium,
458
		       gs_matrix * pmat, bool scale, int rotate)
459
{
460
    double rx = request->x, ry = request->y;
461
    double mx = medium->q.x, my = medium->q.y;
462
 
463
    /* Rotate the request if necessary. */ 
464
    if (rotate & 1) {
465
	double temp = rx;
466
 
467
	rx = ry, ry = temp;
468
    }
469
    /* If 'medium' is flexible, adjust 'mx' and 'my' towards 'rx' and 'ry',
470
       respectively. Note that 'mx' and 'my' have just acquired the largest
471
       permissible value, medium->q. */
472
    if (medium->p.x < mx) {	/* non-empty width range */
473
	if (rx < medium->p.x)
474
	    mx = medium->p.x;	/* use minimum of the range */
475
	else if (rx < mx)
476
	    mx = rx;		/* fits */
477
		/* else leave mx == medium->q.x, i.e., the maximum */
478
    }
479
    if (medium->p.y < my) {	/* non-empty height range */
480
	if (ry < medium->p.y)
481
	    my = medium->p.y;	/* use minimum of the range */
482
	else if (ry < my)
483
	    my = ry;		/* fits */
484
	    /* else leave my == medium->q.y, i.e., the maximum */
485
    }
486
 
487
    /* Translate to align the centers. */ 
488
    gs_make_translation(mx / 2, my / 2, pmat);
489
 
490
    /* Rotate if needed. */ 
491
    if (rotate)
492
	gs_matrix_rotate(pmat, 90.0 * rotate, pmat);
493
 
494
    /* Scale if needed. */ 
495
    if (scale) {
496
	double xfactor = mx / rx;
497
	double yfactor = my / ry;
498
	double factor = min(xfactor, yfactor);
499
 
500
	if (factor < 1)
501
	    gs_matrix_scale(pmat, factor, factor, pmat);
502
    }
503
    /* Now translate the origin back, */ 
504
    /* using the original, unswapped request. */ 
505
    gs_matrix_translate(pmat, -request->x / 2, -request->y / 2, pmat);
506
}
507
#undef MIN_MEDIA_SIZE
508
 
509
/* ------ Initialization procedure ------ */
510
 
511
const op_def zmedia2_l2_op_defs[] =
512
{
513
    op_def_begin_level2(),
514
    {"4.matchmedia", zmatchmedia},
515
    {"6.matchpagesize", zmatchpagesize},
516
    op_def_end(0)
517
};