#!/usr/bin/perl

use strict;
use Tk;
require Tk::FileSelect;
require Tk::Dialog;

my $fname = $ENV{'HOME'};
my $main = new MainWindow(-title => 'Datei durchsuchen');
$main->Label(-text => 'Datei durchsuchen')->pack;

my $whatframe=$main->Frame;
$whatframe->pack;
$whatframe->Label(-text => 'Suchstring')->pack(-side => 'left');
my $what = $whatframe->Entry(-width => 15);
$what->pack(-side => 'right');

my $fileframe=$main->Frame;
$fileframe->pack;
my $filename = $fileframe->Entry(-width => 40, -textvariable => \$fname);
$filename->pack(-side => 'left');
$fileframe->Button(-text => 'Durchsuchen...',
	      -command => sub{$fname=do_browse($fname);}
		  )->pack(-side => 'right');
$main->Button(-text => 'Suchen',
	      -command => sub{do_search($fname, $what->get)}
	     )->pack;
MainLoop;

sub bad_file 
  {
  my ($sel) = @_;
  $sel="Auswahl" unless $sel;
  my $dialog=$main->Dialog(-title => 'keine Textdatei',
			   -text => "$sel ist keine Textdatei");
  $dialog->Show;
  }

sub do_browse 
  {
  my ($dir) = @_;

  my $fs = $main->FileSelect;
  my $new = $fs->Show;
  if (-T $new) 
    { $dir = $new; } 
  else 
    { bad_file($new); }
  return $dir;
  }


sub do_search 
  {
  my ($f, $w) = @_;

  unless (-T $f) 
    {
    bad_file($f);
    return;
    }

  open (FILE,$f);
  my $line;
  my $tmp;
  my @found=();

  for ($line = 1; !eof(FILE); $line++) 
    {
    $tmp=<FILE>;
    chomp $tmp;
    push @found, "Zeile $line: $tmp" if $tmp=~/$w/;
    }

  my $dialog = $main->DialogBox(-title => 'Suchergebnisse');
  my $frame = $dialog->add('Frame');
  $frame->pack(-fill => 'both', -expand => 1);
  $frame->Label(-text => "Suche nach\"$w\" in $f:")->pack;

  my $listbox = $frame->Scrolled('Listbox');
  $listbox->pack(-fill => 'both', -expand => 1);
  $listbox->insert('end',@found);

  $dialog->Show;
  close FILE;
  }

