summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/context/ruby/base/tool.rb
blob: 1f10c955654c4b35d76ca863b0f70b32b6dd7191 (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
# module    : base/tool
# 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

require 'timeout'
require 'socket'
require 'rbconfig'

module Tool

    $constructedtempdir = ''

    def Tool.constructtempdir(create,mainpath='',fallback='')
        begin
            mainpath += '/' unless mainpath.empty?
            timeout(5) do
                begin
                    t = Time.now
                    u = t.usec.to_s % [1..2] [0..3]
                    pth = t.strftime("#{mainpath}%Y%m%d-%H%M%S-#{u}-#{Process.pid}")
                #
                #    problems with 1.9
                #
                #    if pth == $constructedtempdir
                #        # sleep(0.01)
                #        retry
                #    end
                    pth == $constructedtempdir
                #
                    Dir.mkdir(pth) if create
                    $constructedtempdir = pth
                    return pth
                rescue
                    # sleep(0.01)
                    retry
                end
            end
        rescue TimeoutError
            # ok
        rescue
            # ok
        end
        unless fallback.empty?
            begin
                pth = "#{mainpath}#{fallback}"
                mkdir(pth) if create
                $constructedtempdir = path
                return pth
            rescue
                return '.'
            end
        else
            return '.'
        end

    end

    def Tool.findtempdir(*vars)
        constructtempdir(false,*vars)
    end

    def Tool.maketempdir(*vars)
        constructtempdir(true,*vars)
    end

    # print maketempdir + "\n"
    # print maketempdir + "\n"
    # print maketempdir + "\n"
    # print maketempdir + "\n"
    # print maketempdir + "\n"


    def Tool.ruby_platform
        case RUBY_PLATFORM
            when /(mswin|bccwin|mingw|cygwin)/i then 'mswin'
            when /(linux)/i                     then 'linux'
            when /(netbsd|unix)/i               then 'unix'
            when /(darwin|rhapsody|nextstep)/i  then 'macosx'
            else                                     'unix'
        end
    end

    $defaultlineseparator = $/ # $RS in require 'English'

    def Tool.file_platform(filename)

        begin
            if f = open(filename,'rb') then
                str = f.read(4000)
                str.gsub!(/(.*?)\%\!PS/mo, "%!PS") # don't look into preamble crap
                f.close
                nn = str.count("\n")
                nr = str.count("\r")
                if nn>nr then
                    return 2
                elsif nn<nr then
                    return 3
                else
                    return 1
                end
            else
                return 0
            end
        rescue
            return 0
        end

    end

    def Tool.path_separator
        return File::PATH_SEPARATOR
    end

    def Tool.line_separator(filename)

        case file_platform(filename)
            when 1 then return $defaultlineseparator
            when 2 then return "\n"
            when 3 then return "\r"
            else        return $defaultlineseparator
        end

    end

    def Tool.default_line_separator
        $defaultlineseparator
    end

    def Tool.simplefilename(old)

        return old # too fragile

        return old if not FileTest.file?(old)

        new = old.downcase
        new.gsub!(/[^A-Za-z0-9\_\-\.\\\/]/o) do # funny chars
            '-'
        end
        if old =~ /[a-zA-Z]\:/o
            # seems like we have a dos/windows drive prefix, so roll back
            new.sub!(/^(.)\-/) do
                $1 + ':'
            end
        end
        # fragile for a.b.c.d.bla-bla.e.eps
        # new.gsub!(/(.+?)\.(.+?)(\..+)$/o)  do # duplicate .
            # $1 + '-' + $2 + $3
        # end
        new.gsub!(/\-+/o)                  do # duplicate -
            '-'
        end
        new

    end

    if RbConfig::CONFIG['host_os'] =~ /mswin/ then

        require 'Win32API'

        GetShortPathName = Win32API.new('kernel32', 'GetShortPathName', ['P','P','N'], 'N')
        GetLongPathName = Win32API.new('kernel32', 'GetLongPathName', ['P','P','N'], 'N')

        def Tool.dowith_pathname (filename,filemethod)
            filename.gsub!(/\\/o,'/')
            case filename
                when /\;/o then
                    # could be a path spec
                    return filename
                when /\s+/o then
                    # danger lurking
                    buffer = ' ' * 260
                    length = filemethod.call(filename,buffer,buffer.size)
                    if length>0 then
                        return buffer.slice(0..length-1)
                    else
                        # when the path or file does not exist, nothing is returned
                        # so we try to handle the path separately from the basename
                        basename = File.basename(filename)
                        pathname = File.dirname(filename)
                        length = filemethod.call(pathname,buffer,260)
                        if length>0 then
                            return buffer.slice(0..length-1) + '/' + basename
                        else
                            return filename
                        end
                    end
                else
                    # no danger
                    return filename
            end
        end

        def Tool.shortpathname(filename)
            dowith_pathname(filename,GetShortPathName)
        end

        def Tool.longpathname(filename)
            dowith_pathname(filename,GetLongPathName)
        end

    else

        def Tool.shortpathname(filename)
            filename
        end

        def Tool.longpathname(filename)
            filename
        end

    end

    # print shortpathname("C:/Program Files/ABBYY FineReader 6.0/matrix.str")+ "!\n"
    # print shortpathname("C:/Program Files/ABBYY FineReader 6.0/matrix.strx")+ "!\n"

    def Tool.checksuffix(old)

        return old unless FileTest.file?(old)

        new = old

        unless new =~ /\./io # no suffix
            f = open(filename,'rb')
            if str = f.gets
                case str
                    when /^\%\!PS/io
                        # logging.report(filename, 'analyzed as EPS')
                        new = new + '.eps'
                    when /^\%PDF/io
                        # logging.report(filename, 'analyzed as PDF')
                        new = new + '.pdf'
                    else
                        # logging.report(filename, 'fallback as TIF')
                        new = new + '.tif'
                end
            end
            f.close
        end

        new.sub!(/\.jpeg$/io) do
            '.jpg'
        end
        new.sub!(/\.tiff$/io) do
            '.tif'
        end
        new.sub!(/\.ai$/io) do
            '.eps'
        end
        new.sub!(/\.ai([a-z0-9]*)$/io) do
            '-' + $1 + '.eps'
        end
        new

    end

    def Tool.cleanfilename(old,logging=nil)

        return old if not FileTest.file?(old)

        new = checksuffix(simplefilename(old))
        unless new == old
            begin # bugged, should only be name, not path
                File.rename(old,new)
                logging.report("renaming fuzzy name #{old} to #{new}") unless logging
                return old
            rescue
                logging.report("unable to rename fuzzy name #{old} to #{new}") unless logging
            end
        end
        return new

    end

    def Tool.servername
        host = Socket::gethostname
        begin
            Socket::gethostbyname(host)[0]
        rescue
            host
        end
    end

    # print file_platform(ARGV[0])

end