summaryrefslogtreecommitdiffstats
path: root/src/interfaces/driver.php
blob: cb8857a94b8907299c3df93e9e9fb90dc5693da3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
<?php
/**
 * File containing the abstract ezcGraphDriver class
 *
 * @package Graph
 * @version //autogentag//
 * @copyright Copyright (C) 2005-2007 eZ systems as. All rights reserved.
 * @license http://ez.no/licenses/new_bsd New BSD License
 */
/**
 * Abstract class to be extended for ezcGraph output drivers.
 *
 * @package Graph
 */
abstract class ezcGraphDriver
{
    /**
     * Drveroptions
     * 
     * @var ezcDriverOptions
     */
    protected $options;
    
    /**
     * Constructor
     * 
     * @param array $options Default option array
     * @return void
     * @ignore
     */
    abstract public function __construct( array $options = array() );
    
    /**
     * Options write access
     * 
     * @throws ezcBasePropertyNotFoundException
     *          If Option could not be found
     * @throws ezcBaseValueException
     *          If value is out of range
     * @param mixed $propertyName   Option name
     * @param mixed $propertyValue  Option value;
     * @return mixed
     * @ignore
     */
    public function __set( $propertyName, $propertyValue ) 
    {
        switch ( $propertyName ) {
            case 'options':
                if ( $propertyValue instanceof ezcGraphDriverOptions )
                {
                    $this->options = $propertyValue;
                }
                else
                {
                    throw new ezcBaseValueException( "options", $propertyValue, "instanceof ezcGraphOptions" );
                }
            default:
                throw new ezcBasePropertyNotFoundException( $propertyName );
                break;
        }
    }

    /**
     * __get 
     * 
     * @param mixed $propertyName 
     * @throws ezcBasePropertyNotFoundException
     *          If a the value for the property options is not an instance of
     * @return mixed
     * @ignore
     */
    public function __get( $propertyName )
    {
        switch ( $propertyName )
        {
            case 'options':
                return $this->options;
            default:
                throw new ezcBasePropertyNotFoundException( $propertyName );
        }
    }

    /**
     * Reduces the size of a polygon
     *
     * The method takes a polygon defined by a list of points and reduces its 
     * size by moving all lines to the middle by the given $size value.
     *
     * The detection of the inner side of the polygon depends on the angle at 
     * each edge point. This method will always work for 3 edged polygones, 
     * because the smaller angle will always be on the inner side. For 
     * polygons with more then 3 edges this method may fail. For ezcGraph this
     * is a valid simplification, because we do not have any polygones which 
     * have an inner angle >= 180 degrees.
     * 
     * @param array( ezcGraphCoordinate ) $points 
     * @param float $size 
     * @throws ezcGraphReducementFailedException
     * @return array( ezcGraphCoordinate )
     */
    protected function reducePolygonSize( array $points, $size )
    {
        $pointCount = count( $points );

        // Build normalized vectors between polygon edge points
        $vectors = array();
        for ( $i = 0; $i < $pointCount; ++$i )
        {
            $nextPoint = ( $i + 1 ) % $pointCount;
            $vectors[$i] = ezcGraphVector::fromCoordinate( $points[$nextPoint] )
                            ->sub( $points[$i] );

            // Throw exception if polygon is too small to reduce
            if ( $vectors[$i]->length() < $size )
            {
                throw new ezcGraphReducementFailedException();
            }
            $vectors[$i]->unify();

            // Remove point from list if it the same as the next point
            if ( ( $vectors[$i]->x == $vectors[$i]->y ) && ( $vectors[$i]->x == 0 ) )
            {
                $pointCount--;
                if ( $i === 0 ) 
                {
                    $points = array_slice( $points, $i + 1 );
                }
                else
                {
                    $points = array_merge(
                        array_slice( $points, 0, $i ),
                        array_slice( $points, $i + 1 )
                    );
                }
                $i--;
            }
        }

        // Remove vectors and appendant point, if local angle equals zero 
        // dergrees.
        for ( $i = 0; $i < $pointCount; ++$i ) 
        {
            $nextPoint = ( $i + 1 ) % $pointCount;

            if ( ( abs( $vectors[$i]->x - $vectors[$nextPoint]->x ) < .0001 ) &&
                 ( abs( $vectors[$i]->y - $vectors[$nextPoint]->y ) < .0001 ) )
            {
                $pointCount--;

                $points = array_merge(
                    array_slice( $points, 0, $i + 1 ),
                    array_slice( $points, $i + 2 )
                );
                $vectors = array_merge(
                    array_slice( $vectors, 0, $i + 1 ),
                    array_slice( $vectors, $i + 2 )
                );
                $i--;
            }
        }

        // No reducements for lines
        if ( $pointCount <= 2 )
        {
            return $points;
        }

        // Determine one of the angles - we need to know where the smaller
        // angle is, to determine if the inner side of the polygon is on
        // the left or right hand.
        // 
        // This is a valid simplification for ezcGraph(, for now).
        // 
        // The sign of the scalar products results indicates on which site
        // the smaller angle is, when comparing the orthogonale vector of 
        // one of the vectors with the other. Why? .. use pen and paper ..
        // 
        // It is sufficant to do this once before iterating over the points, 
        // because the inner side of the polygon is on the same side of the 
        // point for each point.
        $last = 0;
        $next = 1;

        $sign = ( 
                -$vectors[$last]->y * $vectors[$next]->x +
                $vectors[$last]->x * $vectors[$next]->y 
            ) < 0 ? 1 : -1;

        // Move points to center
        $newPoints = array();
        for ( $i = 0; $i < $pointCount; ++$i )
        {
            $last = $i;
            $next = ( $i + 1 ) % $pointCount;

            // Orthogonal vector with direction based on the side of the inner
            // angle
            $v = clone $vectors[$next];
            if ( $sign > 0 )
            {
                $v->rotateCounterClockwise()->scalar( $size );
            }
            else
            {
                $v->rotateClockwise()->scalar( $size );
            }

            // get last vector not pointing in reverse direction
            $lastVector = clone $vectors[$last];
            $lastVector->scalar( -1 );

            // Calculate new point: Move point to the center site of the 
            // polygon using the normalized orthogonal vectors next to the 
            // point and the size as distance to move.
            // point + v + size / tan( angle / 2 ) * startVector
            $newPoint = clone $vectors[$next];
            $newPoints[$next] = 
                $v  ->add( 
                        $newPoint
                            ->scalar( 
                                $size / 
                                tan( 
                                    $lastVector->angle( $vectors[$next] ) / 2
                                ) 
                            ) 
                    )
                    ->add( $points[$next] );
        }

        return $newPoints;
    }

    /**
     * Reduce the size of an ellipse
     *
     * The method returns a the edgepoints and angles for an ellipse where all 
     * borders are moved to the inner side of the ellipse by the give $size 
     * value.
     *
     * The method returns an 
     * array (
     *      'center' => (ezcGraphCoordinate) New center point,
     *      'start' => (ezcGraphCoordinate) New outer start point,
     *      'end' => (ezcGraphCoordinate) New outer end point,
     * )
     * 
     * @param ezcGraphCoordinate $center 
     * @param mixed $startAngle 
     * @param mixed $endAngle 
     * @param mixed $size 
     * @throws ezcGraphReducementFailedException
     * @return array
     */
    protected function reduceEllipseSize( ezcGraphCoordinate $center, $width, $height, $startAngle, $endAngle, $size )
    {
        $oldStartPoint = new ezcGraphVector(
            $width * cos( deg2rad( $startAngle ) ) / 2,
            $height * sin( deg2rad( $startAngle ) ) / 2
        );

        $oldEndPoint = new ezcGraphVector(
            $width * cos( deg2rad( $endAngle ) ) / 2,
            $height * sin( deg2rad( $endAngle ) ) / 2
        );

        // We always need radian values..
        $startAngle = deg2rad( $startAngle );
        $endAngle = deg2rad( $endAngle );

        // Calculate normalized vectors for the lines spanning the ellipse
        $unifiedStartVector = ezcGraphVector::fromCoordinate( $oldStartPoint )->unify();
        $unifiedEndVector = ezcGraphVector::fromCoordinate( $oldEndPoint )->unify();
        $startVector = ezcGraphVector::fromCoordinate( $oldStartPoint );
        $endVector = ezcGraphVector::fromCoordinate( $oldEndPoint );

        $oldStartPoint->add( $center );
        $oldEndPoint->add( $center );

        // Use orthogonal vectors of normalized ellipse spanning vectors to 
        $v = clone $unifiedStartVector;
        $v->rotateClockwise()->scalar( $size );

        // calculate new center point
        // center + v + size / tan( angle / 2 ) * startVector
        $centerMovement = clone $unifiedStartVector;
        $newCenter = $v->add( $centerMovement->scalar( $size / tan( ( $endAngle - $startAngle ) / 2 ) ) )->add( $center );

        // Test if center is still inside the ellipse, otherwise the sector 
        // was to small to be reduced
        $innerBoundingBoxSize = 0.7 * min( $width, $height );
        if ( ( $newCenter->x < ( $center->x + $innerBoundingBoxSize ) ) &&
             ( $newCenter->x > ( $center->x - $innerBoundingBoxSize ) ) &&
             ( $newCenter->y < ( $center->y + $innerBoundingBoxSize ) ) &&
             ( $newCenter->y > ( $center->y - $innerBoundingBoxSize ) ) )
        {
            // Point is in inner bounding box -> everything is OK
        }
        elseif ( ( $newCenter->x < ( $center->x - $width ) ) ||
                 ( $newCenter->x > ( $center->x + $width ) ) ||
                 ( $newCenter->y < ( $center->y - $height ) ) ||
                 ( $newCenter->y > ( $center->y + $height ) ) )
        {
            // Quick bounding box check
            throw new ezcGraphReducementFailedException();
        }
        else
        {
            // Perform exact check
            $distance = new ezcGraphVector(
                $newCenter->x - $center->x,
                $newCenter->y - $center->y
            );

            // Convert elipse to circle for correct angle calculation
            $direction = clone $distance;
            $direction->y *= ( $width / $height );
            $angle = $direction->angle( new ezcGraphVector( 0, 1 ) );

            $outerPoint = new ezcGraphVector(
                sin( $angle ) * $width,
                cos( $angle ) * $height
            );

            // Point is not in ellipse any more
            if ( $distance->x > $outerPoint->x )
            {
                throw new ezcGraphReducementFailedException();
            }
        }

        // Use start spanning vector and its orthogonal vector to calculate 
        // new start point
        $newStartPoint = clone $oldStartPoint;

        // Create tangent vector from tangent angle
        
        // Ellipse tangent factor
        $ellipseTangentFactor = sqrt(
            pow( $height, 2 ) *
                pow( cos( $startAngle ), 2 ) +
            pow( $width, 2 ) *
                pow( sin( $startAngle ), 2 )
        );
        $ellipseTangentVector = new ezcGraphVector(
            $width * -sin( $startAngle ) / $ellipseTangentFactor,
            $height * cos( $startAngle ) / $ellipseTangentFactor
        );

        // Reverse spanning vector
        $innerVector = clone $unifiedStartVector;
        $innerVector->scalar( $size )->scalar( -1 );

        $newStartPoint->add( $innerVector)->add( $ellipseTangentVector->scalar( $size ) );
        $newStartVector = clone $startVector;
        $newStartVector->add( $ellipseTangentVector );

        // Use end spanning vector and its orthogonal vector to calculate 
        // new end point
        $newEndPoint = clone $oldEndPoint;

        // Create tangent vector from tangent angle
        
        // Ellipse tangent factor
        $ellipseTangentFactor = sqrt(
            pow( $height, 2 ) *
                pow( cos( $endAngle ), 2 ) +
            pow( $width, 2 ) *
                pow( sin( $endAngle ), 2 )
        );
        $ellipseTangentVector = new ezcGraphVector(
            $width * -sin( $endAngle ) / $ellipseTangentFactor,
            $height * cos( $endAngle ) / $ellipseTangentFactor
        );

        // Reverse spanning vector
        $innerVector = clone $unifiedEndVector;
        $innerVector->scalar( $size )->scalar( -1 );

        $newEndPoint->add( $innerVector )->add( $ellipseTangentVector->scalar( $size )->scalar( -1 ) );
        $newEndVector = clone $endVector;
        $newEndVector->add( $ellipseTangentVector );

        return array(
            'center' => $newCenter,
            'start' => $newStartPoint,
            'end' => $newEndPoint,
            'startAngle' => rad2deg( $startAngle + $startVector->angle( $newStartVector ) ),
            'endAngle' => rad2deg( $endAngle - $endVector->angle( $newEndVector ) ),
        );
    }

    /**
     * Draws a single polygon. 
     * 
     * @param array $points Point array
     * @param ezcGraphColor $color Polygon color
     * @param mixed $filled Filled
     * @param float $thickness Line thickness
     * @return void
     */
    abstract public function drawPolygon( array $points, ezcGraphColor $color, $filled = true, $thickness = 1 );
    
    /**
     * Draws a line 
     * 
     * @param ezcGraphCoordinate $start Start point
     * @param ezcGraphCoordinate $end End point
     * @param ezcGraphColor $color Line color
     * @param float $thickness Line thickness
     * @return void
     */
    abstract public function drawLine( ezcGraphCoordinate $start, ezcGraphCoordinate $end, ezcGraphColor $color, $thickness = 1 );
    
    /**
     * Returns boundings of text depending on the available font extension
     * 
     * @param float $size Textsize
     * @param ezcGraphFontOptions $font Font
     * @param string $text Text
     * @return ezcGraphBoundings Boundings of text
     */
    abstract protected function getTextBoundings( $size, ezcGraphFontOptions $font, $text );
    
    /**
     * Test if string fits in a box with given font size
     *
     * This method splits the text up into tokens and tries to wrap the text
     * in an optimal way to fit in the Box defined by width and height.
     * 
     * If the text fits into the box an array with lines is returned, which 
     * can be used to render the text later:
     *  array(
     *      // Lines
     *      array( 'word', 'word', .. ),
     *  )
     * Otherwise the function will return false.
     *
     * @param string $string Text
     * @param ezcGraphCoordinate $position Topleft position of the text box
     * @param float $width Width of textbox
     * @param float $height Height of textbox
     * @param int $size Fontsize
     * @return mixed Array with lines or false on failure
     */
    protected function testFitStringInTextBox( $string, ezcGraphCoordinate $position, $width, $height, $size )
    {
        // Tokenize String
        $tokens = preg_split( '/\s+/', $string );
        $initialHeight = $height;

        $lines = array( array() );
        $line = 0;
        foreach ( $tokens as $nr => $token )
        {
            // Add token to tested line
            $selectedLine = $lines[$line];
            $selectedLine[] = $token;

            $boundings = $this->getTextBoundings( $size, $this->options->font, implode( ' ', $selectedLine ) );
            // Check if line is too long
            if ( $boundings->width > $width )
            {
                if ( count( $selectedLine ) == 1 )
                {
                    // Return false if one single word does not fit into one line
                    // Scale down font size to fit this word in one line
                    return $width / $boundings->width;
                }
                else
                {
                    // Put word in next line instead and reduce available height by used space
                    $lines[++$line][] = $token;
                    $height -= $size * ( 1 + $this->options->lineSpacing );
                }
            }
            else
            {
                // Everything is ok - put token in this line
                $lines[$line][] = $token;
            }
            
            // Return false if text exceeds vertical limit
            if ( $size > $height )
            {
                return 1;
            }
        }

        // Check width of last line
        $boundings = $this->getTextBoundings( $size, $this->options->font, implode( ' ', $lines[$line] ) );
        if ( $boundings->width > $width )
        {
            return 1;
        }

        // It seems to fit - return line array
        return $lines;
    }

    /**
     * Writes text in a box of desired size
     * 
     * @param string $string Text
     * @param ezcGraphCoordinate $position Top left position
     * @param float $width Width of text box
     * @param float $height Height of text box
     * @param int $align Alignement of text
     * @param ezcGraphRotation $rotation
     * @return void
     */
    abstract public function drawTextBox( $string, ezcGraphCoordinate $position, $width, $height, $align, ezcGraphRotation $rotation = null );
    
    /**
     * Draws a sector of cirlce
     * 
     * @param ezcGraphCoordinate $center Center of circle
     * @param mixed $width Width
     * @param mixed $height Height
     * @param mixed $startAngle Start angle of circle sector
     * @param mixed $endAngle End angle of circle sector
     * @param ezcGraphColor $color Color
     * @param mixed $filled Filled
     * @return void
     */
    abstract public function drawCircleSector( ezcGraphCoordinate $center, $width, $height, $startAngle, $endAngle, ezcGraphColor $color, $filled = true );
    
    /**
     * Draws a circular arc
     * 
     * @param ezcGraphCoordinate $center Center of ellipse
     * @param integer $width Width of ellipse
     * @param integer $height Height of ellipse
     * @param integer $size Height of border
     * @param float $startAngle Starting angle of circle sector
     * @param float $endAngle Ending angle of circle sector
     * @param ezcGraphColor $color Color of Border
     * @return void
     */
    abstract public function drawCircularArc( ezcGraphCoordinate $center, $width, $height, $size, $startAngle, $endAngle, ezcGraphColor $color, $filled = true );
    
    /**
     * Draw circle 
     * 
     * @param ezcGraphCoordinate $center Center of ellipse
     * @param mixed $width Width of ellipse
     * @param mixed $height height of ellipse
     * @param ezcGraphColor $color Color
     * @param mixed $filled Filled
     * @return void
     */
    abstract public function drawCircle( ezcGraphCoordinate $center, $width, $height, ezcGraphColor $color, $filled = true );
    
    /**
     * Draw an image 
     * 
     * @param mixed $file Image file
     * @param ezcGraphCoordinate $position Top left position
     * @param mixed $width Width of image in destination image
     * @param mixed $height Height of image in destination image
     * @return void
     */
    abstract public function drawImage( $file, ezcGraphCoordinate $position, $width, $height );

    /**
     * Return mime type for current image format
     * 
     * @return string
     */
    abstract public function getMimeType();

    /**
     * Render image directly to output
     *
     * The method renders the image directly to the standard output. You 
     * normally do not want to use this function, because it makes it harder 
     * to proper cache the generated graphs.
     * 
     * @return void
     */
    public function renderToOutput()
    {
        header( 'Content-Type: ' . $this->getMimeType() );
        $this->render( 'php://output' );
    }

    /**
     * Finally save image
     * 
     * @param string $file Destination filename
     * @return void
     */
    abstract public function render( $file );
}

?>
OpenPOWER on IntegriCloud