#! perl

sub refresh {
   my ($self) = @_;

   my $ncol = $self->ncol;

   my $text = " " x $ncol;
   my $rend = [($self->{rs_tabbar}) x $ncol];

   my @ofs;

   substr $text, 0, length($self->{newformat}), $self->{newformat};
   @$rend[0 .. length($self->{newformat})-1] = ($self->{rs_tab}) x length($self->{newformat});
   push @ofs, [0, length($self->{newformat}), sub { $_[0]->new_tab }];

   my $ofs = length($self->{newformat});
   my $idx = 0;
   my $dellen = length $self->{tabdelimiter};

   for my $tab (@{ $self->{tabs} }) {
      $idx++;

      my $act = $tab->{activity} && $tab != $self->{cur}
                ? $self->{activitysign} : " " x length $self->{activitysign};

      my $txt = $self->{tabformat};
      $txt =~ s/%a/${act}/g;
      $txt =~ s/%i/${idx}/g;
      $txt = $self->{tabdelimiter}."$txt";
      my $len = length $txt;
      substr $text, $ofs, $len, "$txt";
      @$rend[$ofs + $dellen .. $ofs + $len - 1] = ($self->{rs_tab}) x $len
         if $tab == $self->{cur};

      push @ofs, [ $ofs + $dellen, $ofs + $len, sub { $_[0]->make_current ($tab) } ];

      $ofs += $len;
   }
   substr $text, $ofs, $dellen, $self->{tabdelimiter};
   $self->{tabofs} = \@ofs;

   $self->ROW_t (0, $text, 0, 0, $ncol);
   $self->ROW_r (0, $rend, 0, 0, $ncol);
   $self->want_refresh;
}

sub new_tab {
   my ($self, $command, @argv) = @_;

   my $offset = $self->fheight;

   # save a backlink to us, make sure tabbed is inactive
   push @urxvt::TERM_INIT, sub {
      my ($term) = @_;
      $term->{parent} = $self;

      $term->resource ($_->[0] => $_->[1])
         for @{ $self->{resource} || [] };

      $term->resource (perl_ext_2 => $term->resource ("perl_ext_2") . ",-tabbed");
      
   };

   push @urxvt::TERM_EXT, urxvt::ext::tabbed::tab::;
   my $env = $self->env;
   $env->{'URXVT_SESSION'}=undef;
   $env->{'URXVT_SESSION_COMMAND'}=$command;
   my $term = new urxvt::term
      $env, $urxvt::RXVTNAME,
      -embed => $self->parent,
      @argv,
   ;
   if (@{ $self->{tabs} } == 2) {			# if tabbar hide is on, show it, when second tab create
	   $self->{tabheight} = $self->int_bwidth + $self->fheight + $self->lineSpace;
	   $self->cmd_parse ("\033[?25l");
	   configure $self;
   }
}

sub configure {
   my ($self) = @_;

   my $tab = $self->{cur};

   # this is an extremely dirty way to force a configurenotify, but who cares
   $tab->XMoveResizeWindow (
      $tab->parent,
      0, $self->{tabheight} + 1,
      $self->width, $self->height - $self->{tabheight}
   );
   $tab->XMoveResizeWindow (
      $tab->parent,
      0, $self->{tabheight},
      $self->width, $self->height - $self->{tabheight}
   );
}

sub on_resize_all_windows {
   my ($self, $width, $height) = @_;

   1
}

sub copy_properties {
   my ($self) = @_;
   my $tab = $self->{cur};

   my $wm_normal_hints = $self->XInternAtom ("WM_NORMAL_HINTS");

   my %our_props = map +($_ => undef), $self->XListProperties ($self->parent);

   delete $our_props{$self->XInternAtom ($_)}
      for qw(WM_STATE WM_ICON_SIZE
             _NET_WM_VISIBLE_NAME _NET_WM_VISIBLE_ICON_NAME _NET_WM_ICON_GEOMETRY _NET_FRAME_EXTENTS);

   for my $atom ($tab->XListProperties ($tab->parent)) {
      my ($type, $format, $items) = $self->XGetWindowProperty ($tab->parent, $atom);
      
      delete $our_props{$atom};

      if ($atom == $wm_normal_hints) {
         my (@hints) = unpack "l!*", $items;
      
         $hints[$_] += $self->{tabheight} for (4, 6, 16);
      
         $items = pack "l!*", @hints;
      }

      my ($dtype, $dformat, $ditems) = $self->XGetWindowProperty ($self->parent, $atom);

      if ($dtype != $type or $dformat != $format or $ditems ne $items) {
         $self->XChangeWindowProperty ($self->parent, $atom, $type, $format, $items);
      }
   }

   $self->XDeleteProperty ($self->parent, $_) for keys %our_props;
}

sub make_current {
   my ($self, $tab) = @_;

   if (my $cur = $self->{cur}) {
      delete $cur->{activity};
      $cur->XUnmapWindow ($cur->parent) if $cur->mapped;
      $cur->focus_out;
   }
   
   $self->{cur} = $tab;

   $self->configure;
   $self->copy_properties;
   
   $tab->focus_out; # just in case, should be a nop
   $tab->focus_in if $self->focus;
   
   $tab->XMapWindow ($tab->parent);
   delete $tab->{activity};
   $self->refresh;

   ()
}

sub on_focus_in {
   my ($self, $event) = @_;

   $self->{cur}->focus_in;

   ()
}

sub on_focus_out {
   my ($self, $event) = @_;

   $self->{cur}->focus_out;

   ()
}

sub on_key_press {
   my ($self, $event) = @_;

   $self->{cur}->key_press ($event->{state}, $event->{keycode}, $event->{time});

   1
}

sub on_key_release {
   my ($self, $event) = @_;

   $self->{cur}->key_release ($event->{state}, $event->{keycode}, $event->{time});

   1
}

sub on_button_press {
   1
}

sub on_button_release {
   my ($self, $event) = @_;

   if ($event->{row} == 0) {
      for my $button (@{ $self->{tabofs} }) {
         $button->[2]->($self, $event)
            if $event->{col} >= $button->[0]
               && $event->{col} < $button->[1];
      }
   }

   1
}

sub on_motion_notify {
   1
}

sub on_init {
   my ($self) = @_;

   for (qw(name perl_ext_1 perl_ext_2)) {
      my $val = $self->resource ($_);

      push @{ $self->{resource} }, [$_ => $val]
        if defined $val;
   }

   $self->resource (int_bwidth => 0);
   $self->resource (name => "URxvt.tabbed");
   $self->resource (pty_fd => -1);

   $self->option ($urxvt::OPTION{scrollBar}, 0);

   my $fg    = $self->x_resource ("tabbar-fg");
   my $bg    = $self->x_resource ("tabbar-bg");
   my $tabfg = $self->x_resource ("tab-fg");
   my $tabbg = $self->x_resource ("tab-bg");
   
   $self->{tabformat}    = $self->x_resource ("tab-format");
   $self->{tabdelimiter} = $self->x_resource ("tab-delimiter");
   $self->{activitysign} = $self->x_resource ("tab-activity-sign");
   $self->{newformat}    = $self->x_resource ("new-format");
   $self->{hideonetab}   = $self->x_resource ("hide-singe-tab");

   defined $fg    or $fg    = 3;
   defined $bg    or $bg    = 0;
   defined $tabfg or $tabfg = 0;
   defined $tabbg or $tabbg = 1;


   defined $self->{tabformat}    or $self->{tabformat} = "%a%i%a";
   defined $self->{tabdelimiter} or $self->{tabdelimiter} = "|";
   defined $self->{activitysign} or $self->{activitysign} = "*";
   defined $self->{newformat}    or $self->{newformat} = "[NEW]";
   defined $self->{hideonetab}   or $self->{hideonetab} = 1;

   $self->{hideonetab} = 0 if ($self->{hideonetab} eq "false" ||  $self->{hideonetab} eq "off");

   $self->{rs_tabbar} = urxvt::SET_COLOR (urxvt::DEFAULT_RSTYLE, $fg    + 2, $bg    + 2);
   $self->{rs_tab}    = urxvt::SET_COLOR (urxvt::DEFAULT_RSTYLE, $tabfg + 2, $tabbg + 2);

   ()
}

sub on_start {
   my ($self) = @_;

   if (!$self->{hideonetab}) {
      $self->{tabheight} = $self->int_bwidth + $self->fheight + $self->lineSpace;
      $self->cmd_parse ("\033[?25l");
   }
   my @argv = $self->argv;

   do {
      shift @argv;
   } while @argv && $argv[0] ne "-e";
   
   if ($self->env->{'URXVT_SESSION'} ne "") {
   	$self->{tabheight} = $self->int_bwidth + $self->fheight + $self->lineSpace;
   	$self->cmd_parse ("\033[?25l");

	open(INP, $self->env->{'URXVT_SESSION'});
	while (my $line = <INP>) {
		$self->new_tab ($line, @argv);
	}
	close(INP);
   } else {
	$self->new_tab ("", @argv);
   }

   ()
}

sub on_configure_notify {
   my ($self, $event) = @_;

   $self->configure;
   $self->refresh;

   ()
}

sub on_wm_delete_window {
   my ($self) = @_;

   $_->destroy for @{ $self->{tabs} };

   1
}

sub tab_start {
   my ($self, $tab) = @_;

   $tab->XChangeInput ($tab->parent, urxvt::PropertyChangeMask);

   push @{ $self->{tabs} }, $tab;

#   $tab->{name} ||= scalar @{ $self->{tabs} };
   $self->make_current ($tab);

   ()
}

sub tab_destroy {
   my ($self, $tab) = @_;

   $self->{tabs} = [ grep $_ != $tab, @{ $self->{tabs} } ];

   if (@{ $self->{tabs} }) {
      if ($self->{cur} == $tab) {
         delete $self->{cur};
         $self->make_current ($self->{tabs}[-1]);
      } else {
         $self->refresh;
      }
   } else {
      # delay destruction a tiny bit
      $self->{destroy} = urxvt::iw->new->start->cb (sub { $self->destroy });
   }
   if ($self->{hideonetab} && @{ $self->{tabs} } == 1) {	# if tabbar hide is on, hide it, when only one tab rest
	   $self->{tabheight} = 0;
	   $self->cmd_parse ("\033[?25l");
	   configure $self;
   }

   ()
}

sub tab_key_press {
   my ($self, $tab, $event, $keysym, $str) = @_;
    if ($event->{state} & urxvt::Mod4Mask) {
      if ($keysym == 0xff51 || $keysym == 0xff53) {
         my ($idx) = grep $self->{tabs}[$_] == $tab, 0 .. $#{ $self->{tabs} };

         --$idx if $keysym == 0xff51;
         ++$idx if $keysym == 0xff53;
         $self->make_current ($self->{tabs}[$idx % @{ $self->{tabs}}]);
         
         return 1;
      } elsif ($keysym == 0xff54) {
         $self->new_tab("");
         return 1;
      } elsif ($keysym >= 49 && $keysym <= 57) {			# metakey and number -> jump to the concrete tab
         if ((@{ $self->{tabs} }) >= ($keysym-48)) {
            $self->make_current ($self->{tabs}[$keysym-49]);
	 }
         return 1;
      }
   }

   ()
}

sub tab_property_notify {
   my ($self, $tab, $event) = @_;

   $self->copy_properties
      if $event->{window} == $tab->parent;

   ()
}

sub tab_activity {
   my ($self, $tab) = @_;

   $self->refresh;
}

package urxvt::ext::tabbed::tab;

# helper extension implementing the subwindows of a tabbed terminal.
# simply proxies all interesting calls back to the tabbed class.

{
#   for my $hook qw(start destroy key_press key_release property_notify) {
   for my $hook qw(start destroy key_press property_notify) {
      eval qq{
         sub on_$hook {
            my \$parent = \$_[0]{term}{parent}
               or return;
            \$parent->tab_$hook (\@_)
         }
      };
      die if $@;
   }
}

sub on_add_lines {
  $_[0]->{activity}++
     or $_[0]{term}{parent}->tab_activity ($_[0]);
  ()
}


