summaryrefslogtreecommitdiffstats
path: root/extra/gnumeric/embedder
blob: 23c22d4b88137c124b93e3eb123caa487acc7d93 (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
#!/usr/bin/perl

use strict;
use Getopt::Long;
use IO::Compress::Gzip qw(gzip $GzipError);

my $myself = $0;
$myself =~ s|^.*/||;

my $WIDTH = 70;
my $regfunc = undef;
my @includes;

&GetOptions("register-function=s" => \$regfunc,
	    "include=s" => \@includes,
    );

# -----------------------------------------------------------------------------

print "/* Generated by $myself -- do not edit! */\n\n";
print "#include <gnumeric-config.h>\n";
print "#include <gnm-rsm.h>\n\n";
foreach (@includes) {
    print "#include \"$_\"\n";
}

my $fileno = 0;
my $reg = "";
my $docompress = 0;
print "void\n";
print "$regfunc (void)\n";
print "{\n";
foreach my $file (@ARGV) {
    if ($file eq 'COMPRESS') {
	$docompress = 1;
	next;
    }
    if ($file eq 'NOCOMPRESS') {
	$docompress = 0;
	next;
    }
    &embed ($file, $docompress);
}
print $reg;
print "}\n";

sub embed {
    my ($file, $docompress) = @_;

    print "  /* Embedded file $file */\n";

    my $data;
    {
	local (*FIL);
	local ($/);
	$/ = undef;
	open (*FIL, "<$file") or die "$myself: cannot read $file: $!\n";
	$data = <FIL>;
    }

    if ($docompress) {
	my $zdata;
	gzip \$data => \$zdata
	    or die "gzip failed: $GzipError\n";
	$data = $zdata;
    }

    my $id = "data$fileno";
    $fileno++;

    &embed_data ($data, $id);

    my $len = length ($data);
    $reg .= "  gnm_rsm_register_file (\"$file\", $id, $len);\n";
}

sub embed_data {
    my ($data,$id) = @_;

    my $len = length ($data);
    if ($len == 0) {
	print "  static const char ${id}[] = \"\";\n";
	return;
    }

    print "  static const char ${id}[] =\n";
    my $linelen = 0;
    my $nohex = 0;
    foreach my $c (split (//, $data)) {
	if ($linelen > $WIDTH) {
	    print "\"\n";
	    $linelen = 0;
	}
	if ($linelen == 0) {
	    print "    \"";
	    $linelen += 5;
	} 

	my $thisnohex = $nohex;
	$nohex = 0;

	my $ci = ord ($c);
	if ($c eq "\n") {
	    print "\\n";
	    $linelen += 2;
	} elsif ($c eq "\t") {
	    print "\\t";
	    $linelen += 2;
	} elsif ($c eq '"') {
	    print "\\\"";
	    $linelen += 2;
	} elsif ($c eq "\\") {
	    print "\\\\";
	    $linelen += 2;
	} elsif ($ci >= 32 && $ci < 128) {
	    if ($thisnohex && $c =~ /[a-fA-f0-9]/) {
		print "\"\"";
		$linelen += 2;
	    }
	    print $c;
	    $linelen += 1;
	} else {
	    printf ("\\x%02x", $ci);
	    $linelen += 4;
	    $nohex = 1;
	}
    }
    print "\";\n\n";
}