| 1 | package Term::Title; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | # ABSTRACT: Portable API to set the terminal titlebar | ||
| 5 | |||
| 6 | our $VERSION = '0.09'; | ||
| 7 | |||
| 8 | use Exporter; | ||
| 9 | our @ISA = 'Exporter'; | ||
| 10 | our @EXPORT_OK = qw/set_titlebar set_tab_title/; | ||
| 11 | |||
| 12 | # encodings by terminal type -- except for mswin32 get matched as regex | ||
| 13 | # against $ENV{TERM} | ||
| 14 | # code ref gets title and text to print | ||
| 15 | my %terminal = ( | ||
| 16 | 'xterm|rxvt' => { | ||
| 17 | pre => "\033]2;", | ||
| 18 | post => "\007", | ||
| 19 | }, | ||
| 20 | 'screen' => { | ||
| 21 | pre => "\ek", | ||
| 22 | post => "\e\\", | ||
| 23 | }, | ||
| 24 | 'mswin32' => sub { | ||
| 25 | my ( $title, @optional ) = @_; | ||
| 26 | my $c = Win32::Console->new(); | ||
| 27 | $c->Title($title); | ||
| 28 | print STDOUT @optional, "\n"; | ||
| 29 | }, | ||
| 30 | ); | ||
| 31 | |||
| 32 | my %terminal_tabs = ( | ||
| 33 | 'iterm2' => { | ||
| 34 | is_supported => sub { | ||
| 35 | $ENV{TERM_PROGRAM} and $ENV{TERM_PROGRAM} eq 'iTerm.app'; | ||
| 36 | }, | ||
| 37 | pre => "\033]1;", | ||
| 38 | post => "\007", | ||
| 39 | }, | ||
| 40 | 'konsole' => { | ||
| 41 | is_supported => sub { | ||
| 42 | $ENV{KONSOLE_PROFILE_NAME}; | ||
| 43 | }, | ||
| 44 | pre => "\033]30;", | ||
| 45 | post => "\007", | ||
| 46 | }, | ||
| 47 | ); | ||
| 48 | |||
| 49 | sub _set { | ||
| 50 | my ( $type_cb, $types, $title, @optional ) = @_; | ||
| 51 | $title = q{ } unless defined $title; | ||
| 52 | my $type = $type_cb->(); | ||
| 53 | |||
| 54 | if ($type) { | ||
| 55 | if ( ref $types->{$type} eq 'CODE' ) { | ||
| 56 | $types->{$type}->( $title, @optional ); | ||
| 57 | } | ||
| 58 | elsif ( ref $types->{$type} eq 'HASH' ) { | ||
| 59 | print STDOUT $types->{$type}{pre}, $title, $types->{$type}{post}, @optional, "\n"; | ||
| 60 | } | ||
| 61 | } | ||
| 62 | elsif (@optional) { | ||
| 63 | print STDOUT @optional, "\n"; | ||
| 64 | } | ||
| 65 | return; | ||
| 66 | } | ||
| 67 | |||
| 68 | sub set_titlebar { _set( \&_is_supported, \%terminal, @_ ) } | ||
| 69 | |||
| 70 | sub set_tab_title { _set( \&_is_supported_tabs, \%terminal_tabs, @_ ) } | ||
| 71 | |||
| 72 | sub _is_supported { | ||
| 73 | if ( lc($^O) eq 'mswin32' ) { | ||
| 74 | return 'mswin32' if eval { require Win32::Console }; | ||
| 75 | } | ||
| 76 | else { | ||
| 77 | return unless $ENV{TERM}; | ||
| 78 | for my $k ( keys %terminal ) { | ||
| 79 | return $k if $ENV{TERM} =~ /^(?:$k)/; | ||
| 80 | } | ||
| 81 | } | ||
| 82 | return; | ||
| 83 | } | ||
| 84 | |||
| 85 | sub _is_supported_tabs { | ||
| 86 | for my $k ( keys %terminal_tabs ) { | ||
| 87 | return $k if $terminal_tabs{$k}{is_supported}->(); | ||
| 88 | } | ||
| 89 | |||
| 90 | return; | ||
| 91 | } | ||
| 92 | |||
| 93 | 1; | ||
| 94 | |||
| 95 | __END__ |