# -*-Perl-*-

# instances allowed: one 

# (single instance modules would be silly to use more than one of
# anyway, so we use package local storage.  This is faster and places
# less artificial load on the machine than doing everything through
# the object hash)

package MGMmodule::memuse;
use IO::Seekable;
use vars qw($xpath $widget $graph $memtotal $swaptotal $memuse $swapuse $bars);

sub module_init{
    my$this=shift;
    my$toplevel=$this->{"toplevel"};
    my$xclass=$this->{"xclass"};
    
    $this->read_proc;

    unless ($memtotal){
	$toplevel->optionAdd("$xclass*active",'false',21);
    }
    $toplevel->optionAdd("$xclass.order", 101,21);
    $this;
}

sub module_instance{
    my$this=shift;
    my$toplevel=$this->{"toplevel"};
    return undef if(defined($xpath));
    $xpath=$this->{"xpath"};
    
    my($adj,$mult)=MGM::Graph::scalemod($memtotal);
    $toplevel->optionAdd("$xpath.bar.0.label", "memory ($adj$mult"."B)",21);
    ($adj,$mult)=MGM::Graph::scalemod($swaptotal);
    $toplevel->optionAdd("$xpath.bar.1.label", "swap ($adj$mult"."B)",21);

    $bars=1;
    $bars++ if($swaptotal);

    my($minx,$miny)=&MGM::Graph::calcxysize($this,100,'% used',$bars);
    
    $toplevel->optionAdd("$xpath.minx",        $minx,21);      
    $toplevel->optionAdd("$xpath.miny",        $miny,21);          
    # modify defaults

    # for some reason, reading from /proc/meminfo is *very* expensive.
    # don't do it often.
    $toplevel->optionAdd("$xpath.scalerefresh",2000,21);      # 2s
    $toplevel->optionAdd("$xpath.scalewidadj", 80*$bars,21);  # narrower
    $toplevel->optionAdd("$xpath.bar*litbackground", "#e8d088",21); 
    $this;
}

sub module_run{
    my$this=shift;
    
    $graph=MGM::Graph->new($this,num=>$bars,prompt=>'% used',fixed=>1,
			   rangesetting=>100,rangecurrent=>100);
    $widget=$graph->{"widget"};        # must return the widget
}

sub module_update{ 
    my$this=shift;
    $this->read_proc;
    if($bars==2 && $swaptotal>0){
	$graph->set($memuse/$memtotal*100,$swapuse/$swaptotal*100);
    }else{
	$graph->set($memuse/$memtotal*100);
    }
}

sub read_proc{
    if(open(PROC,"/proc/meminfo")){
	<PROC>;
	$_=<PROC>;
	if(m/^Mem:\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s+(\d+)\s+(\d+)/){
	    $memtotal=$1;
	    $memuse=$2-$3-$4;
	}else{
	    $memtotal=0;
	    $memuse=0;
	}
	$_=<PROC>;
	if(m/^Swap:\s+(\d+)\s+(\d+)/){
	    $swaptotal=$1;
	    $swapuse=$2;
	}else{
	    $swaptotal=0;
	    $swapuse=0;
	}
	close PROC;
    }
}

sub destroy{
    undef $xpath;
}

bless {};

