summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/context/ruby/graphics/gs.rb
blob: cb3d016f4cbd50a1622554eefac71f84f1bff121 (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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# module    : graphics/gs
# copyright : PRAGMA Advanced Document Engineering
# version   : 2002-2005
# author    : Hans Hagen
#
# project   : ConTeXt / eXaMpLe
# concept   : Hans Hagen
# info      : j.hagen@xs4all.nl
# www       : www.pragma-ade.com

# ['base/variables','../variables','variables'].each do |r| begin require r ; rescue Exception ; else break ; end ; end
# ['base/system',   '../system',   'system'   ].each do |r| begin require r ; rescue Exception ; else break ; end ; end

require 'base/variables'
require 'base/system'
require 'ftools'

class GhostScript

    include Variables

    @@pdftrimwhite = 'pdftrimwhite.pl'

    @@pstopdfoptions = [
        'AntiAliasColorImages',
        'AntiAliasGrayImages',
        'AntiAliasMonoImages',
        'ASCII85EncodePages',
        'AutoFilterColorImages',
        'AutoFilterGrayImages',
        'AutoPositionEPSFiles',
        'AutoRotatePages',
        'Binding',
        'ColorConversionStrategy',
        'ColorImageDepth',
        'ColorImageDownsampleThreshold',
        'ColorImageDownsampleType',
        'ColorImageFilter',
        'ColorImageResolution',
        'CompatibilityLevel',
        'CompressPages',
        #'ConvertCMYKImagesToRGB', # buggy
        #'ConvertImagesToIndexed', # buggy
        'CreateJobTicket',
        'DetectBlends',
        'DoThumbnails',
        'DownsampleColorImages',
        'DownsampleGrayImages',
        'DownsampleMonoImages',
        'EmbedAllFonts',
        'EncodeColorImages',
        'EncodeGrayImages',
        'EncodeMonoImages',
        'EndPage',
        'FirstPage',
        'GrayImageDepth',
        'GrayImageDownsampleThreshold',
        'GrayImageDownsampleType',
        'GrayImageFilter',
        'GrayImageResolution',
        'MaxSubsetPct',
        'MonoImageDepth',
        'MonoImageDownsampleThreshold',
        'MonoImageDownsampleType',
        'MonoImageFilter',
        'MonoImageResolution',
        'Optimize',
        'ParseDCSComments',
        'ParseDCSCommentsForDocInfo',
        'PreserveCopyPage',
        'PreserveEPSInfo',
        'PreserveHalftoneInfo',
        'PreserveOPIComments',
        'PreserveOverprintSettings',
        'SubsetFonts',
        'UseFlateCompression'
    ]

    @@methods = Hash.new

    @@methods['raw']         = '1'
    @@methods['bound']       = '2'
    @@methods['bounded']     = '2'
    @@methods['crop']        = '3'
    @@methods['cropped']     = '3'
    @@methods['down']        = '4'
    @@methods['downsample']  = '4'
    @@methods['downsampled'] = '4'
    @@methods['simplify']    = '5'
    @@methods['simplified']  = '5'

    @@tempfile    = 'gstemp'
    @@pstempfile  = @@tempfile + '.ps'
    @@pdftempfile = @@tempfile + '.pdf'

    @@bboxspec = '\s*([\-\d\.]+)' + '\s+([\-\d\.]+)'*3

    def initialize(logger=nil)

        unless logger then
            puts('gs class needs a logger')
            exit
        end

        @variables = Hash.new
        @psoptions = Hash.new
        @logger    = logger

        setvariable('profile',    'gsprofile.ini')
        setvariable('pipe',       true)
        setvariable('method',     2)
        setvariable('force',      false)
        setvariable('colormodel', 'cmyk')
        setvariable('inputfile',  '')
        setvariable('outputfile', '')

        @@pstopdfoptions.each do |key|
            @psoptions[key] = ''
        end

        reset

    end

    def reset
        @llx = @lly = @ulx = @uly = 0
        @oldbbox = [@llx,@lly,@urx,@ury]
        @width = @height = @xoffset = @yoffset = @offset = 0
        @rs = Tool.default_line_separator
    end

    def supported?(filename)
        psfile?(filename) || pdffile?(filename)
    end

    def psfile?(filename)
        filename =~ /\.(eps|epsf|ps|ai\d*)$/io
    end

    def pdffile?(filename)
        filename =~ /\.(pdf)$/io
    end

    def setpsoption(key,value)
        @psoptions[key] = value unless value.empty?
    end

    def setdimensions (llx,lly,urx,ury)
        @oldbbox = [llx,lly,urx,ury]
        @llx, @lly = llx.to_f-@offset, lly.to_f-@offset
        @urx, @ury = urx.to_f+@offset, ury.to_f+@offset
        @width,   @height  = @urx - @llx, @ury - @lly
        @xoffset, @yoffset =    0 - @llx,    0 - @lly
    end

    def setoffset (offset=0)
        @offset = offset.to_f
        setdimensions(@llx,@lly,@urx,@ury) if dimensions?
    end

    def resetdimensions
        setdimensions(0,0,0,0)
    end

    def dimensions?
        (@width>0) && (@height>0)
    end

    def convert

        inpfile = getvariable('inputfile')

        if inpfile.empty? then
            report('no inputfile specified')
            return false
        end

        unless FileTest.file?(inpfile) then
            report("unknown input file #{inpfile}")
            return false
        end

        outfile = getvariable('outputfile')

        if outfile.empty? then
            outfile = inpfile
            outfile = outfile.sub(/^.*[\\\/]/,'')
        end

        outfile = outfile.sub(/\.(pdf|eps|ps|ai)/i, "")
        resultfile = outfile + '.pdf'
        setvariable('outputfile', resultfile)

        # flags

        saveprofile(getvariable('profile'))

        begin
            gsmethod = method(getvariable('method')).to_i
            report("conversion method #{gsmethod}")
        rescue
            gsmethod = 1
            report("fallback conversion method #{gsmethod}")
        end

        debug('piping data') if getvariable('pipe')

        ok = false
        begin
            case gsmethod
                when 0, 1 then ok = convertasis(inpfile,resultfile)
                when 2    then ok = convertbounded(inpfile,resultfile)
                when 3    then ok = convertcropped(inpfile,resultfile)
                when 4    then ok = downsample(inpfile,resultfile,'screen')
                when 5    then ok = downsample(inpfile,resultfile,'prepress')
                else report("invalid conversion method #{gsmethod}")
            end
        rescue
            report("job aborted due to some error: #{$!}")
            begin
                File.delete(resultfile) if test(?e,resultfile)
            rescue
                report("unable to delete faulty #{resultfile}")
            end
            ok = false
        ensure
            deleteprofile(getvariable('profile'))
            File.delete(@@pstempfile)  if test(?e,@@pstempfile)
            File.delete(@@pdftempfile) if test(?e,@@pdftempfile)
        end
        return ok
    end

    # private

    def method (str)
        if @@methods.key?(str) then
            @@methods[str]
        else
            str
        end
    end

    def pdfmethod? (str)
        case method(str).to_i
            when 3, 4, 5 then return true
        end
        return false
    end

    def pdfprefix (str)
        case method(str).to_i
            when 4 then return 'lowres-'
            when 5 then return 'normal-'
        end
        return ''
    end

    def psmethod? (str)
        ! pdfmethod?(str)
    end

    def insertprofile (flags)
        for key in flags.keys do
            replacevariable("flag.#{key}", flags[key])
        end
    end

    def deleteprofile (filename)
        begin
            File.delete(filename) if FileTest.file?(filename)
        rescue
        end
    end

    def saveprofile (filename)
        return if filename.empty? || ! (ini = open(filename,"w"))
        @@pstopdfoptions.each do |k|
            str = @psoptions[k]
            # beware, booleans are translated, but so are yes/no which is dangerous
            if str.class == String then
                if ! str.empty? && (str != 'empty') then
                    str.sub!(/(.+)\-/io, '')
                    str = "/" + str unless str =~ /^(true|false|none|[\d\.\-\+]+)$/
                    ini.puts("-d#{k}=#{str}\n")
                end
            end
        end
        ini.close
        debug("gs profile #{filename} saved")
    end

    def gsstream # private
        if getvariable('pipe') then '-' else @@pstempfile end
    end

    def gscolorswitch
        case getvariable('colormodel')
            when 'cmyk' then '-dProcessColorModel=/DeviceCMYK -dColorConversionStrategy=/CMYK '
            when 'rgb'  then '-dProcessColorModel=/DeviceRGB  -dColorConversionStrategy=/RGB '
            when 'gray' then '-dProcessColorModel=/DeviceGRAY -dColorConversionStrategy=/GRAY '
        else
            ''
        end
    end

    def gsdefaults
        defaults = ''
        begin
            defaults << '-dAutoRotatePages=/None ' if @psoptions['AutoRotatePages'].empty?
        rescue
            defaults << '-dAutoRotatePages=/None '
        end
        return defaults
    end

    def convertasis (inpfile, outfile)

        report("converting #{inpfile} as-is")

        @rs = Tool.line_separator(inpfile)
        debug("platform mac") if @rs == "\r"

        arguments = ''
        arguments << "\@gsprofile.ini "
        arguments << "-q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH "
        arguments << "#{gsdefaults} "
        arguments << "#{gscolorswitch} "
        arguments << "-sOutputFile=#{outfile} #{inpfile} -c quit "

        debug("ghostscript: #{arguments}")
        unless ok = System.run('ghostscript',arguments) then
            begin
                report("removing file #{outfile}")
                File.delete(outfile) if FileTest.file?(outfile)
            rescue
                debug("file #{outfile} may be invalid")
            end
        end
        return ok

    end

    def convertbounded(inpfile, outfile)
        report("converting #{inpfile} bounded")
        do_convertbounded(inpfile, outfile)
    end

    def do_convertbounded(inpfile, outfile)

        begin
            return false if FileTest.file?(outfile) && (! File.delete(outfile))
        rescue
            return false
        end

        arguments = ''
        arguments << "\@gsprofile.ini "
        arguments << "-q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH -dSAFER "
        arguments << "#{gscolorswitch} "
        arguments << "#{gsdefaults} "
        arguments << "-sOutputFile=#{outfile} #{gsstream} -c quit "

        debug("ghostscript: #{arguments}")
        debug('opening input file')

        @rs = Tool.line_separator(inpfile)
        debug("platform mac") if @rs == "\r"

        if FileTest.file?(outfile) and not File.writable?(outfile) then
            report("output file cannot be written")
            return false
        elsif not tmp = open(inpfile, 'rb') then
            report("input file cannot be opened")
            return false
        end

        debug('opening pipe/file')

        if getvariable('pipe') then

            return false unless eps = IO.popen(System.command('ghostscript',arguments),'wb')
            debug('piping data')
            unless pipebounded(tmp,eps) then
                debug('something went wrong in the pipe')
                File.delete(outfile) if test(?e,outfile)
            end
            debug('closing pipe')
            eps.close_write

        else

            return false unless eps = File.open(@@pstempfile, 'wb')

            debug('copying data')

            if pipebounded(tmp,eps) then
                eps.close
                debug('processing temp file')
                begin
                    ok = System.run('ghostscript',arguments)
                rescue
                    ok = false
                    # debug("fatal error: #{$!}")
                ensure
                end
            else
                eps.close
                ok = false
            end

            unless ok then
                begin
                    report('no output file due to error')
                    File.delete(outfile) if test(?e,outfile)
                rescue
                    # debug("fatal error: #{$!}")
                    debug('file',outfile,'may be invalid')
                end
            end

            debug('deleting temp file')
            begin
                File.delete(@@pstempfile) if test(?e,@@pstempfile)
            rescue
            end

        end

        tmp.close
        return FileTest.file?(outfile)

    end

    # hm, strange, no execute here, todo ! ! !

    def getdimensions (inpfile)

        # -dEPSFitPage and -dEPSCrop behave weird (don't work)

        arguments = "-sDEVICE=bbox -dSAFER -dNOPAUSE -dBATCH #{inpfile} "

        debug("ghostscript: #{arguments}")

        begin
            bbox = System.run('ghostscript',arguments,true,true)
        rescue
            bbox = ''
        end

        resetdimensions

        debug('bbox spec', bbox)

        if bbox =~ /(Exact|HiRes)BoundingBox:#{@@bboxspec}/moi then
            debug("high res bbox #{$2} #{$3} #{$4} #{$5}")
            setdimensions($2,$3,$4,$5)
        elsif bbox =~ /BoundingBox:#{@@bboxspec}/moi
            debug("low res bbox #{$1} #{$2} #{$3} #{$4}")
            setdimensions($1,$2,$3,$4)
        end

        return dimensions?

    end

    # def convertcropped (inpfile, outfile)
        # report("converting #{inpfile} cropped")
        # do_convertbounded(inpfile, @@pdftempfile)
        # return unless test(?e,@@pdftempfile)
        # arguments = " --offset=#{@offset} #{@@pdftempfile} #{outfile}"
        # report("calling #{@@pdftrimwhite}")
        # unless ok = System.run(@@pdftrimwhite,arguments) then
            # report('cropping failed')
            # begin
                # File.delete(outfile)
            # rescue
            # end
            # begin
                # File.move(@@pdftempfile,outfile)
            # rescue
                # File.copy(@@pdftempfile,outfile)
                # File.delete(@@pdftempfile)
            # end
        # end
        # return ok
    # end

    def convertcropped (inpfile, outfile)
        report("converting #{inpfile} cropped")
        if File.expand_path(inpfile) == File.expand_path(outfile) then
            report("output filename must be different")
        elsif inpfile =~ /\.pdf$/io then
            System.run("pdftops -eps #{inpfile} #{@@pstempfile}")
            if getdimensions(@@pstempfile) then
                report("tight boundingbox found")
            end
            do_convertbounded(@@pstempfile, outfile)
            File.delete(@@pstempfile) if FileTest.file?(@@pstempfile)
        else
            if getdimensions(inpfile) then
                report("tight boundingbox found")
            end
            do_convertbounded(inpfile, outfile)
        end
        resetdimensions
        return true
    end


    def pipebounded (eps, out)

        epsbbox, skip, buffer = false, false, ''

        while str = eps.gets(rs=@rs) do
            if str =~ /^%!PS/oi then
                debug("looks like a valid ps file")
                break
            elsif str =~ /%PDF\-\d+\.\d+/oi then
                debug("looks like a pdf file, so let\'s quit")
                return false
            end
        end

        # why no BeginData check

        eps.rewind

if dimensions? then

        debug('using found boundingbox')

else

        debug('locating boundingbox')
        while str = eps.gets(rs=@rs) do
            case str
                when /^%%Page:/io then
                    break
                when /^%%(Crop|HiResBounding|ExactBounding)Box:#{@@bboxspec}/moi then
                    debug('high res boundingbox found')
                    setdimensions($2,$3,$4,$5)
                    break
                when /^%%BoundingBox:#{@@bboxspec}/moi then
                    debug('low res boundingbox found')
                    setdimensions($1,$2,$3,$4)
            end
        end
        debug('no boundingbox found') if @width == 0

end

        eps.rewind

        while str = eps.gets(rs=@rs) do
            if str.sub!(/^(.*)%!PS/moi, "%!PS") then
                debug("removing pre banner data")
                out.puts(str)
                break
            end
        end

        while str = eps.gets(rs=@rs) do
            if skip then
                skip = false if str =~ /^%+(EndData|EndPhotoshop|BeginProlog).*$/o
                out.puts(str) if $1 == "BeginProlog"
            elsif str =~ /^%(BeginPhotoshop)\:\s*\d+.*$/o then
                skip = true
            elsif str =~ /^%%/mos then
                if ! epsbbox && str =~ /^%%(Page:|EndProlog)/io then
                    out.puts(str) if $1 == "EndProlog"
                    debug('faking papersize')
                    # out.puts("<< /PageSize [#{@width} #{@height}] >> setpagedevice\n")
                    if ! dimensions? then
                        out.puts("<< /PageSize [1 1] >> setpagedevice\n")
                    else
                        out.puts("<< /PageSize [#{@width} #{@height}] >> setpagedevice\n")
                    end
                    out.puts("gsave #{@xoffset} #{@yoffset} translate\n")
                    epsbbox = true
                elsif str =~ /^%%BeginBinary\:\s*\d+\s*$/o then
                    debug('copying binary data')
                    out.puts(str)
                    while str = eps.gets(rs=@rs)
                        if str =~ /^%%EndBinary\s*$/o then
                            out.puts(str)
                        else
                            out.write(str)
                        end
                    end
                elsif str =~ /^%AI9\_PrivateDataBegin/o then
                    debug('ignore private ai crap')
                    break
                elsif str =~ /^%%EOF/o then
                    debug('ignore post eof crap')
                    break
                # elsif str =~ /^%%PageTrailer/o then
                    # debug('ignoring post page trailer crap')
                    # break
                elsif str =~ /^%%Trailer/o then
                    debug('ignoring post trailer crap')
                    break
                elsif str =~ /^%%Creator.*Illustrator.*$/io then
                    debug('getting rid of problematic creator spec')
                    str = "% Creator: Adobe Illustrator ..."
                    out.puts(str)
                elsif str =~ /^%%AI.*(PaperRect|Margin)/io then
                    debug('removing AI paper crap')
                elsif str =~ /^%%AI.*Version.*$/io then
                    debug('removing dangerous version info')
                elsif str =~ /^(%+AI.*Thumbnail.*)$/o then
                    debug('skipping AI thumbnail')
                    skip = true
                else
                    out.puts(str)
                end
            else
                out.puts(str)
            end
        end

        debug('done, sending EOF')

        out.puts "grestore\n%%EOF\n"

        # ok = $? == 0
        # report('process aborted, broken pipe, fatal error') unless ok
        # return ok

resetdimensions

        return true

    end

    def downsample (inpfile, outfile, method='screen')

        # gs <= 8.50

        report("downsampling #{inpfile}")

        doit = true
        unless getvariable('force') then
            begin
                if f = File.open(inpfile) then
                    f.binmode
                    while doit && (data = f.gets) do
                        if data =~ /\/ArtBox\s*\[\s*[\d\.]+\s+[\d\.]+\s+[\d\.]+\s+[\d\.]+\s*\]/io then
                            doit = false
                        end
                    end
                    f.close
                end
            rescue
            end
        end

        if doit then
            arguments = ''
            arguments << "-dPDFSETTINGS=/#{method} -dEmbedAllFonts=true "
            arguments << "#{gscolorswitch} "
            arguments << "#{gsdefaults} "
            arguments << "-q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH -dSAFER "
            arguments << "-sOutputFile=#{outfile} #{inpfile} -c quit "
            unless ok = System.run('ghostscript',arguments) then
                begin
                    File.delete(outfile) if FileTest.file?(outfile)
                    report("removing file #{outfile}")
                rescue
                    debug("file #{outfile} may be invalid")
                end
            end
            return ok
        else
            report("crop problem, straight copying #{inpfile}")
            File.copy(inpfile,outfile)
            return false
        end

    end

end