Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying CP437 ('extended ascii') in Perl/Gtk

Tags:

ascii

perl

gtk

Is there any way in which I can display old-fashioned extended ASCII (cp437) in a Gtk2::TextView? (Google suggests no answers.)

If there is some way of changing the charset used by a GTK widget, I can't find it.

Or maybe it's necessary to use Perl's Encode module, as I tried in the script below, but that doesn't work either.

#!/usr/bin/perl
# Display ASCII

use strict;
use diagnostics;
use warnings;
use Encode;

use Glib qw(TRUE FALSE);
use Gtk2 '-init';

# Open a Gtk2 window, with a Gtk2::TextView to display text
my $window = Gtk2::Window->new('toplevel');
$window->set_title('Extended ASCII viewer');
$window->set_position('center');
$window->set_default_size(600, 400);
$window->signal_connect('delete-event' => sub {

    Gtk2->main_quit();
    exit;
});

my $scrollWin = Gtk2::ScrolledWindow->new(undef, undef);
$window->add($scrollWin);
$scrollWin->set_policy('automatic', 'automatic');     
$scrollWin->set_border_width(0);

my $textView = Gtk2::TextView->new;
$scrollWin->add_with_viewport($textView);
$textView->can_focus(FALSE);
$textView->set_wrap_mode('word-char');
$textView->set_justification('left');
my $buffer = $textView->get_buffer();

$window->show_all();   

# In cp437, this is a series of accented A characters
my $string = chr (131) . chr (132) . chr (133) . chr (134);

# Display plain text
$buffer->insert_with_tags_by_name($buffer->get_end_iter(), $string . "\n");

# Display UTF-8 text
my $utfString = encode('utf8', $string);
$buffer->insert_with_tags_by_name($buffer->get_end_iter(), $utfString . "\n");

# Display cp437
my $cpString = decode ('cp437', $string);
my $utfString2 = encode('utf-8', $cpString);
$buffer->insert_with_tags_by_name($buffer->get_end_iter(), $utfString2 . "\n");

# Other suggestion
my $otherString = encode("utf-8", decode ("cp437", $string));
$buffer->insert_with_tags_by_name($buffer->get_end_iter(), $otherString . "\n");

# Directly decode a hex character (as suggested)
my $hexString = encode("utf-8", decode("cp437", "\xBA"));
$buffer->insert_with_tags_by_name($buffer->get_end_iter(), $hexString . "\n");

Gtk2->main();

enter image description here

like image 429
lesrol Avatar asked Apr 09 '18 15:04

lesrol


1 Answers

Gtk wants to receive UTF-8 encoded strings, so anything you pass to a Gtk widget should be UTF-8 encoded.

If your input is cp437, then you'll want to decode it first and reencode it as UTF-8.

my $cp437_string = chr(153) x 10;               # cp437 encoded
my $string = decode('cp437', $cp437_string);    # Unicode code point encoded
my $utf8_string = encode('utf-8', $string);     # utf-8 encoded
$buffer->insert_with_tags_by_name(
    $buffer->get_end_iter(), $utf8_string . "\n");
like image 78
mob Avatar answered Sep 30 '22 21:09

mob