package Mud::Platform;
use strict;
use Mac::Events qw(TickCount WaitNextEvent);

# the responsiveness-vs-CPU tradeoff
use constant SLEEP_TICKS => 5;

sub p_select {
  my $done = defined $_[3] ? TickCount() + $_[3] * 60 : undef;
  my $result;
  while (
    (not $done or TickCount() < $done)
    and not $result
    and not $Mud::Scheduler::Quit
  ) {
    WaitNextEvent(SLEEP_TICKS);
    $result = select($_[0], $_[1], $_[2], 0);
  }
  return 0 unless $result;
}

### Monitor/quit window ###############################################

use Mac::Windows qw(SizeWindow GrowWindow floatGrowProc TrackGoAway);
use Mac::QuickDraw qw(SetPort MoveTo DrawString EraseRect TextSize);

use constant WINV => 16;
use vars qw($MonWin $MonPort $MonWid);
{
  local ($DB::single, $DB::trace) = (0, 0);
  $MonWid ||= 210;
  $MonWin and $MonWin->dispose;
  $MonWin = MacColorWindow->new(
    Rect->new(20, 40, 200, 40+WINV),
    "mpMUD", 1, floatGrowProc, 1
  );
  $MonWin->sethook(drawgrowicon => sub {1});
  $MonWin->sethook(goaway => sub {my($my,$pt) = @_; $Mud::Scheduler::Quit = 'monitor click' if TrackGoAway($my->{port}, $pt); 1;});
  $MonWin->sethook(grow => sub {
    my($my,$pt) = @_;
    if (my($w,$h) = GrowWindow($my->{port}, $pt, Rect->new(30, WINV, 1024, WINV * 10))) {
      $my->invalgrowarea;
      SizeWindow($my->{port}, $MonWid = $w, $h);
      $my->invalgrowarea;
      $my->layout;
    }
    1;
  });
  SetPort $MonPort = $MonWin->window;
  TextSize(9);
  $MonWin->drawgrowicon;
}

sub mon_set {
  return unless $MonWin and $MonWin->window;
  local ($DB::single, $DB::trace) = (0, 0);
  SetPort($MonPort);
  MoveTo(3, WINV - 5);
  EraseRect(Rect->new(0, 0, $MonWid, WINV));
  DrawString($_[0]);
}

END {$MonWin->dispose if $MonWin;}


1;
__END__
