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