File: CodePage.pm

package info (click to toggle)
biber 2.21-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,476 kB
  • sloc: perl: 17,643; sh: 1,069; xml: 896; makefile: 11
file content (259 lines) | stat: -rw-r--r-- 7,695 bytes parent folder | download
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
package Biber::CodePage;
use v5.24;
use strict;
use warnings;
use parent qw(Exporter);
our @EXPORT = qw( decode_CS_system encode_CS_system get_CS_system
                  is_Unicode_system
                  set_CP_Win_console set_CS_defaults  set_STD_encodings );
our @EXPORT_OK = qw( get_CS_log string_analysis );

# Handling of code page issues, especially on Windows.

use Encode qw( encode decode );
use Unicode::Normalize qw( checkNFC checkNFD );

# My default CS for system (filenames for subroutine, @ARGV): UTF-8.
# Then update according to system settings (if any).
our $CS_system = 'UTF-8';
our $CS_console = 'UTF-8';

# Win32 specific CP **numbers**.  Initialize to 65001 (utf-8), and change
# to correspond to results from system calls.
# Corresponding CS name: Prefix by 'CP'.
# Preserve intial values for console/terminal to allow restore on exit.
# Declarations
our ($CP_Win_system, $CP_init_Win_console_in, $CP_init_Win_console_out);

# Initial defaults
$CP_Win_system = $CP_init_Win_console_in = $CP_init_Win_console_out = '65001';

our $init_success;
our $verbose = 0;

# Log of what I did, including warnings in sequence
our $log = '';
# Warnings only
our $warnings = '';

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

sub CP_format {
    # Can do extra formatting here
    my $s = join( '', @_ ) . "\n";
}
sub CP_log {
    my $s = CP_format(@_); 
    $log .= $s;
    print( $s ) if $verbose;
}
sub CP_warn {
    my $s = CP_format(@_); 
    $log .= $s;
    $warnings .= $s;
    warn $s;
}
#--------------------------


# ==========================================
# Externally usable subroutines.

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

sub decode_CS_system($) {
    my $s = $_[0];
    return decode( $CS_system, $s );
}

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

sub encode_CS_system($) {
    my $s = $_[0];
    return encode( $CS_system, $s );
}

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

sub get_CS_console() {
    return $CS_console;
}

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

sub get_CS_system() {
    return $CS_system;
}

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

sub get_CS_log() {
    return $log;
}

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

sub is_Unicode_system() {
    return (uc($CS_system) eq 'UTF-8') || (uc($CS_system) eq 'CP65001');
}

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

sub set_STD_encodings($) {
    # Set coding scheme for STDOUT, STDERR & STDIN.
    my $CS = shift;
    my $CS_string = ":encoding($CS)";
    binmode( STDOUT, $CS_string );
    binmode( STDERR, $CS_string );
    binmode( STDIN,  $CS_string );
}

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

sub set_CP_Win_console($) {
    # Set code page for console i/o on Windows 
    my $CP = shift;
    if ($^O eq "MSWin32") {
        CP_log( "Setting Windows Console CPs to $CP, and matching encoding for STDOUT, etc.");
        if ( ! Win32::SetConsoleOutputCP($CP) ) {
            CP_warn( "Cannot set Windows Console Output CP to $CP." );
        }
        if ( ! Win32::SetConsoleCP($CP) ) {
            CP_warn( "Cannot set Windows Console Input CP to $CP." );
        }
        $CS_console = "CP$CP";
        set_STD_encodings( $CS_console );
    }
    else {
        CP_warn( "I don't set console CP on non-Windows systems" );
    }
}

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

sub set_CS_defaults() {
    # Set console to use UTF-8
    if ($^O eq "MSWin32") {
        CP_log( "Setting console, STDOUT etc to use UTF-8" );
        set_CP_Win_console( 65001 );
    }
    else {
        set_STD_encodings( 'UTF-8' );
    }
}

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

sub show_CPs() {
    if ($^O eq "MSWin32") {
        my $CP_in  = Win32::GetConsoleCP();
        my $CP_out = Win32::GetConsoleOutputCP();
        my $CP_sys = Win32::GetACP();
        return "Codepage info: Windows CPs: (in, out, system) = ($CP_in, $CP_out, $CP_sys)";
    }
    else {
        return "Codepage info: CSs are UTF-8";
    }
}

#==================

# Useful for debugging, etc

sub string_analysis {
    # JCC's utility for showing properties of strings
    # Usage: e.g.,
    #     say "Code page info: Showing string details:\n",
    #         string_analysis("Code page info: ", $string);
    my ($prefix, $s, $bytes) = @_;
    # The string in $s has character semantics unless the third argument is set.
    # Prefix lines with $prefix.  (Useful if sending result to a logger.)
    # Returned result is an encoded string.  

    # Accumulate lines of analysis results:
    my @result = ();
    my $unicode_string = utf8::is_utf8($s);
    my $s1 = $s;
    if (! $bytes ) { $s1 = encode( 'UTF-8', $s ); }
    push @result, "Given string is '$s'.";
    push @result, 'Perl flag = ' . ($unicode_string ? 'utf8' : 'NOT utf8')
                  . ", len = " . length($s);
    my $isNFC = checkNFC($s);
    my $isNFD = checkNFD($s);
    if ($isNFC && $isNFD) {
        push @result,
            "Reported to be NFC and NFD, i.e., no relevant accented characers";
    }
    elsif ($isNFC) { push @result, "Reported to be NFC"; }
    elsif ($isNFD) { push @result, "Reported to be NFD"; }
    else { push @result, "Reported to be neither NFC nor NFD"; }
    if ($bytes) { push @result, "Bytes:"; }
    elsif ($s1 eq $s) { push @result, "ASCII string, code points = UTF-8 bytes"; }
    else { push @result, "Code points:"; }
    my @code = unpack( 'U*', $s );
    @code = map { sprintf('%4X', $_) }  @code;
    push @result, join( ' ', @code );
    if($s1 ne $s) {
        push @result, "UTF-8:";
        my @code1 = unpack( 'U*', $s1 );
        @code1 = map { sprintf('%4X', $_) }  @code1;
        push @result, join( ' ', @code1 );
    }
    foreach (@result) { $_ = "$prefix$_"; }
    return join( "\n", @result );
}

#=============================================

# On Windows, obtain current code page values.
# The console code pages will be restored on exit.
# This code is executed in Perl's compile phase for this module, before any
# other code gets a chance to change the console code pages (including me).


$init_success = 1;
if ($^O eq "MSWin32") {
    eval {  require Win32;
            $CP_Win_system = Win32::GetACP();
            $CS_system = 'CP' . $CP_Win_system;
            $CP_init_Win_console_in = Win32::GetConsoleCP();
            $CP_init_Win_console_out = Win32::GetConsoleOutputCP();
    };
    if ($@) { CP_warn( "Trouble finding and setting code pages used by Windows:",
                       "  $@",
                       "  I'LL CONTINUE WITH UTF-8." ); 
              $init_success = 0;
    }
    else {
        CP_log( 
            "Initial Win CP for (console input, console output, system): ".
            "(CP$CP_init_Win_console_in, CP$CP_init_Win_console_out, CP$CP_Win_system)" );
        CP_log( "At program termination will revert Windows console CPs to ",
                "(in,out) = ($CP_init_Win_console_in,$CP_init_Win_console_out)" );
    }
}

# Make the following settings at start of program execution, not at module
# compile time.  Otherwise when there are errors in later parts of
# compilation, the console CPs will be changed, but the END block to restore
# them will not be executed.
INIT {
    # Set a sensible defaults for STD i/o, for consistency of screen output
    # across operating systems.
    set_CS_defaults();
}

# Ensure that on ctrl/C interruption, etc, the END block is obeyed, and Windows console CPs are restored:
use sigtrap qw(die untrapped normal-signals);
END {
    # Restore initial state of console
    if ($^O eq "MSWin32") {
        CP_log( "Resetting console CPs to (in, out) = ",
                "($CP_init_Win_console_in, $CP_init_Win_console_in)" ); 
        Win32::SetConsoleCP($CP_init_Win_console_in);
        Win32::SetConsoleOutputCP($CP_init_Win_console_out);
    }
    # Don't worry about what to do with STDOUT, etc; it should be unimportant from here.
}

1;