]> git.vpit.fr Git - perl/scripts/xchat.git/blob - Xchat/XPI/Utils.pm
8fab3c469aae892395cf1ceec3f48bd49e1df141
[perl/scripts/xchat.git] / Xchat / XPI / Utils.pm
1 package Xchat::XPI::Utils;
2
3 use strict;
4 use warnings;
5
6 use Xchat qw<:all>;
7
8 our $VERSION = '0.02';
9
10 my @rcolors;
11 BEGIN {
12  if (nickcmp(get_info('version'), '2.4.0') < 0) {
13   @rcolors = (3, 4, 6, 8, 9, 10, 11, 12, 13);
14  } else {
15   @rcolors = (19, 20, 22, 24, 25, 26, 27, 28, 29);
16  }
17 }
18
19 sub dye_nick {
20  my $nick = $_[0];
21  my $col  = 0;
22  $col    += ord for split //, $nick;
23  return sprintf "\003%d%s", $rcolors[$col % @rcolors], $nick;
24 }
25
26 sub save_context {
27  my $cur_cxt = get_context;
28  bless \$cur_cxt, 'Xchat::XPI::Utils::ContextGuard';
29 }
30
31 sub local_context {
32  return unless @_ >= 2;
33  my $code    = pop;
34  my $new_cxt = (@_ == 1) ? $_[0] : find_context(@_);
35  my $cur_cxt = get_context;
36  if (set_context $new_cxt) {
37   my $guard = bless \$cur_cxt, 'Xchat::XPI::Utils::ContextGuard';
38   return $code->();
39  } else {
40   return undef;
41  }
42 }
43
44 sub Xchat::XPI::Utils::ContextGuard::DESTROY {
45  set_context ${$_[0]};
46 }
47
48 sub called_from_script (&) {
49  my $code  = shift;
50  my $level = 0;
51  my ($package, $filename);
52  while (1) {
53   my @frame = caller $level;
54   last unless @frame;
55   if ($frame[0] !~ /^(?:Xchat|HexChat)::XPI\b/) {
56    ($package, $filename) = @frame[0, 1];
57    last;
58   }
59   ++$level;
60  }
61  if (defined $filename) {
62   my $internal_package = Xchat::Embed::file2pkg($filename);
63   my $mock = sub { $internal_package, $package };
64   no warnings 'redefine';
65   local *Xchat::Embed::find_pkg   = $mock;
66   local *HexChat::Embed::find_pkg = $mock;
67   $code->();
68  }
69 }
70
71 use base qw<Exporter>;
72
73 our @EXPORT         = ();
74 our %EXPORT_TAGS    = ('funcs' => [ qw<
75  dye_nick
76  save_context local_context
77  called_from_script
78 > ]);
79 our @EXPORT_OK      = map { @$_ } values %EXPORT_TAGS;
80 $EXPORT_TAGS{'all'} = [ @EXPORT_OK ];
81
82 1;