code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#!/usr/bin/env perl # Copyright (c) 2000-2003, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc. # Use is subject to license terms. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; version 2 # of the License. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free # Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, # MA 02110-1335 USA # # Test of creating a simple table and inserting $record_count records in it, # $opt_loop_count rows in order, $opt_loop_count rows in reverse order and # $opt_loop_count rows in random order # # changes made for Oracle compatibility # - $limits->{'func_odbc_mod'} is OK from crash-me, but it fails here so set we # set it to 0 in server-cfg # - the default server config runs out of rollback segments, so we added a # couple of disconnect/connects to reset # ##################### Standard benchmark inits ############################## use Cwd; use DBI; use Benchmark; use Data::Dumper; $opt_loop_count=100000; # number of rows/3 $small_loop_count=10; # Loop for full table retrieval $range_loop_count=$small_loop_count*50; $many_keys_loop_count=$opt_loop_count; $opt_read_key_loop_count=$opt_loop_count; $pwd = cwd(); $pwd = "." if ($pwd eq ''); require "$pwd/bench-init.pl" || die "Can't read Configuration file: $!\n"; if ($opt_small_test) { $opt_loop_count/=100; $many_keys_loop_count=$opt_loop_count/10; $range_loop_count=10; $opt_read_key_loop_count=10; } elsif ($opt_small_tables) { $opt_loop_count=10000; # number of rows/3 $many_keys_loop_count=$opt_loop_count; $opt_read_key_loop_count=10; } elsif ($opt_small_key_tables) { $many_keys_loop_count/=10; } if ($opt_loop_count < 100) { $opt_loop_count=100; # Some tests must have some data to work! } $range_loop_count=min($opt_loop_count,$range_loop_count); print "Testing the speed of inserting data into 1 table and do some selects on it.\n"; print "The tests are done with a table that has $opt_loop_count rows.\n\n"; #### #### Generating random keys #### print "Generating random keys\n"; $random[$opt_loop_count]=0; for ($i=0 ; $i < $opt_loop_count ; $i++) { $random[$i]=$i+$opt_loop_count; } my $tmpvar=1; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $swap=$tmpvar % $opt_loop_count; $tmp=$random[$i]; $random[$i]=$random[$swap]; $random[$swap]=$tmp; } $total_rows=$opt_loop_count*3; #### #### Connect and start timeing #### $start_time=new Benchmark; $dbh = $server->connect(); #### #### Create needed tables #### goto keys_test if ($opt_stage == 2); goto select_test if ($opt_skip_create); print "Creating tables\n"; $dbh->do("drop table bench1" . $server->{'drop_attr'}); $dbh->do("drop table bench2" . $server->{'drop_attr'}); $dbh->do("drop table bench3" . $server->{'drop_attr'}); do_many($dbh,$server->create("bench1", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)", "index ix_id3 (id3)"])); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } #### #### Insert $total_rows records in order, in reverse order and random. #### $loop_time=new Benchmark; if ($opt_fast_insert) { $query="insert into bench1 values "; } else { $query="insert into bench1 (id,id2,id3,dummy1) values "; } if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; print "Transactions enabled\n" if ($opt_debug); } if (($opt_fast || $opt_fast_insert) && $server->{'limits'}->{'insert_multi_value'}) { $query_size=$server->{'limits'}->{'query_size'}; print "Inserting $opt_loop_count multiple-value rows in order\n"; $res=$query; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmp= "($i,$i,$i,'ABCDEFGHIJ'),"; if (length($tmp)+length($res) < $query_size) { $res.= $tmp; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp; } } print "Inserting $opt_loop_count multiple-value rows in reverse order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmp= "(" . ($total_rows-1-$i) . "," .($total_rows-1-$i) . "," .($total_rows-1-$i) . ",'BCDEFGHIJK'),"; if (length($tmp)+length($res) < $query_size) { $res.= $tmp; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp; } } print "Inserting $opt_loop_count multiple-value rows in random order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmp= "(" . $random[$i] . "," . $random[$i] . "," . $random[$i] . ",'CDEFGHIJKL')," or die $DBI::errstr; if (length($tmp)+length($res) < $query_size) { $res.= $tmp; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp; } } $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; } else { print "Inserting $opt_loop_count rows in order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $sth = $dbh->do($query . "($i,$i,$i,'ABCDEFGHIJ')") or die $DBI::errstr; } print "Inserting $opt_loop_count rows in reverse order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $sth = $dbh->do($query . "(" . ($total_rows-1-$i) . "," . ($total_rows-1-$i) . "," . ($total_rows-1-$i) . ",'BCDEFGHIJK')") or die $DBI::errstr; } print "Inserting $opt_loop_count rows in random order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $sth = $dbh->do($query . "(". $random[$i] . "," . $random[$i] . "," . $random[$i] . ",'CDEFGHIJKL')") or die $DBI::errstr; } } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for insert (" . ($total_rows) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh,"bench1"); } if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } #### #### insert $opt_loop_count records with duplicate id #### if ($limits->{'unique_index'}) { print "Testing insert of duplicates\n"; $loop_time=new Benchmark; if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($total_rows); $tmpquery = "$query ($tmp,$tmp,2,'D')"; if ($dbh->do($tmpquery)) { die "Didn't get an error when inserting duplicate record $tmp\n"; } } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for insert_duplicates (" . ($opt_loop_count) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } #### #### Do some selects on the table #### select_test: # ----------------- prepared+executed/prepared*executed tests print "Test of prepared+execute/once prepared many execute selects\n"; $loop_time=new Benchmark; for ($i=1 ; $i <= $opt_loop_count ; $i++) { my ($key_value)=$random[$i]; my ($query)= "select * from bench1 where id=$key_value"; print "$query\n" if ($opt_debug); $sth = $dbh->prepare($query); if (! $sth) { die "error in prepare select with id = $key_value : $DBI::errstr"; }; if (! $sth->execute) { die "cannot execute prepare select with id = $key_value : $DBI::errstr"; } while ($sth->fetchrow_arrayref) { }; $sth->finish; }; $end_time=new Benchmark; print "Time for prepared_select ($opt_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $query= "select * from bench1 where id=?"; $sth = $dbh->prepare($query); if (! $sth) { die "cannot prepare select: $DBI::errstr"; }; for ($i=1 ; $i <= $opt_loop_count ; $i++) { my ($key_value)=$random[$i]; $sth->bind_param(1,$key_value); print "$query , id = $key_value\n" if ($opt_debug); if (! $sth->execute) { die "cannot execute prepare select with id = $key_value : $DBI::errstr"; } while ($sth->fetchrow_arrayref) { }; }; $sth->finish; $end_time=new Benchmark; print "Time for once_prepared_select ($opt_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; print "Retrieving data from the table\n"; $loop_time=new Benchmark; $error=0; # It's really a small table, so we can try a select on everything $count=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { if (($found_rows=fetch_all_rows($dbh,"select id from bench1")) != $total_rows) { if (!$error++) { print "Warning: Got $found_rows rows when selecting a whole table of " . ($total_rows) . " rows\nContact the database or DBD author!\n"; } } $count+=$found_rows; } $end_time=new Benchmark; print "Time for select_big ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # # Do a lot of different ORDER BY queries # $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id,id2 from bench1 order by id,id2",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id,id2 from bench1 order by id desc, id2 desc",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key_desc ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id from bench1 order by id desc",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key_prefix ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id3 from bench1 order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key2 ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "id2" : "*"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select $sel from bench1 order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key_diff ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "id" : "*"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select $sel from bench1 order by id2,id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "dummy1" : "dummy1,id3"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { $start=$opt_loop_count/$range_loop_count*$i; $end=$start+$i; $rows+=fetch_all_rows($dbh,"select $sel from bench1 where id>=$start and id <= $end order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_range ($range_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "dummy1" : "dummy1,id"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { $start=$opt_loop_count/$range_loop_count*$i; $end=$start+$i; $rows+=fetch_all_rows($dbh,"select $sel from bench1 where id>=$start and id <= $end order by id",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_key_prefix ($range_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "id2" : "id2,id3"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { $start=$opt_loop_count/$range_loop_count*$i; $end=$start+$range_loop_count; $rows+=fetch_all_rows($dbh,"select $sel from bench1 where id3>=$start and id3 <= $end order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_key2_diff ($range_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # # Test of select on 2 different keys with or # (In this case database can only use keys if they do an automatic union). # $loop_time=new Benchmark; $estimated=0; $rows=0; $count=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { my $rnd=$i; my $rnd2=$random[$i]; $rows+=fetch_all_rows($dbh,"select id2 from bench1 where id=$rnd or id3=$rnd2",1); $count++; $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$count, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for select_diff_key ($count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # Test select that is very popular when using ODBC check_or_range("id","select_range_prefix"); check_or_range("id3","select_range_key2"); # Check reading on direct key on id and id3 check_select_key("*","id","select_key_prefix"); check_select_key2("*","id","id2","select_key"); check_select_key2("id,id2","id","id2","select_key_return_key"); check_select_key("*","id3","select_key2"); check_select_key("id3","id3","select_key2_return_key"); check_select_key("id,id2","id3","select_key2_return_prim"); #### #### A lot of simple selects on ranges #### @Q=("select * from bench1 where !id!=3 or !id!=2 or !id!=1 or !id!=4 or !id!=16 or !id!=10", 6, "select * from bench1 where !id!>=" . ($total_rows-1) ." or !id!<1", 2, "select * from bench1 where !id!>=1 and !id!<=2", 2, "select * from bench1 where (!id!>=1 and !id!<=2) or (!id!>=1 and !id!<=2)", 2, "select * from bench1 where !id!>=1 and !id!<=10 and !id!<=5", 5, "select * from bench1 where (!id!>0 and !id!<2) or !id!>=" . ($total_rows-1), 2, "select * from bench1 where (!id!>0 and !id!<2) or (!id!>= " . ($opt_loop_count/2) . " and !id! <= " . ($opt_loop_count/2+2) . ") or !id! = " . ($opt_loop_count/2-1), 5, "select * from bench1 where (!id!>=5 and !id!<=10) or (!id!>=1 and !id!<=4)", 10, "select * from bench1 where (!id!=1 or !id!=2) and (!id!=3 or !id!=4)", 0, "select * from bench1 where (!id!=1 or !id!=2) and (!id!=2 or !id!=3)", 1, "select * from bench1 where (!id!=1 or !id!=5 or !id!=20 or !id!=40) and (!id!=1 or !id!>=20 or !id!=4)", 3, "select * from bench1 where ((!id!=1 or !id!=3) or (!id!>1 and !id!<3)) and !id!<=2", 2, "select * from bench1 where (!id! >= 0 and !id! < 4) or (!id! >=4 and !id! < 6)", 6, "select * from bench1 where !id! <= -1 or (!id! >= 0 and !id! <= 5) or (!id! >=4 and !id! < 6) or (!id! >=6 and !id! <=7) or (!id!>7 and !id! <= 8)", 9, "select * from bench1 where (!id!>=1 and !id!<=2 or !id!>=4 and !id!<=5) or (!id!>=0 and !id! <=10)", 11, "select * from bench1 where (!id!>=1 and !id!<=2 or !id!>=4 and !id!<=5) or (!id!>2 and !id! <=10)", 10, "select * from bench1 where (!id!>1 or !id! <1) and !id!<=2", 2, "select * from bench1 where !id! <= 2 and (!id!>1 or !id! <=1)", 3, "select * from bench1 where (!id!>=1 or !id! <1) and !id!<=2", 3, "select * from bench1 where (!id!>=1 or !id! <=2) and !id!<=2", 3 ); print "\nTest of compares with simple ranges\n"; check_select_range("id","select_range_prefix"); check_select_range("id3","select_range_key2"); #### #### Some group queries #### if ($limits->{'group_functions'}) { $loop_time=new Benchmark; $count=1; $estimated=0; for ($tests=0 ; $tests < $small_loop_count ; $tests++) { $sth=$dbh->prepare($query="select count(*) from bench1") or die $DBI::errstr; $sth->execute or die $sth->errstr; if (($sth->fetchrow_array)[0] != $total_rows) { print "Warning: '$query' returned wrong result\n"; } $sth->finish; # min, max in keys are very normal $count+=7; fetch_all_rows($dbh,"select min(id) from bench1"); fetch_all_rows($dbh,"select max(id) from bench1"); fetch_all_rows($dbh,"select sum(id+0.0) from bench1"); fetch_all_rows($dbh,"select min(id3),max(id3),sum(id3-0.0) from bench1"); if ($limits->{'group_func_sql_min_str'}) { fetch_all_rows($dbh,"select min(dummy1),max(dummy1) from bench1"); } $count++; $sth=$dbh->prepare($query="select count(*) from bench1 where id >= " . ($opt_loop_count*2)) or die $DBI::errstr; $sth->execute or die $DBI::errstr; if (($sth->fetchrow_array)[0] != $opt_loop_count) { print "Warning: '$query' returned wrong result\n"; } $sth->finish; $count++; $sth=$dbh->prepare($query="select count(*),sum(id+0.0),min(id),max(id),avg(id-0.0) from bench1") or die $DBI::errstr; $sth->execute or die $DBI::errstr; @row=$sth->fetchrow_array; if ($row[0] != $total_rows || int($row[1]+0.5) != int((($total_rows-1)/2*$total_rows)+0.5) || $row[2] != 0 || $row[3] != $total_rows-1 || 1-$row[4]/(($total_rows-1)/2) > 0.001) { # PostgreSQL 6.3 fails here print "Warning: '$query' returned wrong result: @row\n"; } $sth->finish; if ($limits->{'func_odbc_mod'}) { $tmp="mod(id,10)"; if ($limits->{'func_extra_%'}) { $tmp="id % 10"; # For postgreSQL } $count++; if ($limits->{'group_by_alias'}) { if (fetch_all_rows($dbh,$query=$server->query("select $tmp as last_digit,count(*) from bench1 group by last_digit")) != 10) { print "Warning: '$query' returned wrong number of rows\n"; } } elsif ($limits->{'group_by_position'}) { if (fetch_all_rows($dbh,$query=$server->query("select $tmp,count(*) from bench1 group by 1")) != 10) { print "Warning: '$query' returned wrong number of rows\n"; } } } if ($limits->{'order_by_position'} && $limits->{'group_by_position'}) { $count++; if (fetch_all_rows($dbh, $query="select id,id3,dummy1 from bench1 where id < 100+$count-$count group by id,id3,dummy1 order by id desc,id3,dummy1") != 100) { print "Warning: '$query' returned wrong number of rows\n"; } } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $small_loop_count)); } print_time($estimated); print " for select_group ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=$estimated=0; for ($tests=1 ; $tests <= $range_loop_count*5 ; $tests++) { $count+=6; fetch_all_rows($dbh,"select min(id) from bench1"); fetch_all_rows($dbh,"select max(id) from bench1"); fetch_all_rows($dbh,"select min(id2) from bench1 where id=$tests"); fetch_all_rows($dbh,"select max(id2) from bench1 where id=$tests"); if ($limits->{'group_func_sql_min_str'}) { fetch_all_rows($dbh,"select min(dummy1) from bench1 where id=$tests"); fetch_all_rows($dbh,"select max(dummy1) from bench1 where id=$tests"); } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $range_loop_count*5)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for min_max_on_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=$estimated=0; for ($tests=1 ; $tests <= $small_loop_count ; $tests++) { $count+=6; fetch_all_rows($dbh,"select min(id2) from bench1"); fetch_all_rows($dbh,"select max(id2) from bench1"); fetch_all_rows($dbh,"select min(id3) from bench1 where id2=$tests"); fetch_all_rows($dbh,"select max(id3) from bench1 where id2=$tests"); if ($limits->{'group_func_sql_min_str'}) { fetch_all_rows($dbh,"select min(dummy1) from bench1 where id2=$tests"); fetch_all_rows($dbh,"select max(dummy1) from bench1 where id2=$tests"); } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for min_max ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; $total=$opt_loop_count*3; for ($tests=0 ; $tests < $total ; $tests+=$total/100) { $count+=1; fetch_all_rows($dbh,"select count(id) from bench1 where id < $tests"); } $end_time=new Benchmark; print "Time for count_on_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; for ($tests=0 ; $tests < $total ; $tests+=$total/100) { $count+=1; fetch_all_rows($dbh,"select count(dummy1) from bench1 where id2 < $tests"); } $end_time=new Benchmark; print "Time for count ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($limits->{'group_distinct_functions'}) { $loop_time=new Benchmark; $count=$estimated=0; for ($tests=1 ; $tests <= $small_loop_count ; $tests++) { $count+=2; fetch_all_rows($dbh,"select count(distinct dummy1) from bench1"); fetch_all_rows($dbh,"select dummy1,count(distinct id) from bench1 group by dummy1"); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for count_distinct_big ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } #### #### Some updates on the table #### $loop_time=new Benchmark; if ($limits->{'functions'}) { print "\nTesting update of keys with functions\n"; my $update_loop_count=$opt_loop_count/2; for ($i=0 ; $i < $update_loop_count ; $i++) { my $tmp=$opt_loop_count+$random[$i]; # $opt_loop_count*2 <= $tmp < $total_rows $sth = $dbh->do("update bench1 set id3=-$tmp where id3=$tmp") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_of_key ($update_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh,"bench1"); } if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $loop_time=new Benchmark; $count=0; $step=int($opt_loop_count/$range_loop_count+1); for ($i= 0 ; $i < $opt_loop_count ; $i+= $step) { $count++; $sth=$dbh->do("update bench1 set id3= 0-id3 where id3 >= 0 and id3 <= $i") or die $DBI::errstr; } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $count++; $sth=$dbh->do("update bench1 set id3= 0-id3 where id3 >= 0 and id3 < $opt_loop_count") or die $DBI::errstr; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $count++; $sth=$dbh->do("update bench1 set id3= 0-id3 where id3 >= $opt_loop_count and id3 < ". ($opt_loop_count*2)) or die $DBI::errstr; # # Check that everything was updated # In principle we shouldn't time this in the update loop.. # if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $row_count=0; if (($sth=$dbh->prepare("select count(*) from bench1 where id3>=0")) && $sth->execute) { ($row_count)=$sth->fetchrow; } $result=1 + $opt_loop_count-$update_loop_count; if ($row_count != $result) { print "Warning: Update check returned $row_count instead of $result\n"; } $sth->finish; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } #restore id3 to 0 <= id3 < $total_rows/10 or 0<= id3 < $total_rows my $func=($limits->{'func_odbc_floor'}) ? "floor((0-id3)/20)" : "0-id3"; $count++; $sth=$dbh->do($query="update bench1 set id3=$func where id3<0") or die $DBI::errstr; $end_time=new Benchmark; print "Time for update_of_key_big ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } else { print "\nTesting update of keys in loops\n"; # # This is for mSQL that doesn't have functions. Do we really need this ???? # $sth=$dbh->prepare("select id3 from bench1 where id3 >= 0") or die $DBI::errstr; $sth->execute or die $DBI::errstr; $count=0; while (@tmp = $sth->fetchrow_array) { my $tmp1 = "-$tmp[0]"; my $sth1 = $dbh->do("update bench1 set id3 = $tmp1 where id3 = $tmp[0]"); $count++; $end_time=new Benchmark; if (($end_time->[0] - $loop_time->[0]) > $opt_time_limit) { print "note: Aborting update loop because of timeout\n"; last; } } $sth->finish; # Check that everything except id3=0 was updated # In principle we shouldn't time this in the update loop.. # if (fetch_all_rows($dbh,$query="select * from bench1 where id3>=0") != 1) { if ($count == $total_rows) { print "Warning: Wrong information after update: Found '$row_count' rows, but should have been: 1\n"; } } #restore id3 to 0 <= id3 < $total_rows $sth=$dbh->prepare("select id3 from bench1 where id3 < 0") or die $DBI::errstr; $sth->execute or die $DBI::errstr; while (@tmp = $sth->fetchrow_array) { $count++; my $tmp1 = floor((0-$tmp[0])/10); my $sth1 = $dbh->do("update bench1 set id3 = $tmp1 where id3 = $tmp[0]"); } $sth->finish; $end_time=new Benchmark; $estimated=predict_query_time($loop_time,$end_time,\$count,$count, $opt_loop_count*6); if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for update_of_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } if ($opt_fast && defined($server->{vacuum})) { if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } $server->vacuum(1,\$dbh,"bench1"); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } # # Testing some simple updates # print "Testing update with key\n"; $loop_time=new Benchmark; for ($i=0 ; $i < $opt_loop_count*3 ; $i++) { $sth = $dbh->do("update bench1 set dummy1='updated' where id=$i and id2=$i") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_with_key (" . ($opt_loop_count*3) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; print "Testing update with key, no changes in data\n"; $loop_time=new Benchmark; for ($i=0 ; $i < $opt_loop_count*3 ; $i++) { $sth = $dbh->do("update bench1 set dummy1='updated' where id=$i and id2=$i") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_with_key_record_unchanged (" . ($opt_loop_count*3) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; for ($i=1 ; $i < $opt_loop_count*3 ; $i+=3) { $sth = $dbh->do("update bench1 set dummy1='really updated' where id=$i") or die $DBI::errstr; $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,($i-1)/3, $opt_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for update_with_key_prefix (" . ($opt_loop_count) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; print "\nTesting update of all rows\n"; $loop_time=new Benchmark; for ($i=0 ; $i < $small_loop_count ; $i++) { $sth = $dbh->do("update bench1 set dummy1='updated $i'") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_big ($small_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # # Testing left outer join # if ($limits->{'func_odbc_floor'} && $limits->{'left_outer_join'}) { if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 a READ, bench1 b READ") || die $DBI::errstr; } print "\nTesting left outer join\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(*) from bench1 as a left outer join bench1 as b on (a.id2=b.id3)"); } $end_time=new Benchmark; print "Time for outer_join_on_key ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3)"); } $end_time=new Benchmark; print "Time for outer_join ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $count=0; $loop_time=new Benchmark; for ($i=0 ; $i < $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3) where b.id3 is not null"); } $end_time=new Benchmark; print "Time for outer_join_found ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $count=$estimated=0; $loop_time=new Benchmark; for ($i=1 ; $i <= $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3) where b.id3 is null"); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time, \$count,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for outer_join_not_found ($range_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } ### ### Test speed of IN( value list) ### if ($limits->{'left_outer_join'}) { if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } print "\n"; do_many($dbh,$server->create("bench2", ["id int NOT NULL"], ["primary key (id)"])); $max_tests=min(($limits->{'query_size'}-50)/6, $opt_loop_count); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 READ, bench2 WRITE") || die $DBI::errstr; } test_where_in("bench1","bench2","id",1,10); test_where_in("bench1","bench2","id",11,min(100,$max_tests)); test_where_in("bench1","bench2","id",101,min(1000,$max_tests)); if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } $sth = $dbh->do("DROP TABLE bench2" . $server->{'drop_attr'}) || die $DBI::errstr; if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } #### #### Test INSERT INTO ... SELECT #### if ($limits->{'insert_select'}) { if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } print "\nTesting INSERT INTO ... SELECT\n"; do_many($dbh,$server->create("bench2", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)"])); do_many($dbh,$server->create("bench3", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)", "index index_id3 (id3)"])); $loop_time=new Benchmark; $sth = $dbh->do("INSERT INTO bench2 SELECT * from bench1") || die $DBI::errstr; $end_time=new Benchmark; print "Time for insert_select_1_key (1): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $sth = $dbh->do("INSERT INTO bench3 SELECT * from bench1") || die $DBI::errstr; $end_time=new Benchmark; print "Time for insert_select_2_keys (1): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $sth = $dbh->do("DROP TABLE bench2" . $server->{'drop_attr'}) || die $DBI::errstr; $sth = $dbh->do("DROP TABLE bench3" . $server->{'drop_attr'}) || die $DBI::errstr; $end_time=new Benchmark; print "Time for drop table(2): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh); } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } #### #### Do some deletes on the table #### if (!$opt_skip_delete) { print "\nTesting delete\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < $opt_loop_count ; $i+=10) { $count++; $tmp=$opt_loop_count+$random[$i]; # $opt_loop_count*2 <= $tmp < $total_rows $dbh->do("delete from bench1 where id3=$tmp") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for delete_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $count=0; $loop_time=new Benchmark; for ($i= 0 ; $i < $opt_loop_count ; $i+=$opt_loop_count/10) { $sth=$dbh->do("delete from bench1 where id3 >= 0 and id3 <= $i") or die $DBI::errstr; $count++; } $count+=2; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $sth=$dbh->do("delete from bench1 where id3 >= 0 and id3 <= $opt_loop_count") or die $DBI::errstr; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $sth=$dbh->do("delete from bench1 where id >= $opt_loop_count and id <= " . ($opt_loop_count*2) ) or die $DBI::errstr; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast) { $sth=$dbh->do("delete from bench1") or die $DBI::errstr; } else { $sth = $dbh->do("delete from bench1 where id3 < " . ($total_rows)) or die $DBI::errstr; } $end_time=new Benchmark; print "Time for delete_range ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}) or die $DBI::errstr; } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh); } keys_test: # # Test of insert in table with many keys # This test assumes that the server really create the keys! # my @fields=(); my @keys=(); $keys=min($limits->{'max_index'},16); # 16 is more than enough $seg= min($limits->{'max_index_parts'},$keys,16); # 16 is more than enough print "Insert into table with $keys keys and with a primary key with $seg parts\n"; # Make keys on the most important types @types=(0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1); # A 1 for each char field push(@fields,"field1 tinyint not null"); push(@fields,"field_search tinyint not null"); push(@fields,"field2 mediumint not null"); push(@fields,"field3 smallint not null"); push(@fields,"field4 char(16) not null"); push(@fields,"field5 integer not null"); push(@fields,"field6 float not null"); push(@fields,"field7 double not null"); for ($i=8 ; $i <= $keys ; $i++) { push(@fields,"field$i char(6) not null"); # Should be relatively fair } # First key contains many segments $query="primary key ("; for ($i= 1 ; $i <= $seg ; $i++) { $query.= "field$i,"; } substr($query,-1)=")"; push (@keys,$query); push (@keys,"index index2 (field_search)"); #Create other keys for ($i=3 ; $i <= $keys ; $i++) { push(@keys,"index index$i (field$i)"); } do_many($dbh,$server->create("bench1",\@fields,\@keys)); if ($opt_lock_tables) { $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $loop_time=new Benchmark; if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } $fields=$#fields; if (($opt_fast || $opt_fast_insert) && $server->{'limits'}->{'insert_multi_value'}) { $query_size=$server->{'limits'}->{'query_size'}; $query="insert into bench1 values "; $res=$query; for ($i=0; $i < $many_keys_loop_count; $i++) { $id= $i & 127; $rand=$random[$i]; $tmp="($id,$id,$rand," . ($i & 32766) . ",'ABCDEF$rand',0,$rand,$rand.0,"; for ($j=8; $j <= $fields ; $j++) { $tmp.= ($types[$j] == 0) ? "$rand," : "'$rand',"; } substr($tmp,-1)=")"; if (length($tmp)+length($res) < $query_size) { $res.= $tmp . ","; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp . ","; } } $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; } else { for ($i=0; $i < $many_keys_loop_count; $i++) { $id= $i & 127; $rand=$random[$i]; $query="insert into bench1 values ($id,$id,$rand," . ($i & 32767) . ",'ABCDEF$rand',0,$rand,$rand.0,"; for ($j=8; $j <= $fields ; $j++) { $query.= ($types[$j] == 0) ? "$rand," : "'$rand',"; } substr($query,-1)=")"; print "query1: $query\n" if ($opt_debug); $dbh->do($query) or die "Got error $DBI::errstr with query: $query\n"; } } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for insert_key ($many_keys_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast && defined($server->{vacuum})) { if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } $server->vacuum(1,\$dbh,"bench1"); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } # # update one key of the above # print "Testing update of keys\n"; $loop_time=new Benchmark; if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } for ($i=0 ; $i< 256; $i++) { $dbh->do("update bench1 set field5=1 where field_search=$i") or die "Got error $DBI::errstr with query: update bench1 set field5=1 where field_search=$i\n"; } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for update_of_primary_key_many_keys (256): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast && defined($server->{vacuum})) { if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } $server->vacuum(1,\$dbh,"bench1"); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } if ($server->small_rollback_segment()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } # # Delete everything from table # print "Deleting rows from the table\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < 128 ; $i++) { $count++; $dbh->do("delete from bench1 where field_search = $i") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for delete_big_many_keys ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } print "Deleting everything from table\n"; $count=1; if ($opt_fast) { $query= ($limits->{'truncate_table'} ? "truncate table bench1" : "delete from bench1"); $dbh->do($query) or die $DBI::errstr; } else { $dbh->do("delete from bench1 where field1 > 0") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for delete_all_many_keys ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}) or die $DBI::errstr; if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh); } # # Test multi value inserts if the server supports it # if ($limits->{'insert_multi_value'}) { $query_size=$limits->{'query_size'}; # Same limit for all databases $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}); do_many($dbh,$server->create("bench1", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)", "index index_id3 (id3)"])); $loop_time=new Benchmark; if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 write") || die $DBI::errstr; } if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } print "Inserting $opt_loop_count rows with multiple values\n"; $query="insert into bench1 values "; $res=$query; for ($i=0 ; $i < $opt_loop_count ; $i++) { my $tmp= "($i,$i,$i,'EFGHIJKLM'),"; if (length($i)+length($res) < $query_size) { $res.= $tmp; } else { do_query($dbh,substr($res,0,length($res)-1)); $res=$query .$tmp; } } do_query($dbh,substr($res,0,length($res)-1)); if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES ") || die $DBI::errstr; } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for multiple_value_insert (" . ($opt_loop_count) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES ") || die $DBI::errstr; } # A big table may take a while to drop $loop_time=new Benchmark; $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}) or die $DBI::errstr; $end_time=new Benchmark; print "Time for drop table(1): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } #### #### End of benchmark #### $dbh->disconnect; # close connection end_benchmark($start_time); ### ### Some help functions ### # Do some sample selects on direct key # First select finds a row, the second one doesn't find. sub check_select_key { my ($sel_columns,$column,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$count,$row_count,$estimated); $estimated=0; $loop_time=new Benchmark; $count=0; for ($i=1 ; $i <= $opt_read_key_loop_count; $i++) { $count+=2; $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($total_rows); fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp") or die $DBI::errstr; $tmp+=$total_rows; defined($row_count=fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp")) or die $DBI::errstr; die "Found $row_count rows on impossible id: $tmp\n" if ($row_count); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$i, $opt_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # Same as above, but select on 2 columns sub check_select_key2 { my ($sel_columns,$column,$column2,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$count,$row_count,$estimated); $estimated=0; $loop_time=new Benchmark; $count=0; for ($i=1 ; $i <= $opt_read_key_loop_count; $i++) { $count+=2; $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($total_rows); fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp and $column2=$tmp") or die $DBI::errstr; $tmp+=$total_rows; defined($row_count=fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp and $column2=$tmp")) or die $DBI::errstr; die "Found $row_count rows on impossible id: $tmp\n" if ($row_count); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$i, $opt_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # # Search using some very simple queries # sub check_select_range { my ($column,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$query,$rows,$estimated); $estimated=0; $loop_time=new Benchmark; $found=$count=0; for ($test=1 ; $test <= $range_loop_count; $test++) { $count+=$#Q+1; for ($i=0 ; $i < $#Q ; $i+=2) { $query=$Q[$i]; $rows=$Q[$i+1]; $query =~ s/!id!/$column/g; if (($row_count=fetch_all_rows($dbh,$query)) != $rows) { if ($row_count == undef()) { die "Got error: $DBI::errstr when executing $query\n"; } die "'$query' returned wrong number of rows: $row_count instead of $rows\n"; } $found+=$row_count; } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$test, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count:$found): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # # SELECT * from bench where col=x or col=x or col=x ... sub check_or_range { my ($column,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$columns,$estimated,$found, $or_part,$count,$loop_count); $columns=min($limits->{'max_columns'},50,($limits->{'query_size'}-50)/13); $columns=$columns- ($columns % 4); # Make Divisible by 4 $estimated=0; $loop_time=new Benchmark; $found=0; # The number of tests must be divisible by the following $tmp= $limits->{'func_extra_in_num'} ? 15 : 10; # We need to calculate the exact number of test to make 'Estimated' right $loop_count=$range_loop_count*10+$tmp-1; $loop_count=$loop_count- ($loop_count % $tmp); for ($count=0 ; $count < $loop_count ; ) { for ($rowcnt=0; $rowcnt <= $columns; $rowcnt+= $columns/4) { my $query="select * from bench1 where "; my $or_part= "$column = 1"; $count+=2; for ($i=1 ; $i < $rowcnt ; $i++) { $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($opt_loop_count*4); $or_part.=" or $column=$tmp"; } print $query . $or_part . "\n" if ($opt_debug); ($rows=fetch_all_rows($dbh,$query . $or_part)) or die $DBI::errstr; $found+=$rows; if ($limits->{'func_extra_in_num'}) { my $in_part=$or_part; # Same query, but use 'func_extra_in_num' instead. $in_part=~ s/ = / IN \(/; $in_part=~ s/ or $column=/,/g; $in_part.= ")"; fetch_all_rows($dbh,$query . $in_part) or die $DBI::errstr; $count++; } # Do it a little harder by setting a extra range defined(($rows=fetch_all_rows($dbh,"$query($or_part) and $column < 10"))) or die $DBI::errstr; $found+=$rows; } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$count, $loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count:$found): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # # General test of SELECT ... WHERE id in(value-list) # sub test_where_in { my ($t1,$t2,$id,$from,$to)= @_; return if ($from >= $to); $query="SELECT $t1.* FROM $t1 WHERE $id IN ("; for ($i=1 ; $i <= $to ; $i++) { $query.="$i,"; } $query=substr($query,0,length($query)-1) . ")"; # Fill join table to have the same id's as 'query' for ($i= $from ; $i <= $to ; $i++) { $dbh->do("insert into $t2 values($i)") or die $DBI::errstr; } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh,"bench1"); } time_fetch_all_rows("Testing SELECT ... WHERE id in ($to values)", "select_in", $query, $dbh, $range_loop_count); time_fetch_all_rows(undef, "select_join_in", "SELECT $t1.* FROM $t2 left outer join $t1 on ($t1.$id=$t2.$id)", $dbh, $range_loop_count); }
tempesta-tech/mariadb
sql-bench/test-insert.sh
Shell
gpl-2.0
51,085
var UserInformation_AccountStore = new Ext.data.Store({ fields:[ {name : 'Name'}, {name : 'ID'}, {name : 'Mail'}, {name : 'Roles'} ], reader : AccountReader }); var UserInformationItem = [ { fieldLabel : 'User ID', name : 'id', readOnly : true }, { fieldLabel : 'User Name', name : 'username', allowBlank : false, regex : /^[^"'\\><&]*$/, regexText : 'deny following char " < > \\ & \'' }, { id : 'UserInformation_Form_Password', fieldLabel : 'Password', name : 'passwd', inputType : 'password', listeners : { 'change': function() { if (this.getValue() == "") { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false); Ext.getCmp("UserInformation_Form_reenter").allowBlank = true; } else { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true); Ext.getCmp("UserInformation_Form_reenter").allowBlank = false; } } } }, { id : 'UserInformation_Form_reenter', fieldLabel : 'Re-enter', initialPassField : 'passwd', name : 'reenter', inputType : 'password', initialPassField: 'UserInformation_Form_Password', vtype : 'pwdvalid', listeners : { 'change': function() { if (Ext.getCmp("UserInformation_Form_Password").getValue() == "") { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true); this.allowBlank = true; } else { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false); this.allowBlank = false; } } } }, { fieldLabel : 'E-mail Address', name : 'email', vtype : 'email', allowBlank : false } ]; // the form is for UserInformation Page ezScrum.UserInformationForm = Ext.extend(ezScrum.layout.InfoForm, { id : 'UserInformation_Management_From', url : 'getUserData.do', modifyurl : 'updateAccount.do' , store : UserInformation_AccountStore, width:500, bodyStyle:'padding:50px', monitorValid : true, buttonAlign:'center', initComponent : function() { var config = { items : [UserInformationItem], buttons : [{ formBind : true, text : 'Submit', scope : this, handler : this.submit, disabled : true }] } Ext.apply(this, Ext.apply(this.initialConfig, config)); ezScrum.UserInformationForm.superclass.initComponent.apply(this, arguments); }, submit : function() { Ext.getCmp('UserInformationManagement_Page').doModify(); }, loadDataModel: function() { UserManagementMainLoadMaskShow(); Ext.Ajax.request({ scope : this, url : this.url, success: function(response) { UserInformation_AccountStore.loadData(response.responseXML); var record = UserInformation_AccountStore.getAt(0); this.setDataModel(record); UserManagementMainLoadMaskHide(); }, failure: function(response) { UserManagementMainLoadMaskHide(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); }, setDataModel: function(record) { this.getForm().reset(); this.getForm().setValues({ id : record.data['ID'], username: record.data['Name'], passwd : '', reenter : '', email : record.data['Mail'] }); }, doModify: function() { UserManagementMainLoadMaskShow(); Ext.Ajax.request({ scope : this, url : this.modifyurl, params : this.getForm().getValues(), success : function(response) { UserInformation_AccountStore.loadData(response.responseXML); var record = UserInformation_AccountStore.getAt(0); if (record) { Ext.example.msg('Update Account', 'Update Account Success'); } else { Ext.example.msg('Update Account', 'Update Account Failure'); } UserManagementMainLoadMaskHide(); }, failure:function(response){ UserManagementMainLoadMaskHide(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); } }); Ext.reg('UserInformationForm', ezScrum.UserInformationForm);
chusiang/ezScrum_Ubuntu
WebContent/javascript/ezScrumPanel/UserInformationManagementFormPanel.js
JavaScript
gpl-2.0
4,497
/* polygon clipping functions. harry eaton implemented the algorithm described in "A Closed Set of Algorithms for Performing Set Operations on Polygonal Regions in the Plane" which the original code did not do. I also modified it for integer coordinates and faster computation. The license for this modified copy was switched to the GPL per term (3) of the original LGPL license. Copyright (C) 2006 harry eaton based on: poly_Boolean: a polygon clip library Copyright (C) 1997 Alexey Nikitin, Michael Leonov (also the authors of the paper describing the actual algorithm) leonov@propro.iis.nsk.su in turn based on: nclip: a polygon clip library Copyright (C) 1993 Klamer Schutte This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. polygon1.c (C) 1997 Alexey Nikitin, Michael Leonov (C) 1993 Klamer Schutte all cases where original (Klamer Schutte) code is present are marked */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <setjmp.h> #include <math.h> #include <string.h> #include "global.h" #include "rtree.h" #include "heap.h" #define ROUND(a) (long)((a) > 0 ? ((a) + 0.5) : ((a) - 0.5)) #define EPSILON (1E-8) #define IsZero(a, b) (fabs((a) - (b)) < EPSILON) /*********************************************************************/ /* L o n g V e c t o r S t u f f */ /*********************************************************************/ #define Vcopy(a,b) {(a)[0]=(b)[0];(a)[1]=(b)[1];} int vect_equal (Vector v1, Vector v2); void vect_init (Vector v, double x, double y); void vect_sub (Vector res, Vector v2, Vector v3); void vect_min (Vector res, Vector v2, Vector v3); void vect_max (Vector res, Vector v2, Vector v3); double vect_dist2 (Vector v1, Vector v2); double vect_det2 (Vector v1, Vector v2); double vect_len2 (Vector v1); int vect_inters2 (Vector A, Vector B, Vector C, Vector D, Vector S1, Vector S2); /* note that a vertex v's Flags.status represents the edge defined by * v to v->next (i.e. the edge is forward of v) */ #define ISECTED 3 #define UNKNWN 0 #define INSIDE 1 #define OUTSIDE 2 #define SHARED 3 #define SHARED2 4 #define TOUCHES 99 #define NODE_LABEL(n) ((n)->Flags.status) #define LABEL_NODE(n,l) ((n)->Flags.status = (l)) #define error(code) longjmp(*(e), code) #define MemGet(ptr, type) \ if (UNLIKELY (((ptr) = (type *)malloc(sizeof(type))) == NULL)) \ error(err_no_memory); #undef DEBUG_LABEL #undef DEBUG_ALL_LABELS #undef DEBUG_JUMP #undef DEBUG_GATHER #undef DEBUG_ANGLE #undef DEBUG #ifdef DEBUG #define DEBUGP(...) pcb_fprintf(stderr, ## __VA_ARGS__) #else #define DEBUGP(...) #endif /* ///////////////////////////////////////////////////////////////////////////// * / / * 2-Dimentional stuff / * ///////////////////////////////////////////////////////////////////////////// */ #define Vsub2(r,a,b) {(r)[0] = (a)[0] - (b)[0]; (r)[1] = (a)[1] - (b)[1];} #define Vadd2(r,a,b) {(r)[0] = (a)[0] + (b)[0]; (r)[1] = (a)[1] + (b)[1];} #define Vsca2(r,a,s) {(r)[0] = (a)[0] * (s); (r)[1] = (a)[1] * (s);} #define Vcpy2(r,a) {(r)[0] = (a)[0]; (r)[1] = (a)[1];} #define Vequ2(a,b) ((a)[0] == (b)[0] && (a)[1] == (b)[1]) #define Vadds(r,a,b,s) {(r)[0] = ((a)[0] + (b)[0]) * (s); (r)[1] = ((a)[1] + (b)[1]) * (s);} #define Vswp2(a,b) { long t; \ t = (a)[0], (a)[0] = (b)[0], (b)[0] = t; \ t = (a)[1], (a)[1] = (b)[1], (b)[1] = t; \ } #ifdef DEBUG static char *theState (VNODE * v); static void pline_dump (VNODE * v) { VNODE *s, *n; s = v; do { n = v->next; pcb_fprintf (stderr, "Line [%#mS %#mS %#mS %#mS 10 10 \"%s\"]\n", v->point[0], v->point[1], n->point[0], n->point[1], theState (v)); } while ((v = v->next) != s); } static void poly_dump (POLYAREA * p) { POLYAREA *f = p; PLINE *pl; do { pl = p->contours; do { pline_dump (&pl->head); fprintf (stderr, "NEXT PLINE\n"); } while ((pl = pl->next) != NULL); fprintf (stderr, "NEXT POLY\n"); } while ((p = p->f) != f); } #endif /***************************************************************/ /* routines for processing intersections */ /* node_add (C) 1993 Klamer Schutte (C) 1997 Alexey Nikitin, Michael Leonov (C) 2006 harry eaton returns a bit field in new_point that indicates where the point was. 1 means a new node was created and inserted 4 means the intersection was not on the dest point */ static VNODE * node_add_single (VNODE * dest, Vector po) { VNODE *p; if (vect_equal (po, dest->point)) return dest; if (vect_equal (po, dest->next->point)) return dest->next; p = poly_CreateNode (po); if (p == NULL) return NULL; p->cvc_prev = p->cvc_next = NULL; p->Flags.status = UNKNWN; return p; } /* node_add */ #define ISECT_BAD_PARAM (-1) #define ISECT_NO_MEMORY (-2) /* new_descriptor (C) 2006 harry eaton */ static CVCList * new_descriptor (VNODE * a, char poly, char side) { CVCList *l = (CVCList *) malloc (sizeof (CVCList)); Vector v; register double ang, dx, dy; if (!l) return NULL; l->head = NULL; l->parent = a; l->poly = poly; l->side = side; l->next = l->prev = l; if (side == 'P') /* previous */ vect_sub (v, a->prev->point, a->point); else /* next */ vect_sub (v, a->next->point, a->point); /* Uses slope/(slope+1) in quadrant 1 as a proxy for the angle. * It still has the same monotonic sort result * and is far less expensive to compute than the real angle. */ if (vect_equal (v, vect_zero)) { if (side == 'P') { if (a->prev->cvc_prev == (CVCList *) - 1) a->prev->cvc_prev = a->prev->cvc_next = NULL; poly_ExclVertex (a->prev); vect_sub (v, a->prev->point, a->point); } else { if (a->next->cvc_prev == (CVCList *) - 1) a->next->cvc_prev = a->next->cvc_next = NULL; poly_ExclVertex (a->next); vect_sub (v, a->next->point, a->point); } } assert (!vect_equal (v, vect_zero)); dx = fabs ((double) v[0]); dy = fabs ((double) v[1]); ang = dy / (dy + dx); /* now move to the actual quadrant */ if (v[0] < 0 && v[1] >= 0) ang = 2.0 - ang; /* 2nd quadrant */ else if (v[0] < 0 && v[1] < 0) ang += 2.0; /* 3rd quadrant */ else if (v[0] >= 0 && v[1] < 0) ang = 4.0 - ang; /* 4th quadrant */ l->angle = ang; assert (ang >= 0.0 && ang <= 4.0); #ifdef DEBUG_ANGLE DEBUGP ("node on %c at %#mD assigned angle %g on side %c\n", poly, a->point[0], a->point[1], ang, side); #endif return l; } /* insert_descriptor (C) 2006 harry eaton argument a is a cross-vertex node. argument poly is the polygon it comes from ('A' or 'B') argument side is the side this descriptor goes on ('P' for previous 'N' for next. argument start is the head of the list of cvclists */ static CVCList * insert_descriptor (VNODE * a, char poly, char side, CVCList * start) { CVCList *l, *newone, *big, *small; if (!(newone = new_descriptor (a, poly, side))) return NULL; /* search for the CVCList for this point */ if (!start) { start = newone; /* return is also new, so we know where start is */ start->head = newone; /* circular list */ return newone; } else { l = start; do { assert (l->head); if (l->parent->point[0] == a->point[0] && l->parent->point[1] == a->point[1]) { /* this CVCList is at our point */ start = l; newone->head = l->head; break; } if (l->head->parent->point[0] == start->parent->point[0] && l->head->parent->point[1] == start->parent->point[1]) { /* this seems to be a new point */ /* link this cvclist to the list of all cvclists */ for (; l->head != newone; l = l->next) l->head = newone; newone->head = start; return newone; } l = l->head; } while (1); } assert (start); l = big = small = start; do { if (l->next->angle < l->angle) /* find start/end of list */ { small = l->next; big = l; } else if (newone->angle >= l->angle && newone->angle <= l->next->angle) { /* insert new cvc if it lies between existing points */ newone->prev = l; newone->next = l->next; l->next = l->next->prev = newone; return newone; } } while ((l = l->next) != start); /* didn't find it between points, it must go on an end */ if (big->angle <= newone->angle) { newone->prev = big; newone->next = big->next; big->next = big->next->prev = newone; return newone; } assert (small->angle >= newone->angle); newone->next = small; newone->prev = small->prev; small->prev = small->prev->next = newone; return newone; } /* node_add_point (C) 1993 Klamer Schutte (C) 1997 Alexey Nikitin, Michael Leonov return 1 if new node in b, 2 if new node in a and 3 if new node in both */ static VNODE * node_add_single_point (VNODE * a, Vector p) { VNODE *next_a, *new_node; next_a = a->next; new_node = node_add_single (a, p); assert (new_node != NULL); new_node->cvc_prev = new_node->cvc_next = (CVCList *) - 1; if (new_node == a || new_node == next_a) return NULL; return new_node; } /* node_add_point */ /* node_label (C) 2006 harry eaton */ static unsigned int node_label (VNODE * pn) { CVCList *first_l, *l; char this_poly; int region = UNKNWN; assert (pn); assert (pn->cvc_next); this_poly = pn->cvc_next->poly; /* search counter-clockwise in the cross vertex connectivity (CVC) list * * check for shared edges (that could be prev or next in the list since the angles are equal) * and check if this edge (pn -> pn->next) is found between the other poly's entry and exit */ if (pn->cvc_next->angle == pn->cvc_next->prev->angle) l = pn->cvc_next->prev; else l = pn->cvc_next->next; first_l = l; while ((l->poly == this_poly) && (l != first_l->prev)) l = l->next; assert (l->poly != this_poly); assert (l && l->angle >= 0 && l->angle <= 4.0); if (l->poly != this_poly) { if (l->side == 'P') { if (l->parent->prev->point[0] == pn->next->point[0] && l->parent->prev->point[1] == pn->next->point[1]) { region = SHARED2; pn->shared = l->parent->prev; } else region = INSIDE; } else { if (l->angle == pn->cvc_next->angle) { assert (l->parent->next->point[0] == pn->next->point[0] && l->parent->next->point[1] == pn->next->point[1]); region = SHARED; pn->shared = l->parent; } else region = OUTSIDE; } } if (region == UNKNWN) { for (l = l->next; l != pn->cvc_next; l = l->next) { if (l->poly != this_poly) { if (l->side == 'P') region = INSIDE; else region = OUTSIDE; break; } } } assert (region != UNKNWN); assert (NODE_LABEL (pn) == UNKNWN || NODE_LABEL (pn) == region); LABEL_NODE (pn, region); if (region == SHARED || region == SHARED2) return UNKNWN; return region; } /* node_label */ /* add_descriptors (C) 2006 harry eaton */ static CVCList * add_descriptors (PLINE * pl, char poly, CVCList * list) { VNODE *node = &pl->head; do { if (node->cvc_prev) { assert (node->cvc_prev == (CVCList *) - 1 && node->cvc_next == (CVCList *) - 1); list = node->cvc_prev = insert_descriptor (node, poly, 'P', list); if (!node->cvc_prev) return NULL; list = node->cvc_next = insert_descriptor (node, poly, 'N', list); if (!node->cvc_next) return NULL; } } while ((node = node->next) != &pl->head); return list; } static inline void cntrbox_adjust (PLINE * c, Vector p) { c->xmin = min (c->xmin, p[0]); c->xmax = max (c->xmax, p[0] + 1); c->ymin = min (c->ymin, p[1]); c->ymax = max (c->ymax, p[1] + 1); } /* some structures for handling segment intersections using the rtrees */ typedef struct seg { BoxType box; VNODE *v; PLINE *p; int intersected; } seg; typedef struct _insert_node_task insert_node_task; struct _insert_node_task { insert_node_task *next; seg * node_seg; VNODE *new_node; }; typedef struct info { double m, b; rtree_t *tree; VNODE *v; struct seg *s; jmp_buf *env, sego, *touch; int need_restart; insert_node_task *node_insert_list; } info; typedef struct contour_info { PLINE *pa; jmp_buf restart; jmp_buf *getout; int need_restart; insert_node_task *node_insert_list; } contour_info; /* * adjust_tree() * (C) 2006 harry eaton * This replaces the segment in the tree with the two new segments after * a vertex has been added */ static int adjust_tree (rtree_t * tree, struct seg *s) { struct seg *q; q = (seg *)malloc (sizeof (struct seg)); if (!q) return 1; q->intersected = 0; q->v = s->v; q->p = s->p; q->box.X1 = min (q->v->point[0], q->v->next->point[0]); q->box.X2 = max (q->v->point[0], q->v->next->point[0]) + 1; q->box.Y1 = min (q->v->point[1], q->v->next->point[1]); q->box.Y2 = max (q->v->point[1], q->v->next->point[1]) + 1; r_insert_entry (tree, (const BoxType *) q, 1); q = (seg *)malloc (sizeof (struct seg)); if (!q) return 1; q->intersected = 0; q->v = s->v->next; q->p = s->p; q->box.X1 = min (q->v->point[0], q->v->next->point[0]); q->box.X2 = max (q->v->point[0], q->v->next->point[0]) + 1; q->box.Y1 = min (q->v->point[1], q->v->next->point[1]); q->box.Y2 = max (q->v->point[1], q->v->next->point[1]) + 1; r_insert_entry (tree, (const BoxType *) q, 1); r_delete_entry (tree, (const BoxType *) s); return 0; } /* * seg_in_region() * (C) 2006, harry eaton * This prunes the search for boxes that don't intersect the segment. */ static int seg_in_region (const BoxType * b, void *cl) { struct info *i = (struct info *) cl; double y1, y2; /* for zero slope the search is aligned on the axis so it is already pruned */ if (i->m == 0.) return 1; y1 = i->m * b->X1 + i->b; y2 = i->m * b->X2 + i->b; if (min (y1, y2) >= b->Y2) return 0; if (max (y1, y2) < b->Y1) return 0; return 1; /* might intersect */ } /* Prepend a deferred node-insersion task to a list */ static insert_node_task * prepend_insert_node_task (insert_node_task *list, seg *seg, VNODE *new_node) { insert_node_task *task = (insert_node_task *)malloc (sizeof (*task)); task->node_seg = seg; task->new_node = new_node; task->next = list; return task; } /* * seg_in_seg() * (C) 2006 harry eaton * This routine checks if the segment in the tree intersect the search segment. * If it does, the plines are marked as intersected and the point is marked for * the cvclist. If the point is not already a vertex, a new vertex is inserted * and the search for intersections starts over at the beginning. * That is potentially a significant time penalty, but it does solve the snap rounding * problem. There are efficient algorithms for finding intersections with snap * rounding, but I don't have time to implement them right now. */ static int seg_in_seg (const BoxType * b, void *cl) { struct info *i = (struct info *) cl; struct seg *s = (struct seg *) b; Vector s1, s2; int cnt; VNODE *new_node; /* When new nodes are added at the end of a pass due to an intersection * the segments may be altered. If either segment we're looking at has * already been intersected this pass, skip it until the next pass. */ if (s->intersected || i->s->intersected) return 0; cnt = vect_inters2 (s->v->point, s->v->next->point, i->v->point, i->v->next->point, s1, s2); if (!cnt) return 0; if (i->touch) /* if checking touches one find and we're done */ longjmp (*i->touch, TOUCHES); i->s->p->Flags.status = ISECTED; s->p->Flags.status = ISECTED; for (; cnt; cnt--) { bool done_insert_on_i = false; new_node = node_add_single_point (i->v, cnt > 1 ? s2 : s1); if (new_node != NULL) { #ifdef DEBUG_INTERSECT DEBUGP ("new intersection on segment \"i\" at %#mD\n", cnt > 1 ? s2[0] : s1[0], cnt > 1 ? s2[1] : s1[1]); #endif i->node_insert_list = prepend_insert_node_task (i->node_insert_list, i->s, new_node); i->s->intersected = 1; done_insert_on_i = true; } new_node = node_add_single_point (s->v, cnt > 1 ? s2 : s1); if (new_node != NULL) { #ifdef DEBUG_INTERSECT DEBUGP ("new intersection on segment \"s\" at %#mD\n", cnt > 1 ? s2[0] : s1[0], cnt > 1 ? s2[1] : s1[1]); #endif i->node_insert_list = prepend_insert_node_task (i->node_insert_list, s, new_node); s->intersected = 1; return 0; /* Keep looking for intersections with segment "i" */ } /* Skip any remaining r_search hits against segment i, as any futher * intersections will be rejected until the next pass anyway. */ if (done_insert_on_i) longjmp (*i->env, 1); } return 0; } static void * make_edge_tree (PLINE * pb) { struct seg *s; VNODE *bv; rtree_t *ans = r_create_tree (NULL, 0, 0); bv = &pb->head; do { s = (seg *)malloc (sizeof (struct seg)); s->intersected = 0; if (bv->point[0] < bv->next->point[0]) { s->box.X1 = bv->point[0]; s->box.X2 = bv->next->point[0] + 1; } else { s->box.X2 = bv->point[0] + 1; s->box.X1 = bv->next->point[0]; } if (bv->point[1] < bv->next->point[1]) { s->box.Y1 = bv->point[1]; s->box.Y2 = bv->next->point[1] + 1; } else { s->box.Y2 = bv->point[1] + 1; s->box.Y1 = bv->next->point[1]; } s->v = bv; s->p = pb; r_insert_entry (ans, (const BoxType *) s, 1); } while ((bv = bv->next) != &pb->head); return (void *) ans; } static int get_seg (const BoxType * b, void *cl) { struct info *i = (struct info *) cl; struct seg *s = (struct seg *) b; if (i->v == s->v) { i->s = s; longjmp (i->sego, 1); } return 0; } /* * intersect() (and helpers) * (C) 2006, harry eaton * This uses an rtree to find A-B intersections. Whenever a new vertex is * added, the search for intersections is re-started because the rounding * could alter the topology otherwise. * This should use a faster algorithm for snap rounding intersection finding. * The best algorthim is probably found in: * * "Improved output-sensitive snap rounding," John Hershberger, Proceedings * of the 22nd annual symposium on Computational geomerty, 2006, pp 357-366. * http://doi.acm.org/10.1145/1137856.1137909 * * Algorithms described by de Berg, or Goodrich or Halperin, or Hobby would * probably work as well. * */ static int contour_bounds_touch (const BoxType * b, void *cl) { contour_info *c_info = (contour_info *) cl; PLINE *pa = c_info->pa; PLINE *pb = (PLINE *) b; PLINE *rtree_over; PLINE *looping_over; VNODE *av; /* node iterators */ struct info info; BoxType box; jmp_buf restart; /* Have seg_in_seg return to our desired location if it touches */ info.env = &restart; info.touch = c_info->getout; info.need_restart = 0; info.node_insert_list = c_info->node_insert_list; /* Pick which contour has the fewer points, and do the loop * over that. The r_tree makes hit-testing against a contour * faster, so we want to do that on the bigger contour. */ if (pa->Count < pb->Count) { rtree_over = pb; looping_over = pa; } else { rtree_over = pa; looping_over = pb; } av = &looping_over->head; do /* Loop over the nodes in the smaller contour */ { /* check this edge for any insertions */ double dx; info.v = av; /* compute the slant for region trimming */ dx = av->next->point[0] - av->point[0]; if (dx == 0) info.m = 0; else { info.m = (av->next->point[1] - av->point[1]) / dx; info.b = av->point[1] - info.m * av->point[0]; } box.X2 = (box.X1 = av->point[0]) + 1; box.Y2 = (box.Y1 = av->point[1]) + 1; /* fill in the segment in info corresponding to this node */ if (setjmp (info.sego) == 0) { r_search (looping_over->tree, &box, NULL, get_seg, &info); assert (0); } /* If we're going to have another pass anyway, skip this */ if (info.s->intersected && info.node_insert_list != NULL) continue; if (setjmp (restart)) continue; /* NB: If this actually hits anything, we are teleported back to the beginning */ info.tree = rtree_over->tree; if (info.tree) if (UNLIKELY (r_search (info.tree, &info.s->box, seg_in_region, seg_in_seg, &info))) assert (0); /* XXX: Memory allocation failure */ } while ((av = av->next) != &looping_over->head); c_info->node_insert_list = info.node_insert_list; if (info.need_restart) c_info->need_restart = 1; return 0; } static int intersect_impl (jmp_buf * jb, POLYAREA * b, POLYAREA * a, int add) { POLYAREA *t; PLINE *pa; contour_info c_info; int need_restart = 0; insert_node_task *task; c_info.need_restart = 0; c_info.node_insert_list = NULL; /* Search the r-tree of the object with most contours * We loop over the contours of "a". Swap if necessary. */ if (a->contour_tree->size > b->contour_tree->size) { t = b; b = a; a = t; } for (pa = a->contours; pa; pa = pa->next) /* Loop over the contours of POLYAREA "a" */ { BoxType sb; jmp_buf out; int retval; c_info.getout = NULL; c_info.pa = pa; if (!add) { retval = setjmp (out); if (retval) { /* The intersection test short-circuited back here, * we need to clean up, then longjmp to jb */ longjmp (*jb, retval); } c_info.getout = &out; } sb.X1 = pa->xmin; sb.Y1 = pa->ymin; sb.X2 = pa->xmax + 1; sb.Y2 = pa->ymax + 1; r_search (b->contour_tree, &sb, NULL, contour_bounds_touch, &c_info); if (c_info.need_restart) need_restart = 1; } /* Process any deferred node insersions */ task = c_info.node_insert_list; while (task != NULL) { insert_node_task *next = task->next; /* Do insersion */ task->new_node->prev = task->node_seg->v; task->new_node->next = task->node_seg->v->next; task->node_seg->v->next->prev = task->new_node; task->node_seg->v->next = task->new_node; task->node_seg->p->Count++; cntrbox_adjust (task->node_seg->p, task->new_node->point); if (adjust_tree (task->node_seg->p->tree, task->node_seg)) assert (0); /* XXX: Memory allocation failure */ need_restart = 1; /* Any new nodes could intersect */ free (task); task = next; } return need_restart; } static int intersect (jmp_buf * jb, POLYAREA * b, POLYAREA * a, int add) { int call_count = 1; while (intersect_impl (jb, b, a, add)) call_count++; return 0; } static void M_POLYAREA_intersect (jmp_buf * e, POLYAREA * afst, POLYAREA * bfst, int add) { POLYAREA *a = afst, *b = bfst; PLINE *curcA, *curcB; CVCList *the_list = NULL; if (a == NULL || b == NULL) error (err_bad_parm); do { do { if (a->contours->xmax >= b->contours->xmin && a->contours->ymax >= b->contours->ymin && a->contours->xmin <= b->contours->xmax && a->contours->ymin <= b->contours->ymax) { if (UNLIKELY (intersect (e, a, b, add))) error (err_no_memory); } } while (add && (a = a->f) != afst); for (curcB = b->contours; curcB != NULL; curcB = curcB->next) if (curcB->Flags.status == ISECTED) { the_list = add_descriptors (curcB, 'B', the_list); if (UNLIKELY (the_list == NULL)) error (err_no_memory); } } while (add && (b = b->f) != bfst); do { for (curcA = a->contours; curcA != NULL; curcA = curcA->next) if (curcA->Flags.status == ISECTED) { the_list = add_descriptors (curcA, 'A', the_list); if (UNLIKELY (the_list == NULL)) error (err_no_memory); } } while (add && (a = a->f) != afst); } /* M_POLYAREA_intersect */ static inline int cntrbox_inside (PLINE * c1, PLINE * c2) { assert (c1 != NULL && c2 != NULL); return ((c1->xmin >= c2->xmin) && (c1->ymin >= c2->ymin) && (c1->xmax <= c2->xmax) && (c1->ymax <= c2->ymax)); } /*****************************************************************/ /* Routines for making labels */ static int count_contours_i_am_inside (const BoxType * b, void *cl) { PLINE *me = (PLINE *) cl; PLINE *check = (PLINE *) b; if (poly_ContourInContour (check, me)) return 1; return 0; } /* cntr_in_M_POLYAREA returns poly is inside outfst ? TRUE : FALSE */ static int cntr_in_M_POLYAREA (PLINE * poly, POLYAREA * outfst, BOOLp test) { POLYAREA *outer = outfst; heap_t *heap; assert (poly != NULL); assert (outer != NULL); heap = heap_create (); do { if (cntrbox_inside (poly, outer->contours)) heap_insert (heap, outer->contours->area, (void *) outer); } /* if checking touching, use only the first polygon */ while (!test && (outer = outer->f) != outfst); /* we need only check the smallest poly container * but we must loop in case the box containter is not * the poly container */ do { if (heap_is_empty (heap)) break; outer = (POLYAREA *) heap_remove_smallest (heap); switch (r_search (outer->contour_tree, (BoxType *) poly, NULL, count_contours_i_am_inside, poly)) { case 0: /* Didn't find anything in this piece, Keep looking */ break; case 1: /* Found we are inside this piece, and not any of its holes */ heap_destroy (&heap); return TRUE; case 2: /* Found inside a hole in the smallest polygon so far. No need to check the other polygons */ heap_destroy (&heap); return FALSE; default: printf ("Something strange here\n"); break; } } while (1); heap_destroy (&heap); return FALSE; } /* cntr_in_M_POLYAREA */ #ifdef DEBUG static char * theState (VNODE * v) { static char u[] = "UNKNOWN"; static char i[] = "INSIDE"; static char o[] = "OUTSIDE"; static char s[] = "SHARED"; static char s2[] = "SHARED2"; switch (NODE_LABEL (v)) { case INSIDE: return i; case OUTSIDE: return o; case SHARED: return s; case SHARED2: return s2; default: return u; } } #ifdef DEBUG_ALL_LABELS static void print_labels (PLINE * a) { VNODE *c = &a->head; do { DEBUGP ("%#mD->%#mD labeled %s\n", c->point[0], c->point[1], c->next->point[0], c->next->point[1], theState (c)); } while ((c = c->next) != &a->head); } #endif #endif /* label_contour (C) 2006 harry eaton (C) 1993 Klamer Schutte (C) 1997 Alexey Nikitin, Michael Leonov */ static BOOLp label_contour (PLINE * a) { VNODE *cur = &a->head; VNODE *first_labelled = NULL; int label = UNKNWN; do { if (cur->cvc_next) /* examine cross vertex */ { label = node_label (cur); if (first_labelled == NULL) first_labelled = cur; continue; } if (first_labelled == NULL) continue; /* This labels nodes which aren't cross-connected */ assert (label == INSIDE || label == OUTSIDE); LABEL_NODE (cur, label); } while ((cur = cur->next) != first_labelled); #ifdef DEBUG_ALL_LABELS print_labels (a); DEBUGP ("\n\n"); #endif return FALSE; } /* label_contour */ static BOOLp cntr_label_POLYAREA (PLINE * poly, POLYAREA * ppl, BOOLp test) { assert (ppl != NULL && ppl->contours != NULL); if (poly->Flags.status == ISECTED) { label_contour (poly); /* should never get here when BOOLp is true */ } else if (cntr_in_M_POLYAREA (poly, ppl, test)) { if (test) return TRUE; poly->Flags.status = INSIDE; } else { if (test) return false; poly->Flags.status = OUTSIDE; } return FALSE; } /* cntr_label_POLYAREA */ static BOOLp M_POLYAREA_label_separated (PLINE * afst, POLYAREA * b, BOOLp touch) { PLINE *curc = afst; for (curc = afst; curc != NULL; curc = curc->next) { if (cntr_label_POLYAREA (curc, b, touch) && touch) return TRUE; } return FALSE; } static BOOLp M_POLYAREA_label (POLYAREA * afst, POLYAREA * b, BOOLp touch) { POLYAREA *a = afst; PLINE *curc; assert (a != NULL); do { for (curc = a->contours; curc != NULL; curc = curc->next) if (cntr_label_POLYAREA (curc, b, touch)) { if (touch) return TRUE; } } while (!touch && (a = a->f) != afst); return FALSE; } /****************************************************************/ /* routines for temporary storing resulting contours */ static void InsCntr (jmp_buf * e, PLINE * c, POLYAREA ** dst) { POLYAREA *newp; if (*dst == NULL) { MemGet (*dst, POLYAREA); (*dst)->f = (*dst)->b = *dst; newp = *dst; } else { MemGet (newp, POLYAREA); newp->f = *dst; newp->b = (*dst)->b; newp->f->b = newp->b->f = newp; } newp->contours = c; newp->contour_tree = r_create_tree (NULL, 0, 0); r_insert_entry (newp->contour_tree, (BoxType *) c, 0); c->next = NULL; } /* InsCntr */ static void PutContour (jmp_buf * e, PLINE * cntr, POLYAREA ** contours, PLINE ** holes, POLYAREA * owner, POLYAREA * parent, PLINE * parent_contour) { assert (cntr != NULL); assert (cntr->Count > 2); cntr->next = NULL; if (cntr->Flags.orient == PLF_DIR) { if (owner != NULL) r_delete_entry (owner->contour_tree, (BoxType *) cntr); InsCntr (e, cntr, contours); } /* put hole into temporary list */ else { /* if we know this belongs inside the parent, put it there now */ if (parent_contour) { cntr->next = parent_contour->next; parent_contour->next = cntr; if (owner != parent) { if (owner != NULL) r_delete_entry (owner->contour_tree, (BoxType *) cntr); r_insert_entry (parent->contour_tree, (BoxType *) cntr, 0); } } else { cntr->next = *holes; *holes = cntr; /* let cntr be 1st hole in list */ /* We don't insert the holes into an r-tree, * they just form a linked list */ if (owner != NULL) r_delete_entry (owner->contour_tree, (BoxType *) cntr); } } } /* PutContour */ static inline void remove_contour (POLYAREA * piece, PLINE * prev_contour, PLINE * contour, int remove_rtree_entry) { if (piece->contours == contour) piece->contours = contour->next; else if (prev_contour != NULL) { assert (prev_contour->next == contour); prev_contour->next = contour->next; } contour->next = NULL; if (remove_rtree_entry) r_delete_entry (piece->contour_tree, (BoxType *) contour); } struct polyarea_info { BoxType BoundingBox; POLYAREA *pa; }; static int heap_it (const BoxType * b, void *cl) { heap_t *heap = (heap_t *) cl; struct polyarea_info *pa_info = (struct polyarea_info *) b; PLINE *p = pa_info->pa->contours; if (p->Count == 0) return 0; /* how did this happen? */ heap_insert (heap, p->area, pa_info); return 1; } struct find_inside_info { jmp_buf jb; PLINE *want_inside; PLINE *result; }; static int find_inside (const BoxType * b, void *cl) { struct find_inside_info *info = (struct find_inside_info *) cl; PLINE *check = (PLINE *) b; /* Do test on check to see if it inside info->want_inside */ /* If it is: */ if (check->Flags.orient == PLF_DIR) { return 0; } if (poly_ContourInContour (info->want_inside, check)) { info->result = check; longjmp (info->jb, 1); } return 0; } static void InsertHoles (jmp_buf * e, POLYAREA * dest, PLINE ** src) { POLYAREA *curc; PLINE *curh, *container; heap_t *heap; rtree_t *tree; int i; int num_polyareas = 0; struct polyarea_info *all_pa_info, *pa_info; if (*src == NULL) return; /* empty hole list */ if (dest == NULL) error (err_bad_parm); /* empty contour list */ /* Count dest polyareas */ curc = dest; do { num_polyareas++; } while ((curc = curc->f) != dest); /* make a polyarea info table */ /* make an rtree of polyarea info table */ all_pa_info = (struct polyarea_info *) malloc (sizeof (struct polyarea_info) * num_polyareas); tree = r_create_tree (NULL, 0, 0); i = 0; curc = dest; do { all_pa_info[i].BoundingBox.X1 = curc->contours->xmin; all_pa_info[i].BoundingBox.Y1 = curc->contours->ymin; all_pa_info[i].BoundingBox.X2 = curc->contours->xmax; all_pa_info[i].BoundingBox.Y2 = curc->contours->ymax; all_pa_info[i].pa = curc; r_insert_entry (tree, (const BoxType *) &all_pa_info[i], 0); i++; } while ((curc = curc->f) != dest); /* loop through the holes and put them where they belong */ while ((curh = *src) != NULL) { *src = curh->next; container = NULL; /* build a heap of all of the polys that the hole is inside its bounding box */ heap = heap_create (); r_search (tree, (BoxType *) curh, NULL, heap_it, heap); if (heap_is_empty (heap)) { #ifndef NDEBUG #ifdef DEBUG poly_dump (dest); #endif #endif poly_DelContour (&curh); error (err_bad_parm); } /* Now search the heap for the container. If there was only one item * in the heap, assume it is the container without the expense of * proving it. */ pa_info = (struct polyarea_info *) heap_remove_smallest (heap); if (heap_is_empty (heap)) { /* only one possibility it must be the right one */ assert (poly_ContourInContour (pa_info->pa->contours, curh)); container = pa_info->pa->contours; } else { do { if (poly_ContourInContour (pa_info->pa->contours, curh)) { container = pa_info->pa->contours; break; } if (heap_is_empty (heap)) break; pa_info = (struct polyarea_info *) heap_remove_smallest (heap); } while (1); } heap_destroy (&heap); if (container == NULL) { /* bad input polygons were given */ #ifndef NDEBUG #ifdef DEBUG poly_dump (dest); #endif #endif curh->next = NULL; poly_DelContour (&curh); error (err_bad_parm); } else { /* Need to check if this new hole means we need to kick out any old ones for reprocessing */ while (1) { struct find_inside_info info; PLINE *prev; info.want_inside = curh; /* Set jump return */ if (setjmp (info.jb)) { /* Returned here! */ } else { info.result = NULL; /* Rtree search, calling back a routine to longjmp back with data about any hole inside the added one */ /* Be sure not to bother jumping back to report the main contour! */ r_search (pa_info->pa->contour_tree, (BoxType *) curh, NULL, find_inside, &info); /* Nothing found? */ break; } /* We need to find the contour before it, so we can update its next pointer */ prev = container; while (prev->next != info.result) { prev = prev->next; } /* Remove hole from the contour */ remove_contour (pa_info->pa, prev, info.result, TRUE); /* Add hole as the next on the list to be processed in this very function */ info.result->next = *src; *src = info.result; } /* End check for kicked out holes */ /* link at front of hole list */ curh->next = container->next; container->next = curh; r_insert_entry (pa_info->pa->contour_tree, (BoxType *) curh, 0); } } r_destroy_tree (&tree); free (all_pa_info); } /* InsertHoles */ /****************************************************************/ /* routines for collecting result */ typedef enum { FORW, BACKW } DIRECTION; /* Start Rule */ typedef int (*S_Rule) (VNODE *, DIRECTION *); /* Jump Rule */ typedef int (*J_Rule) (char, VNODE *, DIRECTION *); static int UniteS_Rule (VNODE * cur, DIRECTION * initdir) { *initdir = FORW; return (NODE_LABEL (cur) == OUTSIDE) || (NODE_LABEL (cur) == SHARED); } static int IsectS_Rule (VNODE * cur, DIRECTION * initdir) { *initdir = FORW; return (NODE_LABEL (cur) == INSIDE) || (NODE_LABEL (cur) == SHARED); } static int SubS_Rule (VNODE * cur, DIRECTION * initdir) { *initdir = FORW; return (NODE_LABEL (cur) == OUTSIDE) || (NODE_LABEL (cur) == SHARED2); } static int XorS_Rule (VNODE * cur, DIRECTION * initdir) { if (cur->Flags.status == INSIDE) { *initdir = BACKW; return TRUE; } if (cur->Flags.status == OUTSIDE) { *initdir = FORW; return TRUE; } return FALSE; } static int IsectJ_Rule (char p, VNODE * v, DIRECTION * cdir) { assert (*cdir == FORW); return (v->Flags.status == INSIDE || v->Flags.status == SHARED); } static int UniteJ_Rule (char p, VNODE * v, DIRECTION * cdir) { assert (*cdir == FORW); return (v->Flags.status == OUTSIDE || v->Flags.status == SHARED); } static int XorJ_Rule (char p, VNODE * v, DIRECTION * cdir) { if (v->Flags.status == INSIDE) { *cdir = BACKW; return TRUE; } if (v->Flags.status == OUTSIDE) { *cdir = FORW; return TRUE; } return FALSE; } static int SubJ_Rule (char p, VNODE * v, DIRECTION * cdir) { if (p == 'B' && v->Flags.status == INSIDE) { *cdir = BACKW; return TRUE; } if (p == 'A' && v->Flags.status == OUTSIDE) { *cdir = FORW; return TRUE; } if (v->Flags.status == SHARED2) { if (p == 'A') *cdir = FORW; else *cdir = BACKW; return TRUE; } return FALSE; } /* return the edge that comes next. * if the direction is BACKW, then we return the next vertex * so that prev vertex has the flags for the edge * * returns true if an edge is found, false otherwise */ static int jump (VNODE ** cur, DIRECTION * cdir, J_Rule rule) { CVCList *d, *start; VNODE *e; DIRECTION newone; if (!(*cur)->cvc_prev) /* not a cross-vertex */ { if (*cdir == FORW ? (*cur)->Flags.mark : (*cur)->prev->Flags.mark) return FALSE; return TRUE; } #ifdef DEBUG_JUMP DEBUGP ("jump entering node at %$mD\n", (*cur)->point[0], (*cur)->point[1]); #endif if (*cdir == FORW) d = (*cur)->cvc_prev->prev; else d = (*cur)->cvc_next->prev; start = d; do { e = d->parent; if (d->side == 'P') e = e->prev; newone = *cdir; if (!e->Flags.mark && rule (d->poly, e, &newone)) { if ((d->side == 'N' && newone == FORW) || (d->side == 'P' && newone == BACKW)) { #ifdef DEBUG_JUMP if (newone == FORW) DEBUGP ("jump leaving node at %#mD\n", e->next->point[0], e->next->point[1]); else DEBUGP ("jump leaving node at %#mD\n", e->point[0], e->point[1]); #endif *cur = d->parent; *cdir = newone; return TRUE; } } } while ((d = d->prev) != start); return FALSE; } static int Gather (VNODE * start, PLINE ** result, J_Rule v_rule, DIRECTION initdir) { VNODE *cur = start, *newn; DIRECTION dir = initdir; #ifdef DEBUG_GATHER DEBUGP ("gather direction = %d\n", dir); #endif assert (*result == NULL); do { /* see where to go next */ if (!jump (&cur, &dir, v_rule)) break; /* add edge to polygon */ if (!*result) { *result = poly_NewContour (cur->point); if (*result == NULL) return err_no_memory; } else { if ((newn = poly_CreateNode (cur->point)) == NULL) return err_no_memory; poly_InclVertex ((*result)->head.prev, newn); } #ifdef DEBUG_GATHER DEBUGP ("gather vertex at %#mD\n", cur->point[0], cur->point[1]); #endif /* Now mark the edge as included. */ newn = (dir == FORW ? cur : cur->prev); newn->Flags.mark = 1; /* for SHARED edge mark both */ if (newn->shared) newn->shared->Flags.mark = 1; /* Advance to the next edge. */ cur = (dir == FORW ? cur->next : cur->prev); } while (1); return err_ok; } /* Gather */ static void Collect1 (jmp_buf * e, VNODE * cur, DIRECTION dir, POLYAREA ** contours, PLINE ** holes, J_Rule j_rule) { PLINE *p = NULL; /* start making contour */ int errc = err_ok; if ((errc = Gather (dir == FORW ? cur : cur->next, &p, j_rule, dir)) != err_ok) { if (p != NULL) poly_DelContour (&p); error (errc); } if (!p) return; poly_PreContour (p, TRUE); if (p->Count > 2) { #ifdef DEBUG_GATHER DEBUGP ("adding contour with %d verticies and direction %c\n", p->Count, p->Flags.orient ? 'F' : 'B'); #endif PutContour (e, p, contours, holes, NULL, NULL, NULL); } else { /* some sort of computation error ? */ #ifdef DEBUG_GATHER DEBUGP ("Bad contour! Not enough points!!\n"); #endif poly_DelContour (&p); } } static void Collect (jmp_buf * e, PLINE * a, POLYAREA ** contours, PLINE ** holes, S_Rule s_rule, J_Rule j_rule) { VNODE *cur, *other; DIRECTION dir; cur = &a->head; do { if (s_rule (cur, &dir) && cur->Flags.mark == 0) Collect1 (e, cur, dir, contours, holes, j_rule); other = cur; if ((other->cvc_prev && jump (&other, &dir, j_rule))) Collect1 (e, other, dir, contours, holes, j_rule); } while ((cur = cur->next) != &a->head); } /* Collect */ static int cntr_Collect (jmp_buf * e, PLINE ** A, POLYAREA ** contours, PLINE ** holes, int action, POLYAREA * owner, POLYAREA * parent, PLINE * parent_contour) { PLINE *tmprev; if ((*A)->Flags.status == ISECTED) { switch (action) { case PBO_UNITE: Collect (e, *A, contours, holes, UniteS_Rule, UniteJ_Rule); break; case PBO_ISECT: Collect (e, *A, contours, holes, IsectS_Rule, IsectJ_Rule); break; case PBO_XOR: Collect (e, *A, contours, holes, XorS_Rule, XorJ_Rule); break; case PBO_SUB: Collect (e, *A, contours, holes, SubS_Rule, SubJ_Rule); break; }; } else { switch (action) { case PBO_ISECT: if ((*A)->Flags.status == INSIDE) { tmprev = *A; /* disappear this contour (rtree entry removed in PutContour) */ *A = tmprev->next; tmprev->next = NULL; PutContour (e, tmprev, contours, holes, owner, NULL, NULL); return TRUE; } break; case PBO_XOR: if ((*A)->Flags.status == INSIDE) { tmprev = *A; /* disappear this contour (rtree entry removed in PutContour) */ *A = tmprev->next; tmprev->next = NULL; poly_InvContour (tmprev); PutContour (e, tmprev, contours, holes, owner, NULL, NULL); return TRUE; } /* break; *//* Fall through (I think this is correct! pcjc2) */ case PBO_UNITE: case PBO_SUB: if ((*A)->Flags.status == OUTSIDE) { tmprev = *A; /* disappear this contour (rtree entry removed in PutContour) */ *A = tmprev->next; tmprev->next = NULL; PutContour (e, tmprev, contours, holes, owner, parent, parent_contour); return TRUE; } break; } } return FALSE; } /* cntr_Collect */ static void M_B_AREA_Collect (jmp_buf * e, POLYAREA * bfst, POLYAREA ** contours, PLINE ** holes, int action) { POLYAREA *b = bfst; PLINE **cur, **next, *tmp; assert (b != NULL); do { for (cur = &b->contours; *cur != NULL; cur = next) { next = &((*cur)->next); if ((*cur)->Flags.status == ISECTED) continue; if ((*cur)->Flags.status == INSIDE) switch (action) { case PBO_XOR: case PBO_SUB: poly_InvContour (*cur); case PBO_ISECT: tmp = *cur; *cur = tmp->next; next = cur; tmp->next = NULL; tmp->Flags.status = UNKNWN; PutContour (e, tmp, contours, holes, b, NULL, NULL); break; case PBO_UNITE: break; /* nothing to do - already included */ } else if ((*cur)->Flags.status == OUTSIDE) switch (action) { case PBO_XOR: case PBO_UNITE: /* include */ tmp = *cur; *cur = tmp->next; next = cur; tmp->next = NULL; tmp->Flags.status = UNKNWN; PutContour (e, tmp, contours, holes, b, NULL, NULL); break; case PBO_ISECT: case PBO_SUB: break; /* do nothing, not included */ } } } while ((b = b->f) != bfst); } static inline int contour_is_first (POLYAREA * a, PLINE * cur) { return (a->contours == cur); } static inline int contour_is_last (PLINE * cur) { return (cur->next == NULL); } static inline void remove_polyarea (POLYAREA ** list, POLYAREA * piece) { /* If this item was the start of the list, advance that pointer */ if (*list == piece) *list = (*list)->f; /* But reset it to NULL if it wraps around and hits us again */ if (*list == piece) *list = NULL; piece->b->f = piece->f; piece->f->b = piece->b; piece->f = piece->b = piece; } static void M_POLYAREA_separate_isected (jmp_buf * e, POLYAREA ** pieces, PLINE ** holes, PLINE ** isected) { POLYAREA *a = *pieces; POLYAREA *anext; PLINE *curc, *next, *prev; int finished; if (a == NULL) return; /* TODO: STASH ENOUGH INFORMATION EARLIER ON, SO WE CAN REMOVE THE INTERSECTED CONTOURS WITHOUT HAVING TO WALK THE FULL DATA-STRUCTURE LOOKING FOR THEM. */ do { int hole_contour = 0; int is_outline = 1; anext = a->f; finished = (anext == *pieces); prev = NULL; for (curc = a->contours; curc != NULL; curc = next, is_outline = 0) { int is_first = contour_is_first (a, curc); int is_last = contour_is_last (curc); int isect_contour = (curc->Flags.status == ISECTED); next = curc->next; if (isect_contour || hole_contour) { /* Reset the intersection flags, since we keep these pieces */ if (curc->Flags.status != ISECTED) curc->Flags.status = UNKNWN; remove_contour (a, prev, curc, !(is_first && is_last)); if (isect_contour) { /* Link into the list of intersected contours */ curc->next = *isected; *isected = curc; } else if (hole_contour) { /* Link into the list of holes */ curc->next = *holes; *holes = curc; } else { assert (0); } if (is_first && is_last) { remove_polyarea (pieces, a); poly_Free (&a); /* NB: Sets a to NULL */ } } else { /* Note the item we just didn't delete as the next candidate for having its "next" pointer adjusted. Saves walking the contour list when we delete one. */ prev = curc; } /* If we move or delete an outer contour, we need to move any holes we wish to keep within that contour to the holes list. */ if (is_outline && isect_contour) hole_contour = 1; } /* If we deleted all the pieces of the polyarea, *pieces is NULL */ } while ((a = anext), *pieces != NULL && !finished); } struct find_inside_m_pa_info { jmp_buf jb; POLYAREA *want_inside; PLINE *result; }; static int find_inside_m_pa (const BoxType * b, void *cl) { struct find_inside_m_pa_info *info = (struct find_inside_m_pa_info *) cl; PLINE *check = (PLINE *) b; /* Don't report for the main contour */ if (check->Flags.orient == PLF_DIR) return 0; /* Don't look at contours marked as being intersected */ if (check->Flags.status == ISECTED) return 0; if (cntr_in_M_POLYAREA (check, info->want_inside, FALSE)) { info->result = check; longjmp (info->jb, 1); } return 0; } static void M_POLYAREA_update_primary (jmp_buf * e, POLYAREA ** pieces, PLINE ** holes, int action, POLYAREA * bpa) { POLYAREA *a = *pieces; POLYAREA *b; POLYAREA *anext; PLINE *curc, *next, *prev; BoxType box; /* int inv_inside = 0; */ int del_inside = 0; int del_outside = 0; int finished; if (a == NULL) return; switch (action) { case PBO_ISECT: del_outside = 1; break; case PBO_UNITE: case PBO_SUB: del_inside = 1; break; case PBO_XOR: /* NOT IMPLEMENTED OR USED */ /* inv_inside = 1; */ assert (0); break; } box = *((BoxType *) bpa->contours); b = bpa; while ((b = b->f) != bpa) { BoxType *b_box = (BoxType *) b->contours; MAKEMIN (box.X1, b_box->X1); MAKEMIN (box.Y1, b_box->Y1); MAKEMAX (box.X2, b_box->X2); MAKEMAX (box.Y2, b_box->Y2); } if (del_inside) { do { anext = a->f; finished = (anext == *pieces); /* Test the outer contour first, as we may need to remove all children */ /* We've not yet split intersected contours out, just ignore them */ if (a->contours->Flags.status != ISECTED && /* Pre-filter on bounding box */ ((a->contours->xmin >= box.X1) && (a->contours->ymin >= box.Y1) && (a->contours->xmax <= box.X2) && (a->contours->ymax <= box.Y2)) && /* Then test properly */ cntr_in_M_POLYAREA (a->contours, bpa, FALSE)) { /* Delete this contour, all children -> holes queue */ /* Delete the outer contour */ curc = a->contours; remove_contour (a, NULL, curc, FALSE); /* Rtree deleted in poly_Free below */ /* a->contours now points to the remaining holes */ poly_DelContour (&curc); if (a->contours != NULL) { /* Find the end of the list of holes */ curc = a->contours; while (curc->next != NULL) curc = curc->next; /* Take the holes and prepend to the holes queue */ curc->next = *holes; *holes = a->contours; a->contours = NULL; } remove_polyarea (pieces, a); poly_Free (&a); /* NB: Sets a to NULL */ continue; } /* Loop whilst we find INSIDE contours to delete */ while (1) { struct find_inside_m_pa_info info; PLINE *prev; info.want_inside = bpa; /* Set jump return */ if (setjmp (info.jb)) { /* Returned here! */ } else { info.result = NULL; /* r-tree search, calling back a routine to longjmp back with * data about any hole inside the B polygon. * NB: Does not jump back to report the main contour! */ r_search (a->contour_tree, &box, NULL, find_inside_m_pa, &info); /* Nothing found? */ break; } /* We need to find the contour before it, so we can update its next pointer */ prev = a->contours; while (prev->next != info.result) { prev = prev->next; } /* Remove hole from the contour */ remove_contour (a, prev, info.result, TRUE); poly_DelContour (&info.result); } /* End check for deleted holes */ /* If we deleted all the pieces of the polyarea, *pieces is NULL */ } while ((a = anext), *pieces != NULL && !finished); return; } else { /* This path isn't optimised for speed */ } do { int hole_contour = 0; int is_outline = 1; anext = a->f; finished = (anext == *pieces); prev = NULL; for (curc = a->contours; curc != NULL; curc = next, is_outline = 0) { int is_first = contour_is_first (a, curc); int is_last = contour_is_last (curc); int del_contour = 0; next = curc->next; if (del_outside) del_contour = curc->Flags.status != ISECTED && !cntr_in_M_POLYAREA (curc, bpa, FALSE); /* Skip intersected contours */ if (curc->Flags.status == ISECTED) { prev = curc; continue; } /* Reset the intersection flags, since we keep these pieces */ curc->Flags.status = UNKNWN; if (del_contour || hole_contour) { remove_contour (a, prev, curc, !(is_first && is_last)); if (del_contour) { /* Delete the contour */ poly_DelContour (&curc); /* NB: Sets curc to NULL */ } else if (hole_contour) { /* Link into the list of holes */ curc->next = *holes; *holes = curc; } else { assert (0); } if (is_first && is_last) { remove_polyarea (pieces, a); poly_Free (&a); /* NB: Sets a to NULL */ } } else { /* Note the item we just didn't delete as the next candidate for having its "next" pointer adjusted. Saves walking the contour list when we delete one. */ prev = curc; } /* If we move or delete an outer contour, we need to move any holes we wish to keep within that contour to the holes list. */ if (is_outline && del_contour) hole_contour = 1; } /* If we deleted all the pieces of the polyarea, *pieces is NULL */ } while ((a = anext), *pieces != NULL && !finished); } static void M_POLYAREA_Collect_separated (jmp_buf * e, PLINE * afst, POLYAREA ** contours, PLINE ** holes, int action, BOOLp maybe) { PLINE **cur, **next; for (cur = &afst; *cur != NULL; cur = next) { next = &((*cur)->next); /* if we disappear a contour, don't advance twice */ if (cntr_Collect (e, cur, contours, holes, action, NULL, NULL, NULL)) next = cur; } } static void M_POLYAREA_Collect (jmp_buf * e, POLYAREA * afst, POLYAREA ** contours, PLINE ** holes, int action, BOOLp maybe) { POLYAREA *a = afst; POLYAREA *parent = NULL; /* Quiet compiler warning */ PLINE **cur, **next, *parent_contour; assert (a != NULL); while ((a = a->f) != afst); /* now the non-intersect parts are collected in temp/holes */ do { if (maybe && a->contours->Flags.status != ISECTED) parent_contour = a->contours; else parent_contour = NULL; /* Take care of the first contour - so we know if we * can shortcut reparenting some of its children */ cur = &a->contours; if (*cur != NULL) { next = &((*cur)->next); /* if we disappear a contour, don't advance twice */ if (cntr_Collect (e, cur, contours, holes, action, a, NULL, NULL)) { parent = (*contours)->b; /* InsCntr inserts behind the head */ next = cur; } else parent = a; cur = next; } for (; *cur != NULL; cur = next) { next = &((*cur)->next); /* if we disappear a contour, don't advance twice */ if (cntr_Collect (e, cur, contours, holes, action, a, parent, parent_contour)) next = cur; } } while ((a = a->f) != afst); } /* determine if two polygons touch or overlap */ BOOLp Touching (POLYAREA * a, POLYAREA * b) { jmp_buf e; int code; if ((code = setjmp (e)) == 0) { #ifdef DEBUG if (!poly_Valid (a)) return -1; if (!poly_Valid (b)) return -1; #endif M_POLYAREA_intersect (&e, a, b, false); if (M_POLYAREA_label (a, b, TRUE)) return TRUE; if (M_POLYAREA_label (b, a, TRUE)) return TRUE; } else if (code == TOUCHES) return TRUE; return FALSE; } /* the main clipping routines */ int poly_Boolean (const POLYAREA * a_org, const POLYAREA * b_org, POLYAREA ** res, int action) { POLYAREA *a = NULL, *b = NULL; if (!poly_M_Copy0 (&a, a_org) || !poly_M_Copy0 (&b, b_org)) return err_no_memory; return poly_Boolean_free (a, b, res, action); } /* poly_Boolean */ /* just like poly_Boolean but frees the input polys */ int poly_Boolean_free (POLYAREA * ai, POLYAREA * bi, POLYAREA ** res, int action) { POLYAREA *a = ai, *b = bi; PLINE *a_isected = NULL; PLINE *p, *holes = NULL; jmp_buf e; int code; *res = NULL; if (!a) { switch (action) { case PBO_XOR: case PBO_UNITE: *res = bi; return err_ok; case PBO_SUB: case PBO_ISECT: if (b != NULL) poly_Free (&b); return err_ok; } } if (!b) { switch (action) { case PBO_SUB: case PBO_XOR: case PBO_UNITE: *res = ai; return err_ok; case PBO_ISECT: if (a != NULL) poly_Free (&a); return err_ok; } } if ((code = setjmp (e)) == 0) { #ifdef DEBUG assert (poly_Valid (a)); assert (poly_Valid (b)); #endif /* intersect needs to make a list of the contours in a and b which are intersected */ M_POLYAREA_intersect (&e, a, b, TRUE); /* We could speed things up a lot here if we only processed the relevant contours */ /* NB: Relevant parts of a are labeled below */ M_POLYAREA_label (b, a, FALSE); *res = a; M_POLYAREA_update_primary (&e, res, &holes, action, b); M_POLYAREA_separate_isected (&e, res, &holes, &a_isected); M_POLYAREA_label_separated (a_isected, b, FALSE); M_POLYAREA_Collect_separated (&e, a_isected, res, &holes, action, FALSE); M_B_AREA_Collect (&e, b, res, &holes, action); poly_Free (&b); /* free a_isected */ while ((p = a_isected) != NULL) { a_isected = p->next; poly_DelContour (&p); } InsertHoles (&e, *res, &holes); } /* delete holes if any left */ while ((p = holes) != NULL) { holes = p->next; poly_DelContour (&p); } if (code) { poly_Free (res); return code; } assert (!*res || poly_Valid (*res)); return code; } /* poly_Boolean_free */ static void clear_marks (POLYAREA * p) { POLYAREA *n = p; PLINE *c; VNODE *v; do { for (c = n->contours; c; c = c->next) { v = &c->head; do { v->Flags.mark = 0; } while ((v = v->next) != &c->head); } } while ((n = n->f) != p); } /* compute the intersection and subtraction (divides "a" into two pieces) * and frees the input polys. This assumes that bi is a single simple polygon. */ int poly_AndSubtract_free (POLYAREA * ai, POLYAREA * bi, POLYAREA ** aandb, POLYAREA ** aminusb) { POLYAREA *a = ai, *b = bi; PLINE *p, *holes = NULL; jmp_buf e; int code; *aandb = NULL; *aminusb = NULL; if ((code = setjmp (e)) == 0) { #ifdef DEBUG if (!poly_Valid (a)) return -1; if (!poly_Valid (b)) return -1; #endif M_POLYAREA_intersect (&e, a, b, TRUE); M_POLYAREA_label (a, b, FALSE); M_POLYAREA_label (b, a, FALSE); M_POLYAREA_Collect (&e, a, aandb, &holes, PBO_ISECT, FALSE); InsertHoles (&e, *aandb, &holes); assert (poly_Valid (*aandb)); /* delete holes if any left */ while ((p = holes) != NULL) { holes = p->next; poly_DelContour (&p); } holes = NULL; clear_marks (a); clear_marks (b); M_POLYAREA_Collect (&e, a, aminusb, &holes, PBO_SUB, FALSE); InsertHoles (&e, *aminusb, &holes); poly_Free (&a); poly_Free (&b); assert (poly_Valid (*aminusb)); } /* delete holes if any left */ while ((p = holes) != NULL) { holes = p->next; poly_DelContour (&p); } if (code) { poly_Free (aandb); poly_Free (aminusb); return code; } assert (!*aandb || poly_Valid (*aandb)); assert (!*aminusb || poly_Valid (*aminusb)); return code; } /* poly_AndSubtract_free */ static inline int cntrbox_pointin (PLINE * c, Vector p) { return (p[0] >= c->xmin && p[1] >= c->ymin && p[0] <= c->xmax && p[1] <= c->ymax); } static inline int node_neighbours (VNODE * a, VNODE * b) { return (a == b) || (a->next == b) || (b->next == a) || (a->next == b->next); } VNODE * poly_CreateNode (Vector v) { VNODE *res; Coord *c; assert (v); res = (VNODE *) calloc (1, sizeof (VNODE)); if (res == NULL) return NULL; // bzero (res, sizeof (VNODE) - sizeof(Vector)); c = res->point; *c++ = *v++; *c = *v; return res; } void poly_IniContour (PLINE * c) { if (c == NULL) return; /* bzero (c, sizeof(PLINE)); */ c->head.next = c->head.prev = &c->head; c->xmin = c->ymin = COORD_MAX; c->xmax = c->ymax = -COORD_MAX - 1; c->is_round = FALSE; c->cx = 0; c->cy = 0; c->radius = 0; } PLINE * poly_NewContour (Vector v) { PLINE *res; res = (PLINE *) calloc (1, sizeof (PLINE)); if (res == NULL) return NULL; poly_IniContour (res); if (v != NULL) { Vcopy (res->head.point, v); cntrbox_adjust (res, v); } return res; } void poly_ClrContour (PLINE * c) { VNODE *cur; assert (c != NULL); while ((cur = c->head.next) != &c->head) { poly_ExclVertex (cur); free (cur); } poly_IniContour (c); } void poly_DelContour (PLINE ** c) { VNODE *cur, *prev; if (*c == NULL) return; for (cur = (*c)->head.prev; cur != &(*c)->head; cur = prev) { prev = cur->prev; if (cur->cvc_next != NULL) { free (cur->cvc_next); free (cur->cvc_prev); } free (cur); } if ((*c)->head.cvc_next != NULL) { free ((*c)->head.cvc_next); free ((*c)->head.cvc_prev); } /* FIXME -- strict aliasing violation. */ if ((*c)->tree) { rtree_t *r = (*c)->tree; r_destroy_tree (&r); } free (*c), *c = NULL; } void poly_PreContour (PLINE * C, BOOLp optimize) { double area = 0; VNODE *p, *c; Vector p1, p2; assert (C != NULL); if (optimize) { for (c = (p = &C->head)->next; c != &C->head; c = (p = c)->next) { /* if the previous node is on the same line with this one, we should remove it */ Vsub2 (p1, c->point, p->point); Vsub2 (p2, c->next->point, c->point); /* If the product below is zero then * the points on either side of c * are on the same line! * So, remove the point c */ if (vect_det2 (p1, p2) == 0) { poly_ExclVertex (c); free (c); c = p; } } } C->Count = 0; C->xmin = C->xmax = C->head.point[0]; C->ymin = C->ymax = C->head.point[1]; p = (c = &C->head)->prev; if (c != p) { do { /* calculate area for orientation */ area += (double) (p->point[0] - c->point[0]) * (p->point[1] + c->point[1]); cntrbox_adjust (C, c->point); C->Count++; } while ((c = (p = c)->next) != &C->head); } C->area = ABS (area); if (C->Count > 2) C->Flags.orient = ((area < 0) ? PLF_INV : PLF_DIR); C->tree = (rtree_t *)make_edge_tree (C); } /* poly_PreContour */ static int flip_cb (const BoxType * b, void *cl) { struct seg *s = (struct seg *) b; s->v = s->v->prev; return 1; } void poly_InvContour (PLINE * c) { VNODE *cur, *next; #ifndef NDEBUG int r; #endif assert (c != NULL); cur = &c->head; do { next = cur->next; cur->next = cur->prev; cur->prev = next; /* fix the segment tree */ } while ((cur = next) != &c->head); c->Flags.orient ^= 1; if (c->tree) { #ifndef NDEBUG r = #endif r_search (c->tree, NULL, NULL, flip_cb, NULL); #ifndef NDEBUG assert (r == c->Count); #endif } } void poly_ExclVertex (VNODE * node) { assert (node != NULL); if (node->cvc_next) { free (node->cvc_next); free (node->cvc_prev); } node->prev->next = node->next; node->next->prev = node->prev; } void poly_InclVertex (VNODE * after, VNODE * node) { double a, b; assert (after != NULL); assert (node != NULL); node->prev = after; node->next = after->next; after->next = after->next->prev = node; /* remove points on same line */ if (node->prev->prev == node) return; /* we don't have 3 points in the poly yet */ a = (node->point[1] - node->prev->prev->point[1]); a *= (node->prev->point[0] - node->prev->prev->point[0]); b = (node->point[0] - node->prev->prev->point[0]); b *= (node->prev->point[1] - node->prev->prev->point[1]); if (fabs (a - b) < EPSILON) { VNODE *t = node->prev; t->prev->next = node; node->prev = t->prev; free (t); } } BOOLp poly_CopyContour (PLINE ** dst, PLINE * src) { VNODE *cur, *newnode; assert (src != NULL); *dst = NULL; *dst = poly_NewContour (src->head.point); if (*dst == NULL) return FALSE; (*dst)->Count = src->Count; (*dst)->Flags.orient = src->Flags.orient; (*dst)->xmin = src->xmin, (*dst)->xmax = src->xmax; (*dst)->ymin = src->ymin, (*dst)->ymax = src->ymax; (*dst)->area = src->area; for (cur = src->head.next; cur != &src->head; cur = cur->next) { if ((newnode = poly_CreateNode (cur->point)) == NULL) return FALSE; // newnode->Flags = cur->Flags; poly_InclVertex ((*dst)->head.prev, newnode); } (*dst)->tree = (rtree_t *)make_edge_tree (*dst); return TRUE; } /**********************************************************************/ /* polygon routines */ BOOLp poly_Copy0 (POLYAREA ** dst, const POLYAREA * src) { *dst = NULL; if (src != NULL) *dst = (POLYAREA *)calloc (1, sizeof (POLYAREA)); if (*dst == NULL) return FALSE; (*dst)->contour_tree = r_create_tree (NULL, 0, 0); return poly_Copy1 (*dst, src); } BOOLp poly_Copy1 (POLYAREA * dst, const POLYAREA * src) { PLINE *cur, **last = &dst->contours; *last = NULL; dst->f = dst->b = dst; for (cur = src->contours; cur != NULL; cur = cur->next) { if (!poly_CopyContour (last, cur)) return FALSE; r_insert_entry (dst->contour_tree, (BoxType *) * last, 0); last = &(*last)->next; } return TRUE; } void poly_M_Incl (POLYAREA ** list, POLYAREA * a) { if (*list == NULL) a->f = a->b = a, *list = a; else { a->f = *list; a->b = (*list)->b; (*list)->b = (*list)->b->f = a; } } BOOLp poly_M_Copy0 (POLYAREA ** dst, const POLYAREA * srcfst) { const POLYAREA *src = srcfst; POLYAREA *di; *dst = NULL; if (src == NULL) return FALSE; do { if ((di = poly_Create ()) == NULL || !poly_Copy1 (di, src)) return FALSE; poly_M_Incl (dst, di); } while ((src = src->f) != srcfst); return TRUE; } BOOLp poly_InclContour (POLYAREA * p, PLINE * c) { PLINE *tmp; if ((c == NULL) || (p == NULL)) return FALSE; if (c->Flags.orient == PLF_DIR) { if (p->contours != NULL) return FALSE; p->contours = c; } else { if (p->contours == NULL) return FALSE; /* link at front of hole list */ tmp = p->contours->next; p->contours->next = c; c->next = tmp; } r_insert_entry (p->contour_tree, (BoxType *) c, 0); return TRUE; } typedef struct pip { int f; Vector p; jmp_buf env; } pip; static int crossing (const BoxType * b, void *cl) { struct seg *s = (struct seg *) b; struct pip *p = (struct pip *) cl; if (s->v->point[1] <= p->p[1]) { if (s->v->next->point[1] > p->p[1]) { Vector v1, v2; long long cross; Vsub2 (v1, s->v->next->point, s->v->point); Vsub2 (v2, p->p, s->v->point); cross = (long long) v1[0] * v2[1] - (long long) v2[0] * v1[1]; if (cross == 0) { p->f = 1; longjmp (p->env, 1); } if (cross > 0) p->f += 1; } } else { if (s->v->next->point[1] <= p->p[1]) { Vector v1, v2; long long cross; Vsub2 (v1, s->v->next->point, s->v->point); Vsub2 (v2, p->p, s->v->point); cross = (long long) v1[0] * v2[1] - (long long) v2[0] * v1[1]; if (cross == 0) { p->f = 1; longjmp (p->env, 1); } if (cross < 0) p->f -= 1; } } return 1; } int poly_InsideContour (PLINE * c, Vector p) { struct pip info; BoxType ray; if (!cntrbox_pointin (c, p)) return FALSE; info.f = 0; info.p[0] = ray.X1 = p[0]; info.p[1] = ray.Y1 = p[1]; ray.X2 = COORD_MAX; ray.Y2 = p[1] + 1; if (setjmp (info.env) == 0) r_search (c->tree, &ray, NULL, crossing, &info); return info.f; } BOOLp poly_CheckInside (POLYAREA * p, Vector v0) { PLINE *cur; if ((p == NULL) || (v0 == NULL) || (p->contours == NULL)) return FALSE; cur = p->contours; if (poly_InsideContour (cur, v0)) { for (cur = cur->next; cur != NULL; cur = cur->next) if (poly_InsideContour (cur, v0)) return FALSE; return TRUE; } return FALSE; } BOOLp poly_M_CheckInside (POLYAREA * p, Vector v0) { POLYAREA *cur; if ((p == NULL) || (v0 == NULL)) return FALSE; cur = p; do { if (poly_CheckInside (cur, v0)) return TRUE; } while ((cur = cur->f) != p); return FALSE; } static double dot (Vector A, Vector B) { return (double)A[0] * (double)B[0] + (double)A[1] * (double)B[1]; } /* Compute whether point is inside a triangle formed by 3 other pints */ /* Algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html */ static int point_in_triangle (Vector A, Vector B, Vector C, Vector P) { Vector v0, v1, v2; double dot00, dot01, dot02, dot11, dot12; double invDenom; double u, v; /* Compute vectors */ v0[0] = C[0] - A[0]; v0[1] = C[1] - A[1]; v1[0] = B[0] - A[0]; v1[1] = B[1] - A[1]; v2[0] = P[0] - A[0]; v2[1] = P[1] - A[1]; /* Compute dot products */ dot00 = dot (v0, v0); dot01 = dot (v0, v1); dot02 = dot (v0, v2); dot11 = dot (v1, v1); dot12 = dot (v1, v2); /* Compute barycentric coordinates */ invDenom = 1. / (dot00 * dot11 - dot01 * dot01); u = (dot11 * dot02 - dot01 * dot12) * invDenom; v = (dot00 * dot12 - dot01 * dot02) * invDenom; /* Check if point is in triangle */ return (u > 0.0) && (v > 0.0) && (u + v < 1.0); } /* Returns the dot product of Vector A->B, and a vector * orthogonal to Vector C->D. The result is not normalisd, so will be * weighted by the magnitude of the C->D vector. */ static double dot_orthogonal_to_direction (Vector A, Vector B, Vector C, Vector D) { Vector l1, l2, l3; l1[0] = B[0] - A[0]; l1[1] = B[1] - A[1]; l2[0] = D[0] - C[0]; l2[1] = D[1] - C[1]; l3[0] = -l2[1]; l3[1] = l2[0]; return dot (l1, l3); } /* Algorithm from http://www.exaflop.org/docs/cgafaq/cga2.html * * "Given a simple polygon, find some point inside it. Here is a method based * on the proof that there exists an internal diagonal, in [O'Rourke, 13-14]. * The idea is that the midpoint of a diagonal is interior to the polygon. * * 1. Identify a convex vertex v; let its adjacent vertices be a and b. * 2. For each other vertex q do: * 2a. If q is inside avb, compute distance to v (orthogonal to ab). * 2b. Save point q if distance is a new min. * 3. If no point is inside, return midpoint of ab, or centroid of avb. * 4. Else if some point inside, qv is internal: return its midpoint." * * [O'Rourke]: Computational Geometry in C (2nd Ed.) * Joseph O'Rourke, Cambridge University Press 1998, * ISBN 0-521-64010-5 Pbk, ISBN 0-521-64976-5 Hbk */ static void poly_ComputeInteriorPoint (PLINE *poly, Vector v) { VNODE *pt1, *pt2, *pt3, *q; VNODE *min_q = NULL; double dist; double min_dist = 0.0; double dir = (poly->Flags.orient == PLF_DIR) ? 1. : -1; /* Find a convex node on the polygon */ pt1 = &poly->head; do { double dot_product; pt2 = pt1->next; pt3 = pt2->next; dot_product = dot_orthogonal_to_direction (pt1->point, pt2->point, pt3->point, pt2->point); if (dot_product * dir > 0.) break; } while ((pt1 = pt1->next) != &poly->head); /* Loop over remaining vertices */ q = pt3; do { /* Is current vertex "q" outside pt1 pt2 pt3 triangle? */ if (!point_in_triangle (pt1->point, pt2->point, pt3->point, q->point)) continue; /* NO: compute distance to pt2 (v) orthogonal to pt1 - pt3) */ /* Record minimum */ dist = dot_orthogonal_to_direction (q->point, pt2->point, pt1->point, pt3->point); if (min_q == NULL || dist < min_dist) { min_dist = dist; min_q = q; } } while ((q = q->next) != pt2); /* Were any "q" found inside pt1 pt2 pt3? */ if (min_q == NULL) { /* NOT FOUND: Return midpoint of pt1 pt3 */ v[0] = (pt1->point[0] + pt3->point[0]) / 2; v[1] = (pt1->point[1] + pt3->point[1]) / 2; } else { /* FOUND: Return mid point of min_q, pt2 */ v[0] = (pt2->point[0] + min_q->point[0]) / 2; v[1] = (pt2->point[1] + min_q->point[1]) / 2; } } /* NB: This function assumes the caller _knows_ the contours do not * intersect. If the contours intersect, the result is undefined. * It will return the correct result if the two contours share * common points beteween their contours. (Identical contours * are treated as being inside each other). */ int poly_ContourInContour (PLINE * poly, PLINE * inner) { Vector point; assert (poly != NULL); assert (inner != NULL); if (cntrbox_inside (inner, poly)) { /* We need to prove the "inner" contour is not outside * "poly" contour. If it is outside, we can return. */ if (!poly_InsideContour (poly, inner->head.point)) return 0; poly_ComputeInteriorPoint (inner, point); return poly_InsideContour (poly, point); } return 0; } void poly_Init (POLYAREA * p) { p->f = p->b = p; p->contours = NULL; p->contour_tree = r_create_tree (NULL, 0, 0); } POLYAREA * poly_Create (void) { POLYAREA *res; if ((res = (POLYAREA *)malloc (sizeof (POLYAREA))) != NULL) poly_Init (res); return res; } void poly_FreeContours (PLINE ** pline) { PLINE *pl; while ((pl = *pline) != NULL) { *pline = pl->next; poly_DelContour (&pl); } } void poly_Free (POLYAREA ** p) { POLYAREA *cur; if (*p == NULL) return; for (cur = (*p)->f; cur != *p; cur = (*p)->f) { poly_FreeContours (&cur->contours); r_destroy_tree (&cur->contour_tree); cur->f->b = cur->b; cur->b->f = cur->f; free (cur); } poly_FreeContours (&cur->contours); r_destroy_tree (&cur->contour_tree); free (*p), *p = NULL; } static BOOLp inside_sector (VNODE * pn, Vector p2) { Vector cdir, ndir, pdir; int p_c, n_c, p_n; assert (pn != NULL); vect_sub (cdir, p2, pn->point); vect_sub (pdir, pn->point, pn->prev->point); vect_sub (ndir, pn->next->point, pn->point); p_c = vect_det2 (pdir, cdir) >= 0; n_c = vect_det2 (ndir, cdir) >= 0; p_n = vect_det2 (pdir, ndir) >= 0; if ((p_n && p_c && n_c) || ((!p_n) && (p_c || n_c))) return TRUE; else return FALSE; } /* inside_sector */ /* returns TRUE if bad contour */ BOOLp poly_ChkContour (PLINE * a) { VNODE *a1, *a2, *hit1, *hit2; Vector i1, i2; int icnt; assert (a != NULL); a1 = &a->head; do { a2 = a1; do { if (!node_neighbours (a1, a2) && (icnt = vect_inters2 (a1->point, a1->next->point, a2->point, a2->next->point, i1, i2)) > 0) { if (icnt > 1) return TRUE; if (vect_dist2 (i1, a1->point) < EPSILON) hit1 = a1; else if (vect_dist2 (i1, a1->next->point) < EPSILON) hit1 = a1->next; else hit1 = NULL; if (vect_dist2 (i1, a2->point) < EPSILON) hit2 = a2; else if (vect_dist2 (i1, a2->next->point) < EPSILON) hit2 = a2->next; else hit2 = NULL; if ((hit1 == NULL) && (hit2 == NULL)) { /* If the intersection didn't land on an end-point of either * line, we know the lines cross and we return TRUE. */ return TRUE; } else if (hit1 == NULL) { /* An end-point of the second line touched somewhere along the length of the first line. Check where the second line leads. */ if (inside_sector (hit2, a1->point) != inside_sector (hit2, a1->next->point)) return TRUE; } else if (hit2 == NULL) { /* An end-point of the first line touched somewhere along the length of the second line. Check where the first line leads. */ if (inside_sector (hit1, a2->point) != inside_sector (hit1, a2->next->point)) return TRUE; } else { /* Both lines intersect at an end-point. Check where they lead. */ if (inside_sector (hit1, hit2->prev->point) != inside_sector (hit1, hit2->next->point)) return TRUE; } } } while ((a2 = a2->next) != &a->head); } while ((a1 = a1->next) != &a->head); return FALSE; } BOOLp poly_Valid (POLYAREA * p) { PLINE *c; if ((p == NULL) || (p->contours == NULL)) return FALSE; if (p->contours->Flags.orient == PLF_INV || poly_ChkContour (p->contours)) { #ifndef NDEBUG VNODE *v, *n; DEBUGP ("Invalid Outer PLINE\n"); if (p->contours->Flags.orient == PLF_INV) DEBUGP ("failed orient\n"); if (poly_ChkContour (p->contours)) DEBUGP ("failed self-intersection\n"); v = &p->contours->head; do { n = v->next; pcb_fprintf (stderr, "Line [%#mS %#mS %#mS %#mS 100 100 \"\"]\n", v->point[0], v->point[1], n->point[0], n->point[1]); } while ((v = v->next) != &p->contours->head); #endif return FALSE; } for (c = p->contours->next; c != NULL; c = c->next) { if (c->Flags.orient == PLF_DIR || poly_ChkContour (c) || !poly_ContourInContour (p->contours, c)) { #ifndef NDEBUG VNODE *v, *n; DEBUGP ("Invalid Inner PLINE orient = %d\n", c->Flags.orient); if (c->Flags.orient == PLF_DIR) DEBUGP ("failed orient\n"); if (poly_ChkContour (c)) DEBUGP ("failed self-intersection\n"); if (!poly_ContourInContour (p->contours, c)) DEBUGP ("failed containment\n"); v = &c->head; do { n = v->next; pcb_fprintf (stderr, "Line [%#mS %#mS %#mS %#mS 100 100 \"\"]\n", v->point[0], v->point[1], n->point[0], n->point[1]); } while ((v = v->next) != &c->head); #endif return FALSE; } } return TRUE; } Vector vect_zero = { (long) 0, (long) 0 }; /*********************************************************************/ /* L o n g V e c t o r S t u f f */ /*********************************************************************/ void vect_init (Vector v, double x, double y) { v[0] = (long) x; v[1] = (long) y; } /* vect_init */ #define Vzero(a) ((a)[0] == 0. && (a)[1] == 0.) #define Vsub(a,b,c) {(a)[0]=(b)[0]-(c)[0];(a)[1]=(b)[1]-(c)[1];} int vect_equal (Vector v1, Vector v2) { return (v1[0] == v2[0] && v1[1] == v2[1]); } /* vect_equal */ void vect_sub (Vector res, Vector v1, Vector v2) { Vsub (res, v1, v2)} /* vect_sub */ void vect_min (Vector v1, Vector v2, Vector v3) { v1[0] = (v2[0] < v3[0]) ? v2[0] : v3[0]; v1[1] = (v2[1] < v3[1]) ? v2[1] : v3[1]; } /* vect_min */ void vect_max (Vector v1, Vector v2, Vector v3) { v1[0] = (v2[0] > v3[0]) ? v2[0] : v3[0]; v1[1] = (v2[1] > v3[1]) ? v2[1] : v3[1]; } /* vect_max */ double vect_len2 (Vector v) { return ((double) v[0] * v[0] + (double) v[1] * v[1]); /* why sqrt? only used for compares */ } double vect_dist2 (Vector v1, Vector v2) { double dx = v1[0] - v2[0]; double dy = v1[1] - v2[1]; return (dx * dx + dy * dy); /* why sqrt */ } /* value has sign of angle between vectors */ double vect_det2 (Vector v1, Vector v2) { return (((double) v1[0] * v2[1]) - ((double) v2[0] * v1[1])); } static double vect_m_dist (Vector v1, Vector v2) { double dx = v1[0] - v2[0]; double dy = v1[1] - v2[1]; double dd = (dx * dx + dy * dy); /* sqrt */ if (dx > 0) return +dd; if (dx < 0) return -dd; if (dy > 0) return +dd; return -dd; } /* vect_m_dist */ /* vect_inters2 (C) 1993 Klamer Schutte (C) 1997 Michael Leonov, Alexey Nikitin */ int vect_inters2 (Vector p1, Vector p2, Vector q1, Vector q2, Vector S1, Vector S2) { double s, t, deel; double rpx, rpy, rqx, rqy; if (max (p1[0], p2[0]) < min (q1[0], q2[0]) || max (q1[0], q2[0]) < min (p1[0], p2[0]) || max (p1[1], p2[1]) < min (q1[1], q2[1]) || max (q1[1], q2[1]) < min (p1[1], p2[1])) return 0; rpx = p2[0] - p1[0]; rpy = p2[1] - p1[1]; rqx = q2[0] - q1[0]; rqy = q2[1] - q1[1]; deel = rpy * rqx - rpx * rqy; /* -vect_det(rp,rq); */ /* coordinates are 30-bit integers so deel will be exactly zero * if the lines are parallel */ if (deel == 0) /* parallel */ { double dc1, dc2, d1, d2, h; /* Check to see whether p1-p2 and q1-q2 are on the same line */ Vector hp1, hq1, hp2, hq2, q1p1, q1q2; Vsub2 (q1p1, q1, p1); Vsub2 (q1q2, q1, q2); /* If this product is not zero then p1-p2 and q1-q2 are not on same line! */ if (vect_det2 (q1p1, q1q2) != 0) return 0; dc1 = 0; /* m_len(p1 - p1) */ dc2 = vect_m_dist (p1, p2); d1 = vect_m_dist (p1, q1); d2 = vect_m_dist (p1, q2); /* Sorting the independent points from small to large */ Vcpy2 (hp1, p1); Vcpy2 (hp2, p2); Vcpy2 (hq1, q1); Vcpy2 (hq2, q2); if (dc1 > dc2) { /* hv and h are used as help-variable. */ Vswp2 (hp1, hp2); h = dc1, dc1 = dc2, dc2 = h; } if (d1 > d2) { Vswp2 (hq1, hq2); h = d1, d1 = d2, d2 = h; } /* Now the line-pieces are compared */ if (dc1 < d1) { if (dc2 < d1) return 0; if (dc2 < d2) { Vcpy2 (S1, hp2); Vcpy2 (S2, hq1); } else { Vcpy2 (S1, hq1); Vcpy2 (S2, hq2); }; } else { if (dc1 > d2) return 0; if (dc2 < d2) { Vcpy2 (S1, hp1); Vcpy2 (S2, hp2); } else { Vcpy2 (S1, hp1); Vcpy2 (S2, hq2); }; } return (Vequ2 (S1, S2) ? 1 : 2); } else { /* not parallel */ /* * We have the lines: * l1: p1 + s(p2 - p1) * l2: q1 + t(q2 - q1) * And we want to know the intersection point. * Calculate t: * p1 + s(p2-p1) = q1 + t(q2-q1) * which is similar to the two equations: * p1x + s * rpx = q1x + t * rqx * p1y + s * rpy = q1y + t * rqy * Multiplying these by rpy resp. rpx gives: * rpy * p1x + s * rpx * rpy = rpy * q1x + t * rpy * rqx * rpx * p1y + s * rpx * rpy = rpx * q1y + t * rpx * rqy * Subtracting these gives: * rpy * p1x - rpx * p1y = rpy * q1x - rpx * q1y + t * ( rpy * rqx - rpx * rqy ) * So t can be isolated: * t = (rpy * ( p1x - q1x ) + rpx * ( - p1y + q1y )) / ( rpy * rqx - rpx * rqy ) * and s can be found similarly * s = (rqy * (q1x - p1x) + rqx * (p1y - q1y))/( rqy * rpx - rqx * rpy) */ if (Vequ2 (q1, p1) || Vequ2 (q1, p2)) { S1[0] = q1[0]; S1[1] = q1[1]; } else if (Vequ2 (q2, p1) || Vequ2 (q2, p2)) { S1[0] = q2[0]; S1[1] = q2[1]; } else { s = (rqy * (p1[0] - q1[0]) + rqx * (q1[1] - p1[1])) / deel; if (s < 0 || s > 1.) return 0; t = (rpy * (p1[0] - q1[0]) + rpx * (q1[1] - p1[1])) / deel; if (t < 0 || t > 1.) return 0; S1[0] = q1[0] + ROUND (t * rqx); S1[1] = q1[1] + ROUND (t * rqy); } return 1; } } /* vect_inters2 */ /* how about expanding polygons so that edges can be arcs rather than * lines. Consider using the third coordinate to store the radius of the * arc. The arc would pass through the vertex points. Positive radius * would indicate the arc bows left (center on right of P1-P2 path) * negative radius would put the center on the other side. 0 radius * would mean the edge is a line instead of arc * The intersections of the two circles centered at the vertex points * would determine the two possible arc centers. If P2.x > P1.x then * the center with smaller Y is selected for positive r. If P2.y > P1.y * then the center with greate X is selected for positive r. * * the vec_inters2() routine would then need to handle line-line * line-arc and arc-arc intersections. * * perhaps reverse tracing the arc would require look-ahead to check * for arcs */
szdiy/pcb-temorary
src/polygon1.c
C
gpl-2.0
83,865
/* * This file is part of JPhotoAlbum. * Copyright 2004 Jari Karjala <jpkware.com> & Tarja Hakala <hakalat.net> * * @version $Id: JPhotoDirectory.java,v 1.1.1.1 2004/05/21 18:24:59 jkarjala Exp $ */ /** Container for a single photo, may not always contain a real photo, but * just text element. * @see JPhotoAlbumLink.java */ package fi.iki.jka; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.FileCacheImageInputStream; import com.drew.metadata.exif.ExifDirectory; public class JPhotoDirectory extends JPhoto { public JPhotoDirectory() { this(defaultOwner, null); } public JPhotoDirectory(JPhotoCollection owner) { this(owner, null); } public JPhotoDirectory(File original) { this(defaultOwner, original); } public JPhotoDirectory(JPhotoCollection owner, File original) { super(owner, original); } public BufferedImage getThumbImage() { InputStream ins = getClass().getClassLoader().getResourceAsStream("pics/directory.png"); Iterator readers = ImageIO.getImageReadersBySuffix("png"); ImageReader imageReader = (ImageReader)readers.next(); BufferedImage thumb = null; try { imageReader.setInput(new FileCacheImageInputStream(ins, null)); thumb = imageReader.read(0); ins.close(); } catch (Exception e) { System.out.println("getThumbImage:"+e); } imageReader.dispose(); return thumb; } public BufferedImage getCachedThumb() { return getThumbImage(); } public BufferedImage getThumbImageAsync() { return getThumbImage(); } public BufferedImage getFullImage() { return null; } public ExifDirectory getExifDirectory() { return null; } public String toString() { return "Directory='"+getImageName()+"'"; } }
91wzhang/sei-jphotoalbum
src/fi/iki/jka/JPhotoDirectory.java
Java
gpl-2.0
2,070
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Tue Aug 12 22:14:04 PDT 2014 --> <title>org.creativecommons.nutch (apache-nutch 1.9 API)</title> <meta name="date" content="2014-08-12"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../org/creativecommons/nutch/package-summary.html" target="classFrame">org.creativecommons.nutch</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="CCIndexingFilter.html" title="class in org.creativecommons.nutch" target="classFrame">CCIndexingFilter</a></li> <li><a href="CCParseFilter.html" title="class in org.creativecommons.nutch" target="classFrame">CCParseFilter</a></li> <li><a href="CCParseFilter.Walker.html" title="class in org.creativecommons.nutch" target="classFrame">CCParseFilter.Walker</a></li> </ul> </div> </body> </html>
aglne/nutcher
nutch-chinese/apache-nutch-1.9/docs/api/org/creativecommons/nutch/package-frame.html
HTML
gpl-2.0
1,055
/* GStreamer * Copyright (C) <2003> David A. Schleef <ds@schleef.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:gstvalue * @short_description: GValue implementations specific * to GStreamer * * GValue implementations specific to GStreamer. * * Note that operations on the same #GValue from multiple threads may lead to * undefined behaviour. * * Last reviewed on 2008-03-11 (0.10.18) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "gst_private.h" #include "glib-compat-private.h" #include <gst/gst.h> #include <gobject/gvaluecollector.h> #include "gstutils.h" typedef struct _GstValueUnionInfo GstValueUnionInfo; struct _GstValueUnionInfo { GType type1; GType type2; GstValueUnionFunc func; }; typedef struct _GstValueIntersectInfo GstValueIntersectInfo; struct _GstValueIntersectInfo { GType type1; GType type2; GstValueIntersectFunc func; }; typedef struct _GstValueSubtractInfo GstValueSubtractInfo; struct _GstValueSubtractInfo { GType minuend; GType subtrahend; GstValueSubtractFunc func; }; #define FUNDAMENTAL_TYPE_ID_MAX \ (G_TYPE_FUNDAMENTAL_MAX >> G_TYPE_FUNDAMENTAL_SHIFT) #define FUNDAMENTAL_TYPE_ID(type) \ ((type) >> G_TYPE_FUNDAMENTAL_SHIFT) #define VALUE_LIST_SIZE(v) (((GArray *) (v)->data[0].v_pointer)->len) #define VALUE_LIST_GET_VALUE(v, index) ((const GValue *) &g_array_index ((GArray *) (v)->data[0].v_pointer, GValue, (index))) static GArray *gst_value_table; static GHashTable *gst_value_hash; static GstValueTable *gst_value_tables_fundamental[FUNDAMENTAL_TYPE_ID_MAX + 1]; static GArray *gst_value_union_funcs; static GArray *gst_value_intersect_funcs; static GArray *gst_value_subtract_funcs; /* Forward declarations */ static gchar *gst_value_serialize_fraction (const GValue * value); static GstValueCompareFunc gst_value_get_compare_func (const GValue * value1); static gint gst_value_compare_with_func (const GValue * value1, const GValue * value2, GstValueCompareFunc compare); static gchar *gst_string_wrap (const gchar * s); static gchar *gst_string_take_and_wrap (gchar * s); static gchar *gst_string_unwrap (const gchar * s); static inline GstValueTable * gst_value_hash_lookup_type (GType type) { if (G_LIKELY (G_TYPE_IS_FUNDAMENTAL (type))) return gst_value_tables_fundamental[FUNDAMENTAL_TYPE_ID (type)]; else return g_hash_table_lookup (gst_value_hash, (gpointer) type); } static void gst_value_hash_add_type (GType type, const GstValueTable * table) { if (G_TYPE_IS_FUNDAMENTAL (type)) gst_value_tables_fundamental[FUNDAMENTAL_TYPE_ID (type)] = (gpointer) table; g_hash_table_insert (gst_value_hash, (gpointer) type, (gpointer) table); } /******** * list * ********/ /* two helper functions to serialize/stringify any type of list * regular lists are done with { }, arrays with < > */ static gchar * gst_value_serialize_any_list (const GValue * value, const gchar * begin, const gchar * end) { guint i; GArray *array = value->data[0].v_pointer; GString *s; GValue *v; gchar *s_val; guint alen = array->len; /* estimate minimum string length to minimise re-allocs in GString */ s = g_string_sized_new (2 + (6 * alen) + 2); g_string_append (s, begin); for (i = 0; i < alen; i++) { v = &g_array_index (array, GValue, i); s_val = gst_value_serialize (v); g_string_append (s, s_val); g_free (s_val); if (i < alen - 1) { g_string_append_len (s, ", ", 2); } } g_string_append (s, end); return g_string_free (s, FALSE); } static void gst_value_transform_any_list_string (const GValue * src_value, GValue * dest_value, const gchar * begin, const gchar * end) { GValue *list_value; GArray *array; GString *s; guint i; gchar *list_s; guint alen; array = src_value->data[0].v_pointer; alen = array->len; /* estimate minimum string length to minimise re-allocs in GString */ s = g_string_sized_new (2 + (10 * alen) + 2); g_string_append (s, begin); for (i = 0; i < alen; i++) { list_value = &g_array_index (array, GValue, i); if (i != 0) { g_string_append_len (s, ", ", 2); } list_s = g_strdup_value_contents (list_value); g_string_append (s, list_s); g_free (list_s); } g_string_append (s, end); dest_value->data[0].v_pointer = g_string_free (s, FALSE); } /* * helper function to see if a type is fixed. Is used internally here and * there. Do not export, since it doesn't work for types where the content * decides the fixedness (e.g. GST_TYPE_ARRAY). */ static gboolean gst_type_is_fixed (GType type) { /* the basic int, string, double types */ if (type <= G_TYPE_MAKE_FUNDAMENTAL (G_TYPE_RESERVED_GLIB_LAST)) { return TRUE; } /* our fundamental types that are certainly not fixed */ if (type == GST_TYPE_INT_RANGE || type == GST_TYPE_DOUBLE_RANGE || type == GST_TYPE_INT64_RANGE || type == GST_TYPE_LIST || type == GST_TYPE_FRACTION_RANGE) { return FALSE; } /* other (boxed) types that are fixed */ if (type == GST_TYPE_BUFFER) { return TRUE; } /* heavy checks */ if (G_TYPE_IS_FUNDAMENTAL (type) || G_TYPE_FUNDAMENTAL (type) <= G_TYPE_MAKE_FUNDAMENTAL (G_TYPE_RESERVED_GLIB_LAST)) { return TRUE; } return FALSE; } /* GValue functions usable for both regular lists and arrays */ static void gst_value_init_list_or_array (GValue * value) { value->data[0].v_pointer = g_array_new (FALSE, TRUE, sizeof (GValue)); } static GArray * copy_garray_of_gstvalue (const GArray * src) { GArray *dest; guint i, len; len = src->len; dest = g_array_sized_new (FALSE, TRUE, sizeof (GValue), len); g_array_set_size (dest, len); for (i = 0; i < len; i++) { gst_value_init_and_copy (&g_array_index (dest, GValue, i), &g_array_index (src, GValue, i)); } return dest; } static void gst_value_copy_list_or_array (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = copy_garray_of_gstvalue ((GArray *) src_value->data[0].v_pointer); } static void gst_value_free_list_or_array (GValue * value) { guint i, len; GArray *src = (GArray *) value->data[0].v_pointer; len = src->len; if ((value->data[1].v_uint & G_VALUE_NOCOPY_CONTENTS) == 0) { for (i = 0; i < len; i++) { g_value_unset (&g_array_index (src, GValue, i)); } g_array_free (src, TRUE); } } static gpointer gst_value_list_or_array_peek_pointer (const GValue * value) { return value->data[0].v_pointer; } static gchar * gst_value_collect_list_or_array (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (collect_flags & G_VALUE_NOCOPY_CONTENTS) { value->data[0].v_pointer = collect_values[0].v_pointer; value->data[1].v_uint = G_VALUE_NOCOPY_CONTENTS; } else { value->data[0].v_pointer = copy_garray_of_gstvalue ((GArray *) collect_values[0].v_pointer); } return NULL; } static gchar * gst_value_lcopy_list_or_array (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { GArray **dest = collect_values[0].v_pointer; if (!dest) return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!value->data[0].v_pointer) return g_strdup_printf ("invalid value given for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_flags & G_VALUE_NOCOPY_CONTENTS) { *dest = (GArray *) value->data[0].v_pointer; } else { *dest = copy_garray_of_gstvalue ((GArray *) value->data[0].v_pointer); } return NULL; } /** * gst_value_list_append_value: * @value: a #GValue of type #GST_TYPE_LIST * @append_value: the value to append * * Appends @append_value to the GstValueList in @value. */ void gst_value_list_append_value (GValue * value, const GValue * append_value) { GValue val = { 0, }; g_return_if_fail (GST_VALUE_HOLDS_LIST (value)); g_return_if_fail (G_IS_VALUE (append_value)); gst_value_init_and_copy (&val, append_value); g_array_append_vals ((GArray *) value->data[0].v_pointer, &val, 1); } #ifndef GSTREAMER_LITE /** * gst_value_list_prepend_value: * @value: a #GValue of type #GST_TYPE_LIST * @prepend_value: the value to prepend * * Prepends @prepend_value to the GstValueList in @value. */ void gst_value_list_prepend_value (GValue * value, const GValue * prepend_value) { GValue val = { 0, }; g_return_if_fail (GST_VALUE_HOLDS_LIST (value)); g_return_if_fail (G_IS_VALUE (prepend_value)); gst_value_init_and_copy (&val, prepend_value); g_array_prepend_vals ((GArray *) value->data[0].v_pointer, &val, 1); } #endif // GSTREAMER_LITE /** * gst_value_list_concat: * @dest: (out caller-allocates): an uninitialized #GValue to take the result * @value1: a #GValue * @value2: a #GValue * * Concatenates copies of @value1 and @value2 into a list. Values that are not * of type #GST_TYPE_LIST are treated as if they were lists of length 1. * @dest will be initialized to the type #GST_TYPE_LIST. */ void gst_value_list_concat (GValue * dest, const GValue * value1, const GValue * value2) { guint i, value1_length, value2_length; GArray *array; g_return_if_fail (dest != NULL); g_return_if_fail (G_VALUE_TYPE (dest) == 0); g_return_if_fail (G_IS_VALUE (value1)); g_return_if_fail (G_IS_VALUE (value2)); value1_length = (GST_VALUE_HOLDS_LIST (value1) ? VALUE_LIST_SIZE (value1) : 1); value2_length = (GST_VALUE_HOLDS_LIST (value2) ? VALUE_LIST_SIZE (value2) : 1); g_value_init (dest, GST_TYPE_LIST); array = (GArray *) dest->data[0].v_pointer; g_array_set_size (array, value1_length + value2_length); if (GST_VALUE_HOLDS_LIST (value1)) { for (i = 0; i < value1_length; i++) { gst_value_init_and_copy (&g_array_index (array, GValue, i), VALUE_LIST_GET_VALUE (value1, i)); } } else { gst_value_init_and_copy (&g_array_index (array, GValue, 0), value1); } if (GST_VALUE_HOLDS_LIST (value2)) { for (i = 0; i < value2_length; i++) { gst_value_init_and_copy (&g_array_index (array, GValue, i + value1_length), VALUE_LIST_GET_VALUE (value2, i)); } } else { gst_value_init_and_copy (&g_array_index (array, GValue, value1_length), value2); } } /** * gst_value_list_merge: * @dest: (out caller-allocates): an uninitialized #GValue to take the result * @value1: a #GValue * @value2: a #GValue * * Merges copies of @value1 and @value2. Values that are not * of type #GST_TYPE_LIST are treated as if they were lists of length 1. * * The result will be put into @dest and will either be a list that will not * contain any duplicates, or a non-list type (if @value1 and @value2 * were equal). * * Since: 0.10.32 */ void gst_value_list_merge (GValue * dest, const GValue * value1, const GValue * value2) { guint i, j, k, value1_length, value2_length, skipped; const GValue *src; gboolean skip; GArray *array; g_return_if_fail (dest != NULL); g_return_if_fail (G_VALUE_TYPE (dest) == 0); g_return_if_fail (G_IS_VALUE (value1)); g_return_if_fail (G_IS_VALUE (value2)); value1_length = (GST_VALUE_HOLDS_LIST (value1) ? VALUE_LIST_SIZE (value1) : 1); value2_length = (GST_VALUE_HOLDS_LIST (value2) ? VALUE_LIST_SIZE (value2) : 1); g_value_init (dest, GST_TYPE_LIST); array = (GArray *) dest->data[0].v_pointer; g_array_set_size (array, value1_length + value2_length); if (GST_VALUE_HOLDS_LIST (value1)) { for (i = 0; i < value1_length; i++) { gst_value_init_and_copy (&g_array_index (array, GValue, i), VALUE_LIST_GET_VALUE (value1, i)); } } else { gst_value_init_and_copy (&g_array_index (array, GValue, 0), value1); } j = value1_length; skipped = 0; if (GST_VALUE_HOLDS_LIST (value2)) { for (i = 0; i < value2_length; i++) { skip = FALSE; src = VALUE_LIST_GET_VALUE (value2, i); for (k = 0; k < value1_length; k++) { if (gst_value_compare (&g_array_index (array, GValue, k), src) == GST_VALUE_EQUAL) { skip = TRUE; skipped++; break; } } if (!skip) { gst_value_init_and_copy (&g_array_index (array, GValue, j), src); j++; } } } else { skip = FALSE; for (k = 0; k < value1_length; k++) { if (gst_value_compare (&g_array_index (array, GValue, k), value2) == GST_VALUE_EQUAL) { skip = TRUE; skipped++; break; } } if (!skip) { gst_value_init_and_copy (&g_array_index (array, GValue, j), value2); } } if (skipped) { guint new_size = value1_length + (value2_length - skipped); if (new_size > 1) { /* shrink list */ g_array_set_size (array, new_size); } else { GValue single_dest; /* size is 1, take single value in list and make it new dest */ single_dest = g_array_index (array, GValue, 0); /* clean up old value allocations: must set array size to 0, because * allocated values are not inited meaning g_value_unset() will not * work on them */ g_array_set_size (array, 0); g_value_unset (dest); /* the single value is our new result */ *dest = single_dest; } } } /** * gst_value_list_get_size: * @value: a #GValue of type #GST_TYPE_LIST * * Gets the number of values contained in @value. * * Returns: the number of values */ guint gst_value_list_get_size (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_LIST (value), 0); return ((GArray *) value->data[0].v_pointer)->len; } /** * gst_value_list_get_value: * @value: a #GValue of type #GST_TYPE_LIST * @index: index of value to get from the list * * Gets the value that is a member of the list contained in @value and * has the index @index. * * Returns: (transfer none): the value at the given index */ const GValue * gst_value_list_get_value (const GValue * value, guint index) { g_return_val_if_fail (GST_VALUE_HOLDS_LIST (value), NULL); g_return_val_if_fail (index < VALUE_LIST_SIZE (value), NULL); return (const GValue *) &g_array_index ((GArray *) value->data[0].v_pointer, GValue, index); } /** * gst_value_array_append_value: * @value: a #GValue of type #GST_TYPE_ARRAY * @append_value: the value to append * * Appends @append_value to the GstValueArray in @value. */ void gst_value_array_append_value (GValue * value, const GValue * append_value) { GValue val = { 0, }; g_return_if_fail (GST_VALUE_HOLDS_ARRAY (value)); g_return_if_fail (G_IS_VALUE (append_value)); gst_value_init_and_copy (&val, append_value); g_array_append_vals ((GArray *) value->data[0].v_pointer, &val, 1); } #ifndef GSTREAMER_LITE /** * gst_value_array_prepend_value: * @value: a #GValue of type #GST_TYPE_ARRAY * @prepend_value: the value to prepend * * Prepends @prepend_value to the GstValueArray in @value. */ void gst_value_array_prepend_value (GValue * value, const GValue * prepend_value) { GValue val = { 0, }; g_return_if_fail (GST_VALUE_HOLDS_ARRAY (value)); g_return_if_fail (G_IS_VALUE (prepend_value)); gst_value_init_and_copy (&val, prepend_value); g_array_prepend_vals ((GArray *) value->data[0].v_pointer, &val, 1); } #endif // GSTREAMER_LITE /** * gst_value_array_get_size: * @value: a #GValue of type #GST_TYPE_ARRAY * * Gets the number of values contained in @value. * * Returns: the number of values */ guint gst_value_array_get_size (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_ARRAY (value), 0); return ((GArray *) value->data[0].v_pointer)->len; } /** * gst_value_array_get_value: * @value: a #GValue of type #GST_TYPE_ARRAY * @index: index of value to get from the array * * Gets the value that is a member of the array contained in @value and * has the index @index. * * Returns: (transfer none): the value at the given index */ const GValue * gst_value_array_get_value (const GValue * value, guint index) { g_return_val_if_fail (GST_VALUE_HOLDS_ARRAY (value), NULL); g_return_val_if_fail (index < gst_value_array_get_size (value), NULL); return (const GValue *) &g_array_index ((GArray *) value->data[0].v_pointer, GValue, index); } static void gst_value_transform_list_string (const GValue * src_value, GValue * dest_value) { gst_value_transform_any_list_string (src_value, dest_value, "{ ", " }"); } static void gst_value_transform_array_string (const GValue * src_value, GValue * dest_value) { gst_value_transform_any_list_string (src_value, dest_value, "< ", " >"); } /* Do an unordered compare of the contents of a list */ static gint gst_value_compare_list (const GValue * value1, const GValue * value2) { guint i, j; GArray *array1 = value1->data[0].v_pointer; GArray *array2 = value2->data[0].v_pointer; GValue *v1; GValue *v2; gint len, to_remove; guint8 *removed; GstValueCompareFunc compare; /* get length and do initial length check. */ len = array1->len; if (len != array2->len) return GST_VALUE_UNORDERED; /* place to mark removed value indices of array2 */ removed = g_newa (guint8, len); memset (removed, 0, len); to_remove = len; /* loop over array1, all items should be in array2. When we find an * item in array2, remove it from array2 by marking it as removed */ for (i = 0; i < len; i++) { v1 = &g_array_index (array1, GValue, i); if ((compare = gst_value_get_compare_func (v1))) { for (j = 0; j < len; j++) { /* item is removed, we can skip it */ if (removed[j]) continue; v2 = &g_array_index (array2, GValue, j); if (gst_value_compare_with_func (v1, v2, compare) == GST_VALUE_EQUAL) { /* mark item as removed now that we found it in array2 and * decrement the number of remaining items in array2. */ removed[j] = 1; to_remove--; break; } } /* item in array1 and not in array2, UNORDERED */ if (j == len) return GST_VALUE_UNORDERED; } else return GST_VALUE_UNORDERED; } /* if not all items were removed, array2 contained something not in array1 */ if (to_remove != 0) return GST_VALUE_UNORDERED; /* arrays are equal */ return GST_VALUE_EQUAL; } /* Perform an ordered comparison of the contents of an array */ static gint gst_value_compare_array (const GValue * value1, const GValue * value2) { guint i; GArray *array1 = value1->data[0].v_pointer; GArray *array2 = value2->data[0].v_pointer; guint len = array1->len; GValue *v1; GValue *v2; if (len != array2->len) return GST_VALUE_UNORDERED; for (i = 0; i < len; i++) { v1 = &g_array_index (array1, GValue, i); v2 = &g_array_index (array2, GValue, i); if (gst_value_compare (v1, v2) != GST_VALUE_EQUAL) return GST_VALUE_UNORDERED; } return GST_VALUE_EQUAL; } static gchar * gst_value_serialize_list (const GValue * value) { return gst_value_serialize_any_list (value, "{ ", " }"); } static gboolean gst_value_deserialize_list (GValue * dest, const gchar * s) { g_warning ("gst_value_deserialize_list: unimplemented"); return FALSE; } static gchar * gst_value_serialize_array (const GValue * value) { return gst_value_serialize_any_list (value, "< ", " >"); } static gboolean gst_value_deserialize_array (GValue * dest, const gchar * s) { g_warning ("gst_value_deserialize_array: unimplemented"); return FALSE; } /********** * fourcc * **********/ static void gst_value_init_fourcc (GValue * value) { value->data[0].v_int = 0; } static void gst_value_copy_fourcc (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int = src_value->data[0].v_int; } static gchar * gst_value_collect_fourcc (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { value->data[0].v_int = collect_values[0].v_int; return NULL; } static gchar * gst_value_lcopy_fourcc (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { guint32 *fourcc_p = collect_values[0].v_pointer; if (!fourcc_p) return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *fourcc_p = value->data[0].v_int; return NULL; } /** * gst_value_set_fourcc: * @value: a GValue initialized to #GST_TYPE_FOURCC * @fourcc: the #guint32 fourcc to set * * Sets @value to @fourcc. */ void gst_value_set_fourcc (GValue * value, guint32 fourcc) { g_return_if_fail (GST_VALUE_HOLDS_FOURCC (value)); value->data[0].v_int = fourcc; } /** * gst_value_get_fourcc: * @value: a GValue initialized to #GST_TYPE_FOURCC * * Gets the #guint32 fourcc contained in @value. * * Returns: the #guint32 fourcc contained in @value. */ guint32 gst_value_get_fourcc (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_FOURCC (value), 0); return value->data[0].v_int; } static void gst_value_transform_fourcc_string (const GValue * src_value, GValue * dest_value) { guint32 fourcc = src_value->data[0].v_int; gchar fourcc_char[4]; fourcc_char[0] = (fourcc >> 0) & 0xff; fourcc_char[1] = (fourcc >> 8) & 0xff; fourcc_char[2] = (fourcc >> 16) & 0xff; fourcc_char[3] = (fourcc >> 24) & 0xff; if ((g_ascii_isalnum (fourcc_char[0]) || fourcc_char[0] == ' ') && (g_ascii_isalnum (fourcc_char[1]) || fourcc_char[1] == ' ') && (g_ascii_isalnum (fourcc_char[2]) || fourcc_char[2] == ' ') && (g_ascii_isalnum (fourcc_char[3]) || fourcc_char[3] == ' ')) { dest_value->data[0].v_pointer = g_strdup_printf ("%" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); } else { dest_value->data[0].v_pointer = g_strdup_printf ("0x%08x", fourcc); } } static gint gst_value_compare_fourcc (const GValue * value1, const GValue * value2) { if (value2->data[0].v_int == value1->data[0].v_int) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_fourcc (const GValue * value) { guint32 fourcc = value->data[0].v_int; gchar fourcc_char[4]; fourcc_char[0] = (fourcc >> 0) & 0xff; fourcc_char[1] = (fourcc >> 8) & 0xff; fourcc_char[2] = (fourcc >> 16) & 0xff; fourcc_char[3] = (fourcc >> 24) & 0xff; if ((g_ascii_isalnum (fourcc_char[0]) || fourcc_char[0] == ' ') && (g_ascii_isalnum (fourcc_char[1]) || fourcc_char[1] == ' ') && (g_ascii_isalnum (fourcc_char[2]) || fourcc_char[2] == ' ') && (g_ascii_isalnum (fourcc_char[3]) || fourcc_char[3] == ' ')) { return g_strdup_printf ("%" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); } else { return g_strdup_printf ("0x%08x", fourcc); } } static gboolean gst_value_deserialize_fourcc (GValue * dest, const gchar * s) { gboolean ret = FALSE; guint32 fourcc = 0; gchar *end; gint l = strlen (s); if (l == 4) { fourcc = GST_MAKE_FOURCC (s[0], s[1], s[2], s[3]); ret = TRUE; } else if (l == 3) { fourcc = GST_MAKE_FOURCC (s[0], s[1], s[2], ' '); ret = TRUE; } else if (l == 2) { fourcc = GST_MAKE_FOURCC (s[0], s[1], ' ', ' '); ret = TRUE; } else if (l == 1) { fourcc = GST_MAKE_FOURCC (s[0], ' ', ' ', ' '); ret = TRUE; } else if (g_ascii_isdigit (*s)) { fourcc = strtoul (s, &end, 0); if (*end == 0) { ret = TRUE; } } gst_value_set_fourcc (dest, fourcc); return ret; } /************* * int range * *************/ static void gst_value_init_int_range (GValue * value) { value->data[0].v_int = 0; value->data[1].v_int = 0; } static void gst_value_copy_int_range (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int = src_value->data[0].v_int; dest_value->data[1].v_int = src_value->data[1].v_int; } static gchar * gst_value_collect_int_range (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_int >= collect_values[1].v_int) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); value->data[0].v_int = collect_values[0].v_int; value->data[1].v_int = collect_values[1].v_int; return NULL; } static gchar * gst_value_lcopy_int_range (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { guint32 *int_range_start = collect_values[0].v_pointer; guint32 *int_range_end = collect_values[1].v_pointer; if (!int_range_start) return g_strdup_printf ("start value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!int_range_end) return g_strdup_printf ("end value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *int_range_start = value->data[0].v_int; *int_range_end = value->data[1].v_int; return NULL; } /** * gst_value_set_int_range: * @value: a GValue initialized to GST_TYPE_INT_RANGE * @start: the start of the range * @end: the end of the range * * Sets @value to the range specified by @start and @end. */ void gst_value_set_int_range (GValue * value, gint start, gint end) { g_return_if_fail (GST_VALUE_HOLDS_INT_RANGE (value)); g_return_if_fail (start < end); value->data[0].v_int = start; value->data[1].v_int = end; } /** * gst_value_get_int_range_min: * @value: a GValue initialized to GST_TYPE_INT_RANGE * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range */ gint gst_value_get_int_range_min (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_INT_RANGE (value), 0); return value->data[0].v_int; } /** * gst_value_get_int_range_max: * @value: a GValue initialized to GST_TYPE_INT_RANGE * * Gets the maximum of the range specified by @value. * * Returns: the maxumum of the range */ gint gst_value_get_int_range_max (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_INT_RANGE (value), 0); return value->data[1].v_int; } static void gst_value_transform_int_range_string (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = g_strdup_printf ("[%d,%d]", (int) src_value->data[0].v_int, (int) src_value->data[1].v_int); } static gint gst_value_compare_int_range (const GValue * value1, const GValue * value2) { if (value2->data[0].v_int == value1->data[0].v_int && value2->data[1].v_int == value1->data[1].v_int) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_int_range (const GValue * value) { return g_strdup_printf ("[ %d, %d ]", value->data[0].v_int, value->data[1].v_int); } static gboolean gst_value_deserialize_int_range (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } /*************** * int64 range * ***************/ static void gst_value_init_int64_range (GValue * value) { value->data[0].v_int64 = 0; value->data[1].v_int64 = 0; } static void gst_value_copy_int64_range (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int64 = src_value->data[0].v_int64; dest_value->data[1].v_int64 = src_value->data[1].v_int64; } static gchar * gst_value_collect_int64_range (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_int64 >= collect_values[1].v_int64) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); value->data[0].v_int64 = collect_values[0].v_int64; value->data[1].v_int64 = collect_values[1].v_int64; return NULL; } static gchar * gst_value_lcopy_int64_range (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { guint64 *int_range_start = collect_values[0].v_pointer; guint64 *int_range_end = collect_values[1].v_pointer; if (!int_range_start) return g_strdup_printf ("start value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!int_range_end) return g_strdup_printf ("end value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *int_range_start = value->data[0].v_int64; *int_range_end = value->data[1].v_int64; return NULL; } /** * gst_value_set_int64_range: * @value: a GValue initialized to GST_TYPE_INT64_RANGE * @start: the start of the range * @end: the end of the range * * Sets @value to the range specified by @start and @end. * * Since: 0.10.31 */ void gst_value_set_int64_range (GValue * value, gint64 start, gint64 end) { g_return_if_fail (GST_VALUE_HOLDS_INT64_RANGE (value)); g_return_if_fail (start < end); value->data[0].v_int64 = start; value->data[1].v_int64 = end; } /** * gst_value_get_int64_range_min: * @value: a GValue initialized to GST_TYPE_INT64_RANGE * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range * * Since: 0.10.31 */ gint64 gst_value_get_int64_range_min (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_INT64_RANGE (value), 0); return value->data[0].v_int64; } /** * gst_value_get_int64_range_max: * @value: a GValue initialized to GST_TYPE_INT64_RANGE * * Gets the maximum of the range specified by @value. * * Returns: the maxumum of the range * * Since: 0.10.31 */ gint64 gst_value_get_int64_range_max (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_INT64_RANGE (value), 0); return value->data[1].v_int64; } static void gst_value_transform_int64_range_string (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = g_strdup_printf ("(gint64)[%" G_GINT64_FORMAT ",%" G_GINT64_FORMAT "]", src_value->data[0].v_int64, src_value->data[1].v_int64); } static gint gst_value_compare_int64_range (const GValue * value1, const GValue * value2) { if (value2->data[0].v_int64 == value1->data[0].v_int64 && value2->data[1].v_int64 == value1->data[1].v_int64) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_int64_range (const GValue * value) { return g_strdup_printf ("[ %" G_GINT64_FORMAT ", %" G_GINT64_FORMAT " ]", value->data[0].v_int64, value->data[1].v_int64); } static gboolean gst_value_deserialize_int64_range (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } /**************** * double range * ****************/ static void gst_value_init_double_range (GValue * value) { value->data[0].v_double = 0; value->data[1].v_double = 0; } static void gst_value_copy_double_range (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_double = src_value->data[0].v_double; dest_value->data[1].v_double = src_value->data[1].v_double; } static gchar * gst_value_collect_double_range (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_double >= collect_values[1].v_double) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); value->data[0].v_double = collect_values[0].v_double; value->data[1].v_double = collect_values[1].v_double; return NULL; } static gchar * gst_value_lcopy_double_range (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { gdouble *double_range_start = collect_values[0].v_pointer; gdouble *double_range_end = collect_values[1].v_pointer; if (!double_range_start) return g_strdup_printf ("start value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!double_range_end) return g_strdup_printf ("end value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *double_range_start = value->data[0].v_double; *double_range_end = value->data[1].v_double; return NULL; } /** * gst_value_set_double_range: * @value: a GValue initialized to GST_TYPE_DOUBLE_RANGE * @start: the start of the range * @end: the end of the range * * Sets @value to the range specified by @start and @end. */ void gst_value_set_double_range (GValue * value, gdouble start, gdouble end) { g_return_if_fail (GST_VALUE_HOLDS_DOUBLE_RANGE (value)); g_return_if_fail (start < end); value->data[0].v_double = start; value->data[1].v_double = end; } /** * gst_value_get_double_range_min: * @value: a GValue initialized to GST_TYPE_DOUBLE_RANGE * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range */ gdouble gst_value_get_double_range_min (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_DOUBLE_RANGE (value), 0); return value->data[0].v_double; } /** * gst_value_get_double_range_max: * @value: a GValue initialized to GST_TYPE_DOUBLE_RANGE * * Gets the maximum of the range specified by @value. * * Returns: the maxumum of the range */ gdouble gst_value_get_double_range_max (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_DOUBLE_RANGE (value), 0); return value->data[1].v_double; } static void gst_value_transform_double_range_string (const GValue * src_value, GValue * dest_value) { gchar s1[G_ASCII_DTOSTR_BUF_SIZE], s2[G_ASCII_DTOSTR_BUF_SIZE]; dest_value->data[0].v_pointer = g_strdup_printf ("[%s,%s]", g_ascii_dtostr (s1, G_ASCII_DTOSTR_BUF_SIZE, src_value->data[0].v_double), g_ascii_dtostr (s2, G_ASCII_DTOSTR_BUF_SIZE, src_value->data[1].v_double)); } static gint gst_value_compare_double_range (const GValue * value1, const GValue * value2) { if (value2->data[0].v_double == value1->data[0].v_double && value2->data[0].v_double == value1->data[0].v_double) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_double_range (const GValue * value) { gchar d1[G_ASCII_DTOSTR_BUF_SIZE]; gchar d2[G_ASCII_DTOSTR_BUF_SIZE]; g_ascii_dtostr (d1, G_ASCII_DTOSTR_BUF_SIZE, value->data[0].v_double); g_ascii_dtostr (d2, G_ASCII_DTOSTR_BUF_SIZE, value->data[1].v_double); return g_strdup_printf ("[ %s, %s ]", d1, d2); } static gboolean gst_value_deserialize_double_range (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } /**************** * fraction range * ****************/ static void gst_value_init_fraction_range (GValue * value) { GValue *vals; GType ftype; ftype = GST_TYPE_FRACTION; value->data[0].v_pointer = vals = g_slice_alloc0 (2 * sizeof (GValue)); g_value_init (&vals[0], ftype); g_value_init (&vals[1], ftype); } static void gst_value_free_fraction_range (GValue * value) { GValue *vals = (GValue *) value->data[0].v_pointer; if (vals != NULL) { g_value_unset (&vals[0]); g_value_unset (&vals[1]); g_slice_free1 (2 * sizeof (GValue), vals); value->data[0].v_pointer = NULL; } } static void gst_value_copy_fraction_range (const GValue * src_value, GValue * dest_value) { GValue *vals = (GValue *) dest_value->data[0].v_pointer; GValue *src_vals = (GValue *) src_value->data[0].v_pointer; if (vals == NULL) { gst_value_init_fraction_range (dest_value); vals = dest_value->data[0].v_pointer; } if (src_vals != NULL) { g_value_copy (&src_vals[0], &vals[0]); g_value_copy (&src_vals[1], &vals[1]); } } static gchar * gst_value_collect_fraction_range (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { GValue *vals = (GValue *) value->data[0].v_pointer; if (n_collect_values != 4) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[1].v_int == 0) return g_strdup_printf ("passed '0' as first denominator for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_values[3].v_int == 0) return g_strdup_printf ("passed '0' as second denominator for `%s'", G_VALUE_TYPE_NAME (value)); if (gst_util_fraction_compare (collect_values[0].v_int, collect_values[1].v_int, collect_values[2].v_int, collect_values[3].v_int) >= 0) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); if (vals == NULL) { gst_value_init_fraction_range (value); vals = value->data[0].v_pointer; } gst_value_set_fraction (&vals[0], collect_values[0].v_int, collect_values[1].v_int); gst_value_set_fraction (&vals[1], collect_values[2].v_int, collect_values[3].v_int); return NULL; } static gchar * gst_value_lcopy_fraction_range (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { gint i; gint *dest_values[4]; GValue *vals = (GValue *) value->data[0].v_pointer; if (G_UNLIKELY (n_collect_values != 4)) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); for (i = 0; i < 4; i++) { if (G_UNLIKELY (collect_values[i].v_pointer == NULL)) { return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); } dest_values[i] = collect_values[i].v_pointer; } if (G_UNLIKELY (vals == NULL)) { return g_strdup_printf ("Uninitialised `%s' passed", G_VALUE_TYPE_NAME (value)); } dest_values[0][0] = gst_value_get_fraction_numerator (&vals[0]); dest_values[1][0] = gst_value_get_fraction_denominator (&vals[0]); dest_values[2][0] = gst_value_get_fraction_numerator (&vals[1]); dest_values[3][0] = gst_value_get_fraction_denominator (&vals[1]); return NULL; } /** * gst_value_set_fraction_range: * @value: a GValue initialized to GST_TYPE_FRACTION_RANGE * @start: the start of the range (a GST_TYPE_FRACTION GValue) * @end: the end of the range (a GST_TYPE_FRACTION GValue) * * Sets @value to the range specified by @start and @end. */ void gst_value_set_fraction_range (GValue * value, const GValue * start, const GValue * end) { GValue *vals; g_return_if_fail (GST_VALUE_HOLDS_FRACTION_RANGE (value)); g_return_if_fail (GST_VALUE_HOLDS_FRACTION (start)); g_return_if_fail (GST_VALUE_HOLDS_FRACTION (end)); g_return_if_fail (gst_util_fraction_compare (start->data[0].v_int, start->data[1].v_int, end->data[0].v_int, end->data[1].v_int) < 0); vals = (GValue *) value->data[0].v_pointer; if (vals == NULL) { gst_value_init_fraction_range (value); vals = value->data[0].v_pointer; } g_value_copy (start, &vals[0]); g_value_copy (end, &vals[1]); } /** * gst_value_set_fraction_range_full: * @value: a GValue initialized to GST_TYPE_FRACTION_RANGE * @numerator_start: the numerator start of the range * @denominator_start: the denominator start of the range * @numerator_end: the numerator end of the range * @denominator_end: the denominator end of the range * * Sets @value to the range specified by @numerator_start/@denominator_start * and @numerator_end/@denominator_end. */ void gst_value_set_fraction_range_full (GValue * value, gint numerator_start, gint denominator_start, gint numerator_end, gint denominator_end) { GValue start = { 0 }; GValue end = { 0 }; g_return_if_fail (value != NULL); g_return_if_fail (denominator_start != 0); g_return_if_fail (denominator_end != 0); g_return_if_fail (gst_util_fraction_compare (numerator_start, denominator_start, numerator_end, denominator_end) < 0); g_value_init (&start, GST_TYPE_FRACTION); g_value_init (&end, GST_TYPE_FRACTION); gst_value_set_fraction (&start, numerator_start, denominator_start); gst_value_set_fraction (&end, numerator_end, denominator_end); gst_value_set_fraction_range (value, &start, &end); g_value_unset (&start); g_value_unset (&end); } /** * gst_value_get_fraction_range_min: * @value: a GValue initialized to GST_TYPE_FRACTION_RANGE * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range */ const GValue * gst_value_get_fraction_range_min (const GValue * value) { GValue *vals; g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION_RANGE (value), NULL); vals = (GValue *) value->data[0].v_pointer; if (vals != NULL) { return &vals[0]; } return NULL; } /** * gst_value_get_fraction_range_max: * @value: a GValue initialized to GST_TYPE_FRACTION_RANGE * * Gets the maximum of the range specified by @value. * * Returns: the maximum of the range */ const GValue * gst_value_get_fraction_range_max (const GValue * value) { GValue *vals; g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION_RANGE (value), NULL); vals = (GValue *) value->data[0].v_pointer; if (vals != NULL) { return &vals[1]; } return NULL; } static gchar * gst_value_serialize_fraction_range (const GValue * value) { GValue *vals = (GValue *) value->data[0].v_pointer; gchar *retval; if (vals == NULL) { retval = g_strdup ("[ 0/1, 0/1 ]"); } else { gchar *start, *end; start = gst_value_serialize_fraction (&vals[0]); end = gst_value_serialize_fraction (&vals[1]); retval = g_strdup_printf ("[ %s, %s ]", start, end); g_free (start); g_free (end); } return retval; } static void gst_value_transform_fraction_range_string (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = gst_value_serialize_fraction_range (src_value); } static gint gst_value_compare_fraction_range (const GValue * value1, const GValue * value2) { GValue *vals1, *vals2; GstValueCompareFunc compare; if (value2->data[0].v_pointer == value1->data[0].v_pointer) return GST_VALUE_EQUAL; /* Only possible if both are NULL */ if (value2->data[0].v_pointer == NULL || value1->data[0].v_pointer == NULL) return GST_VALUE_UNORDERED; vals1 = (GValue *) value1->data[0].v_pointer; vals2 = (GValue *) value2->data[0].v_pointer; if ((compare = gst_value_get_compare_func (&vals1[0]))) { if (gst_value_compare_with_func (&vals1[0], &vals2[0], compare) == GST_VALUE_EQUAL && gst_value_compare_with_func (&vals1[1], &vals2[1], compare) == GST_VALUE_EQUAL) return GST_VALUE_EQUAL; } return GST_VALUE_UNORDERED; } static gboolean gst_value_deserialize_fraction_range (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } /*********** * GstCaps * ***********/ /** * gst_value_set_caps: * @value: a GValue initialized to GST_TYPE_CAPS * @caps: (transfer none): the caps to set the value to * * Sets the contents of @value to @caps. A reference to the * provided @caps will be taken by the @value. */ void gst_value_set_caps (GValue * value, const GstCaps * caps) { g_return_if_fail (G_IS_VALUE (value)); g_return_if_fail (G_VALUE_TYPE (value) == GST_TYPE_CAPS); g_return_if_fail (caps == NULL || GST_IS_CAPS (caps)); g_value_set_boxed (value, caps); } /** * gst_value_get_caps: * @value: a GValue initialized to GST_TYPE_CAPS * * Gets the contents of @value. The reference count of the returned * #GstCaps will not be modified, therefore the caller must take one * before getting rid of the @value. * * Returns: (transfer none): the contents of @value */ const GstCaps * gst_value_get_caps (const GValue * value) { g_return_val_if_fail (G_IS_VALUE (value), NULL); g_return_val_if_fail (G_VALUE_TYPE (value) == GST_TYPE_CAPS, NULL); return (GstCaps *) g_value_get_boxed (value); } static gchar * gst_value_serialize_caps (const GValue * value) { GstCaps *caps = g_value_get_boxed (value); return gst_caps_to_string (caps); } static gboolean gst_value_deserialize_caps (GValue * dest, const gchar * s) { GstCaps *caps; caps = gst_caps_from_string (s); if (caps) { g_value_take_boxed (dest, caps); return TRUE; } return FALSE; } /**************** * GstStructure * ****************/ /** * gst_value_set_structure: * @value: a GValue initialized to GST_TYPE_STRUCTURE * @structure: the structure to set the value to * * Sets the contents of @value to @structure. The actual * * Since: 0.10.15 */ void gst_value_set_structure (GValue * value, const GstStructure * structure) { g_return_if_fail (G_IS_VALUE (value)); g_return_if_fail (G_VALUE_TYPE (value) == GST_TYPE_STRUCTURE); g_return_if_fail (structure == NULL || GST_IS_STRUCTURE (structure)); g_value_set_boxed (value, structure); } /** * gst_value_get_structure: * @value: a GValue initialized to GST_TYPE_STRUCTURE * * Gets the contents of @value. * * Returns: (transfer none): the contents of @value * * Since: 0.10.15 */ const GstStructure * gst_value_get_structure (const GValue * value) { g_return_val_if_fail (G_IS_VALUE (value), NULL); g_return_val_if_fail (G_VALUE_TYPE (value) == GST_TYPE_STRUCTURE, NULL); return (GstStructure *) g_value_get_boxed (value); } static gchar * gst_value_serialize_structure (const GValue * value) { GstStructure *structure = g_value_get_boxed (value); return gst_string_take_and_wrap (gst_structure_to_string (structure)); } static gboolean gst_value_deserialize_structure (GValue * dest, const gchar * s) { GstStructure *structure; if (*s != '"') { structure = gst_structure_from_string (s, NULL); } else { gchar *str = gst_string_unwrap (s); if (G_UNLIKELY (!str)) return FALSE; structure = gst_structure_from_string (str, NULL); g_free (str); } if (G_LIKELY (structure)) { g_value_take_boxed (dest, structure); return TRUE; } return FALSE; } /************* * GstBuffer * *************/ static gint gst_value_compare_buffer (const GValue * value1, const GValue * value2) { GstBuffer *buf1 = GST_BUFFER (gst_value_get_mini_object (value1)); GstBuffer *buf2 = GST_BUFFER (gst_value_get_mini_object (value2)); if (GST_BUFFER_SIZE (buf1) != GST_BUFFER_SIZE (buf2)) return GST_VALUE_UNORDERED; if (GST_BUFFER_SIZE (buf1) == 0) return GST_VALUE_EQUAL; g_assert (GST_BUFFER_DATA (buf1)); g_assert (GST_BUFFER_DATA (buf2)); if (memcmp (GST_BUFFER_DATA (buf1), GST_BUFFER_DATA (buf2), GST_BUFFER_SIZE (buf1)) == 0) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_buffer (const GValue * value) { guint8 *data; gint i; gint size; gchar *string; GstBuffer *buffer; buffer = gst_value_get_buffer (value); if (buffer == NULL) return NULL; data = GST_BUFFER_DATA (buffer); size = GST_BUFFER_SIZE (buffer); string = g_malloc (size * 2 + 1); for (i = 0; i < size; i++) { sprintf (string + i * 2, "%02x", data[i]); } string[size * 2] = 0; return string; } static gboolean gst_value_deserialize_buffer (GValue * dest, const gchar * s) { GstBuffer *buffer; gint len; gchar ts[3]; guint8 *data; gint i; len = strlen (s); if (len & 1) goto wrong_length; buffer = gst_buffer_new_and_alloc (len / 2); data = GST_BUFFER_DATA (buffer); for (i = 0; i < len / 2; i++) { if (!isxdigit ((int) s[i * 2]) || !isxdigit ((int) s[i * 2 + 1])) goto wrong_char; ts[0] = s[i * 2 + 0]; ts[1] = s[i * 2 + 1]; ts[2] = 0; data[i] = (guint8) strtoul (ts, NULL, 16); } gst_value_take_buffer (dest, buffer); return TRUE; /* ERRORS */ wrong_length: { return FALSE; } wrong_char: { gst_buffer_unref (buffer); return FALSE; } } /*********** * boolean * ***********/ static gint gst_value_compare_boolean (const GValue * value1, const GValue * value2) { if ((value1->data[0].v_int != 0) == (value2->data[0].v_int != 0)) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_boolean (const GValue * value) { if (value->data[0].v_int) { return g_strdup ("true"); } return g_strdup ("false"); } static gboolean gst_value_deserialize_boolean (GValue * dest, const gchar * s) { gboolean ret = FALSE; if (g_ascii_strcasecmp (s, "true") == 0 || g_ascii_strcasecmp (s, "yes") == 0 || g_ascii_strcasecmp (s, "t") == 0 || strcmp (s, "1") == 0) { g_value_set_boolean (dest, TRUE); ret = TRUE; } else if (g_ascii_strcasecmp (s, "false") == 0 || g_ascii_strcasecmp (s, "no") == 0 || g_ascii_strcasecmp (s, "f") == 0 || strcmp (s, "0") == 0) { g_value_set_boolean (dest, FALSE); ret = TRUE; } return ret; } #define CREATE_SERIALIZATION_START(_type,_macro) \ static gint \ gst_value_compare_ ## _type \ (const GValue * value1, const GValue * value2) \ { \ g ## _type val1 = g_value_get_ ## _type (value1); \ g ## _type val2 = g_value_get_ ## _type (value2); \ if (val1 > val2) \ return GST_VALUE_GREATER_THAN; \ if (val1 < val2) \ return GST_VALUE_LESS_THAN; \ return GST_VALUE_EQUAL; \ } \ \ static gchar * \ gst_value_serialize_ ## _type (const GValue * value) \ { \ GValue val = { 0, }; \ g_value_init (&val, G_TYPE_STRING); \ if (!g_value_transform (value, &val)) \ g_assert_not_reached (); \ /* NO_COPY_MADNESS!!! */ \ return (char *) g_value_get_string (&val); \ } /* deserialize the given s into to as a gint64. * check if the result is actually storeable in the given size number of * bytes. */ static gboolean gst_value_deserialize_int_helper (gint64 * to, const gchar * s, gint64 min, gint64 max, gint size) { gboolean ret = FALSE; gchar *end; gint64 mask = -1; errno = 0; *to = g_ascii_strtoull (s, &end, 0); /* a range error is a definitive no-no */ if (errno == ERANGE) { return FALSE; } if (*end == 0) { ret = TRUE; } else { if (g_ascii_strcasecmp (s, "little_endian") == 0) { *to = G_LITTLE_ENDIAN; ret = TRUE; } else if (g_ascii_strcasecmp (s, "big_endian") == 0) { *to = G_BIG_ENDIAN; ret = TRUE; } else if (g_ascii_strcasecmp (s, "byte_order") == 0) { *to = G_BYTE_ORDER; ret = TRUE; } else if (g_ascii_strcasecmp (s, "min") == 0) { *to = min; ret = TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { *to = max; ret = TRUE; } } if (ret) { /* by definition, a gint64 fits into a gint64; so ignore those */ if (size != sizeof (mask)) { if (*to >= 0) { /* for positive numbers, we create a mask of 1's outside of the range * and 0's inside the range. An and will thus keep only 1 bits * outside of the range */ mask <<= (size * 8); if ((mask & *to) != 0) { ret = FALSE; } } else { /* for negative numbers, we do a 2's complement version */ mask <<= ((size * 8) - 1); if ((mask & *to) != mask) { ret = FALSE; } } } } return ret; } #define CREATE_SERIALIZATION(_type,_macro) \ CREATE_SERIALIZATION_START(_type,_macro) \ \ static gboolean \ gst_value_deserialize_ ## _type (GValue * dest, const gchar *s) \ { \ gint64 x; \ \ if (gst_value_deserialize_int_helper (&x, s, G_MIN ## _macro, \ G_MAX ## _macro, sizeof (g ## _type))) { \ g_value_set_ ## _type (dest, /*(g ## _type)*/ x); \ return TRUE; \ } else { \ return FALSE; \ } \ } #define CREATE_USERIALIZATION(_type,_macro) \ CREATE_SERIALIZATION_START(_type,_macro) \ \ static gboolean \ gst_value_deserialize_ ## _type (GValue * dest, const gchar *s) \ { \ gint64 x; \ gchar *end; \ gboolean ret = FALSE; \ \ errno = 0; \ x = g_ascii_strtoull (s, &end, 0); \ /* a range error is a definitive no-no */ \ if (errno == ERANGE) { \ return FALSE; \ } \ /* the cast ensures the range check later on makes sense */ \ x = (g ## _type) x; \ if (*end == 0) { \ ret = TRUE; \ } else { \ if (g_ascii_strcasecmp (s, "little_endian") == 0) { \ x = G_LITTLE_ENDIAN; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "big_endian") == 0) { \ x = G_BIG_ENDIAN; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "byte_order") == 0) { \ x = G_BYTE_ORDER; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "min") == 0) { \ x = 0; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "max") == 0) { \ x = G_MAX ## _macro; \ ret = TRUE; \ } \ } \ if (ret) { \ if (x > G_MAX ## _macro) { \ ret = FALSE; \ } else { \ g_value_set_ ## _type (dest, x); \ } \ } \ return ret; \ } #define REGISTER_SERIALIZATION(_gtype, _type) \ G_STMT_START { \ static const GstValueTable gst_value = { \ _gtype, \ gst_value_compare_ ## _type, \ gst_value_serialize_ ## _type, \ gst_value_deserialize_ ## _type, \ }; \ \ gst_value_register (&gst_value); \ } G_STMT_END CREATE_SERIALIZATION (int, INT); CREATE_SERIALIZATION (int64, INT64); CREATE_SERIALIZATION (long, LONG); CREATE_USERIALIZATION (uint, UINT); CREATE_USERIALIZATION (uint64, UINT64); CREATE_USERIALIZATION (ulong, ULONG); /* FIXME 0.11: remove this again, plugins shouldn't have uchar properties */ #ifndef G_MAXUCHAR #define G_MAXUCHAR 255 #endif CREATE_USERIALIZATION (uchar, UCHAR); /********** * double * **********/ static gint gst_value_compare_double (const GValue * value1, const GValue * value2) { if (value1->data[0].v_double > value2->data[0].v_double) return GST_VALUE_GREATER_THAN; if (value1->data[0].v_double < value2->data[0].v_double) return GST_VALUE_LESS_THAN; if (value1->data[0].v_double == value2->data[0].v_double) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_double (const GValue * value) { gchar d[G_ASCII_DTOSTR_BUF_SIZE]; g_ascii_dtostr (d, G_ASCII_DTOSTR_BUF_SIZE, value->data[0].v_double); return g_strdup (d); } static gboolean gst_value_deserialize_double (GValue * dest, const gchar * s) { gdouble x; gboolean ret = FALSE; gchar *end; x = g_ascii_strtod (s, &end); if (*end == 0) { ret = TRUE; } else { if (g_ascii_strcasecmp (s, "min") == 0) { x = -G_MAXDOUBLE; ret = TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { x = G_MAXDOUBLE; ret = TRUE; } } if (ret) { g_value_set_double (dest, x); } return ret; } /********* * float * *********/ static gint gst_value_compare_float (const GValue * value1, const GValue * value2) { if (value1->data[0].v_float > value2->data[0].v_float) return GST_VALUE_GREATER_THAN; if (value1->data[0].v_float < value2->data[0].v_float) return GST_VALUE_LESS_THAN; if (value1->data[0].v_float == value2->data[0].v_float) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * gst_value_serialize_float (const GValue * value) { gchar d[G_ASCII_DTOSTR_BUF_SIZE]; g_ascii_dtostr (d, G_ASCII_DTOSTR_BUF_SIZE, value->data[0].v_float); return g_strdup (d); } static gboolean gst_value_deserialize_float (GValue * dest, const gchar * s) { gdouble x; gboolean ret = FALSE; gchar *end; x = g_ascii_strtod (s, &end); if (*end == 0) { ret = TRUE; } else { if (g_ascii_strcasecmp (s, "min") == 0) { x = -G_MAXFLOAT; ret = TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { x = G_MAXFLOAT; ret = TRUE; } } if (x > G_MAXFLOAT || x < -G_MAXFLOAT) ret = FALSE; if (ret) { g_value_set_float (dest, (float) x); } return ret; } /********** * string * **********/ static gint gst_value_compare_string (const GValue * value1, const GValue * value2) { if (G_UNLIKELY (!value1->data[0].v_pointer || !value2->data[0].v_pointer)) { /* if only one is NULL, no match - otherwise both NULL == EQUAL */ if (value1->data[0].v_pointer != value2->data[0].v_pointer) return GST_VALUE_UNORDERED; } else { gint x = strcmp (value1->data[0].v_pointer, value2->data[0].v_pointer); if (x < 0) return GST_VALUE_LESS_THAN; if (x > 0) return GST_VALUE_GREATER_THAN; } return GST_VALUE_EQUAL; } static gint gst_string_measure_wrapping (const gchar * s) { gint len; gboolean wrap = FALSE; if (G_UNLIKELY (s == NULL)) return -1; /* Special case: the actual string NULL needs wrapping */ if (G_UNLIKELY (strcmp (s, "NULL") == 0)) return 4; len = 0; while (*s) { if (GST_ASCII_IS_STRING (*s)) { len++; } else if (*s < 0x20 || *s >= 0x7f) { wrap = TRUE; len += 4; } else { wrap = TRUE; len += 2; } s++; } /* Wrap the string if we found something that needs * wrapping, or the empty string (len == 0) */ return (wrap || len == 0) ? len : -1; } static gchar * gst_string_wrap_inner (const gchar * s, gint len) { gchar *d, *e; e = d = g_malloc (len + 3); *e++ = '\"'; while (*s) { if (GST_ASCII_IS_STRING (*s)) { *e++ = *s++; } else if (*s < 0x20 || *s >= 0x7f) { *e++ = '\\'; *e++ = '0' + ((*(guchar *) s) >> 6); *e++ = '0' + (((*s) >> 3) & 0x7); *e++ = '0' + ((*s++) & 0x7); } else { *e++ = '\\'; *e++ = *s++; } } *e++ = '\"'; *e = 0; g_assert (e - d <= len + 3); return d; } /* Do string wrapping/escaping */ static gchar * gst_string_wrap (const gchar * s) { gint len = gst_string_measure_wrapping (s); if (G_LIKELY (len < 0)) return g_strdup (s); return gst_string_wrap_inner (s, len); } /* Same as above, but take ownership of the string */ static gchar * gst_string_take_and_wrap (gchar * s) { gchar *out; gint len = gst_string_measure_wrapping (s); if (G_LIKELY (len < 0)) return s; out = gst_string_wrap_inner (s, len); g_free (s); return out; } /* * This function takes a string delimited with double quotes (") * and unescapes any \xxx octal numbers. * * If sequences of \y are found where y is not in the range of * 0->3, y is copied unescaped. * * If \xyy is found where x is an octal number but y is not, an * error is encountered and NULL is returned. * * the input string must be \0 terminated. */ static gchar * gst_string_unwrap (const gchar * s) { gchar *ret; gchar *read, *write; /* NULL string returns NULL */ if (s == NULL) return NULL; /* strings not starting with " are invalid */ if (*s != '"') return NULL; /* make copy of original string to hold the result. This * string will always be smaller than the original */ ret = g_strdup (s); read = ret; write = ret; /* need to move to the next position as we parsed the " */ read++; while (*read) { if (GST_ASCII_IS_STRING (*read)) { /* normal chars are just copied */ *write++ = *read++; } else if (*read == '"') { /* quote marks end of string */ break; } else if (*read == '\\') { /* got an escape char, move to next position to read a tripplet * of octal numbers */ read++; /* is the next char a possible first octal number? */ if (*read >= '0' && *read <= '3') { /* parse other 2 numbers, if one of them is not in the range of * an octal number, we error. We also catch the case where a zero * byte is found here. */ if (read[1] < '0' || read[1] > '7' || read[2] < '0' || read[2] > '7') goto beach; /* now convert the octal number to a byte again. */ *write++ = ((read[0] - '0') << 6) + ((read[1] - '0') << 3) + (read[2] - '0'); read += 3; } else { /* if we run into a \0 here, we definately won't get a quote later */ if (*read == 0) goto beach; /* else copy \X sequence */ *write++ = *read++; } } else { /* weird character, error */ goto beach; } } /* if the string is not ending in " and zero terminated, we error */ if (*read != '"' || read[1] != '\0') goto beach; /* null terminate result string and return */ *write = '\0'; return ret; beach: g_free (ret); return NULL; } static gchar * gst_value_serialize_string (const GValue * value) { return gst_string_wrap (value->data[0].v_pointer); } static gboolean gst_value_deserialize_string (GValue * dest, const gchar * s) { if (G_UNLIKELY (strcmp (s, "NULL") == 0)) { g_value_set_string (dest, NULL); return TRUE; } else if (G_LIKELY (*s != '"')) { if (!g_utf8_validate (s, -1, NULL)) return FALSE; g_value_set_string (dest, s); return TRUE; } else { gchar *str = gst_string_unwrap (s); if (G_UNLIKELY (!str)) return FALSE; g_value_take_string (dest, str); } return TRUE; } /******** * enum * ********/ static gint gst_value_compare_enum (const GValue * value1, const GValue * value2) { GEnumValue *en1, *en2; GEnumClass *klass1 = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (value1)); GEnumClass *klass2 = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (value2)); g_return_val_if_fail (klass1, GST_VALUE_UNORDERED); g_return_val_if_fail (klass2, GST_VALUE_UNORDERED); en1 = g_enum_get_value (klass1, g_value_get_enum (value1)); en2 = g_enum_get_value (klass2, g_value_get_enum (value2)); g_type_class_unref (klass1); g_type_class_unref (klass2); g_return_val_if_fail (en1, GST_VALUE_UNORDERED); g_return_val_if_fail (en2, GST_VALUE_UNORDERED); if (en1->value < en2->value) return GST_VALUE_LESS_THAN; if (en1->value > en2->value) return GST_VALUE_GREATER_THAN; return GST_VALUE_EQUAL; } static gchar * gst_value_serialize_enum (const GValue * value) { GEnumValue *en; GEnumClass *klass = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (value)); g_return_val_if_fail (klass, NULL); en = g_enum_get_value (klass, g_value_get_enum (value)); g_type_class_unref (klass); /* might be one of the custom formats registered later */ if (G_UNLIKELY (en == NULL && G_VALUE_TYPE (value) == GST_TYPE_FORMAT)) { const GstFormatDefinition *format_def; format_def = gst_format_get_details (g_value_get_enum (value)); g_return_val_if_fail (format_def != NULL, NULL); return g_strdup (format_def->description); } g_return_val_if_fail (en, NULL); return g_strdup (en->value_name); } static gint gst_value_deserialize_enum_iter_cmp (const GstFormatDefinition * format_def, const gchar * s) { if (g_ascii_strcasecmp (s, format_def->nick) == 0) return 0; return g_ascii_strcasecmp (s, format_def->description); } static gboolean gst_value_deserialize_enum (GValue * dest, const gchar * s) { GEnumValue *en; gchar *endptr = NULL; GEnumClass *klass = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (dest)); g_return_val_if_fail (klass, FALSE); if (!(en = g_enum_get_value_by_name (klass, s))) { if (!(en = g_enum_get_value_by_nick (klass, s))) { gint i = strtol (s, &endptr, 0); if (endptr && *endptr == '\0') { en = g_enum_get_value (klass, i); } } } g_type_class_unref (klass); /* might be one of the custom formats registered later */ if (G_UNLIKELY (en == NULL && G_VALUE_TYPE (dest) == GST_TYPE_FORMAT)) { const GstFormatDefinition *format_def; GstIterator *iter; iter = gst_format_iterate_definitions (); format_def = gst_iterator_find_custom (iter, (GCompareFunc) gst_value_deserialize_enum_iter_cmp, (gpointer) s); g_return_val_if_fail (format_def != NULL, FALSE); g_value_set_enum (dest, (gint) format_def->value); gst_iterator_free (iter); return TRUE; } g_return_val_if_fail (en, FALSE); g_value_set_enum (dest, en->value); return TRUE; } /******** * flags * ********/ /* we just compare the value here */ static gint gst_value_compare_flags (const GValue * value1, const GValue * value2) { guint fl1, fl2; GFlagsClass *klass1 = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (value1)); GFlagsClass *klass2 = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (value2)); g_return_val_if_fail (klass1, GST_VALUE_UNORDERED); g_return_val_if_fail (klass2, GST_VALUE_UNORDERED); fl1 = g_value_get_flags (value1); fl2 = g_value_get_flags (value2); g_type_class_unref (klass1); g_type_class_unref (klass2); if (fl1 < fl2) return GST_VALUE_LESS_THAN; if (fl1 > fl2) return GST_VALUE_GREATER_THAN; return GST_VALUE_EQUAL; } /* the different flags are serialized separated with a + */ static gchar * gst_value_serialize_flags (const GValue * value) { guint flags; GFlagsValue *fl; GFlagsClass *klass = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (value)); gchar *result, *tmp; gboolean first = TRUE; g_return_val_if_fail (klass, NULL); flags = g_value_get_flags (value); /* if no flags are set, try to serialize to the _NONE string */ if (!flags) { fl = g_flags_get_first_value (klass, flags); return g_strdup (fl->value_name); } /* some flags are set, so serialize one by one */ result = g_strdup (""); while (flags) { fl = g_flags_get_first_value (klass, flags); if (fl != NULL) { tmp = g_strconcat (result, (first ? "" : "+"), fl->value_name, NULL); g_free (result); result = tmp; first = FALSE; /* clear flag */ flags &= ~fl->value; } } g_type_class_unref (klass); return result; } static gboolean gst_value_deserialize_flags (GValue * dest, const gchar * s) { GFlagsValue *fl; gchar *endptr = NULL; GFlagsClass *klass = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (dest)); gchar **split; guint flags; gint i; g_return_val_if_fail (klass, FALSE); /* split into parts delimited with + */ split = g_strsplit (s, "+", 0); flags = 0; i = 0; /* loop over each part */ while (split[i]) { if (!(fl = g_flags_get_value_by_name (klass, split[i]))) { if (!(fl = g_flags_get_value_by_nick (klass, split[i]))) { gint val = strtol (split[i], &endptr, 0); /* just or numeric value */ if (endptr && *endptr == '\0') { flags |= val; } } } if (fl) { flags |= fl->value; } i++; } g_strfreev (split); g_type_class_unref (klass); g_value_set_flags (dest, flags); return TRUE; } /********* * union * *********/ static gboolean gst_value_union_int_int_range (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_int <= src1->data[0].v_int && src2->data[1].v_int >= src1->data[0].v_int) { gst_value_init_and_copy (dest, src2); return TRUE; } return FALSE; } static gboolean gst_value_union_int_range_int_range (GValue * dest, const GValue * src1, const GValue * src2) { gint min; gint max; min = MAX (src1->data[0].v_int, src2->data[0].v_int); max = MIN (src1->data[1].v_int, src2->data[1].v_int); if (min <= max) { g_value_init (dest, GST_TYPE_INT_RANGE); gst_value_set_int_range (dest, MIN (src1->data[0].v_int, src2->data[0].v_int), MAX (src1->data[1].v_int, src2->data[1].v_int)); return TRUE; } return FALSE; } /**************** * intersection * ****************/ static gboolean gst_value_intersect_int_int_range (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_int <= src1->data[0].v_int && src2->data[1].v_int >= src1->data[0].v_int) { gst_value_init_and_copy (dest, src1); return TRUE; } return FALSE; } static gboolean gst_value_intersect_int_range_int_range (GValue * dest, const GValue * src1, const GValue * src2) { gint min; gint max; min = MAX (src1->data[0].v_int, src2->data[0].v_int); max = MIN (src1->data[1].v_int, src2->data[1].v_int); if (min < max) { g_value_init (dest, GST_TYPE_INT_RANGE); gst_value_set_int_range (dest, min, max); return TRUE; } if (min == max) { g_value_init (dest, G_TYPE_INT); g_value_set_int (dest, min); return TRUE; } return FALSE; } static gboolean gst_value_intersect_int64_int64_range (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_int64 <= src1->data[0].v_int64 && src2->data[1].v_int64 >= src1->data[0].v_int64) { gst_value_init_and_copy (dest, src1); return TRUE; } return FALSE; } static gboolean gst_value_intersect_int64_range_int64_range (GValue * dest, const GValue * src1, const GValue * src2) { gint64 min; gint64 max; min = MAX (src1->data[0].v_int64, src2->data[0].v_int64); max = MIN (src1->data[1].v_int64, src2->data[1].v_int64); if (min < max) { g_value_init (dest, GST_TYPE_INT64_RANGE); gst_value_set_int64_range (dest, min, max); return TRUE; } if (min == max) { g_value_init (dest, G_TYPE_INT64); g_value_set_int64 (dest, min); return TRUE; } return FALSE; } static gboolean gst_value_intersect_double_double_range (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_double <= src1->data[0].v_double && src2->data[1].v_double >= src1->data[0].v_double) { gst_value_init_and_copy (dest, src1); return TRUE; } return FALSE; } static gboolean gst_value_intersect_double_range_double_range (GValue * dest, const GValue * src1, const GValue * src2) { gdouble min; gdouble max; min = MAX (src1->data[0].v_double, src2->data[0].v_double); max = MIN (src1->data[1].v_double, src2->data[1].v_double); if (min < max) { g_value_init (dest, GST_TYPE_DOUBLE_RANGE); gst_value_set_double_range (dest, min, max); return TRUE; } if (min == max) { g_value_init (dest, G_TYPE_DOUBLE); g_value_set_int (dest, (int) min); return TRUE; } return FALSE; } static gboolean gst_value_intersect_list (GValue * dest, const GValue * value1, const GValue * value2) { guint i, size; GValue intersection = { 0, }; gboolean ret = FALSE; size = VALUE_LIST_SIZE (value1); for (i = 0; i < size; i++) { const GValue *cur = VALUE_LIST_GET_VALUE (value1, i); if (gst_value_intersect (&intersection, cur, value2)) { /* append value */ if (!ret) { gst_value_init_and_copy (dest, &intersection); ret = TRUE; } else if (GST_VALUE_HOLDS_LIST (dest)) { gst_value_list_append_value (dest, &intersection); } else { GValue temp = { 0, }; gst_value_init_and_copy (&temp, dest); g_value_unset (dest); gst_value_list_concat (dest, &temp, &intersection); g_value_unset (&temp); } g_value_unset (&intersection); } } return ret; } static gboolean gst_value_intersect_array (GValue * dest, const GValue * src1, const GValue * src2) { guint size; guint n; GValue val = { 0 }; /* only works on similar-sized arrays */ size = gst_value_array_get_size (src1); if (size != gst_value_array_get_size (src2)) return FALSE; g_value_init (dest, GST_TYPE_ARRAY); for (n = 0; n < size; n++) { if (!gst_value_intersect (&val, gst_value_array_get_value (src1, n), gst_value_array_get_value (src2, n))) { g_value_unset (dest); return FALSE; } gst_value_array_append_value (dest, &val); g_value_unset (&val); } return TRUE; } static gboolean gst_value_intersect_fraction_fraction_range (GValue * dest, const GValue * src1, const GValue * src2) { gint res1, res2; GValue *vals; GstValueCompareFunc compare; vals = src2->data[0].v_pointer; if (vals == NULL) return FALSE; if ((compare = gst_value_get_compare_func (src1))) { res1 = gst_value_compare_with_func (&vals[0], src1, compare); res2 = gst_value_compare_with_func (&vals[1], src1, compare); if ((res1 == GST_VALUE_EQUAL || res1 == GST_VALUE_LESS_THAN) && (res2 == GST_VALUE_EQUAL || res2 == GST_VALUE_GREATER_THAN)) { gst_value_init_and_copy (dest, src1); return TRUE; } } return FALSE; } static gboolean gst_value_intersect_fraction_range_fraction_range (GValue * dest, const GValue * src1, const GValue * src2) { GValue *min; GValue *max; gint res; GValue *vals1, *vals2; GstValueCompareFunc compare; vals1 = src1->data[0].v_pointer; vals2 = src2->data[0].v_pointer; g_return_val_if_fail (vals1 != NULL && vals2 != NULL, FALSE); if ((compare = gst_value_get_compare_func (&vals1[0]))) { /* min = MAX (src1.start, src2.start) */ res = gst_value_compare_with_func (&vals1[0], &vals2[0], compare); g_return_val_if_fail (res != GST_VALUE_UNORDERED, FALSE); if (res == GST_VALUE_LESS_THAN) min = &vals2[0]; /* Take the max of the 2 */ else min = &vals1[0]; /* max = MIN (src1.end, src2.end) */ res = gst_value_compare_with_func (&vals1[1], &vals2[1], compare); g_return_val_if_fail (res != GST_VALUE_UNORDERED, FALSE); if (res == GST_VALUE_GREATER_THAN) max = &vals2[1]; /* Take the min of the 2 */ else max = &vals1[1]; res = gst_value_compare_with_func (min, max, compare); g_return_val_if_fail (res != GST_VALUE_UNORDERED, FALSE); if (res == GST_VALUE_LESS_THAN) { g_value_init (dest, GST_TYPE_FRACTION_RANGE); vals1 = dest->data[0].v_pointer; g_value_copy (min, &vals1[0]); g_value_copy (max, &vals1[1]); return TRUE; } if (res == GST_VALUE_EQUAL) { gst_value_init_and_copy (dest, min); return TRUE; } } return FALSE; } /*************** * subtraction * ***************/ static gboolean gst_value_subtract_int_int_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint min = gst_value_get_int_range_min (subtrahend); gint max = gst_value_get_int_range_max (subtrahend); gint val = g_value_get_int (minuend); /* subtracting a range from an int only works if the int is not in the * range */ if (val < min || val > max) { /* and the result is the int */ gst_value_init_and_copy (dest, minuend); return TRUE; } return FALSE; } /* creates a new int range based on input values. */ static gboolean gst_value_create_new_range (GValue * dest, gint min1, gint max1, gint min2, gint max2) { GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ if (min1 <= max1 && min2 <= max2) { pv1 = &v1; pv2 = &v2; } else if (min1 <= max1) { pv1 = dest; pv2 = NULL; } else if (min2 <= max2) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (min1 < max1) { g_value_init (pv1, GST_TYPE_INT_RANGE); gst_value_set_int_range (pv1, min1, max1); } else if (min1 == max1) { g_value_init (pv1, G_TYPE_INT); g_value_set_int (pv1, min1); } if (min2 < max2) { g_value_init (pv2, GST_TYPE_INT_RANGE); gst_value_set_int_range (pv2, min2, max2); } else if (min2 == max2) { g_value_init (pv2, G_TYPE_INT); g_value_set_int (pv2, min2); } if (min1 <= max1 && min2 <= max2) { gst_value_list_concat (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } static gboolean gst_value_subtract_int_range_int (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint min = gst_value_get_int_range_min (minuend); gint max = gst_value_get_int_range_max (minuend); gint val = g_value_get_int (subtrahend); g_return_val_if_fail (min < max, FALSE); /* value is outside of the range, return range unchanged */ if (val < min || val > max) { gst_value_init_and_copy (dest, minuend); return TRUE; } else { /* max must be MAXINT too as val <= max */ if (val == G_MAXINT) { max--; val--; } /* min must be MININT too as val >= max */ if (val == G_MININT) { min++; val++; } gst_value_create_new_range (dest, min, val - 1, val + 1, max); } return TRUE; } static gboolean gst_value_subtract_int_range_int_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint min1 = gst_value_get_int_range_min (minuend); gint max1 = gst_value_get_int_range_max (minuend); gint min2 = gst_value_get_int_range_min (subtrahend); gint max2 = gst_value_get_int_range_max (subtrahend); if (max2 == G_MAXINT && min2 == G_MININT) { return FALSE; } else if (max2 == G_MAXINT) { return gst_value_create_new_range (dest, min1, MIN (min2 - 1, max1), 1, 0); } else if (min2 == G_MININT) { return gst_value_create_new_range (dest, MAX (max2 + 1, min1), max1, 1, 0); } else { return gst_value_create_new_range (dest, min1, MIN (min2 - 1, max1), MAX (max2 + 1, min1), max1); } } static gboolean gst_value_subtract_int64_int64_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint64 min = gst_value_get_int64_range_min (subtrahend); gint64 max = gst_value_get_int64_range_max (subtrahend); gint64 val = g_value_get_int64 (minuend); /* subtracting a range from an int64 only works if the int64 is not in the * range */ if (val < min || val > max) { /* and the result is the int64 */ gst_value_init_and_copy (dest, minuend); return TRUE; } return FALSE; } /* creates a new int64 range based on input values. */ static gboolean gst_value_create_new_int64_range (GValue * dest, gint64 min1, gint64 max1, gint64 min2, gint64 max2) { GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ if (min1 <= max1 && min2 <= max2) { pv1 = &v1; pv2 = &v2; } else if (min1 <= max1) { pv1 = dest; pv2 = NULL; } else if (min2 <= max2) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (min1 < max1) { g_value_init (pv1, GST_TYPE_INT64_RANGE); gst_value_set_int64_range (pv1, min1, max1); } else if (min1 == max1) { g_value_init (pv1, G_TYPE_INT64); g_value_set_int64 (pv1, min1); } if (min2 < max2) { g_value_init (pv2, GST_TYPE_INT64_RANGE); gst_value_set_int64_range (pv2, min2, max2); } else if (min2 == max2) { g_value_init (pv2, G_TYPE_INT64); g_value_set_int64 (pv2, min2); } if (min1 <= max1 && min2 <= max2) { gst_value_list_concat (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } static gboolean gst_value_subtract_int64_range_int64 (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint64 min = gst_value_get_int64_range_min (minuend); gint64 max = gst_value_get_int64_range_max (minuend); gint64 val = g_value_get_int64 (subtrahend); g_return_val_if_fail (min < max, FALSE); /* value is outside of the range, return range unchanged */ if (val < min || val > max) { gst_value_init_and_copy (dest, minuend); return TRUE; } else { /* max must be MAXINT64 too as val <= max */ if (val == G_MAXINT64) { max--; val--; } /* min must be MININT64 too as val >= max */ if (val == G_MININT64) { min++; val++; } gst_value_create_new_int64_range (dest, min, val - 1, val + 1, max); } return TRUE; } static gboolean gst_value_subtract_int64_range_int64_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint64 min1 = gst_value_get_int64_range_min (minuend); gint64 max1 = gst_value_get_int64_range_max (minuend); gint64 min2 = gst_value_get_int64_range_min (subtrahend); gint64 max2 = gst_value_get_int64_range_max (subtrahend); if (max2 == G_MAXINT64 && min2 == G_MININT64) { return FALSE; } else if (max2 == G_MAXINT64) { return gst_value_create_new_int64_range (dest, min1, MIN (min2 - 1, max1), 1, 0); } else if (min2 == G_MININT64) { return gst_value_create_new_int64_range (dest, MAX (max2 + 1, min1), max1, 1, 0); } else { return gst_value_create_new_int64_range (dest, min1, MIN (min2 - 1, max1), MAX (max2 + 1, min1), max1); } } static gboolean gst_value_subtract_double_double_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gdouble min = gst_value_get_double_range_min (subtrahend); gdouble max = gst_value_get_double_range_max (subtrahend); gdouble val = g_value_get_double (minuend); if (val < min || val > max) { gst_value_init_and_copy (dest, minuend); return TRUE; } return FALSE; } static gboolean gst_value_subtract_double_range_double (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we cannot create a hole in * a double range. We return the original range */ gst_value_init_and_copy (dest, minuend); return TRUE; } static gboolean gst_value_subtract_double_range_double_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we have to approximate */ /* done like with ints */ gdouble min1 = gst_value_get_double_range_min (minuend); gdouble max2 = gst_value_get_double_range_max (minuend); gdouble max1 = MIN (gst_value_get_double_range_min (subtrahend), max2); gdouble min2 = MAX (gst_value_get_double_range_max (subtrahend), min1); GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ if (min1 < max1 && min2 < max2) { pv1 = &v1; pv2 = &v2; } else if (min1 < max1) { pv1 = dest; pv2 = NULL; } else if (min2 < max2) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (min1 < max1) { g_value_init (pv1, GST_TYPE_DOUBLE_RANGE); gst_value_set_double_range (pv1, min1, max1); } if (min2 < max2) { g_value_init (pv2, GST_TYPE_DOUBLE_RANGE); gst_value_set_double_range (pv2, min2, max2); } if (min1 < max1 && min2 < max2) { gst_value_list_concat (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } static gboolean gst_value_subtract_from_list (GValue * dest, const GValue * minuend, const GValue * subtrahend) { guint i, size; GValue subtraction = { 0, }; gboolean ret = FALSE; GType ltype; ltype = gst_value_list_get_type (); size = VALUE_LIST_SIZE (minuend); for (i = 0; i < size; i++) { const GValue *cur = VALUE_LIST_GET_VALUE (minuend, i); if (gst_value_subtract (&subtraction, cur, subtrahend)) { if (!ret) { gst_value_init_and_copy (dest, &subtraction); ret = TRUE; } else if (G_VALUE_HOLDS (dest, ltype) && !G_VALUE_HOLDS (&subtraction, ltype)) { gst_value_list_append_value (dest, &subtraction); } else { GValue temp = { 0, }; gst_value_init_and_copy (&temp, dest); g_value_unset (dest); gst_value_list_concat (dest, &temp, &subtraction); g_value_unset (&temp); } g_value_unset (&subtraction); } } return ret; } static gboolean gst_value_subtract_list (GValue * dest, const GValue * minuend, const GValue * subtrahend) { guint i, size; GValue data[2] = { {0,}, {0,} }; GValue *subtraction = &data[0], *result = &data[1]; gst_value_init_and_copy (result, minuend); size = VALUE_LIST_SIZE (subtrahend); for (i = 0; i < size; i++) { const GValue *cur = VALUE_LIST_GET_VALUE (subtrahend, i); if (gst_value_subtract (subtraction, result, cur)) { GValue *temp = result; result = subtraction; subtraction = temp; g_value_unset (subtraction); } else { g_value_unset (result); return FALSE; } } gst_value_init_and_copy (dest, result); g_value_unset (result); return TRUE; } static gboolean gst_value_subtract_fraction_fraction_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { const GValue *min = gst_value_get_fraction_range_min (subtrahend); const GValue *max = gst_value_get_fraction_range_max (subtrahend); GstValueCompareFunc compare; if ((compare = gst_value_get_compare_func (minuend))) { /* subtracting a range from an fraction only works if the fraction * is not in the range */ if (gst_value_compare_with_func (minuend, min, compare) == GST_VALUE_LESS_THAN || gst_value_compare_with_func (minuend, max, compare) == GST_VALUE_GREATER_THAN) { /* and the result is the value */ gst_value_init_and_copy (dest, minuend); return TRUE; } } return FALSE; } static gboolean gst_value_subtract_fraction_range_fraction (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we cannot create a hole in * a range. We return the original range */ gst_value_init_and_copy (dest, minuend); return TRUE; } static gboolean gst_value_subtract_fraction_range_fraction_range (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we have to approximate */ /* done like with ints and doubles. Creates a list of 2 fraction ranges */ const GValue *min1 = gst_value_get_fraction_range_min (minuend); const GValue *max2 = gst_value_get_fraction_range_max (minuend); const GValue *max1 = gst_value_get_fraction_range_min (subtrahend); const GValue *min2 = gst_value_get_fraction_range_max (subtrahend); gint cmp1, cmp2; GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ GstValueCompareFunc compare; g_return_val_if_fail (min1 != NULL && max1 != NULL, FALSE); g_return_val_if_fail (min2 != NULL && max2 != NULL, FALSE); compare = gst_value_get_compare_func (min1); g_return_val_if_fail (compare, FALSE); cmp1 = gst_value_compare_with_func (max2, max1, compare); g_return_val_if_fail (cmp1 != GST_VALUE_UNORDERED, FALSE); if (cmp1 == GST_VALUE_LESS_THAN) max1 = max2; cmp1 = gst_value_compare_with_func (min1, min2, compare); g_return_val_if_fail (cmp1 != GST_VALUE_UNORDERED, FALSE); if (cmp1 == GST_VALUE_GREATER_THAN) min2 = min1; cmp1 = gst_value_compare_with_func (min1, max1, compare); cmp2 = gst_value_compare_with_func (min2, max2, compare); if (cmp1 == GST_VALUE_LESS_THAN && cmp2 == GST_VALUE_LESS_THAN) { pv1 = &v1; pv2 = &v2; } else if (cmp1 == GST_VALUE_LESS_THAN) { pv1 = dest; pv2 = NULL; } else if (cmp2 == GST_VALUE_LESS_THAN) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (cmp1 == GST_VALUE_LESS_THAN) { g_value_init (pv1, GST_TYPE_FRACTION_RANGE); gst_value_set_fraction_range (pv1, min1, max1); } if (cmp2 == GST_VALUE_LESS_THAN) { g_value_init (pv2, GST_TYPE_FRACTION_RANGE); gst_value_set_fraction_range (pv2, min2, max2); } if (cmp1 == GST_VALUE_LESS_THAN && cmp2 == GST_VALUE_LESS_THAN) { gst_value_list_concat (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } /************** * comparison * **************/ /* * gst_value_get_compare_func: * @value1: a value to get the compare function for * * Determines the compare function to be used with values of the same type as * @value1. The function can be given to gst_value_compare_with_func(). * * Returns: A #GstValueCompareFunc value */ static GstValueCompareFunc gst_value_get_compare_func (const GValue * value1) { GstValueTable *table, *best = NULL; guint i; GType type1; type1 = G_VALUE_TYPE (value1); /* this is a fast check */ best = gst_value_hash_lookup_type (type1); /* slower checks */ if (G_UNLIKELY (!best || !best->compare)) { guint len = gst_value_table->len; best = NULL; for (i = 0; i < len; i++) { table = &g_array_index (gst_value_table, GstValueTable, i); if (table->compare && g_type_is_a (type1, table->type)) { if (!best || g_type_is_a (table->type, best->type)) best = table; } } } if (G_LIKELY (best)) return best->compare; return NULL; } /** * gst_value_can_compare: * @value1: a value to compare * @value2: another value to compare * * Determines if @value1 and @value2 can be compared. * * Returns: TRUE if the values can be compared */ gboolean gst_value_can_compare (const GValue * value1, const GValue * value2) { g_return_val_if_fail (G_IS_VALUE (value1), FALSE); g_return_val_if_fail (G_IS_VALUE (value2), FALSE); if (G_VALUE_TYPE (value1) != G_VALUE_TYPE (value2)) return FALSE; return gst_value_get_compare_func (value1) != NULL; } /** * gst_value_compare: * @value1: a value to compare * @value2: another value to compare * * Compares @value1 and @value2. If @value1 and @value2 cannot be * compared, the function returns GST_VALUE_UNORDERED. Otherwise, * if @value1 is greater than @value2, GST_VALUE_GREATER_THAN is returned. * If @value1 is less than @value2, GST_VALUE_LESS_THAN is returned. * If the values are equal, GST_VALUE_EQUAL is returned. * * Returns: comparison result */ gint gst_value_compare (const GValue * value1, const GValue * value2) { GstValueCompareFunc compare; g_return_val_if_fail (G_IS_VALUE (value1), GST_VALUE_LESS_THAN); g_return_val_if_fail (G_IS_VALUE (value2), GST_VALUE_GREATER_THAN); if (G_VALUE_TYPE (value1) != G_VALUE_TYPE (value2)) return GST_VALUE_UNORDERED; compare = gst_value_get_compare_func (value1); if (compare) { return compare (value1, value2); } g_critical ("unable to compare values of type %s\n", g_type_name (G_VALUE_TYPE (value1))); return GST_VALUE_UNORDERED; } /* * gst_value_compare_with_func: * @value1: a value to compare * @value2: another value to compare * @compare: compare function * * Compares @value1 and @value2 using the @compare function. Works like * gst_value_compare() but allows to save time determining the compare function * a multiple times. * * Returns: comparison result */ static gint gst_value_compare_with_func (const GValue * value1, const GValue * value2, GstValueCompareFunc compare) { g_assert (compare); if (G_VALUE_TYPE (value1) != G_VALUE_TYPE (value2)) return GST_VALUE_UNORDERED; return compare (value1, value2); } /* union */ /** * gst_value_can_union: * @value1: a value to union * @value2: another value to union * * Determines if @value1 and @value2 can be non-trivially unioned. * Any two values can be trivially unioned by adding both of them * to a GstValueList. However, certain types have the possibility * to be unioned in a simpler way. For example, an integer range * and an integer can be unioned if the integer is a subset of the * integer range. If there is the possibility that two values can * be unioned, this function returns TRUE. * * Returns: TRUE if there is a function allowing the two values to * be unioned. */ gboolean gst_value_can_union (const GValue * value1, const GValue * value2) { GstValueUnionInfo *union_info; guint i, len; g_return_val_if_fail (G_IS_VALUE (value1), FALSE); g_return_val_if_fail (G_IS_VALUE (value2), FALSE); len = gst_value_union_funcs->len; for (i = 0; i < len; i++) { union_info = &g_array_index (gst_value_union_funcs, GstValueUnionInfo, i); if (union_info->type1 == G_VALUE_TYPE (value1) && union_info->type2 == G_VALUE_TYPE (value2)) return TRUE; if (union_info->type1 == G_VALUE_TYPE (value2) && union_info->type2 == G_VALUE_TYPE (value1)) return TRUE; } return FALSE; } /** * gst_value_union: * @dest: (out caller-allocates): the destination value * @value1: a value to union * @value2: another value to union * * Creates a GValue corresponding to the union of @value1 and @value2. * * Returns: always returns %TRUE */ /* FIXME: change return type to 'void'? */ gboolean gst_value_union (GValue * dest, const GValue * value1, const GValue * value2) { GstValueUnionInfo *union_info; guint i, len; g_return_val_if_fail (dest != NULL, FALSE); g_return_val_if_fail (G_IS_VALUE (value1), FALSE); g_return_val_if_fail (G_IS_VALUE (value2), FALSE); len = gst_value_union_funcs->len; for (i = 0; i < len; i++) { union_info = &g_array_index (gst_value_union_funcs, GstValueUnionInfo, i); if (union_info->type1 == G_VALUE_TYPE (value1) && union_info->type2 == G_VALUE_TYPE (value2)) { if (union_info->func (dest, value1, value2)) { return TRUE; } } if (union_info->type1 == G_VALUE_TYPE (value2) && union_info->type2 == G_VALUE_TYPE (value1)) { if (union_info->func (dest, value2, value1)) { return TRUE; } } } gst_value_list_concat (dest, value1, value2); return TRUE; } /** * gst_value_register_union_func: * @type1: a type to union * @type2: another type to union * @func: a function that implments creating a union between the two types * * Registers a union function that can create a union between #GValue items * of the type @type1 and @type2. * * Union functions should be registered at startup before any pipelines are * started, as gst_value_register_union_func() is not thread-safe and cannot * be used at the same time as gst_value_union() or gst_value_can_union(). */ void gst_value_register_union_func (GType type1, GType type2, GstValueUnionFunc func) { GstValueUnionInfo union_info; union_info.type1 = type1; union_info.type2 = type2; union_info.func = func; g_array_append_val (gst_value_union_funcs, union_info); } /* intersection */ /** * gst_value_can_intersect: * @value1: a value to intersect * @value2: another value to intersect * * Determines if intersecting two values will produce a valid result. * Two values will produce a valid intersection if they have the same * type, or if there is a method (registered by * gst_value_register_intersect_func()) to calculate the intersection. * * Returns: TRUE if the values can intersect */ gboolean gst_value_can_intersect (const GValue * value1, const GValue * value2) { GstValueIntersectInfo *intersect_info; guint i, len; GType ltype, type1, type2; g_return_val_if_fail (G_IS_VALUE (value1), FALSE); g_return_val_if_fail (G_IS_VALUE (value2), FALSE); ltype = gst_value_list_get_type (); /* special cases */ if (G_VALUE_HOLDS (value1, ltype) || G_VALUE_HOLDS (value2, ltype)) return TRUE; type1 = G_VALUE_TYPE (value1); type2 = G_VALUE_TYPE (value2); /* practically all GstValue types have a compare function (_can_compare=TRUE) * GstStructure and GstCaps have npot, but are intersectable */ if (type1 == type2) return TRUE; /* check registered intersect functions */ len = gst_value_intersect_funcs->len; for (i = 0; i < len; i++) { intersect_info = &g_array_index (gst_value_intersect_funcs, GstValueIntersectInfo, i); if ((intersect_info->type1 == type1 && intersect_info->type2 == type2) || (intersect_info->type1 == type2 && intersect_info->type2 == type1)) return TRUE; } return gst_value_can_compare (value1, value2); } /** * gst_value_intersect: * @dest: (out caller-allocates): a uninitialized #GValue that will hold the calculated * intersection value * @value1: a value to intersect * @value2: another value to intersect * * Calculates the intersection of two values. If the values have * a non-empty intersection, the value representing the intersection * is placed in @dest. If the intersection is non-empty, @dest is * not modified. * * Returns: TRUE if the intersection is non-empty */ gboolean gst_value_intersect (GValue * dest, const GValue * value1, const GValue * value2) { GstValueIntersectInfo *intersect_info; guint i, len; GType ltype, type1, type2; g_return_val_if_fail (dest != NULL, FALSE); g_return_val_if_fail (G_IS_VALUE (value1), FALSE); g_return_val_if_fail (G_IS_VALUE (value2), FALSE); ltype = gst_value_list_get_type (); /* special cases first */ if (G_VALUE_HOLDS (value1, ltype)) return gst_value_intersect_list (dest, value1, value2); if (G_VALUE_HOLDS (value2, ltype)) return gst_value_intersect_list (dest, value2, value1); if (gst_value_compare (value1, value2) == GST_VALUE_EQUAL) { gst_value_init_and_copy (dest, value1); return TRUE; } type1 = G_VALUE_TYPE (value1); type2 = G_VALUE_TYPE (value2); len = gst_value_intersect_funcs->len; for (i = 0; i < len; i++) { intersect_info = &g_array_index (gst_value_intersect_funcs, GstValueIntersectInfo, i); if (intersect_info->type1 == type1 && intersect_info->type2 == type2) { return intersect_info->func (dest, value1, value2); } if (intersect_info->type1 == type2 && intersect_info->type2 == type1) { return intersect_info->func (dest, value2, value1); } } return FALSE; } /** * gst_value_register_intersect_func: * @type1: the first type to intersect * @type2: the second type to intersect * @func: the intersection function * * Registers a function that is called to calculate the intersection * of the values having the types @type1 and @type2. * * Intersect functions should be registered at startup before any pipelines are * started, as gst_value_register_intersect_func() is not thread-safe and * cannot be used at the same time as gst_value_intersect() or * gst_value_can_intersect(). */ void gst_value_register_intersect_func (GType type1, GType type2, GstValueIntersectFunc func) { GstValueIntersectInfo intersect_info; intersect_info.type1 = type1; intersect_info.type2 = type2; intersect_info.func = func; g_array_append_val (gst_value_intersect_funcs, intersect_info); } /* subtraction */ /** * gst_value_subtract: * @dest: (out caller-allocates): the destination value for the result if the * subtraction is not empty * @minuend: the value to subtract from * @subtrahend: the value to subtract * * Subtracts @subtrahend from @minuend and stores the result in @dest. * Note that this means subtraction as in sets, not as in mathematics. * * Returns: %TRUE if the subtraction is not empty */ gboolean gst_value_subtract (GValue * dest, const GValue * minuend, const GValue * subtrahend) { GstValueSubtractInfo *info; guint i, len; GType ltype, mtype, stype; g_return_val_if_fail (dest != NULL, FALSE); g_return_val_if_fail (G_IS_VALUE (minuend), FALSE); g_return_val_if_fail (G_IS_VALUE (subtrahend), FALSE); ltype = gst_value_list_get_type (); /* special cases first */ if (G_VALUE_HOLDS (minuend, ltype)) return gst_value_subtract_from_list (dest, minuend, subtrahend); if (G_VALUE_HOLDS (subtrahend, ltype)) return gst_value_subtract_list (dest, minuend, subtrahend); mtype = G_VALUE_TYPE (minuend); stype = G_VALUE_TYPE (subtrahend); len = gst_value_subtract_funcs->len; for (i = 0; i < len; i++) { info = &g_array_index (gst_value_subtract_funcs, GstValueSubtractInfo, i); if (info->minuend == mtype && info->subtrahend == stype) { return info->func (dest, minuend, subtrahend); } } if (gst_value_compare (minuend, subtrahend) != GST_VALUE_EQUAL) { gst_value_init_and_copy (dest, minuend); return TRUE; } return FALSE; } #if 0 gboolean gst_value_subtract (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gboolean ret = gst_value_subtract2 (dest, minuend, subtrahend); g_printerr ("\"%s\" - \"%s\" = \"%s\"\n", gst_value_serialize (minuend), gst_value_serialize (subtrahend), ret ? gst_value_serialize (dest) : "---"); return ret; } #endif /** * gst_value_can_subtract: * @minuend: the value to subtract from * @subtrahend: the value to subtract * * Checks if it's possible to subtract @subtrahend from @minuend. * * Returns: TRUE if a subtraction is possible */ gboolean gst_value_can_subtract (const GValue * minuend, const GValue * subtrahend) { GstValueSubtractInfo *info; guint i, len; GType ltype, mtype, stype; g_return_val_if_fail (G_IS_VALUE (minuend), FALSE); g_return_val_if_fail (G_IS_VALUE (subtrahend), FALSE); ltype = gst_value_list_get_type (); /* special cases */ if (G_VALUE_HOLDS (minuend, ltype) || G_VALUE_HOLDS (subtrahend, ltype)) return TRUE; mtype = G_VALUE_TYPE (minuend); stype = G_VALUE_TYPE (subtrahend); len = gst_value_subtract_funcs->len; for (i = 0; i < len; i++) { info = &g_array_index (gst_value_subtract_funcs, GstValueSubtractInfo, i); if (info->minuend == mtype && info->subtrahend == stype) return TRUE; } return gst_value_can_compare (minuend, subtrahend); } /** * gst_value_register_subtract_func: * @minuend_type: type of the minuend * @subtrahend_type: type of the subtrahend * @func: function to use * * Registers @func as a function capable of subtracting the values of * @subtrahend_type from values of @minuend_type. * * Subtract functions should be registered at startup before any pipelines are * started, as gst_value_register_subtract_func() is not thread-safe and * cannot be used at the same time as gst_value_subtract(). */ void gst_value_register_subtract_func (GType minuend_type, GType subtrahend_type, GstValueSubtractFunc func) { GstValueSubtractInfo info; /* one type must be unfixed, other subtractions can be done as comparisons */ g_return_if_fail (!gst_type_is_fixed (minuend_type) || !gst_type_is_fixed (subtrahend_type)); info.minuend = minuend_type; info.subtrahend = subtrahend_type; info.func = func; g_array_append_val (gst_value_subtract_funcs, info); } /** * gst_value_register: * @table: structure containing functions to register * * Registers functions to perform calculations on #GValue items of a given * type. Each type can only be added once. */ void gst_value_register (const GstValueTable * table) { GstValueTable *found; g_return_if_fail (table != NULL); g_array_append_val (gst_value_table, *table); found = gst_value_hash_lookup_type (table->type); if (found) g_warning ("adding type %s multiple times", g_type_name (table->type)); /* FIXME: we're not really doing the const justice, we assume the table is * static */ gst_value_hash_add_type (table->type, table); } /** * gst_value_init_and_copy: * @dest: (out caller-allocates): the target value * @src: the source value * * Initialises the target value to be of the same type as source and then copies * the contents from source to target. */ void gst_value_init_and_copy (GValue * dest, const GValue * src) { g_return_if_fail (G_IS_VALUE (src)); g_return_if_fail (dest != NULL); g_value_init (dest, G_VALUE_TYPE (src)); g_value_copy (src, dest); } /** * gst_value_serialize: * @value: a #GValue to serialize * * tries to transform the given @value into a string representation that allows * getting back this string later on using gst_value_deserialize(). * * Free-function: g_free * * Returns: (transfer full): the serialization for @value or NULL if none exists */ gchar * gst_value_serialize (const GValue * value) { guint i, len; GValue s_val = { 0 }; GstValueTable *table, *best; gchar *s; GType type; g_return_val_if_fail (G_IS_VALUE (value), NULL); type = G_VALUE_TYPE (value); best = gst_value_hash_lookup_type (type); if (G_UNLIKELY (!best || !best->serialize)) { len = gst_value_table->len; best = NULL; for (i = 0; i < len; i++) { table = &g_array_index (gst_value_table, GstValueTable, i); if (table->serialize && g_type_is_a (type, table->type)) { if (!best || g_type_is_a (table->type, best->type)) best = table; } } } if (G_LIKELY (best)) return best->serialize (value); g_value_init (&s_val, G_TYPE_STRING); if (g_value_transform (value, &s_val)) { s = gst_string_wrap (g_value_get_string (&s_val)); } else { s = NULL; } g_value_unset (&s_val); return s; } /** * gst_value_deserialize: * @dest: (out caller-allocates): #GValue to fill with contents of * deserialization * @src: string to deserialize * * Tries to deserialize a string into the type specified by the given GValue. * If the operation succeeds, TRUE is returned, FALSE otherwise. * * Returns: TRUE on success */ gboolean gst_value_deserialize (GValue * dest, const gchar * src) { GstValueTable *table, *best; guint i, len; GType type; g_return_val_if_fail (src != NULL, FALSE); g_return_val_if_fail (G_IS_VALUE (dest), FALSE); type = G_VALUE_TYPE (dest); best = gst_value_hash_lookup_type (type); if (G_UNLIKELY (!best || !best->deserialize)) { len = gst_value_table->len; best = NULL; for (i = 0; i < len; i++) { table = &g_array_index (gst_value_table, GstValueTable, i); if (table->deserialize && g_type_is_a (type, table->type)) { if (!best || g_type_is_a (table->type, best->type)) best = table; } } } if (G_LIKELY (best)) return best->deserialize (dest, src); return FALSE; } /** * gst_value_is_fixed: * @value: the #GValue to check * * Tests if the given GValue, if available in a GstStructure (or any other * container) contains a "fixed" (which means: one value) or an "unfixed" * (which means: multiple possible values, such as data lists or data * ranges) value. * * Returns: true if the value is "fixed". */ gboolean gst_value_is_fixed (const GValue * value) { GType type; g_return_val_if_fail (G_IS_VALUE (value), FALSE); type = G_VALUE_TYPE (value); /* the most common types are just basic plain glib types */ if (type <= G_TYPE_MAKE_FUNDAMENTAL (G_TYPE_RESERVED_GLIB_LAST)) { return TRUE; } if (type == GST_TYPE_ARRAY) { gint size, n; const GValue *kid; /* check recursively */ size = gst_value_array_get_size (value); for (n = 0; n < size; n++) { kid = gst_value_array_get_value (value, n); if (!gst_value_is_fixed (kid)) return FALSE; } return TRUE; } return gst_type_is_fixed (type); } /************ * fraction * ************/ /* helper functions */ static void gst_value_init_fraction (GValue * value) { value->data[0].v_int = 0; value->data[1].v_int = 1; } static void gst_value_copy_fraction (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int = src_value->data[0].v_int; dest_value->data[1].v_int = src_value->data[1].v_int; } static gchar * gst_value_collect_fraction (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[1].v_int == 0) return g_strdup_printf ("passed '0' as denominator for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_int < -G_MAXINT) return g_strdup_printf ("passed value smaller than -G_MAXINT as numerator for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_values[1].v_int < -G_MAXINT) return g_strdup_printf ("passed value smaller than -G_MAXINT as denominator for `%s'", G_VALUE_TYPE_NAME (value)); gst_value_set_fraction (value, collect_values[0].v_int, collect_values[1].v_int); return NULL; } static gchar * gst_value_lcopy_fraction (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { gint *numerator = collect_values[0].v_pointer; gint *denominator = collect_values[1].v_pointer; if (!numerator) return g_strdup_printf ("numerator for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!denominator) return g_strdup_printf ("denominator for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *numerator = value->data[0].v_int; *denominator = value->data[1].v_int; return NULL; } /** * gst_value_set_fraction: * @value: a GValue initialized to #GST_TYPE_FRACTION * @numerator: the numerator of the fraction * @denominator: the denominator of the fraction * * Sets @value to the fraction specified by @numerator over @denominator. * The fraction gets reduced to the smallest numerator and denominator, * and if necessary the sign is moved to the numerator. */ void gst_value_set_fraction (GValue * value, gint numerator, gint denominator) { gint gcd = 0; g_return_if_fail (GST_VALUE_HOLDS_FRACTION (value)); g_return_if_fail (denominator != 0); g_return_if_fail (denominator >= -G_MAXINT); g_return_if_fail (numerator >= -G_MAXINT); /* normalize sign */ if (denominator < 0) { numerator = -numerator; denominator = -denominator; } /* check for reduction */ gcd = gst_util_greatest_common_divisor (numerator, denominator); if (gcd) { numerator /= gcd; denominator /= gcd; } g_assert (denominator > 0); value->data[0].v_int = numerator; value->data[1].v_int = denominator; } /** * gst_value_get_fraction_numerator: * @value: a GValue initialized to #GST_TYPE_FRACTION * * Gets the numerator of the fraction specified by @value. * * Returns: the numerator of the fraction. */ gint gst_value_get_fraction_numerator (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION (value), 0); return value->data[0].v_int; } /** * gst_value_get_fraction_denominator: * @value: a GValue initialized to #GST_TYPE_FRACTION * * Gets the denominator of the fraction specified by @value. * * Returns: the denominator of the fraction. */ gint gst_value_get_fraction_denominator (const GValue * value) { g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION (value), 1); return value->data[1].v_int; } /** * gst_value_fraction_multiply: * @product: a GValue initialized to #GST_TYPE_FRACTION * @factor1: a GValue initialized to #GST_TYPE_FRACTION * @factor2: a GValue initialized to #GST_TYPE_FRACTION * * Multiplies the two #GValue items containing a #GST_TYPE_FRACTION and sets * @product to the product of the two fractions. * * Returns: FALSE in case of an error (like integer overflow), TRUE otherwise. */ gboolean gst_value_fraction_multiply (GValue * product, const GValue * factor1, const GValue * factor2) { gint n1, n2, d1, d2; gint res_n, res_d; g_return_val_if_fail (product != NULL, FALSE); g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION (factor1), FALSE); g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION (factor2), FALSE); n1 = factor1->data[0].v_int; n2 = factor2->data[0].v_int; d1 = factor1->data[1].v_int; d2 = factor2->data[1].v_int; if (!gst_util_fraction_multiply (n1, d1, n2, d2, &res_n, &res_d)) return FALSE; gst_value_set_fraction (product, res_n, res_d); return TRUE; } /** * gst_value_fraction_subtract: * @dest: a GValue initialized to #GST_TYPE_FRACTION * @minuend: a GValue initialized to #GST_TYPE_FRACTION * @subtrahend: a GValue initialized to #GST_TYPE_FRACTION * * Subtracts the @subtrahend from the @minuend and sets @dest to the result. * * Returns: FALSE in case of an error (like integer overflow), TRUE otherwise. */ gboolean gst_value_fraction_subtract (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint n1, n2, d1, d2; gint res_n, res_d; g_return_val_if_fail (dest != NULL, FALSE); g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION (minuend), FALSE); g_return_val_if_fail (GST_VALUE_HOLDS_FRACTION (subtrahend), FALSE); n1 = minuend->data[0].v_int; n2 = subtrahend->data[0].v_int; d1 = minuend->data[1].v_int; d2 = subtrahend->data[1].v_int; if (!gst_util_fraction_add (n1, d1, -n2, d2, &res_n, &res_d)) return FALSE; gst_value_set_fraction (dest, res_n, res_d); return TRUE; } static gchar * gst_value_serialize_fraction (const GValue * value) { gint32 numerator = value->data[0].v_int; gint32 denominator = value->data[1].v_int; gboolean positive = TRUE; /* get the sign and make components absolute */ if (numerator < 0) { numerator = -numerator; positive = !positive; } if (denominator < 0) { denominator = -denominator; positive = !positive; } return g_strdup_printf ("%s%d/%d", positive ? "" : "-", numerator, denominator); } static gboolean gst_value_deserialize_fraction (GValue * dest, const gchar * s) { gint num, den; gint num_chars; if (G_UNLIKELY (s == NULL)) return FALSE; if (G_UNLIKELY (dest == NULL || !GST_VALUE_HOLDS_FRACTION (dest))) return FALSE; if (sscanf (s, "%d/%d%n", &num, &den, &num_chars) >= 2) { if (s[num_chars] != 0) return FALSE; if (den == 0) return FALSE; gst_value_set_fraction (dest, num, den); return TRUE; } else if (g_ascii_strcasecmp (s, "1/max") == 0) { gst_value_set_fraction (dest, 1, G_MAXINT); return TRUE; } else if (sscanf (s, "%d%n", &num, &num_chars) >= 1) { if (s[num_chars] != 0) return FALSE; gst_value_set_fraction (dest, num, 1); return TRUE; } else if (g_ascii_strcasecmp (s, "min") == 0) { gst_value_set_fraction (dest, -G_MAXINT, 1); return TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { gst_value_set_fraction (dest, G_MAXINT, 1); return TRUE; } return FALSE; } static void gst_value_transform_fraction_string (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = gst_value_serialize_fraction (src_value); } static void gst_value_transform_string_fraction (const GValue * src_value, GValue * dest_value) { if (!gst_value_deserialize_fraction (dest_value, src_value->data[0].v_pointer)) /* If the deserialize fails, ensure we leave the fraction in a * valid, if incorrect, state */ gst_value_set_fraction (dest_value, 0, 1); } static void gst_value_transform_double_fraction (const GValue * src_value, GValue * dest_value) { gdouble src = g_value_get_double (src_value); gint n, d; gst_util_double_to_fraction (src, &n, &d); gst_value_set_fraction (dest_value, n, d); } static void gst_value_transform_float_fraction (const GValue * src_value, GValue * dest_value) { gfloat src = g_value_get_float (src_value); gint n, d; gst_util_double_to_fraction (src, &n, &d); gst_value_set_fraction (dest_value, n, d); } static void gst_value_transform_fraction_double (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_double = ((double) src_value->data[0].v_int) / ((double) src_value->data[1].v_int); } static void gst_value_transform_fraction_float (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_float = ((float) src_value->data[0].v_int) / ((float) src_value->data[1].v_int); } static gint gst_value_compare_fraction (const GValue * value1, const GValue * value2) { gint n1, n2; gint d1, d2; gint ret; n1 = value1->data[0].v_int; n2 = value2->data[0].v_int; d1 = value1->data[1].v_int; d2 = value2->data[1].v_int; /* fractions are reduced when set, so we can quickly see if they're equal */ if (n1 == n2 && d1 == d2) return GST_VALUE_EQUAL; if (d1 == 0 && d2 == 0) return GST_VALUE_UNORDERED; else if (d1 == 0) return GST_VALUE_GREATER_THAN; else if (d2 == 0) return GST_VALUE_LESS_THAN; ret = gst_util_fraction_compare (n1, d1, n2, d2); if (ret == -1) return GST_VALUE_LESS_THAN; else if (ret == 1) return GST_VALUE_GREATER_THAN; /* Equality can't happen here because we check for that * first already */ g_return_val_if_reached (GST_VALUE_UNORDERED); } /********* * GDate * *********/ /** * gst_value_set_date: * @value: a GValue initialized to GST_TYPE_DATE * @date: the date to set the value to * * Sets the contents of @value to coorespond to @date. The actual * #GDate structure is copied before it is used. */ void gst_value_set_date (GValue * value, const GDate * date) { g_return_if_fail (G_VALUE_TYPE (value) == GST_TYPE_DATE); g_return_if_fail (g_date_valid (date)); g_value_set_boxed (value, date); } /** * gst_value_get_date: * @value: a GValue initialized to GST_TYPE_DATE * * Gets the contents of @value. * * Returns: (transfer none): the contents of @value */ const GDate * gst_value_get_date (const GValue * value) { g_return_val_if_fail (G_VALUE_TYPE (value) == GST_TYPE_DATE, NULL); return (const GDate *) g_value_get_boxed (value); } static gpointer gst_date_copy (gpointer boxed) { const GDate *date = (const GDate *) boxed; if (!g_date_valid (date)) { GST_WARNING ("invalid GDate"); return NULL; } return g_date_new_julian (g_date_get_julian (date)); } static gint gst_value_compare_date (const GValue * value1, const GValue * value2) { const GDate *date1 = (const GDate *) g_value_get_boxed (value1); const GDate *date2 = (const GDate *) g_value_get_boxed (value2); guint32 j1, j2; if (date1 == date2) return GST_VALUE_EQUAL; if ((date1 == NULL || !g_date_valid (date1)) && (date2 != NULL && g_date_valid (date2))) { return GST_VALUE_LESS_THAN; } if ((date2 == NULL || !g_date_valid (date2)) && (date1 != NULL && g_date_valid (date1))) { return GST_VALUE_GREATER_THAN; } if (date1 == NULL || date2 == NULL || !g_date_valid (date1) || !g_date_valid (date2)) { return GST_VALUE_UNORDERED; } j1 = g_date_get_julian (date1); j2 = g_date_get_julian (date2); if (j1 == j2) return GST_VALUE_EQUAL; else if (j1 < j2) return GST_VALUE_LESS_THAN; else return GST_VALUE_GREATER_THAN; } static gchar * gst_value_serialize_date (const GValue * val) { const GDate *date = (const GDate *) g_value_get_boxed (val); if (date == NULL || !g_date_valid (date)) return g_strdup ("9999-99-99"); return g_strdup_printf ("%04u-%02u-%02u", g_date_get_year (date), g_date_get_month (date), g_date_get_day (date)); } static gboolean gst_value_deserialize_date (GValue * dest, const gchar * s) { guint year, month, day; if (!s || sscanf (s, "%04u-%02u-%02u", &year, &month, &day) != 3) return FALSE; if (!g_date_valid_dmy (day, month, year)) return FALSE; g_value_take_boxed (dest, g_date_new_dmy (day, month, year)); return TRUE; } /************* * GstDateTime * *************/ static gint gst_value_compare_date_time (const GValue * value1, const GValue * value2) { const GstDateTime *date1 = (const GstDateTime *) g_value_get_boxed (value1); const GstDateTime *date2 = (const GstDateTime *) g_value_get_boxed (value2); gint ret; if (date1 == date2) return GST_VALUE_EQUAL; if ((date1 == NULL) && (date2 != NULL)) { return GST_VALUE_LESS_THAN; } if ((date2 == NULL) && (date1 != NULL)) { return GST_VALUE_LESS_THAN; } ret = priv_gst_date_time_compare (date1, date2); if (ret == 0) return GST_VALUE_EQUAL; else if (ret < 0) return GST_VALUE_LESS_THAN; else return GST_VALUE_GREATER_THAN; } static gchar * gst_value_serialize_date_time (const GValue * val) { GstDateTime *date = (GstDateTime *) g_value_get_boxed (val); gfloat offset; gint tzhour, tzminute; if (date == NULL) return g_strdup ("null"); offset = gst_date_time_get_time_zone_offset (date); tzhour = (gint) ABS (offset); tzminute = (gint) ((ABS (offset) - tzhour) * 60); return g_strdup_printf ("\"%04d-%02d-%02dT%02d:%02d:%02d.%06d" "%c%02d%02d\"", gst_date_time_get_year (date), gst_date_time_get_month (date), gst_date_time_get_day (date), gst_date_time_get_hour (date), gst_date_time_get_minute (date), gst_date_time_get_second (date), gst_date_time_get_microsecond (date), offset >= 0 ? '+' : '-', tzhour, tzminute); } static gboolean gst_value_deserialize_date_time (GValue * dest, const gchar * s) { gint year, month, day, hour, minute, second, usecond; gchar signal; gint offset = 0; gfloat tzoffset = 0; gint ret; if (!s || strcmp (s, "null") == 0) { return FALSE; } ret = sscanf (s, "%04d-%02d-%02dT%02d:%02d:%02d.%06d%c%04d", &year, &month, &day, &hour, &minute, &second, &usecond, &signal, &offset); if (ret >= 9) { tzoffset = (offset / 100) + ((offset % 100) / 60.0); if (signal == '-') tzoffset = -tzoffset; } else return FALSE; g_value_take_boxed (dest, gst_date_time_new (tzoffset, year, month, day, hour, minute, second + (usecond / 1000000.0))); return TRUE; } static void gst_value_transform_date_string (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = gst_value_serialize_date (src_value); } static void gst_value_transform_string_date (const GValue * src_value, GValue * dest_value) { gst_value_deserialize_date (dest_value, src_value->data[0].v_pointer); } static void gst_value_transform_object_string (const GValue * src_value, GValue * dest_value) { GstObject *obj; gchar *str; obj = g_value_get_object (src_value); if (obj) { str = g_strdup_printf ("(%s) %s", G_OBJECT_TYPE_NAME (obj), GST_OBJECT_NAME (obj)); } else { str = g_strdup ("NULL"); } dest_value->data[0].v_pointer = str; } static GTypeInfo _info = { 0, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, }; static GTypeFundamentalInfo _finfo = { 0 }; #define FUNC_VALUE_GET_TYPE(type, name) \ GType gst_ ## type ## _get_type (void) \ { \ static volatile GType gst_ ## type ## _type = 0; \ \ if (g_once_init_enter (&gst_ ## type ## _type)) { \ GType _type; \ _info.value_table = & _gst_ ## type ## _value_table; \ _type = g_type_register_fundamental ( \ g_type_fundamental_next (), \ name, &_info, &_finfo, 0); \ g_once_init_leave(&gst_ ## type ## _type, _type); \ } \ \ return gst_ ## type ## _type; \ } static const GTypeValueTable _gst_fourcc_value_table = { gst_value_init_fourcc, NULL, gst_value_copy_fourcc, NULL, (char *) "i", gst_value_collect_fourcc, (char *) "p", gst_value_lcopy_fourcc }; FUNC_VALUE_GET_TYPE (fourcc, "GstFourcc"); static const GTypeValueTable _gst_int_range_value_table = { gst_value_init_int_range, NULL, gst_value_copy_int_range, NULL, (char *) "ii", gst_value_collect_int_range, (char *) "pp", gst_value_lcopy_int_range }; FUNC_VALUE_GET_TYPE (int_range, "GstIntRange"); static const GTypeValueTable _gst_int64_range_value_table = { gst_value_init_int64_range, NULL, gst_value_copy_int64_range, NULL, (char *) "qq", gst_value_collect_int64_range, (char *) "pp", gst_value_lcopy_int64_range }; FUNC_VALUE_GET_TYPE (int64_range, "GstInt64Range"); static const GTypeValueTable _gst_double_range_value_table = { gst_value_init_double_range, NULL, gst_value_copy_double_range, NULL, (char *) "dd", gst_value_collect_double_range, (char *) "pp", gst_value_lcopy_double_range }; FUNC_VALUE_GET_TYPE (double_range, "GstDoubleRange"); static const GTypeValueTable _gst_fraction_range_value_table = { gst_value_init_fraction_range, gst_value_free_fraction_range, gst_value_copy_fraction_range, NULL, (char *) "iiii", gst_value_collect_fraction_range, (char *) "pppp", gst_value_lcopy_fraction_range }; FUNC_VALUE_GET_TYPE (fraction_range, "GstFractionRange"); static const GTypeValueTable _gst_value_list_value_table = { gst_value_init_list_or_array, gst_value_free_list_or_array, gst_value_copy_list_or_array, gst_value_list_or_array_peek_pointer, (char *) "p", gst_value_collect_list_or_array, (char *) "p", gst_value_lcopy_list_or_array }; FUNC_VALUE_GET_TYPE (value_list, "GstValueList"); static const GTypeValueTable _gst_value_array_value_table = { gst_value_init_list_or_array, gst_value_free_list_or_array, gst_value_copy_list_or_array, gst_value_list_or_array_peek_pointer, (char *) "p", gst_value_collect_list_or_array, (char *) "p", gst_value_lcopy_list_or_array }; FUNC_VALUE_GET_TYPE (value_array, "GstValueArray"); static const GTypeValueTable _gst_fraction_value_table = { gst_value_init_fraction, NULL, gst_value_copy_fraction, NULL, (char *) "ii", gst_value_collect_fraction, (char *) "pp", gst_value_lcopy_fraction }; FUNC_VALUE_GET_TYPE (fraction, "GstFraction"); GType gst_date_get_type (void) { static GType gst_date_type = 0; if (G_UNLIKELY (gst_date_type == 0)) { /* FIXME 0.11: we require GLib 2.8 already * Not using G_TYPE_DATE here on purpose, even if we could * if GLIB_CHECK_VERSION(2,8,0) was true: we don't want the * serialised strings to have different type strings depending * on what version is used, so FIXME when we require GLib-2.8 */ gst_date_type = g_boxed_type_register_static ("GstDate", (GBoxedCopyFunc) gst_date_copy, (GBoxedFreeFunc) g_date_free); } return gst_date_type; } GType gst_date_time_get_type (void) { static GType gst_date_time_type = 0; if (G_UNLIKELY (gst_date_time_type == 0)) { gst_date_time_type = g_boxed_type_register_static ("GstDateTime", (GBoxedCopyFunc) gst_date_time_ref, (GBoxedFreeFunc) gst_date_time_unref); } return gst_date_time_type; } void _gst_value_initialize (void) { gst_value_table = g_array_new (FALSE, FALSE, sizeof (GstValueTable)); gst_value_hash = g_hash_table_new (NULL, NULL); gst_value_union_funcs = g_array_new (FALSE, FALSE, sizeof (GstValueUnionInfo)); gst_value_intersect_funcs = g_array_new (FALSE, FALSE, sizeof (GstValueIntersectInfo)); gst_value_subtract_funcs = g_array_new (FALSE, FALSE, sizeof (GstValueSubtractInfo)); { static GstValueTable gst_value = { 0, gst_value_compare_fourcc, gst_value_serialize_fourcc, gst_value_deserialize_fourcc, }; gst_value.type = gst_fourcc_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_int_range, gst_value_serialize_int_range, gst_value_deserialize_int_range, }; gst_value.type = gst_int_range_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_int64_range, gst_value_serialize_int64_range, gst_value_deserialize_int64_range, }; gst_value.type = gst_int64_range_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_double_range, gst_value_serialize_double_range, gst_value_deserialize_double_range, }; gst_value.type = gst_double_range_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_fraction_range, gst_value_serialize_fraction_range, gst_value_deserialize_fraction_range, }; gst_value.type = gst_fraction_range_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_list, gst_value_serialize_list, gst_value_deserialize_list, }; gst_value.type = gst_value_list_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_array, gst_value_serialize_array, gst_value_deserialize_array, }; gst_value.type = gst_value_array_get_type (); gst_value_register (&gst_value); } { #if 0 static const GTypeValueTable value_table = { gst_value_init_buffer, NULL, gst_value_copy_buffer, NULL, "i", NULL, /*gst_value_collect_buffer, */ "p", NULL /*gst_value_lcopy_buffer */ }; #endif static GstValueTable gst_value = { 0, gst_value_compare_buffer, gst_value_serialize_buffer, gst_value_deserialize_buffer, }; gst_value.type = GST_TYPE_BUFFER; gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_fraction, gst_value_serialize_fraction, gst_value_deserialize_fraction, }; gst_value.type = gst_fraction_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, NULL, gst_value_serialize_caps, gst_value_deserialize_caps, }; gst_value.type = GST_TYPE_CAPS; gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, NULL, gst_value_serialize_structure, gst_value_deserialize_structure, }; gst_value.type = GST_TYPE_STRUCTURE; gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_date, gst_value_serialize_date, gst_value_deserialize_date, }; gst_value.type = gst_date_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, gst_value_compare_date_time, gst_value_serialize_date_time, gst_value_deserialize_date_time, }; gst_value.type = gst_date_time_get_type (); gst_value_register (&gst_value); } REGISTER_SERIALIZATION (G_TYPE_DOUBLE, double); REGISTER_SERIALIZATION (G_TYPE_FLOAT, float); REGISTER_SERIALIZATION (G_TYPE_STRING, string); REGISTER_SERIALIZATION (G_TYPE_BOOLEAN, boolean); REGISTER_SERIALIZATION (G_TYPE_ENUM, enum); REGISTER_SERIALIZATION (G_TYPE_FLAGS, flags); REGISTER_SERIALIZATION (G_TYPE_INT, int); REGISTER_SERIALIZATION (G_TYPE_INT64, int64); REGISTER_SERIALIZATION (G_TYPE_LONG, long); REGISTER_SERIALIZATION (G_TYPE_UINT, uint); REGISTER_SERIALIZATION (G_TYPE_UINT64, uint64); REGISTER_SERIALIZATION (G_TYPE_ULONG, ulong); REGISTER_SERIALIZATION (G_TYPE_UCHAR, uchar); g_value_register_transform_func (GST_TYPE_FOURCC, G_TYPE_STRING, gst_value_transform_fourcc_string); g_value_register_transform_func (GST_TYPE_INT_RANGE, G_TYPE_STRING, gst_value_transform_int_range_string); g_value_register_transform_func (GST_TYPE_INT64_RANGE, G_TYPE_STRING, gst_value_transform_int64_range_string); g_value_register_transform_func (GST_TYPE_DOUBLE_RANGE, G_TYPE_STRING, gst_value_transform_double_range_string); g_value_register_transform_func (GST_TYPE_FRACTION_RANGE, G_TYPE_STRING, gst_value_transform_fraction_range_string); g_value_register_transform_func (GST_TYPE_LIST, G_TYPE_STRING, gst_value_transform_list_string); g_value_register_transform_func (GST_TYPE_ARRAY, G_TYPE_STRING, gst_value_transform_array_string); g_value_register_transform_func (GST_TYPE_FRACTION, G_TYPE_STRING, gst_value_transform_fraction_string); g_value_register_transform_func (G_TYPE_STRING, GST_TYPE_FRACTION, gst_value_transform_string_fraction); g_value_register_transform_func (GST_TYPE_FRACTION, G_TYPE_DOUBLE, gst_value_transform_fraction_double); g_value_register_transform_func (GST_TYPE_FRACTION, G_TYPE_FLOAT, gst_value_transform_fraction_float); g_value_register_transform_func (G_TYPE_DOUBLE, GST_TYPE_FRACTION, gst_value_transform_double_fraction); g_value_register_transform_func (G_TYPE_FLOAT, GST_TYPE_FRACTION, gst_value_transform_float_fraction); g_value_register_transform_func (GST_TYPE_DATE, G_TYPE_STRING, gst_value_transform_date_string); g_value_register_transform_func (G_TYPE_STRING, GST_TYPE_DATE, gst_value_transform_string_date); g_value_register_transform_func (GST_TYPE_OBJECT, G_TYPE_STRING, gst_value_transform_object_string); gst_value_register_intersect_func (G_TYPE_INT, GST_TYPE_INT_RANGE, gst_value_intersect_int_int_range); gst_value_register_intersect_func (GST_TYPE_INT_RANGE, GST_TYPE_INT_RANGE, gst_value_intersect_int_range_int_range); gst_value_register_intersect_func (G_TYPE_INT64, GST_TYPE_INT64_RANGE, gst_value_intersect_int64_int64_range); gst_value_register_intersect_func (GST_TYPE_INT64_RANGE, GST_TYPE_INT64_RANGE, gst_value_intersect_int64_range_int64_range); gst_value_register_intersect_func (G_TYPE_DOUBLE, GST_TYPE_DOUBLE_RANGE, gst_value_intersect_double_double_range); gst_value_register_intersect_func (GST_TYPE_DOUBLE_RANGE, GST_TYPE_DOUBLE_RANGE, gst_value_intersect_double_range_double_range); gst_value_register_intersect_func (GST_TYPE_ARRAY, GST_TYPE_ARRAY, gst_value_intersect_array); gst_value_register_intersect_func (GST_TYPE_FRACTION, GST_TYPE_FRACTION_RANGE, gst_value_intersect_fraction_fraction_range); gst_value_register_intersect_func (GST_TYPE_FRACTION_RANGE, GST_TYPE_FRACTION_RANGE, gst_value_intersect_fraction_range_fraction_range); gst_value_register_subtract_func (G_TYPE_INT, GST_TYPE_INT_RANGE, gst_value_subtract_int_int_range); gst_value_register_subtract_func (GST_TYPE_INT_RANGE, G_TYPE_INT, gst_value_subtract_int_range_int); gst_value_register_subtract_func (GST_TYPE_INT_RANGE, GST_TYPE_INT_RANGE, gst_value_subtract_int_range_int_range); gst_value_register_subtract_func (G_TYPE_INT64, GST_TYPE_INT64_RANGE, gst_value_subtract_int64_int64_range); gst_value_register_subtract_func (GST_TYPE_INT64_RANGE, G_TYPE_INT64, gst_value_subtract_int64_range_int64); gst_value_register_subtract_func (GST_TYPE_INT64_RANGE, GST_TYPE_INT64_RANGE, gst_value_subtract_int64_range_int64_range); gst_value_register_subtract_func (G_TYPE_DOUBLE, GST_TYPE_DOUBLE_RANGE, gst_value_subtract_double_double_range); gst_value_register_subtract_func (GST_TYPE_DOUBLE_RANGE, G_TYPE_DOUBLE, gst_value_subtract_double_range_double); gst_value_register_subtract_func (GST_TYPE_DOUBLE_RANGE, GST_TYPE_DOUBLE_RANGE, gst_value_subtract_double_range_double_range); gst_value_register_subtract_func (GST_TYPE_FRACTION, GST_TYPE_FRACTION_RANGE, gst_value_subtract_fraction_fraction_range); gst_value_register_subtract_func (GST_TYPE_FRACTION_RANGE, GST_TYPE_FRACTION, gst_value_subtract_fraction_range_fraction); gst_value_register_subtract_func (GST_TYPE_FRACTION_RANGE, GST_TYPE_FRACTION_RANGE, gst_value_subtract_fraction_range_fraction_range); /* see bug #317246, #64994, #65041 */ { volatile GType date_type = G_TYPE_DATE; g_type_name (date_type); } gst_value_register_union_func (G_TYPE_INT, GST_TYPE_INT_RANGE, gst_value_union_int_int_range); gst_value_register_union_func (GST_TYPE_INT_RANGE, GST_TYPE_INT_RANGE, gst_value_union_int_range_int_range); #if 0 /* Implement these if needed */ gst_value_register_union_func (GST_TYPE_FRACTION, GST_TYPE_FRACTION_RANGE, gst_value_union_fraction_fraction_range); gst_value_register_union_func (GST_TYPE_FRACTION_RANGE, GST_TYPE_FRACTION_RANGE, gst_value_union_fraction_range_fraction_range); #endif }
loveyoupeng/rt
modules/media/src/main/native/gstreamer/gstreamer-lite/gstreamer/gst/gstvalue.c
C
gpl-2.0
140,229
/* This file is part of the KDE project Copyright (C) 2004 Cedric Pasteur <cedric.pasteur@free.fr> Copyright (C) 2004 Alexander Dymo <cloudtemple@mskat.net> Copyright (C) 2012 Friedrich W. H. Kossebau <kossebau@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KPROPERTY_DATEEDIT_H #define KPROPERTY_DATEEDIT_H #include "koproperty/Factory.h" #include <QDateEdit> namespace KoProperty { class KOPROPERTY_EXPORT DateEdit : public QDateEdit { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue USER true) public: DateEdit(const Property* prop, QWidget* parent); virtual ~DateEdit(); QVariant value() const; signals: void commitData(QWidget* editor); public slots: void setValue(const QVariant& value); protected: virtual void paintEvent(QPaintEvent* event); protected slots: void onDateChanged(); }; class KOPROPERTY_EXPORT DateDelegate : public EditorCreatorInterface, public ValueDisplayInterface { public: DateDelegate(); virtual QString displayTextForProperty(const Property* prop) const; virtual QWidget* createEditor(int type, QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; }; } #endif
ddelemeny/calligra
libs/koproperty/editors/dateedit.h
C
gpl-2.0
2,001
# PHP > Lesson 3 > Assignment 1 Vous devez afficher un tableau contenant 100 éléments sur plusieurs pages. - Le tableau est contenu dans `$data`. - Vous pouvez voir la structure des données dans `data.php` - Le script `index.php` doit utiliser un paramètre `page` et `count`. - `page` indique le n° de page - `page=0` indique la première page. - Si `page` n'est pas défini, la valeur par défaut est 0. - `count` indique le nombre d'élément par page. - Si `count` n'est pas défini, sa valeur vaut 15. - Vous ne devez modifier QUE le fichier `index.php`, et normalement uniquement à l'interieur des balises `tbody` et `tfoot`. ## Exemple `index.php?page=0&count=20` affiche les élements 0 à 19 `index.php?page=2&count=10` affiche les élements 20 à 29 ## Bonus Créer des liens de navigation de page en page (page suivante, page précédente) dans le footer de la page. ## Bonus 2 Créer des liens pour aller directement à une page avec un n° donné. ## Ressources - [La fonction array_slice](http://php.net/manual/fr/function.array-slice.php) - [$_GET](http://php.net/manual/fr/reserved.variables.get.php)
blank-project/_blank
exercises/php/lesson3/assignment1/README.md
Markdown
gpl-2.0
1,135
// Copyright 2013 Dolphin Emulator Project // Licensed under GPLv2 // Refer to the license.txt file included. #pragma once #include <map> #include <string> #include <vector> #include "Common/CommonTypes.h" #include "DiscIO/Volume.h" namespace File { struct FSTEntry; } // // --- this volume type is used for reading files directly from the hard drive --- // namespace DiscIO { class CVolumeDirectory : public IVolume { public: CVolumeDirectory(const std::string& _rDirectory, bool _bIsWii, const std::string& _rApploader = "", const std::string& _rDOL = ""); ~CVolumeDirectory(); static bool IsValidDirectory(const std::string& _rDirectory); bool Read(u64 _Offset, u64 _Length, u8* _pBuffer) const override; bool RAWRead(u64 _Offset, u64 _Length, u8* _pBuffer) const override; std::string GetUniqueID() const override; void SetUniqueID(std::string _ID); std::string GetMakerID() const override; std::vector<std::string> GetNames() const override; void SetName(std::string); u32 GetFSTSize() const override; std::string GetApploaderDate() const override; ECountry GetCountry() const override; u64 GetSize() const override; u64 GetRawSize() const override; void BuildFST(); private: static std::string ExtractDirectoryName(const std::string& _rDirectory); void SetDiskTypeWii(); void SetDiskTypeGC(); bool SetApploader(const std::string& _rApploader); void SetDOL(const std::string& _rDOL); // writing to read buffer void WriteToBuffer(u64 _SrcStartAddress, u64 _SrcLength, u8* _Src, u64& _Address, u64& _Length, u8*& _pBuffer) const; void PadToAddress(u64 _StartAddress, u64& _Address, u64& _Length, u8*& _pBuffer) const; void Write32(u32 data, u32 offset, u8* buffer); // FST creation void WriteEntryData(u32& entryOffset, u8 type, u32 nameOffset, u64 dataOffset, u32 length); void WriteEntryName(u32& nameOffset, const std::string& name); void WriteEntry(const File::FSTEntry& entry, u32& fstOffset, u32& nameOffset, u64& dataOffset, u32 parentEntryNum); // returns number of entries found in _Directory u32 AddDirectoryEntries(const std::string& _Directory, File::FSTEntry& parentEntry); std::string m_rootDirectory; std::map<u64, std::string> m_virtualDisk; u32 m_totalNameSize; // gc has no shift, wii has 2 bit shift u32 m_addressShift; // first address on disk containing file data u64 m_dataStartAddress; u64 m_fstNameOffset; u64 m_fstSize; u8* m_FSTData; u8* m_diskHeader; #pragma pack(push, 1) struct SDiskHeaderInfo { u32 debug_mntr_size; u32 simulated_mem_size; u32 arg_offset; u32 debug_flag; u32 track_location; u32 track_size; u32 countrycode; u32 unknown; u32 unknown2; // All the data is byteswapped SDiskHeaderInfo() { debug_mntr_size = 0; simulated_mem_size = 0; arg_offset = 0; debug_flag = 0; track_location = 0; track_size = 0; countrycode = 0; unknown = 0; unknown2 = 0; } }; #pragma pack(pop) SDiskHeaderInfo* m_diskHeaderInfo; u64 m_apploaderSize; u8* m_apploader; u64 m_DOLSize; u8* m_DOL; static const u8 ENTRY_SIZE = 0x0c; static const u8 FILE_ENTRY = 0; static const u8 DIRECTORY_ENTRY = 1; static const u64 DISKHEADER_ADDRESS = 0; static const u64 DISKHEADERINFO_ADDRESS = 0x440; static const u64 APPLOADER_ADDRESS = 0x2440; static const u32 MAX_NAME_LENGTH = 0x3df; u64 FST_ADDRESS; u64 DOL_ADDRESS; }; } // namespace
Sonicadvance1/dolphin
Source/Core/DiscIO/VolumeDirectory.h
C
gpl-2.0
3,411
<html> <head> <title>WATOBO - Interceptor</title> </head> <body> <h1>Thank you for using WATOBO - The Webapplication Toolbox</h1> Info:<br> Version: WATOBO_VERSION<br /> Home dir: WATOBO_HOME<br /> <br /><br /> <a href="watobo.pem">Download Certificate</a> </body> </html>
LubyRuffy/watobo
lib/watobo/interceptor/html/index.html
HTML
gpl-2.0
302
/* poly/gsl_poly.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_POLY_H__ #define __GSL_POLY_H__ #include <stdlib.h> #include <gsl/gsl_complex.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* Evaluate polynomial * * c[0] + c[1] x + c[2] x^2 + ... + c[len-1] x^(len-1) * * exceptions: none */ double gsl_poly_eval(const double c[], const int len, const double x); #ifdef HAVE_INLINE extern inline double gsl_poly_eval(const double c[], const int len, const double x) { int i; double ans = c[len-1]; for(i=len-1; i>0; i--) ans = c[i-1] + x * ans; return ans; } #endif /* HAVE_INLINE */ /* Solve for real or complex roots of the standard quadratic equation, * returning the number of real roots. * * Roots are returned ordered. */ int gsl_poly_solve_quadratic (double a, double b, double c, double * x0, double * x1); int gsl_poly_complex_solve_quadratic (double a, double b, double c, gsl_complex * z0, gsl_complex * z1); /* Solve for real roots of the cubic equation * x^3 + a x^2 + b x + c = 0, returning the * number of real roots. * * Roots are returned ordered. */ int gsl_poly_solve_cubic (double a, double b, double c, double * x0, double * x1, double * x2); int gsl_poly_complex_solve_cubic (double a, double b, double c, gsl_complex * z0, gsl_complex * z1, gsl_complex * z2); /* Solve for the complex roots of a general real polynomial */ typedef struct { size_t nc ; double * matrix ; } gsl_poly_complex_workspace ; gsl_poly_complex_workspace * gsl_poly_complex_workspace_alloc (size_t n); void gsl_poly_complex_workspace_free (gsl_poly_complex_workspace * w); int gsl_poly_complex_solve (const double * a, size_t n, gsl_poly_complex_workspace * w, gsl_complex_packed_ptr z); __END_DECLS #endif /* __GSL_POLY_H__ */
SESA/EbbRT-libgsl
include/gsl/gsl_poly.h
C
gpl-2.0
2,776
/* * thinkpad_acpi.c - ThinkPad ACPI Extras * * * Copyright (C) 2004-2005 Borislav Deianov <borislav@users.sf.net> * Copyright (C) 2006-2009 Henrique de Moraes Holschuh <hmh@hmh.eng.br> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define TPACPI_VERSION "0.24" #define TPACPI_SYSFS_VERSION 0x020700 /* * Changelog: * 2007-10-20 changelog trimmed down * * 2007-03-27 0.14 renamed to thinkpad_acpi and moved to * drivers/misc. * * 2006-11-22 0.13 new maintainer * changelog now lives in git commit history, and will * not be updated further in-file. * * 2005-03-17 0.11 support for 600e, 770x * thanks to Jamie Lentin <lentinj@dial.pipex.com> * * 2005-01-16 0.9 use MODULE_VERSION * thanks to Henrik Brix Andersen <brix@gentoo.org> * fix parameter passing on module loading * thanks to Rusty Russell <rusty@rustcorp.com.au> * thanks to Jim Radford <radford@blackbean.org> * 2004-11-08 0.8 fix init error case, don't return from a macro * thanks to Chris Wright <chrisw@osdl.org> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/string.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/nvram.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sysfs.h> #include <linux/backlight.h> #include <linux/fb.h> #include <linux/platform_device.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <linux/input.h> #include <linux/leds.h> #include <linux/rfkill.h> #include <asm/uaccess.h> #include <linux/dmi.h> #include <linux/jiffies.h> #include <linux/workqueue.h> #include <sound/core.h> #include <sound/control.h> #include <sound/initval.h> #include <acpi/acpi_drivers.h> #include <linux/pci_ids.h> /* ThinkPad CMOS commands */ #define TP_CMOS_VOLUME_DOWN 0 #define TP_CMOS_VOLUME_UP 1 #define TP_CMOS_VOLUME_MUTE 2 #define TP_CMOS_BRIGHTNESS_UP 4 #define TP_CMOS_BRIGHTNESS_DOWN 5 #define TP_CMOS_THINKLIGHT_ON 12 #define TP_CMOS_THINKLIGHT_OFF 13 /* NVRAM Addresses */ enum tp_nvram_addr { TP_NVRAM_ADDR_HK2 = 0x57, TP_NVRAM_ADDR_THINKLIGHT = 0x58, TP_NVRAM_ADDR_VIDEO = 0x59, TP_NVRAM_ADDR_BRIGHTNESS = 0x5e, TP_NVRAM_ADDR_MIXER = 0x60, }; /* NVRAM bit masks */ enum { TP_NVRAM_MASK_HKT_THINKPAD = 0x08, TP_NVRAM_MASK_HKT_ZOOM = 0x20, TP_NVRAM_MASK_HKT_DISPLAY = 0x40, TP_NVRAM_MASK_HKT_HIBERNATE = 0x80, TP_NVRAM_MASK_THINKLIGHT = 0x10, TP_NVRAM_MASK_HKT_DISPEXPND = 0x30, TP_NVRAM_MASK_HKT_BRIGHTNESS = 0x20, TP_NVRAM_MASK_LEVEL_BRIGHTNESS = 0x0f, TP_NVRAM_POS_LEVEL_BRIGHTNESS = 0, TP_NVRAM_MASK_MUTE = 0x40, TP_NVRAM_MASK_HKT_VOLUME = 0x80, TP_NVRAM_MASK_LEVEL_VOLUME = 0x0f, TP_NVRAM_POS_LEVEL_VOLUME = 0, }; /* Misc NVRAM-related */ enum { TP_NVRAM_LEVEL_VOLUME_MAX = 14, }; /* ACPI HIDs */ #define TPACPI_ACPI_IBM_HKEY_HID "IBM0068" #define TPACPI_ACPI_LENOVO_HKEY_HID "LEN0068" #define TPACPI_ACPI_EC_HID "PNP0C09" /* Input IDs */ #define TPACPI_HKEY_INPUT_PRODUCT 0x5054 /* "TP" */ #define TPACPI_HKEY_INPUT_VERSION 0x4101 /* ACPI \WGSV commands */ enum { TP_ACPI_WGSV_GET_STATE = 0x01, /* Get state information */ TP_ACPI_WGSV_PWR_ON_ON_RESUME = 0x02, /* Resume WWAN powered on */ TP_ACPI_WGSV_PWR_OFF_ON_RESUME = 0x03, /* Resume WWAN powered off */ TP_ACPI_WGSV_SAVE_STATE = 0x04, /* Save state for S4/S5 */ }; /* TP_ACPI_WGSV_GET_STATE bits */ enum { TP_ACPI_WGSV_STATE_WWANEXIST = 0x0001, /* WWAN hw available */ TP_ACPI_WGSV_STATE_WWANPWR = 0x0002, /* WWAN radio enabled */ TP_ACPI_WGSV_STATE_WWANPWRRES = 0x0004, /* WWAN state at resume */ TP_ACPI_WGSV_STATE_WWANBIOSOFF = 0x0008, /* WWAN disabled in BIOS */ TP_ACPI_WGSV_STATE_BLTHEXIST = 0x0001, /* BLTH hw available */ TP_ACPI_WGSV_STATE_BLTHPWR = 0x0002, /* BLTH radio enabled */ TP_ACPI_WGSV_STATE_BLTHPWRRES = 0x0004, /* BLTH state at resume */ TP_ACPI_WGSV_STATE_BLTHBIOSOFF = 0x0008, /* BLTH disabled in BIOS */ TP_ACPI_WGSV_STATE_UWBEXIST = 0x0010, /* UWB hw available */ TP_ACPI_WGSV_STATE_UWBPWR = 0x0020, /* UWB radio enabled */ }; /* HKEY events */ enum tpacpi_hkey_event_t { /* Hotkey-related */ TP_HKEY_EV_HOTKEY_BASE = 0x1001, /* first hotkey (FN+F1) */ TP_HKEY_EV_BRGHT_UP = 0x1010, /* Brightness up */ TP_HKEY_EV_BRGHT_DOWN = 0x1011, /* Brightness down */ TP_HKEY_EV_VOL_UP = 0x1015, /* Volume up or unmute */ TP_HKEY_EV_VOL_DOWN = 0x1016, /* Volume down or unmute */ TP_HKEY_EV_VOL_MUTE = 0x1017, /* Mixer output mute */ /* Reasons for waking up from S3/S4 */ TP_HKEY_EV_WKUP_S3_UNDOCK = 0x2304, /* undock requested, S3 */ TP_HKEY_EV_WKUP_S4_UNDOCK = 0x2404, /* undock requested, S4 */ TP_HKEY_EV_WKUP_S3_BAYEJ = 0x2305, /* bay ejection req, S3 */ TP_HKEY_EV_WKUP_S4_BAYEJ = 0x2405, /* bay ejection req, S4 */ TP_HKEY_EV_WKUP_S3_BATLOW = 0x2313, /* battery empty, S3 */ TP_HKEY_EV_WKUP_S4_BATLOW = 0x2413, /* battery empty, S4 */ /* Auto-sleep after eject request */ TP_HKEY_EV_BAYEJ_ACK = 0x3003, /* bay ejection complete */ TP_HKEY_EV_UNDOCK_ACK = 0x4003, /* undock complete */ /* Misc bay events */ TP_HKEY_EV_OPTDRV_EJ = 0x3006, /* opt. drive tray ejected */ /* User-interface events */ TP_HKEY_EV_LID_CLOSE = 0x5001, /* laptop lid closed */ TP_HKEY_EV_LID_OPEN = 0x5002, /* laptop lid opened */ TP_HKEY_EV_TABLET_TABLET = 0x5009, /* tablet swivel up */ TP_HKEY_EV_TABLET_NOTEBOOK = 0x500a, /* tablet swivel down */ TP_HKEY_EV_PEN_INSERTED = 0x500b, /* tablet pen inserted */ TP_HKEY_EV_PEN_REMOVED = 0x500c, /* tablet pen removed */ TP_HKEY_EV_BRGHT_CHANGED = 0x5010, /* backlight control event */ /* Thermal events */ TP_HKEY_EV_ALARM_BAT_HOT = 0x6011, /* battery too hot */ TP_HKEY_EV_ALARM_BAT_XHOT = 0x6012, /* battery critically hot */ TP_HKEY_EV_ALARM_SENSOR_HOT = 0x6021, /* sensor too hot */ TP_HKEY_EV_ALARM_SENSOR_XHOT = 0x6022, /* sensor critically hot */ TP_HKEY_EV_THM_TABLE_CHANGED = 0x6030, /* thermal table changed */ /* Misc */ TP_HKEY_EV_RFKILL_CHANGED = 0x7000, /* rfkill switch changed */ }; /**************************************************************************** * Main driver */ #define TPACPI_NAME "thinkpad" #define TPACPI_DESC "ThinkPad ACPI Extras" #define TPACPI_FILE TPACPI_NAME "_acpi" #define TPACPI_URL "http://ibm-acpi.sf.net/" #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net" #define TPACPI_PROC_DIR "ibm" #define TPACPI_ACPI_EVENT_PREFIX "ibm" #define TPACPI_DRVR_NAME TPACPI_FILE #define TPACPI_DRVR_SHORTNAME "tpacpi" #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon" #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd" #define TPACPI_WORKQUEUE_NAME "ktpacpid" #define TPACPI_MAX_ACPI_ARGS 3 /* Debugging printk groups */ #define TPACPI_DBG_ALL 0xffff #define TPACPI_DBG_DISCLOSETASK 0x8000 #define TPACPI_DBG_INIT 0x0001 #define TPACPI_DBG_EXIT 0x0002 #define TPACPI_DBG_RFKILL 0x0004 #define TPACPI_DBG_HKEY 0x0008 #define TPACPI_DBG_FAN 0x0010 #define TPACPI_DBG_BRGHT 0x0020 #define TPACPI_DBG_MIXER 0x0040 #define onoff(status, bit) ((status) & (1 << (bit)) ? "on" : "off") #define enabled(status, bit) ((status) & (1 << (bit)) ? "enabled" : "disabled") #define strlencmp(a, b) (strncmp((a), (b), strlen(b))) /**************************************************************************** * Driver-wide structs and misc. variables */ struct ibm_struct; struct tp_acpi_drv_struct { const struct acpi_device_id *hid; struct acpi_driver *driver; void (*notify) (struct ibm_struct *, u32); acpi_handle *handle; u32 type; struct acpi_device *device; }; struct ibm_struct { char *name; int (*read) (struct seq_file *); int (*write) (char *); void (*exit) (void); void (*resume) (void); void (*suspend) (pm_message_t state); void (*shutdown) (void); struct list_head all_drivers; struct tp_acpi_drv_struct *acpi; struct { u8 acpi_driver_registered:1; u8 acpi_notify_installed:1; u8 proc_created:1; u8 init_called:1; u8 experimental:1; } flags; }; struct ibm_init_struct { char param[32]; int (*init) (struct ibm_init_struct *); mode_t base_procfs_mode; struct ibm_struct *data; }; static struct { u32 bluetooth:1; u32 hotkey:1; u32 hotkey_mask:1; u32 hotkey_wlsw:1; u32 hotkey_tablet:1; u32 light:1; u32 light_status:1; u32 bright_acpimode:1; u32 bright_unkfw:1; u32 wan:1; u32 uwb:1; u32 fan_ctrl_status_undef:1; u32 second_fan:1; u32 beep_needs_two_args:1; u32 mixer_no_level_control:1; u32 input_device_registered:1; u32 platform_drv_registered:1; u32 platform_drv_attrs_registered:1; u32 sensors_pdrv_registered:1; u32 sensors_pdrv_attrs_registered:1; u32 sensors_pdev_attrs_registered:1; u32 hotkey_poll_active:1; } tp_features; static struct { u16 hotkey_mask_ff:1; u16 volume_ctrl_forbidden:1; } tp_warned; struct thinkpad_id_data { unsigned int vendor; /* ThinkPad vendor: * PCI_VENDOR_ID_IBM/PCI_VENDOR_ID_LENOVO */ char *bios_version_str; /* Something like 1ZET51WW (1.03z) */ char *ec_version_str; /* Something like 1ZHT51WW-1.04a */ u16 bios_model; /* 1Y = 0x5931, 0 = unknown */ u16 ec_model; u16 bios_release; /* 1ZETK1WW = 0x314b, 0 = unknown */ u16 ec_release; char *model_str; /* ThinkPad T43 */ char *nummodel_str; /* 9384A9C for a 9384-A9C model */ }; static struct thinkpad_id_data thinkpad_id; static enum { TPACPI_LIFE_INIT = 0, TPACPI_LIFE_RUNNING, TPACPI_LIFE_EXITING, } tpacpi_lifecycle; static int experimental; static u32 dbg_level; static struct workqueue_struct *tpacpi_wq; enum led_status_t { TPACPI_LED_OFF = 0, TPACPI_LED_ON, TPACPI_LED_BLINK, }; /* Special LED class that can defer work */ struct tpacpi_led_classdev { struct led_classdev led_classdev; struct work_struct work; enum led_status_t new_state; unsigned int led; }; /* brightness level capabilities */ static unsigned int bright_maxlvl; /* 0 = unknown */ #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES static int dbg_wlswemul; static int tpacpi_wlsw_emulstate; static int dbg_bluetoothemul; static int tpacpi_bluetooth_emulstate; static int dbg_wwanemul; static int tpacpi_wwan_emulstate; static int dbg_uwbemul; static int tpacpi_uwb_emulstate; #endif /************************************************************************* * Debugging helpers */ #define dbg_printk(a_dbg_level, format, arg...) \ do { \ if (dbg_level & (a_dbg_level)) \ printk(KERN_DEBUG pr_fmt("%s: " format), \ __func__, ##arg); \ } while (0) #ifdef CONFIG_THINKPAD_ACPI_DEBUG #define vdbg_printk dbg_printk static const char *str_supported(int is_supported); #else static inline const char *str_supported(int is_supported) { return ""; } #define vdbg_printk(a_dbg_level, format, arg...) \ no_printk(format, ##arg) #endif static void tpacpi_log_usertask(const char * const what) { printk(KERN_DEBUG pr_fmt("%s: access by process with PID %d\n"), what, task_tgid_vnr(current)); } #define tpacpi_disclose_usertask(what, format, arg...) \ do { \ if (unlikely((dbg_level & TPACPI_DBG_DISCLOSETASK) && \ (tpacpi_lifecycle == TPACPI_LIFE_RUNNING))) { \ printk(KERN_DEBUG pr_fmt("%s: PID %d: " format), \ what, task_tgid_vnr(current), ## arg); \ } \ } while (0) /* * Quirk handling helpers * * ThinkPad IDs and versions seen in the field so far * are two-characters from the set [0-9A-Z], i.e. base 36. * * We use values well outside that range as specials. */ #define TPACPI_MATCH_ANY 0xffffU #define TPACPI_MATCH_UNKNOWN 0U /* TPID('1', 'Y') == 0x5931 */ #define TPID(__c1, __c2) (((__c2) << 8) | (__c1)) #define TPACPI_Q_IBM(__id1, __id2, __quirk) \ { .vendor = PCI_VENDOR_ID_IBM, \ .bios = TPID(__id1, __id2), \ .ec = TPACPI_MATCH_ANY, \ .quirks = (__quirk) } #define TPACPI_Q_LNV(__id1, __id2, __quirk) \ { .vendor = PCI_VENDOR_ID_LENOVO, \ .bios = TPID(__id1, __id2), \ .ec = TPACPI_MATCH_ANY, \ .quirks = (__quirk) } #define TPACPI_QEC_LNV(__id1, __id2, __quirk) \ { .vendor = PCI_VENDOR_ID_LENOVO, \ .bios = TPACPI_MATCH_ANY, \ .ec = TPID(__id1, __id2), \ .quirks = (__quirk) } struct tpacpi_quirk { unsigned int vendor; u16 bios; u16 ec; unsigned long quirks; }; /** * tpacpi_check_quirks() - search BIOS/EC version on a list * @qlist: array of &struct tpacpi_quirk * @qlist_size: number of elements in @qlist * * Iterates over a quirks list until one is found that matches the * ThinkPad's vendor, BIOS and EC model. * * Returns 0 if nothing matches, otherwise returns the quirks field of * the matching &struct tpacpi_quirk entry. * * The match criteria is: vendor, ec and bios much match. */ static unsigned long __init tpacpi_check_quirks( const struct tpacpi_quirk *qlist, unsigned int qlist_size) { while (qlist_size) { if ((qlist->vendor == thinkpad_id.vendor || qlist->vendor == TPACPI_MATCH_ANY) && (qlist->bios == thinkpad_id.bios_model || qlist->bios == TPACPI_MATCH_ANY) && (qlist->ec == thinkpad_id.ec_model || qlist->ec == TPACPI_MATCH_ANY)) return qlist->quirks; qlist_size--; qlist++; } return 0; } static inline bool __pure __init tpacpi_is_lenovo(void) { return thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO; } static inline bool __pure __init tpacpi_is_ibm(void) { return thinkpad_id.vendor == PCI_VENDOR_ID_IBM; } /**************************************************************************** **************************************************************************** * * ACPI Helpers and device model * **************************************************************************** ****************************************************************************/ /************************************************************************* * ACPI basic handles */ static acpi_handle root_handle; static acpi_handle ec_handle; #define TPACPI_HANDLE(object, parent, paths...) \ static acpi_handle object##_handle; \ static const acpi_handle *object##_parent __initdata = \ &parent##_handle; \ static char *object##_paths[] __initdata = { paths } TPACPI_HANDLE(ecrd, ec, "ECRD"); /* 570 */ TPACPI_HANDLE(ecwr, ec, "ECWR"); /* 570 */ TPACPI_HANDLE(cmos, root, "\\UCMS", /* R50, R50e, R50p, R51, */ /* T4x, X31, X40 */ "\\CMOS", /* A3x, G4x, R32, T23, T30, X22-24, X30 */ "\\CMS", /* R40, R40e */ ); /* all others */ TPACPI_HANDLE(hkey, ec, "\\_SB.HKEY", /* 600e/x, 770e, 770x */ "^HKEY", /* R30, R31 */ "HKEY", /* all others */ ); /* 570 */ /************************************************************************* * ACPI helpers */ static int acpi_evalf(acpi_handle handle, void *res, char *method, char *fmt, ...) { char *fmt0 = fmt; struct acpi_object_list params; union acpi_object in_objs[TPACPI_MAX_ACPI_ARGS]; struct acpi_buffer result, *resultp; union acpi_object out_obj; acpi_status status; va_list ap; char res_type; int success; int quiet; if (!*fmt) { pr_err("acpi_evalf() called with empty format\n"); return 0; } if (*fmt == 'q') { quiet = 1; fmt++; } else quiet = 0; res_type = *(fmt++); params.count = 0; params.pointer = &in_objs[0]; va_start(ap, fmt); while (*fmt) { char c = *(fmt++); switch (c) { case 'd': /* int */ in_objs[params.count].integer.value = va_arg(ap, int); in_objs[params.count++].type = ACPI_TYPE_INTEGER; break; /* add more types as needed */ default: pr_err("acpi_evalf() called " "with invalid format character '%c'\n", c); va_end(ap); return 0; } } va_end(ap); if (res_type != 'v') { result.length = sizeof(out_obj); result.pointer = &out_obj; resultp = &result; } else resultp = NULL; status = acpi_evaluate_object(handle, method, &params, resultp); switch (res_type) { case 'd': /* int */ success = (status == AE_OK && out_obj.type == ACPI_TYPE_INTEGER); if (success && res) *(int *)res = out_obj.integer.value; break; case 'v': /* void */ success = status == AE_OK; break; /* add more types as needed */ default: pr_err("acpi_evalf() called " "with invalid format character '%c'\n", res_type); return 0; } if (!success && !quiet) pr_err("acpi_evalf(%s, %s, ...) failed: %s\n", method, fmt0, acpi_format_exception(status)); return success; } static int acpi_ec_read(int i, u8 *p) { int v; if (ecrd_handle) { if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i)) return 0; *p = v; } else { if (ec_read(i, p) < 0) return 0; } return 1; } static int acpi_ec_write(int i, u8 v) { if (ecwr_handle) { if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v)) return 0; } else { if (ec_write(i, v) < 0) return 0; } return 1; } static int issue_thinkpad_cmos_command(int cmos_cmd) { if (!cmos_handle) return -ENXIO; if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd)) return -EIO; return 0; } /************************************************************************* * ACPI device model */ #define TPACPI_ACPIHANDLE_INIT(object) \ drv_acpi_handle_init(#object, &object##_handle, *object##_parent, \ object##_paths, ARRAY_SIZE(object##_paths)) static void __init drv_acpi_handle_init(const char *name, acpi_handle *handle, const acpi_handle parent, char **paths, const int num_paths) { int i; acpi_status status; vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n", name); for (i = 0; i < num_paths; i++) { status = acpi_get_handle(parent, paths[i], handle); if (ACPI_SUCCESS(status)) { dbg_printk(TPACPI_DBG_INIT, "Found ACPI handle %s for %s\n", paths[i], name); return; } } vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n", name); *handle = NULL; } static acpi_status __init tpacpi_acpi_handle_locate_callback(acpi_handle handle, u32 level, void *context, void **return_value) { *(acpi_handle *)return_value = handle; return AE_CTRL_TERMINATE; } static void __init tpacpi_acpi_handle_locate(const char *name, const char *hid, acpi_handle *handle) { acpi_status status; acpi_handle device_found; BUG_ON(!name || !hid || !handle); vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s, using HID %s\n", name, hid); memset(&device_found, 0, sizeof(device_found)); status = acpi_get_devices(hid, tpacpi_acpi_handle_locate_callback, (void *)name, &device_found); *handle = NULL; if (ACPI_SUCCESS(status)) { *handle = device_found; dbg_printk(TPACPI_DBG_INIT, "Found ACPI handle for %s\n", name); } else { vdbg_printk(TPACPI_DBG_INIT, "Could not locate an ACPI handle for %s: %s\n", name, acpi_format_exception(status)); } } static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data) { struct ibm_struct *ibm = data; if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING) return; if (!ibm || !ibm->acpi || !ibm->acpi->notify) return; ibm->acpi->notify(ibm, event); } static int __init setup_acpi_notify(struct ibm_struct *ibm) { acpi_status status; int rc; BUG_ON(!ibm->acpi); if (!*ibm->acpi->handle) return 0; vdbg_printk(TPACPI_DBG_INIT, "setting up ACPI notify for %s\n", ibm->name); rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device); if (rc < 0) { pr_err("acpi_bus_get_device(%s) failed: %d\n", ibm->name, rc); return -ENODEV; } ibm->acpi->device->driver_data = ibm; sprintf(acpi_device_class(ibm->acpi->device), "%s/%s", TPACPI_ACPI_EVENT_PREFIX, ibm->name); status = acpi_install_notify_handler(*ibm->acpi->handle, ibm->acpi->type, dispatch_acpi_notify, ibm); if (ACPI_FAILURE(status)) { if (status == AE_ALREADY_EXISTS) { pr_notice("another device driver is already " "handling %s events\n", ibm->name); } else { pr_err("acpi_install_notify_handler(%s) failed: %s\n", ibm->name, acpi_format_exception(status)); } return -ENODEV; } ibm->flags.acpi_notify_installed = 1; return 0; } static int __init tpacpi_device_add(struct acpi_device *device) { return 0; } static int __init register_tpacpi_subdriver(struct ibm_struct *ibm) { int rc; dbg_printk(TPACPI_DBG_INIT, "registering %s as an ACPI driver\n", ibm->name); BUG_ON(!ibm->acpi); ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL); if (!ibm->acpi->driver) { pr_err("failed to allocate memory for ibm->acpi->driver\n"); return -ENOMEM; } sprintf(ibm->acpi->driver->name, "%s_%s", TPACPI_NAME, ibm->name); ibm->acpi->driver->ids = ibm->acpi->hid; ibm->acpi->driver->ops.add = &tpacpi_device_add; rc = acpi_bus_register_driver(ibm->acpi->driver); if (rc < 0) { pr_err("acpi_bus_register_driver(%s) failed: %d\n", ibm->name, rc); kfree(ibm->acpi->driver); ibm->acpi->driver = NULL; } else if (!rc) ibm->flags.acpi_driver_registered = 1; return rc; } /**************************************************************************** **************************************************************************** * * Procfs Helpers * **************************************************************************** ****************************************************************************/ static int dispatch_proc_show(struct seq_file *m, void *v) { struct ibm_struct *ibm = m->private; if (!ibm || !ibm->read) return -EINVAL; return ibm->read(m); } static int dispatch_proc_open(struct inode *inode, struct file *file) { return single_open(file, dispatch_proc_show, PDE(inode)->data); } static ssize_t dispatch_proc_write(struct file *file, const char __user *userbuf, size_t count, loff_t *pos) { struct ibm_struct *ibm = PDE(file->f_path.dentry->d_inode)->data; char *kernbuf; int ret; if (!ibm || !ibm->write) return -EINVAL; if (count > PAGE_SIZE - 2) return -EINVAL; kernbuf = kmalloc(count + 2, GFP_KERNEL); if (!kernbuf) return -ENOMEM; if (copy_from_user(kernbuf, userbuf, count)) { kfree(kernbuf); return -EFAULT; } kernbuf[count] = 0; strcat(kernbuf, ","); ret = ibm->write(kernbuf); if (ret == 0) ret = count; kfree(kernbuf); return ret; } static const struct file_operations dispatch_proc_fops = { .owner = THIS_MODULE, .open = dispatch_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = dispatch_proc_write, }; static char *next_cmd(char **cmds) { char *start = *cmds; char *end; while ((end = strchr(start, ',')) && end == start) start = end + 1; if (!end) return NULL; *end = 0; *cmds = end + 1; return start; } /**************************************************************************** **************************************************************************** * * Device model: input, hwmon and platform * **************************************************************************** ****************************************************************************/ static struct platform_device *tpacpi_pdev; static struct platform_device *tpacpi_sensors_pdev; static struct device *tpacpi_hwmon; static struct input_dev *tpacpi_inputdev; static struct mutex tpacpi_inputdev_send_mutex; static LIST_HEAD(tpacpi_all_drivers); static int tpacpi_suspend_handler(struct platform_device *pdev, pm_message_t state) { struct ibm_struct *ibm, *itmp; list_for_each_entry_safe(ibm, itmp, &tpacpi_all_drivers, all_drivers) { if (ibm->suspend) (ibm->suspend)(state); } return 0; } static int tpacpi_resume_handler(struct platform_device *pdev) { struct ibm_struct *ibm, *itmp; list_for_each_entry_safe(ibm, itmp, &tpacpi_all_drivers, all_drivers) { if (ibm->resume) (ibm->resume)(); } return 0; } static void tpacpi_shutdown_handler(struct platform_device *pdev) { struct ibm_struct *ibm, *itmp; list_for_each_entry_safe(ibm, itmp, &tpacpi_all_drivers, all_drivers) { if (ibm->shutdown) (ibm->shutdown)(); } } static struct platform_driver tpacpi_pdriver = { .driver = { .name = TPACPI_DRVR_NAME, .owner = THIS_MODULE, }, .suspend = tpacpi_suspend_handler, .resume = tpacpi_resume_handler, .shutdown = tpacpi_shutdown_handler, }; static struct platform_driver tpacpi_hwmon_pdriver = { .driver = { .name = TPACPI_HWMON_DRVR_NAME, .owner = THIS_MODULE, }, }; /************************************************************************* * sysfs support helpers */ struct attribute_set { unsigned int members, max_members; struct attribute_group group; }; struct attribute_set_obj { struct attribute_set s; struct attribute *a; } __attribute__((packed)); static struct attribute_set *create_attr_set(unsigned int max_members, const char *name) { struct attribute_set_obj *sobj; if (max_members == 0) return NULL; /* Allocates space for implicit NULL at the end too */ sobj = kzalloc(sizeof(struct attribute_set_obj) + max_members * sizeof(struct attribute *), GFP_KERNEL); if (!sobj) return NULL; sobj->s.max_members = max_members; sobj->s.group.attrs = &sobj->a; sobj->s.group.name = name; return &sobj->s; } #define destroy_attr_set(_set) \ kfree(_set); /* not multi-threaded safe, use it in a single thread per set */ static int add_to_attr_set(struct attribute_set *s, struct attribute *attr) { if (!s || !attr) return -EINVAL; if (s->members >= s->max_members) return -ENOMEM; s->group.attrs[s->members] = attr; s->members++; return 0; } static int add_many_to_attr_set(struct attribute_set *s, struct attribute **attr, unsigned int count) { int i, res; for (i = 0; i < count; i++) { res = add_to_attr_set(s, attr[i]); if (res) return res; } return 0; } static void delete_attr_set(struct attribute_set *s, struct kobject *kobj) { sysfs_remove_group(kobj, &s->group); destroy_attr_set(s); } #define register_attr_set_with_sysfs(_attr_set, _kobj) \ sysfs_create_group(_kobj, &_attr_set->group) static int parse_strtoul(const char *buf, unsigned long max, unsigned long *value) { char *endp; *value = simple_strtoul(skip_spaces(buf), &endp, 0); endp = skip_spaces(endp); if (*endp || *value > max) return -EINVAL; return 0; } static void tpacpi_disable_brightness_delay(void) { if (acpi_evalf(hkey_handle, NULL, "PWMS", "qvd", 0)) pr_notice("ACPI backlight control delay disabled\n"); } static void printk_deprecated_attribute(const char * const what, const char * const details) { tpacpi_log_usertask("deprecated sysfs attribute"); pr_warn("WARNING: sysfs attribute %s is deprecated and " "will be removed. %s\n", what, details); } /************************************************************************* * rfkill and radio control support helpers */ /* * ThinkPad-ACPI firmware handling model: * * WLSW (master wireless switch) is event-driven, and is common to all * firmware-controlled radios. It cannot be controlled, just monitored, * as expected. It overrides all radio state in firmware * * The kernel, a masked-off hotkey, and WLSW can change the radio state * (TODO: verify how WLSW interacts with the returned radio state). * * The only time there are shadow radio state changes, is when * masked-off hotkeys are used. */ /* * Internal driver API for radio state: * * int: < 0 = error, otherwise enum tpacpi_rfkill_state * bool: true means radio blocked (off) */ enum tpacpi_rfkill_state { TPACPI_RFK_RADIO_OFF = 0, TPACPI_RFK_RADIO_ON }; /* rfkill switches */ enum tpacpi_rfk_id { TPACPI_RFK_BLUETOOTH_SW_ID = 0, TPACPI_RFK_WWAN_SW_ID, TPACPI_RFK_UWB_SW_ID, TPACPI_RFK_SW_MAX }; static const char *tpacpi_rfkill_names[] = { [TPACPI_RFK_BLUETOOTH_SW_ID] = "bluetooth", [TPACPI_RFK_WWAN_SW_ID] = "wwan", [TPACPI_RFK_UWB_SW_ID] = "uwb", [TPACPI_RFK_SW_MAX] = NULL }; /* ThinkPad-ACPI rfkill subdriver */ struct tpacpi_rfk { struct rfkill *rfkill; enum tpacpi_rfk_id id; const struct tpacpi_rfk_ops *ops; }; struct tpacpi_rfk_ops { /* firmware interface */ int (*get_status)(void); int (*set_status)(const enum tpacpi_rfkill_state); }; static struct tpacpi_rfk *tpacpi_rfkill_switches[TPACPI_RFK_SW_MAX]; /* Query FW and update rfkill sw state for a given rfkill switch */ static int tpacpi_rfk_update_swstate(const struct tpacpi_rfk *tp_rfk) { int status; if (!tp_rfk) return -ENODEV; status = (tp_rfk->ops->get_status)(); if (status < 0) return status; rfkill_set_sw_state(tp_rfk->rfkill, (status == TPACPI_RFK_RADIO_OFF)); return status; } /* Query FW and update rfkill sw state for all rfkill switches */ static void tpacpi_rfk_update_swstate_all(void) { unsigned int i; for (i = 0; i < TPACPI_RFK_SW_MAX; i++) tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[i]); } /* * Sync the HW-blocking state of all rfkill switches, * do notice it causes the rfkill core to schedule uevents */ static void tpacpi_rfk_update_hwblock_state(bool blocked) { unsigned int i; struct tpacpi_rfk *tp_rfk; for (i = 0; i < TPACPI_RFK_SW_MAX; i++) { tp_rfk = tpacpi_rfkill_switches[i]; if (tp_rfk) { if (rfkill_set_hw_state(tp_rfk->rfkill, blocked)) { /* ignore -- we track sw block */ } } } } /* Call to get the WLSW state from the firmware */ static int hotkey_get_wlsw(void); /* Call to query WLSW state and update all rfkill switches */ static bool tpacpi_rfk_check_hwblock_state(void) { int res = hotkey_get_wlsw(); int hw_blocked; /* When unknown or unsupported, we have to assume it is unblocked */ if (res < 0) return false; hw_blocked = (res == TPACPI_RFK_RADIO_OFF); tpacpi_rfk_update_hwblock_state(hw_blocked); return hw_blocked; } static int tpacpi_rfk_hook_set_block(void *data, bool blocked) { struct tpacpi_rfk *tp_rfk = data; int res; dbg_printk(TPACPI_DBG_RFKILL, "request to change radio state to %s\n", blocked ? "blocked" : "unblocked"); /* try to set radio state */ res = (tp_rfk->ops->set_status)(blocked ? TPACPI_RFK_RADIO_OFF : TPACPI_RFK_RADIO_ON); /* and update the rfkill core with whatever the FW really did */ tpacpi_rfk_update_swstate(tp_rfk); return (res < 0) ? res : 0; } static const struct rfkill_ops tpacpi_rfk_rfkill_ops = { .set_block = tpacpi_rfk_hook_set_block, }; static int __init tpacpi_new_rfkill(const enum tpacpi_rfk_id id, const struct tpacpi_rfk_ops *tp_rfkops, const enum rfkill_type rfktype, const char *name, const bool set_default) { struct tpacpi_rfk *atp_rfk; int res; bool sw_state = false; bool hw_state; int sw_status; BUG_ON(id >= TPACPI_RFK_SW_MAX || tpacpi_rfkill_switches[id]); atp_rfk = kzalloc(sizeof(struct tpacpi_rfk), GFP_KERNEL); if (atp_rfk) atp_rfk->rfkill = rfkill_alloc(name, &tpacpi_pdev->dev, rfktype, &tpacpi_rfk_rfkill_ops, atp_rfk); if (!atp_rfk || !atp_rfk->rfkill) { pr_err("failed to allocate memory for rfkill class\n"); kfree(atp_rfk); return -ENOMEM; } atp_rfk->id = id; atp_rfk->ops = tp_rfkops; sw_status = (tp_rfkops->get_status)(); if (sw_status < 0) { pr_err("failed to read initial state for %s, error %d\n", name, sw_status); } else { sw_state = (sw_status == TPACPI_RFK_RADIO_OFF); if (set_default) { /* try to keep the initial state, since we ask the * firmware to preserve it across S5 in NVRAM */ rfkill_init_sw_state(atp_rfk->rfkill, sw_state); } } hw_state = tpacpi_rfk_check_hwblock_state(); rfkill_set_hw_state(atp_rfk->rfkill, hw_state); res = rfkill_register(atp_rfk->rfkill); if (res < 0) { pr_err("failed to register %s rfkill switch: %d\n", name, res); rfkill_destroy(atp_rfk->rfkill); kfree(atp_rfk); return res; } tpacpi_rfkill_switches[id] = atp_rfk; pr_info("rfkill switch %s: radio is %sblocked\n", name, (sw_state || hw_state) ? "" : "un"); return 0; } static void tpacpi_destroy_rfkill(const enum tpacpi_rfk_id id) { struct tpacpi_rfk *tp_rfk; BUG_ON(id >= TPACPI_RFK_SW_MAX); tp_rfk = tpacpi_rfkill_switches[id]; if (tp_rfk) { rfkill_unregister(tp_rfk->rfkill); rfkill_destroy(tp_rfk->rfkill); tpacpi_rfkill_switches[id] = NULL; kfree(tp_rfk); } } static void printk_deprecated_rfkill_attribute(const char * const what) { printk_deprecated_attribute(what, "Please switch to generic rfkill before year 2010"); } /* sysfs <radio> enable ------------------------------------------------ */ static ssize_t tpacpi_rfk_sysfs_enable_show(const enum tpacpi_rfk_id id, struct device_attribute *attr, char *buf) { int status; printk_deprecated_rfkill_attribute(attr->attr.name); /* This is in the ABI... */ if (tpacpi_rfk_check_hwblock_state()) { status = TPACPI_RFK_RADIO_OFF; } else { status = tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]); if (status < 0) return status; } return snprintf(buf, PAGE_SIZE, "%d\n", (status == TPACPI_RFK_RADIO_ON) ? 1 : 0); } static ssize_t tpacpi_rfk_sysfs_enable_store(const enum tpacpi_rfk_id id, struct device_attribute *attr, const char *buf, size_t count) { unsigned long t; int res; printk_deprecated_rfkill_attribute(attr->attr.name); if (parse_strtoul(buf, 1, &t)) return -EINVAL; tpacpi_disclose_usertask(attr->attr.name, "set to %ld\n", t); /* This is in the ABI... */ if (tpacpi_rfk_check_hwblock_state() && !!t) return -EPERM; res = tpacpi_rfkill_switches[id]->ops->set_status((!!t) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF); tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]); return (res < 0) ? res : count; } /* procfs -------------------------------------------------------------- */ static int tpacpi_rfk_procfs_read(const enum tpacpi_rfk_id id, struct seq_file *m) { if (id >= TPACPI_RFK_SW_MAX) seq_printf(m, "status:\t\tnot supported\n"); else { int status; /* This is in the ABI... */ if (tpacpi_rfk_check_hwblock_state()) { status = TPACPI_RFK_RADIO_OFF; } else { status = tpacpi_rfk_update_swstate( tpacpi_rfkill_switches[id]); if (status < 0) return status; } seq_printf(m, "status:\t\t%s\n", (status == TPACPI_RFK_RADIO_ON) ? "enabled" : "disabled"); seq_printf(m, "commands:\tenable, disable\n"); } return 0; } static int tpacpi_rfk_procfs_write(const enum tpacpi_rfk_id id, char *buf) { char *cmd; int status = -1; int res = 0; if (id >= TPACPI_RFK_SW_MAX) return -ENODEV; while ((cmd = next_cmd(&buf))) { if (strlencmp(cmd, "enable") == 0) status = TPACPI_RFK_RADIO_ON; else if (strlencmp(cmd, "disable") == 0) status = TPACPI_RFK_RADIO_OFF; else return -EINVAL; } if (status != -1) { tpacpi_disclose_usertask("procfs", "attempt to %s %s\n", (status == TPACPI_RFK_RADIO_ON) ? "enable" : "disable", tpacpi_rfkill_names[id]); res = (tpacpi_rfkill_switches[id]->ops->set_status)(status); tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]); } return res; } /************************************************************************* * thinkpad-acpi driver attributes */ /* interface_version --------------------------------------------------- */ static ssize_t tpacpi_driver_interface_version_show( struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION); } static DRIVER_ATTR(interface_version, S_IRUGO, tpacpi_driver_interface_version_show, NULL); /* debug_level --------------------------------------------------------- */ static ssize_t tpacpi_driver_debug_show(struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level); } static ssize_t tpacpi_driver_debug_store(struct device_driver *drv, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 0xffff, &t)) return -EINVAL; dbg_level = t; return count; } static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO, tpacpi_driver_debug_show, tpacpi_driver_debug_store); /* version ------------------------------------------------------------- */ static ssize_t tpacpi_driver_version_show(struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "%s v%s\n", TPACPI_DESC, TPACPI_VERSION); } static DRIVER_ATTR(version, S_IRUGO, tpacpi_driver_version_show, NULL); /* --------------------------------------------------------------------- */ #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES /* wlsw_emulstate ------------------------------------------------------ */ static ssize_t tpacpi_driver_wlsw_emulstate_show(struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wlsw_emulstate); } static ssize_t tpacpi_driver_wlsw_emulstate_store(struct device_driver *drv, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 1, &t)) return -EINVAL; if (tpacpi_wlsw_emulstate != !!t) { tpacpi_wlsw_emulstate = !!t; tpacpi_rfk_update_hwblock_state(!t); /* negative logic */ } return count; } static DRIVER_ATTR(wlsw_emulstate, S_IWUSR | S_IRUGO, tpacpi_driver_wlsw_emulstate_show, tpacpi_driver_wlsw_emulstate_store); /* bluetooth_emulstate ------------------------------------------------- */ static ssize_t tpacpi_driver_bluetooth_emulstate_show( struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_bluetooth_emulstate); } static ssize_t tpacpi_driver_bluetooth_emulstate_store( struct device_driver *drv, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 1, &t)) return -EINVAL; tpacpi_bluetooth_emulstate = !!t; return count; } static DRIVER_ATTR(bluetooth_emulstate, S_IWUSR | S_IRUGO, tpacpi_driver_bluetooth_emulstate_show, tpacpi_driver_bluetooth_emulstate_store); /* wwan_emulstate ------------------------------------------------- */ static ssize_t tpacpi_driver_wwan_emulstate_show( struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wwan_emulstate); } static ssize_t tpacpi_driver_wwan_emulstate_store( struct device_driver *drv, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 1, &t)) return -EINVAL; tpacpi_wwan_emulstate = !!t; return count; } static DRIVER_ATTR(wwan_emulstate, S_IWUSR | S_IRUGO, tpacpi_driver_wwan_emulstate_show, tpacpi_driver_wwan_emulstate_store); /* uwb_emulstate ------------------------------------------------- */ static ssize_t tpacpi_driver_uwb_emulstate_show( struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_uwb_emulstate); } static ssize_t tpacpi_driver_uwb_emulstate_store( struct device_driver *drv, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 1, &t)) return -EINVAL; tpacpi_uwb_emulstate = !!t; return count; } static DRIVER_ATTR(uwb_emulstate, S_IWUSR | S_IRUGO, tpacpi_driver_uwb_emulstate_show, tpacpi_driver_uwb_emulstate_store); #endif /* --------------------------------------------------------------------- */ static struct driver_attribute *tpacpi_driver_attributes[] = { &driver_attr_debug_level, &driver_attr_version, &driver_attr_interface_version, }; static int __init tpacpi_create_driver_attributes(struct device_driver *drv) { int i, res; i = 0; res = 0; while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) { res = driver_create_file(drv, tpacpi_driver_attributes[i]); i++; } #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (!res && dbg_wlswemul) res = driver_create_file(drv, &driver_attr_wlsw_emulstate); if (!res && dbg_bluetoothemul) res = driver_create_file(drv, &driver_attr_bluetooth_emulstate); if (!res && dbg_wwanemul) res = driver_create_file(drv, &driver_attr_wwan_emulstate); if (!res && dbg_uwbemul) res = driver_create_file(drv, &driver_attr_uwb_emulstate); #endif return res; } static void tpacpi_remove_driver_attributes(struct device_driver *drv) { int i; for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++) driver_remove_file(drv, tpacpi_driver_attributes[i]); #ifdef THINKPAD_ACPI_DEBUGFACILITIES driver_remove_file(drv, &driver_attr_wlsw_emulstate); driver_remove_file(drv, &driver_attr_bluetooth_emulstate); driver_remove_file(drv, &driver_attr_wwan_emulstate); driver_remove_file(drv, &driver_attr_uwb_emulstate); #endif } /************************************************************************* * Firmware Data */ /* * Table of recommended minimum BIOS versions * * Reasons for listing: * 1. Stable BIOS, listed because the unknown amount of * bugs and bad ACPI behaviour on older versions * * 2. BIOS or EC fw with known bugs that trigger on Linux * * 3. BIOS with known reduced functionality in older versions * * We recommend the latest BIOS and EC version. * We only support the latest BIOS and EC fw version as a rule. * * Sources: IBM ThinkPad Public Web Documents (update changelogs), * Information from users in ThinkWiki * * WARNING: we use this table also to detect that the machine is * a ThinkPad in some cases, so don't remove entries lightly. */ #define TPV_Q(__v, __id1, __id2, __bv1, __bv2) \ { .vendor = (__v), \ .bios = TPID(__id1, __id2), \ .ec = TPACPI_MATCH_ANY, \ .quirks = TPACPI_MATCH_ANY << 16 \ | (__bv1) << 8 | (__bv2) } #define TPV_Q_X(__v, __bid1, __bid2, __bv1, __bv2, \ __eid, __ev1, __ev2) \ { .vendor = (__v), \ .bios = TPID(__bid1, __bid2), \ .ec = __eid, \ .quirks = (__ev1) << 24 | (__ev2) << 16 \ | (__bv1) << 8 | (__bv2) } #define TPV_QI0(__id1, __id2, __bv1, __bv2) \ TPV_Q(PCI_VENDOR_ID_IBM, __id1, __id2, __bv1, __bv2) /* Outdated IBM BIOSes often lack the EC id string */ #define TPV_QI1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \ TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2, \ __bv1, __bv2, TPID(__id1, __id2), \ __ev1, __ev2), \ TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2, \ __bv1, __bv2, TPACPI_MATCH_UNKNOWN, \ __ev1, __ev2) /* Outdated IBM BIOSes often lack the EC id string */ #define TPV_QI2(__bid1, __bid2, __bv1, __bv2, \ __eid1, __eid2, __ev1, __ev2) \ TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2, \ __bv1, __bv2, TPID(__eid1, __eid2), \ __ev1, __ev2), \ TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2, \ __bv1, __bv2, TPACPI_MATCH_UNKNOWN, \ __ev1, __ev2) #define TPV_QL0(__id1, __id2, __bv1, __bv2) \ TPV_Q(PCI_VENDOR_ID_LENOVO, __id1, __id2, __bv1, __bv2) #define TPV_QL1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \ TPV_Q_X(PCI_VENDOR_ID_LENOVO, __id1, __id2, \ __bv1, __bv2, TPID(__id1, __id2), \ __ev1, __ev2) #define TPV_QL2(__bid1, __bid2, __bv1, __bv2, \ __eid1, __eid2, __ev1, __ev2) \ TPV_Q_X(PCI_VENDOR_ID_LENOVO, __bid1, __bid2, \ __bv1, __bv2, TPID(__eid1, __eid2), \ __ev1, __ev2) static const struct tpacpi_quirk tpacpi_bios_version_qtable[] __initconst = { /* Numeric models ------------------ */ /* FW MODEL BIOS VERS */ TPV_QI0('I', 'M', '6', '5'), /* 570 */ TPV_QI0('I', 'U', '2', '6'), /* 570E */ TPV_QI0('I', 'B', '5', '4'), /* 600 */ TPV_QI0('I', 'H', '4', '7'), /* 600E */ TPV_QI0('I', 'N', '3', '6'), /* 600E */ TPV_QI0('I', 'T', '5', '5'), /* 600X */ TPV_QI0('I', 'D', '4', '8'), /* 770, 770E, 770ED */ TPV_QI0('I', 'I', '4', '2'), /* 770X */ TPV_QI0('I', 'O', '2', '3'), /* 770Z */ /* A-series ------------------------- */ /* FW MODEL BIOS VERS EC VERS */ TPV_QI0('I', 'W', '5', '9'), /* A20m */ TPV_QI0('I', 'V', '6', '9'), /* A20p */ TPV_QI0('1', '0', '2', '6'), /* A21e, A22e */ TPV_QI0('K', 'U', '3', '6'), /* A21e */ TPV_QI0('K', 'X', '3', '6'), /* A21m, A22m */ TPV_QI0('K', 'Y', '3', '8'), /* A21p, A22p */ TPV_QI0('1', 'B', '1', '7'), /* A22e */ TPV_QI0('1', '3', '2', '0'), /* A22m */ TPV_QI0('1', 'E', '7', '3'), /* A30/p (0) */ TPV_QI1('1', 'G', '4', '1', '1', '7'), /* A31/p (0) */ TPV_QI1('1', 'N', '1', '6', '0', '7'), /* A31/p (0) */ /* G-series ------------------------- */ /* FW MODEL BIOS VERS */ TPV_QI0('1', 'T', 'A', '6'), /* G40 */ TPV_QI0('1', 'X', '5', '7'), /* G41 */ /* R-series, T-series --------------- */ /* FW MODEL BIOS VERS EC VERS */ TPV_QI0('1', 'C', 'F', '0'), /* R30 */ TPV_QI0('1', 'F', 'F', '1'), /* R31 */ TPV_QI0('1', 'M', '9', '7'), /* R32 */ TPV_QI0('1', 'O', '6', '1'), /* R40 */ TPV_QI0('1', 'P', '6', '5'), /* R40 */ TPV_QI0('1', 'S', '7', '0'), /* R40e */ TPV_QI1('1', 'R', 'D', 'R', '7', '1'), /* R50/p, R51, T40/p, T41/p, T42/p (1) */ TPV_QI1('1', 'V', '7', '1', '2', '8'), /* R50e, R51 (1) */ TPV_QI1('7', '8', '7', '1', '0', '6'), /* R51e (1) */ TPV_QI1('7', '6', '6', '9', '1', '6'), /* R52 (1) */ TPV_QI1('7', '0', '6', '9', '2', '8'), /* R52, T43 (1) */ TPV_QI0('I', 'Y', '6', '1'), /* T20 */ TPV_QI0('K', 'Z', '3', '4'), /* T21 */ TPV_QI0('1', '6', '3', '2'), /* T22 */ TPV_QI1('1', 'A', '6', '4', '2', '3'), /* T23 (0) */ TPV_QI1('1', 'I', '7', '1', '2', '0'), /* T30 (0) */ TPV_QI1('1', 'Y', '6', '5', '2', '9'), /* T43/p (1) */ TPV_QL1('7', '9', 'E', '3', '5', '0'), /* T60/p */ TPV_QL1('7', 'C', 'D', '2', '2', '2'), /* R60, R60i */ TPV_QL1('7', 'E', 'D', '0', '1', '5'), /* R60e, R60i */ /* BIOS FW BIOS VERS EC FW EC VERS */ TPV_QI2('1', 'W', '9', '0', '1', 'V', '2', '8'), /* R50e (1) */ TPV_QL2('7', 'I', '3', '4', '7', '9', '5', '0'), /* T60/p wide */ /* X-series ------------------------- */ /* FW MODEL BIOS VERS EC VERS */ TPV_QI0('I', 'Z', '9', 'D'), /* X20, X21 */ TPV_QI0('1', 'D', '7', '0'), /* X22, X23, X24 */ TPV_QI1('1', 'K', '4', '8', '1', '8'), /* X30 (0) */ TPV_QI1('1', 'Q', '9', '7', '2', '3'), /* X31, X32 (0) */ TPV_QI1('1', 'U', 'D', '3', 'B', '2'), /* X40 (0) */ TPV_QI1('7', '4', '6', '4', '2', '7'), /* X41 (0) */ TPV_QI1('7', '5', '6', '0', '2', '0'), /* X41t (0) */ TPV_QL1('7', 'B', 'D', '7', '4', '0'), /* X60/s */ TPV_QL1('7', 'J', '3', '0', '1', '3'), /* X60t */ /* (0) - older versions lack DMI EC fw string and functionality */ /* (1) - older versions known to lack functionality */ }; #undef TPV_QL1 #undef TPV_QL0 #undef TPV_QI2 #undef TPV_QI1 #undef TPV_QI0 #undef TPV_Q_X #undef TPV_Q static void __init tpacpi_check_outdated_fw(void) { unsigned long fwvers; u16 ec_version, bios_version; fwvers = tpacpi_check_quirks(tpacpi_bios_version_qtable, ARRAY_SIZE(tpacpi_bios_version_qtable)); if (!fwvers) return; bios_version = fwvers & 0xffffU; ec_version = (fwvers >> 16) & 0xffffU; /* note that unknown versions are set to 0x0000 and we use that */ if ((bios_version > thinkpad_id.bios_release) || (ec_version > thinkpad_id.ec_release && ec_version != TPACPI_MATCH_ANY)) { /* * The changelogs would let us track down the exact * reason, but it is just too much of a pain to track * it. We only list BIOSes that are either really * broken, or really stable to begin with, so it is * best if the user upgrades the firmware anyway. */ pr_warn("WARNING: Outdated ThinkPad BIOS/EC firmware\n"); pr_warn("WARNING: This firmware may be missing critical bug " "fixes and/or important features\n"); } } static bool __init tpacpi_is_fw_known(void) { return tpacpi_check_quirks(tpacpi_bios_version_qtable, ARRAY_SIZE(tpacpi_bios_version_qtable)) != 0; } /**************************************************************************** **************************************************************************** * * Subdrivers * **************************************************************************** ****************************************************************************/ /************************************************************************* * thinkpad-acpi metadata subdriver */ static int thinkpad_acpi_driver_read(struct seq_file *m) { seq_printf(m, "driver:\t\t%s\n", TPACPI_DESC); seq_printf(m, "version:\t%s\n", TPACPI_VERSION); return 0; } static struct ibm_struct thinkpad_acpi_driver_data = { .name = "driver", .read = thinkpad_acpi_driver_read, }; /************************************************************************* * Hotkey subdriver */ /* * ThinkPad firmware event model * * The ThinkPad firmware has two main event interfaces: normal ACPI * notifications (which follow the ACPI standard), and a private event * interface. * * The private event interface also issues events for the hotkeys. As * the driver gained features, the event handling code ended up being * built around the hotkey subdriver. This will need to be refactored * to a more formal event API eventually. * * Some "hotkeys" are actually supposed to be used as event reports, * such as "brightness has changed", "volume has changed", depending on * the ThinkPad model and how the firmware is operating. * * Unlike other classes, hotkey-class events have mask/unmask control on * non-ancient firmware. However, how it behaves changes a lot with the * firmware model and version. */ enum { /* hot key scan codes (derived from ACPI DSDT) */ TP_ACPI_HOTKEYSCAN_FNF1 = 0, TP_ACPI_HOTKEYSCAN_FNF2, TP_ACPI_HOTKEYSCAN_FNF3, TP_ACPI_HOTKEYSCAN_FNF4, TP_ACPI_HOTKEYSCAN_FNF5, TP_ACPI_HOTKEYSCAN_FNF6, TP_ACPI_HOTKEYSCAN_FNF7, TP_ACPI_HOTKEYSCAN_FNF8, TP_ACPI_HOTKEYSCAN_FNF9, TP_ACPI_HOTKEYSCAN_FNF10, TP_ACPI_HOTKEYSCAN_FNF11, TP_ACPI_HOTKEYSCAN_FNF12, TP_ACPI_HOTKEYSCAN_FNBACKSPACE, TP_ACPI_HOTKEYSCAN_FNINSERT, TP_ACPI_HOTKEYSCAN_FNDELETE, TP_ACPI_HOTKEYSCAN_FNHOME, TP_ACPI_HOTKEYSCAN_FNEND, TP_ACPI_HOTKEYSCAN_FNPAGEUP, TP_ACPI_HOTKEYSCAN_FNPAGEDOWN, TP_ACPI_HOTKEYSCAN_FNSPACE, TP_ACPI_HOTKEYSCAN_VOLUMEUP, TP_ACPI_HOTKEYSCAN_VOLUMEDOWN, TP_ACPI_HOTKEYSCAN_MUTE, TP_ACPI_HOTKEYSCAN_THINKPAD, TP_ACPI_HOTKEYSCAN_UNK1, TP_ACPI_HOTKEYSCAN_UNK2, TP_ACPI_HOTKEYSCAN_UNK3, TP_ACPI_HOTKEYSCAN_UNK4, TP_ACPI_HOTKEYSCAN_UNK5, TP_ACPI_HOTKEYSCAN_UNK6, TP_ACPI_HOTKEYSCAN_UNK7, TP_ACPI_HOTKEYSCAN_UNK8, /* Hotkey keymap size */ TPACPI_HOTKEY_MAP_LEN }; enum { /* Keys/events available through NVRAM polling */ TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U, TPACPI_HKEY_NVRAM_GOOD_MASK = 0x00fb8000U, }; enum { /* Positions of some of the keys in hotkey masks */ TP_ACPI_HKEY_DISPSWTCH_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNF7, TP_ACPI_HKEY_DISPXPAND_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNF8, TP_ACPI_HKEY_HIBERNATE_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNF12, TP_ACPI_HKEY_BRGHTUP_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNHOME, TP_ACPI_HKEY_BRGHTDWN_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNEND, TP_ACPI_HKEY_THNKLGHT_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP, TP_ACPI_HKEY_ZOOM_MASK = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE, TP_ACPI_HKEY_VOLUP_MASK = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP, TP_ACPI_HKEY_VOLDWN_MASK = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN, TP_ACPI_HKEY_MUTE_MASK = 1 << TP_ACPI_HOTKEYSCAN_MUTE, TP_ACPI_HKEY_THINKPAD_MASK = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD, }; enum { /* NVRAM to ACPI HKEY group map */ TP_NVRAM_HKEY_GROUP_HK2 = TP_ACPI_HKEY_THINKPAD_MASK | TP_ACPI_HKEY_ZOOM_MASK | TP_ACPI_HKEY_DISPSWTCH_MASK | TP_ACPI_HKEY_HIBERNATE_MASK, TP_NVRAM_HKEY_GROUP_BRIGHTNESS = TP_ACPI_HKEY_BRGHTUP_MASK | TP_ACPI_HKEY_BRGHTDWN_MASK, TP_NVRAM_HKEY_GROUP_VOLUME = TP_ACPI_HKEY_VOLUP_MASK | TP_ACPI_HKEY_VOLDWN_MASK | TP_ACPI_HKEY_MUTE_MASK, }; #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL struct tp_nvram_state { u16 thinkpad_toggle:1; u16 zoom_toggle:1; u16 display_toggle:1; u16 thinklight_toggle:1; u16 hibernate_toggle:1; u16 displayexp_toggle:1; u16 display_state:1; u16 brightness_toggle:1; u16 volume_toggle:1; u16 mute:1; u8 brightness_level; u8 volume_level; }; /* kthread for the hotkey poller */ static struct task_struct *tpacpi_hotkey_task; /* Acquired while the poller kthread is running, use to sync start/stop */ static struct mutex hotkey_thread_mutex; /* * Acquire mutex to write poller control variables as an * atomic block. * * Increment hotkey_config_change when changing them if you * want the kthread to forget old state. * * See HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END */ static struct mutex hotkey_thread_data_mutex; static unsigned int hotkey_config_change; /* * hotkey poller control variables * * Must be atomic or readers will also need to acquire mutex * * HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END * should be used only when the changes need to be taken as * a block, OR when one needs to force the kthread to forget * old state. */ static u32 hotkey_source_mask; /* bit mask 0=ACPI,1=NVRAM */ static unsigned int hotkey_poll_freq = 10; /* Hz */ #define HOTKEY_CONFIG_CRITICAL_START \ do { \ mutex_lock(&hotkey_thread_data_mutex); \ hotkey_config_change++; \ } while (0); #define HOTKEY_CONFIG_CRITICAL_END \ mutex_unlock(&hotkey_thread_data_mutex); #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */ #define hotkey_source_mask 0U #define HOTKEY_CONFIG_CRITICAL_START #define HOTKEY_CONFIG_CRITICAL_END #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */ static struct mutex hotkey_mutex; static enum { /* Reasons for waking up */ TP_ACPI_WAKEUP_NONE = 0, /* None or unknown */ TP_ACPI_WAKEUP_BAYEJ, /* Bay ejection request */ TP_ACPI_WAKEUP_UNDOCK, /* Undock request */ } hotkey_wakeup_reason; static int hotkey_autosleep_ack; static u32 hotkey_orig_mask; /* events the BIOS had enabled */ static u32 hotkey_all_mask; /* all events supported in fw */ static u32 hotkey_reserved_mask; /* events better left disabled */ static u32 hotkey_driver_mask; /* events needed by the driver */ static u32 hotkey_user_mask; /* events visible to userspace */ static u32 hotkey_acpi_mask; /* events enabled in firmware */ static unsigned int hotkey_report_mode; static u16 *hotkey_keycode_map; static struct attribute_set *hotkey_dev_attributes; static void tpacpi_driver_event(const unsigned int hkey_event); static void hotkey_driver_event(const unsigned int scancode); static void hotkey_poll_setup(const bool may_warn); /* HKEY.MHKG() return bits */ #define TP_HOTKEY_TABLET_MASK (1 << 3) static int hotkey_get_wlsw(void) { int status; if (!tp_features.hotkey_wlsw) return -ENODEV; #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_wlswemul) return (tpacpi_wlsw_emulstate) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; #endif if (!acpi_evalf(hkey_handle, &status, "WLSW", "d")) return -EIO; return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; } static int hotkey_get_tablet_mode(int *status) { int s; if (!acpi_evalf(hkey_handle, &s, "MHKG", "d")) return -EIO; *status = ((s & TP_HOTKEY_TABLET_MASK) != 0); return 0; } /* * Reads current event mask from firmware, and updates * hotkey_acpi_mask accordingly. Also resets any bits * from hotkey_user_mask that are unavailable to be * delivered (shadow requirement of the userspace ABI). * * Call with hotkey_mutex held */ static int hotkey_mask_get(void) { if (tp_features.hotkey_mask) { u32 m = 0; if (!acpi_evalf(hkey_handle, &m, "DHKN", "d")) return -EIO; hotkey_acpi_mask = m; } else { /* no mask support doesn't mean no event support... */ hotkey_acpi_mask = hotkey_all_mask; } /* sync userspace-visible mask */ hotkey_user_mask &= (hotkey_acpi_mask | hotkey_source_mask); return 0; } void static hotkey_mask_warn_incomplete_mask(void) { /* log only what the user can fix... */ const u32 wantedmask = hotkey_driver_mask & ~(hotkey_acpi_mask | hotkey_source_mask) & (hotkey_all_mask | TPACPI_HKEY_NVRAM_KNOWN_MASK); if (wantedmask) pr_notice("required events 0x%08x not enabled!\n", wantedmask); } /* * Set the firmware mask when supported * * Also calls hotkey_mask_get to update hotkey_acpi_mask. * * NOTE: does not set bits in hotkey_user_mask, but may reset them. * * Call with hotkey_mutex held */ static int hotkey_mask_set(u32 mask) { int i; int rc = 0; const u32 fwmask = mask & ~hotkey_source_mask; if (tp_features.hotkey_mask) { for (i = 0; i < 32; i++) { if (!acpi_evalf(hkey_handle, NULL, "MHKM", "vdd", i + 1, !!(mask & (1 << i)))) { rc = -EIO; break; } } } /* * We *must* make an inconditional call to hotkey_mask_get to * refresh hotkey_acpi_mask and update hotkey_user_mask * * Take the opportunity to also log when we cannot _enable_ * a given event. */ if (!hotkey_mask_get() && !rc && (fwmask & ~hotkey_acpi_mask)) { pr_notice("asked for hotkey mask 0x%08x, but " "firmware forced it to 0x%08x\n", fwmask, hotkey_acpi_mask); } if (tpacpi_lifecycle != TPACPI_LIFE_EXITING) hotkey_mask_warn_incomplete_mask(); return rc; } /* * Sets hotkey_user_mask and tries to set the firmware mask * * Call with hotkey_mutex held */ static int hotkey_user_mask_set(const u32 mask) { int rc; /* Give people a chance to notice they are doing something that * is bound to go boom on their users sooner or later */ if (!tp_warned.hotkey_mask_ff && (mask == 0xffff || mask == 0xffffff || mask == 0xffffffff)) { tp_warned.hotkey_mask_ff = 1; pr_notice("setting the hotkey mask to 0x%08x is likely " "not the best way to go about it\n", mask); pr_notice("please consider using the driver defaults, " "and refer to up-to-date thinkpad-acpi " "documentation\n"); } /* Try to enable what the user asked for, plus whatever we need. * this syncs everything but won't enable bits in hotkey_user_mask */ rc = hotkey_mask_set((mask | hotkey_driver_mask) & ~hotkey_source_mask); /* Enable the available bits in hotkey_user_mask */ hotkey_user_mask = mask & (hotkey_acpi_mask | hotkey_source_mask); return rc; } /* * Sets the driver hotkey mask. * * Can be called even if the hotkey subdriver is inactive */ static int tpacpi_hotkey_driver_mask_set(const u32 mask) { int rc; /* Do the right thing if hotkey_init has not been called yet */ if (!tp_features.hotkey) { hotkey_driver_mask = mask; return 0; } mutex_lock(&hotkey_mutex); HOTKEY_CONFIG_CRITICAL_START hotkey_driver_mask = mask; #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL hotkey_source_mask |= (mask & ~hotkey_all_mask); #endif HOTKEY_CONFIG_CRITICAL_END rc = hotkey_mask_set((hotkey_acpi_mask | hotkey_driver_mask) & ~hotkey_source_mask); hotkey_poll_setup(true); mutex_unlock(&hotkey_mutex); return rc; } static int hotkey_status_get(int *status) { if (!acpi_evalf(hkey_handle, status, "DHKC", "d")) return -EIO; return 0; } static int hotkey_status_set(bool enable) { if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0)) return -EIO; return 0; } static void tpacpi_input_send_tabletsw(void) { int state; if (tp_features.hotkey_tablet && !hotkey_get_tablet_mode(&state)) { mutex_lock(&tpacpi_inputdev_send_mutex); input_report_switch(tpacpi_inputdev, SW_TABLET_MODE, !!state); input_sync(tpacpi_inputdev); mutex_unlock(&tpacpi_inputdev_send_mutex); } } /* Do NOT call without validating scancode first */ static void tpacpi_input_send_key(const unsigned int scancode) { const unsigned int keycode = hotkey_keycode_map[scancode]; if (keycode != KEY_RESERVED) { mutex_lock(&tpacpi_inputdev_send_mutex); input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN, scancode); input_report_key(tpacpi_inputdev, keycode, 1); input_sync(tpacpi_inputdev); input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN, scancode); input_report_key(tpacpi_inputdev, keycode, 0); input_sync(tpacpi_inputdev); mutex_unlock(&tpacpi_inputdev_send_mutex); } } /* Do NOT call without validating scancode first */ static void tpacpi_input_send_key_masked(const unsigned int scancode) { hotkey_driver_event(scancode); if (hotkey_user_mask & (1 << scancode)) tpacpi_input_send_key(scancode); } #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL static struct tp_acpi_drv_struct ibm_hotkey_acpidriver; /* Do NOT call without validating scancode first */ static void tpacpi_hotkey_send_key(unsigned int scancode) { tpacpi_input_send_key_masked(scancode); if (hotkey_report_mode < 2) { acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device, 0x80, TP_HKEY_EV_HOTKEY_BASE + scancode); } } static void hotkey_read_nvram(struct tp_nvram_state *n, const u32 m) { u8 d; if (m & TP_NVRAM_HKEY_GROUP_HK2) { d = nvram_read_byte(TP_NVRAM_ADDR_HK2); n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD); n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM); n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY); n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE); } if (m & TP_ACPI_HKEY_THNKLGHT_MASK) { d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT); n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT); } if (m & TP_ACPI_HKEY_DISPXPAND_MASK) { d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO); n->displayexp_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPEXPND); } if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) { d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS); n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS) >> TP_NVRAM_POS_LEVEL_BRIGHTNESS; n->brightness_toggle = !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS); } if (m & TP_NVRAM_HKEY_GROUP_VOLUME) { d = nvram_read_byte(TP_NVRAM_ADDR_MIXER); n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME) >> TP_NVRAM_POS_LEVEL_VOLUME; n->mute = !!(d & TP_NVRAM_MASK_MUTE); n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME); } } static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn, struct tp_nvram_state *newn, const u32 event_mask) { #define TPACPI_COMPARE_KEY(__scancode, __member) \ do { \ if ((event_mask & (1 << __scancode)) && \ oldn->__member != newn->__member) \ tpacpi_hotkey_send_key(__scancode); \ } while (0) #define TPACPI_MAY_SEND_KEY(__scancode) \ do { \ if (event_mask & (1 << __scancode)) \ tpacpi_hotkey_send_key(__scancode); \ } while (0) void issue_volchange(const unsigned int oldvol, const unsigned int newvol) { unsigned int i = oldvol; while (i > newvol) { TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN); i--; } while (i < newvol) { TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP); i++; } } void issue_brightnesschange(const unsigned int oldbrt, const unsigned int newbrt) { unsigned int i = oldbrt; while (i > newbrt) { TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND); i--; } while (i < newbrt) { TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME); i++; } } TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle); TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle); TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle); TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle); TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle); TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle); /* * Handle volume * * This code is supposed to duplicate the IBM firmware behaviour: * - Pressing MUTE issues mute hotkey message, even when already mute * - Pressing Volume up/down issues volume up/down hotkey messages, * even when already at maximum or minimum volume * - The act of unmuting issues volume up/down notification, * depending which key was used to unmute * * We are constrained to what the NVRAM can tell us, which is not much * and certainly not enough if more than one volume hotkey was pressed * since the last poll cycle. * * Just to make our life interesting, some newer Lenovo ThinkPads have * bugs in the BIOS and may fail to update volume_toggle properly. */ if (newn->mute) { /* muted */ if (!oldn->mute || oldn->volume_toggle != newn->volume_toggle || oldn->volume_level != newn->volume_level) { /* recently muted, or repeated mute keypress, or * multiple presses ending in mute */ issue_volchange(oldn->volume_level, newn->volume_level); TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE); } } else { /* unmute */ if (oldn->mute) { /* recently unmuted, issue 'unmute' keypress */ TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP); } if (oldn->volume_level != newn->volume_level) { issue_volchange(oldn->volume_level, newn->volume_level); } else if (oldn->volume_toggle != newn->volume_toggle) { /* repeated vol up/down keypress at end of scale ? */ if (newn->volume_level == 0) TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN); else if (newn->volume_level >= TP_NVRAM_LEVEL_VOLUME_MAX) TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP); } } /* handle brightness */ if (oldn->brightness_level != newn->brightness_level) { issue_brightnesschange(oldn->brightness_level, newn->brightness_level); } else if (oldn->brightness_toggle != newn->brightness_toggle) { /* repeated key presses that didn't change state */ if (newn->brightness_level == 0) TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND); else if (newn->brightness_level >= bright_maxlvl && !tp_features.bright_unkfw) TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME); } #undef TPACPI_COMPARE_KEY #undef TPACPI_MAY_SEND_KEY } /* * Polling driver * * We track all events in hotkey_source_mask all the time, since * most of them are edge-based. We only issue those requested by * hotkey_user_mask or hotkey_driver_mask, though. */ static int hotkey_kthread(void *data) { struct tp_nvram_state s[2]; u32 poll_mask, event_mask; unsigned int si, so; unsigned long t; unsigned int change_detector, must_reset; unsigned int poll_freq; mutex_lock(&hotkey_thread_mutex); if (tpacpi_lifecycle == TPACPI_LIFE_EXITING) goto exit; set_freezable(); so = 0; si = 1; t = 0; /* Initial state for compares */ mutex_lock(&hotkey_thread_data_mutex); change_detector = hotkey_config_change; poll_mask = hotkey_source_mask; event_mask = hotkey_source_mask & (hotkey_driver_mask | hotkey_user_mask); poll_freq = hotkey_poll_freq; mutex_unlock(&hotkey_thread_data_mutex); hotkey_read_nvram(&s[so], poll_mask); while (!kthread_should_stop()) { if (t == 0) { if (likely(poll_freq)) t = 1000/poll_freq; else t = 100; /* should never happen... */ } t = msleep_interruptible(t); if (unlikely(kthread_should_stop())) break; must_reset = try_to_freeze(); if (t > 0 && !must_reset) continue; mutex_lock(&hotkey_thread_data_mutex); if (must_reset || hotkey_config_change != change_detector) { /* forget old state on thaw or config change */ si = so; t = 0; change_detector = hotkey_config_change; } poll_mask = hotkey_source_mask; event_mask = hotkey_source_mask & (hotkey_driver_mask | hotkey_user_mask); poll_freq = hotkey_poll_freq; mutex_unlock(&hotkey_thread_data_mutex); if (likely(poll_mask)) { hotkey_read_nvram(&s[si], poll_mask); if (likely(si != so)) { hotkey_compare_and_issue_event(&s[so], &s[si], event_mask); } } so = si; si ^= 1; } exit: mutex_unlock(&hotkey_thread_mutex); return 0; } /* call with hotkey_mutex held */ static void hotkey_poll_stop_sync(void) { if (tpacpi_hotkey_task) { if (frozen(tpacpi_hotkey_task) || freezing(tpacpi_hotkey_task)) thaw_process(tpacpi_hotkey_task); kthread_stop(tpacpi_hotkey_task); tpacpi_hotkey_task = NULL; mutex_lock(&hotkey_thread_mutex); /* at this point, the thread did exit */ mutex_unlock(&hotkey_thread_mutex); } } /* call with hotkey_mutex held */ static void hotkey_poll_setup(const bool may_warn) { const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask; const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask; if (hotkey_poll_freq > 0 && (poll_driver_mask || (poll_user_mask && tpacpi_inputdev->users > 0))) { if (!tpacpi_hotkey_task) { tpacpi_hotkey_task = kthread_run(hotkey_kthread, NULL, TPACPI_NVRAM_KTHREAD_NAME); if (IS_ERR(tpacpi_hotkey_task)) { tpacpi_hotkey_task = NULL; pr_err("could not create kernel thread " "for hotkey polling\n"); } } } else { hotkey_poll_stop_sync(); if (may_warn && (poll_driver_mask || poll_user_mask) && hotkey_poll_freq == 0) { pr_notice("hot keys 0x%08x and/or events 0x%08x " "require polling, which is currently " "disabled\n", poll_user_mask, poll_driver_mask); } } } static void hotkey_poll_setup_safe(const bool may_warn) { mutex_lock(&hotkey_mutex); hotkey_poll_setup(may_warn); mutex_unlock(&hotkey_mutex); } /* call with hotkey_mutex held */ static void hotkey_poll_set_freq(unsigned int freq) { if (!freq) hotkey_poll_stop_sync(); hotkey_poll_freq = freq; } #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */ static void hotkey_poll_setup(const bool __unused) { } static void hotkey_poll_setup_safe(const bool __unused) { } #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */ static int hotkey_inputdev_open(struct input_dev *dev) { switch (tpacpi_lifecycle) { case TPACPI_LIFE_INIT: case TPACPI_LIFE_RUNNING: hotkey_poll_setup_safe(false); return 0; case TPACPI_LIFE_EXITING: return -EBUSY; } /* Should only happen if tpacpi_lifecycle is corrupt */ BUG(); return -EBUSY; } static void hotkey_inputdev_close(struct input_dev *dev) { /* disable hotkey polling when possible */ if (tpacpi_lifecycle != TPACPI_LIFE_EXITING && !(hotkey_source_mask & hotkey_driver_mask)) hotkey_poll_setup_safe(false); } /* sysfs hotkey enable ------------------------------------------------- */ static ssize_t hotkey_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { int res, status; printk_deprecated_attribute("hotkey_enable", "Hotkey reporting is always enabled"); res = hotkey_status_get(&status); if (res) return res; return snprintf(buf, PAGE_SIZE, "%d\n", status); } static ssize_t hotkey_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long t; printk_deprecated_attribute("hotkey_enable", "Hotkeys can be disabled through hotkey_mask"); if (parse_strtoul(buf, 1, &t)) return -EINVAL; if (t == 0) return -EPERM; return count; } static struct device_attribute dev_attr_hotkey_enable = __ATTR(hotkey_enable, S_IWUSR | S_IRUGO, hotkey_enable_show, hotkey_enable_store); /* sysfs hotkey mask --------------------------------------------------- */ static ssize_t hotkey_mask_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask); } static ssize_t hotkey_mask_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long t; int res; if (parse_strtoul(buf, 0xffffffffUL, &t)) return -EINVAL; if (mutex_lock_killable(&hotkey_mutex)) return -ERESTARTSYS; res = hotkey_user_mask_set(t); #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL hotkey_poll_setup(true); #endif mutex_unlock(&hotkey_mutex); tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t); return (res) ? res : count; } static struct device_attribute dev_attr_hotkey_mask = __ATTR(hotkey_mask, S_IWUSR | S_IRUGO, hotkey_mask_show, hotkey_mask_store); /* sysfs hotkey bios_enabled ------------------------------------------- */ static ssize_t hotkey_bios_enabled_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "0\n"); } static struct device_attribute dev_attr_hotkey_bios_enabled = __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL); /* sysfs hotkey bios_mask ---------------------------------------------- */ static ssize_t hotkey_bios_mask_show(struct device *dev, struct device_attribute *attr, char *buf) { printk_deprecated_attribute("hotkey_bios_mask", "This attribute is useless."); return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask); } static struct device_attribute dev_attr_hotkey_bios_mask = __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL); /* sysfs hotkey all_mask ----------------------------------------------- */ static ssize_t hotkey_all_mask_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_all_mask | hotkey_source_mask); } static struct device_attribute dev_attr_hotkey_all_mask = __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL); /* sysfs hotkey recommended_mask --------------------------------------- */ static ssize_t hotkey_recommended_mask_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "0x%08x\n", (hotkey_all_mask | hotkey_source_mask) & ~hotkey_reserved_mask); } static struct device_attribute dev_attr_hotkey_recommended_mask = __ATTR(hotkey_recommended_mask, S_IRUGO, hotkey_recommended_mask_show, NULL); #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL /* sysfs hotkey hotkey_source_mask ------------------------------------- */ static ssize_t hotkey_source_mask_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask); } static ssize_t hotkey_source_mask_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long t; u32 r_ev; int rc; if (parse_strtoul(buf, 0xffffffffUL, &t) || ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0)) return -EINVAL; if (mutex_lock_killable(&hotkey_mutex)) return -ERESTARTSYS; HOTKEY_CONFIG_CRITICAL_START hotkey_source_mask = t; HOTKEY_CONFIG_CRITICAL_END rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) & ~hotkey_source_mask); hotkey_poll_setup(true); /* check if events needed by the driver got disabled */ r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask) & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK; mutex_unlock(&hotkey_mutex); if (rc < 0) pr_err("hotkey_source_mask: " "failed to update the firmware event mask!\n"); if (r_ev) pr_notice("hotkey_source_mask: " "some important events were disabled: 0x%04x\n", r_ev); tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t); return (rc < 0) ? rc : count; } static struct device_attribute dev_attr_hotkey_source_mask = __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO, hotkey_source_mask_show, hotkey_source_mask_store); /* sysfs hotkey hotkey_poll_freq --------------------------------------- */ static ssize_t hotkey_poll_freq_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq); } static ssize_t hotkey_poll_freq_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 25, &t)) return -EINVAL; if (mutex_lock_killable(&hotkey_mutex)) return -ERESTARTSYS; hotkey_poll_set_freq(t); hotkey_poll_setup(true); mutex_unlock(&hotkey_mutex); tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t); return count; } static struct device_attribute dev_attr_hotkey_poll_freq = __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO, hotkey_poll_freq_show, hotkey_poll_freq_store); #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */ /* sysfs hotkey radio_sw (pollable) ------------------------------------ */ static ssize_t hotkey_radio_sw_show(struct device *dev, struct device_attribute *attr, char *buf) { int res; res = hotkey_get_wlsw(); if (res < 0) return res; /* Opportunistic update */ tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF)); return snprintf(buf, PAGE_SIZE, "%d\n", (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1); } static struct device_attribute dev_attr_hotkey_radio_sw = __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL); static void hotkey_radio_sw_notify_change(void) { if (tp_features.hotkey_wlsw) sysfs_notify(&tpacpi_pdev->dev.kobj, NULL, "hotkey_radio_sw"); } /* sysfs hotkey tablet mode (pollable) --------------------------------- */ static ssize_t hotkey_tablet_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { int res, s; res = hotkey_get_tablet_mode(&s); if (res < 0) return res; return snprintf(buf, PAGE_SIZE, "%d\n", !!s); } static struct device_attribute dev_attr_hotkey_tablet_mode = __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL); static void hotkey_tablet_mode_notify_change(void) { if (tp_features.hotkey_tablet) sysfs_notify(&tpacpi_pdev->dev.kobj, NULL, "hotkey_tablet_mode"); } /* sysfs hotkey report_mode -------------------------------------------- */ static ssize_t hotkey_report_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", (hotkey_report_mode != 0) ? hotkey_report_mode : 1); } static struct device_attribute dev_attr_hotkey_report_mode = __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL); /* sysfs wakeup reason (pollable) -------------------------------------- */ static ssize_t hotkey_wakeup_reason_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason); } static struct device_attribute dev_attr_hotkey_wakeup_reason = __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL); static void hotkey_wakeup_reason_notify_change(void) { sysfs_notify(&tpacpi_pdev->dev.kobj, NULL, "wakeup_reason"); } /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */ static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack); } static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete = __ATTR(wakeup_hotunplug_complete, S_IRUGO, hotkey_wakeup_hotunplug_complete_show, NULL); static void hotkey_wakeup_hotunplug_complete_notify_change(void) { sysfs_notify(&tpacpi_pdev->dev.kobj, NULL, "wakeup_hotunplug_complete"); } /* --------------------------------------------------------------------- */ static struct attribute *hotkey_attributes[] __initdata = { &dev_attr_hotkey_enable.attr, &dev_attr_hotkey_bios_enabled.attr, &dev_attr_hotkey_bios_mask.attr, &dev_attr_hotkey_report_mode.attr, &dev_attr_hotkey_wakeup_reason.attr, &dev_attr_hotkey_wakeup_hotunplug_complete.attr, &dev_attr_hotkey_mask.attr, &dev_attr_hotkey_all_mask.attr, &dev_attr_hotkey_recommended_mask.attr, #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL &dev_attr_hotkey_source_mask.attr, &dev_attr_hotkey_poll_freq.attr, #endif }; /* * Sync both the hw and sw blocking state of all switches */ static void tpacpi_send_radiosw_update(void) { int wlsw; /* * We must sync all rfkill controllers *before* issuing any * rfkill input events, or we will race the rfkill core input * handler. * * tpacpi_inputdev_send_mutex works as a synchronization point * for the above. * * We optimize to avoid numerous calls to hotkey_get_wlsw. */ wlsw = hotkey_get_wlsw(); /* Sync hw blocking state first if it is hw-blocked */ if (wlsw == TPACPI_RFK_RADIO_OFF) tpacpi_rfk_update_hwblock_state(true); /* Sync sw blocking state */ tpacpi_rfk_update_swstate_all(); /* Sync hw blocking state last if it is hw-unblocked */ if (wlsw == TPACPI_RFK_RADIO_ON) tpacpi_rfk_update_hwblock_state(false); /* Issue rfkill input event for WLSW switch */ if (!(wlsw < 0)) { mutex_lock(&tpacpi_inputdev_send_mutex); input_report_switch(tpacpi_inputdev, SW_RFKILL_ALL, (wlsw > 0)); input_sync(tpacpi_inputdev); mutex_unlock(&tpacpi_inputdev_send_mutex); } /* * this can be unconditional, as we will poll state again * if userspace uses the notify to read data */ hotkey_radio_sw_notify_change(); } static void hotkey_exit(void) { #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL mutex_lock(&hotkey_mutex); hotkey_poll_stop_sync(); mutex_unlock(&hotkey_mutex); #endif if (hotkey_dev_attributes) delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj); kfree(hotkey_keycode_map); dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY, "restoring original HKEY status and mask\n"); /* yes, there is a bitwise or below, we want the * functions to be called even if one of them fail */ if (((tp_features.hotkey_mask && hotkey_mask_set(hotkey_orig_mask)) | hotkey_status_set(false)) != 0) pr_err("failed to restore hot key mask " "to BIOS defaults\n"); } static void __init hotkey_unmap(const unsigned int scancode) { if (hotkey_keycode_map[scancode] != KEY_RESERVED) { clear_bit(hotkey_keycode_map[scancode], tpacpi_inputdev->keybit); hotkey_keycode_map[scancode] = KEY_RESERVED; } } /* * HKEY quirks: * TPACPI_HK_Q_INIMASK: Supports FN+F3,FN+F4,FN+F12 */ #define TPACPI_HK_Q_INIMASK 0x0001 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = { TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */ TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */ TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */ TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */ TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */ TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */ TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */ TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */ TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */ TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */ TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */ TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */ TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */ TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */ TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */ TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */ TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */ TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */ TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */ }; typedef u16 tpacpi_keymap_entry_t; typedef tpacpi_keymap_entry_t tpacpi_keymap_t[TPACPI_HOTKEY_MAP_LEN]; static int __init hotkey_init(struct ibm_init_struct *iibm) { /* Requirements for changing the default keymaps: * * 1. Many of the keys are mapped to KEY_RESERVED for very * good reasons. Do not change them unless you have deep * knowledge on the IBM and Lenovo ThinkPad firmware for * the various ThinkPad models. The driver behaves * differently for KEY_RESERVED: such keys have their * hot key mask *unset* in mask_recommended, and also * in the initial hot key mask programmed into the * firmware at driver load time, which means the firm- * ware may react very differently if you change them to * something else; * * 2. You must be subscribed to the linux-thinkpad and * ibm-acpi-devel mailing lists, and you should read the * list archives since 2007 if you want to change the * keymaps. This requirement exists so that you will * know the past history of problems with the thinkpad- * acpi driver keymaps, and also that you will be * listening to any bug reports; * * 3. Do not send thinkpad-acpi specific patches directly to * for merging, *ever*. Send them to the linux-acpi * mailinglist for comments. Merging is to be done only * through acpi-test and the ACPI maintainer. * * If the above is too much to ask, don't change the keymap. * Ask the thinkpad-acpi maintainer to do it, instead. */ enum keymap_index { TPACPI_KEYMAP_IBM_GENERIC = 0, TPACPI_KEYMAP_LENOVO_GENERIC, }; static const tpacpi_keymap_t tpacpi_keymaps[] __initconst = { /* Generic keymap for IBM ThinkPads */ [TPACPI_KEYMAP_IBM_GENERIC] = { /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */ KEY_FN_F1, KEY_BATTERY, KEY_COFFEE, KEY_SLEEP, KEY_WLAN, KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8, KEY_FN_F9, KEY_FN_F10, KEY_FN_F11, KEY_SUSPEND, /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */ KEY_UNKNOWN, /* 0x0C: FN+BACKSPACE */ KEY_UNKNOWN, /* 0x0D: FN+INSERT */ KEY_UNKNOWN, /* 0x0E: FN+DELETE */ /* brightness: firmware always reacts to them */ KEY_RESERVED, /* 0x0F: FN+HOME (brightness up) */ KEY_RESERVED, /* 0x10: FN+END (brightness down) */ /* Thinklight: firmware always react to it */ KEY_RESERVED, /* 0x11: FN+PGUP (thinklight toggle) */ KEY_UNKNOWN, /* 0x12: FN+PGDOWN */ KEY_ZOOM, /* 0x13: FN+SPACE (zoom) */ /* Volume: firmware always react to it and reprograms * the built-in *extra* mixer. Never map it to control * another mixer by default. */ KEY_RESERVED, /* 0x14: VOLUME UP */ KEY_RESERVED, /* 0x15: VOLUME DOWN */ KEY_RESERVED, /* 0x16: MUTE */ KEY_VENDOR, /* 0x17: Thinkpad/AccessIBM/Lenovo */ /* (assignments unknown, please report if found) */ KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, }, /* Generic keymap for Lenovo ThinkPads */ [TPACPI_KEYMAP_LENOVO_GENERIC] = { /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */ KEY_FN_F1, KEY_COFFEE, KEY_BATTERY, KEY_SLEEP, KEY_WLAN, KEY_CAMERA, KEY_SWITCHVIDEOMODE, KEY_FN_F8, KEY_FN_F9, KEY_FN_F10, KEY_FN_F11, KEY_SUSPEND, /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */ KEY_UNKNOWN, /* 0x0C: FN+BACKSPACE */ KEY_UNKNOWN, /* 0x0D: FN+INSERT */ KEY_UNKNOWN, /* 0x0E: FN+DELETE */ /* These should be enabled --only-- when ACPI video * is disabled (i.e. in "vendor" mode), and are handled * in a special way by the init code */ KEY_BRIGHTNESSUP, /* 0x0F: FN+HOME (brightness up) */ KEY_BRIGHTNESSDOWN, /* 0x10: FN+END (brightness down) */ KEY_RESERVED, /* 0x11: FN+PGUP (thinklight toggle) */ KEY_UNKNOWN, /* 0x12: FN+PGDOWN */ KEY_ZOOM, /* 0x13: FN+SPACE (zoom) */ /* Volume: z60/z61, T60 (BIOS version?): firmware always * react to it and reprograms the built-in *extra* mixer. * Never map it to control another mixer by default. * * T60?, T61, R60?, R61: firmware and EC tries to send * these over the regular keyboard, so these are no-ops, * but there are still weird bugs re. MUTE, so do not * change unless you get test reports from all Lenovo * models. May cause the BIOS to interfere with the * HDA mixer. */ KEY_RESERVED, /* 0x14: VOLUME UP */ KEY_RESERVED, /* 0x15: VOLUME DOWN */ KEY_RESERVED, /* 0x16: MUTE */ KEY_VENDOR, /* 0x17: Thinkpad/AccessIBM/Lenovo */ /* (assignments unknown, please report if found) */ KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, }, }; static const struct tpacpi_quirk tpacpi_keymap_qtable[] __initconst = { /* Generic maps (fallback) */ { .vendor = PCI_VENDOR_ID_IBM, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY, .quirks = TPACPI_KEYMAP_IBM_GENERIC, }, { .vendor = PCI_VENDOR_ID_LENOVO, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY, .quirks = TPACPI_KEYMAP_LENOVO_GENERIC, }, }; #define TPACPI_HOTKEY_MAP_SIZE sizeof(tpacpi_keymap_t) #define TPACPI_HOTKEY_MAP_TYPESIZE sizeof(tpacpi_keymap_entry_t) int res, i; int status; int hkeyv; bool radiosw_state = false; bool tabletsw_state = false; unsigned long quirks; unsigned long keymap_id; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "initializing hotkey subdriver\n"); BUG_ON(!tpacpi_inputdev); BUG_ON(tpacpi_inputdev->open != NULL || tpacpi_inputdev->close != NULL); TPACPI_ACPIHANDLE_INIT(hkey); mutex_init(&hotkey_mutex); #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL mutex_init(&hotkey_thread_mutex); mutex_init(&hotkey_thread_data_mutex); #endif /* hotkey not supported on 570 */ tp_features.hotkey = hkey_handle != NULL; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "hotkeys are %s\n", str_supported(tp_features.hotkey)); if (!tp_features.hotkey) return 1; quirks = tpacpi_check_quirks(tpacpi_hotkey_qtable, ARRAY_SIZE(tpacpi_hotkey_qtable)); tpacpi_disable_brightness_delay(); /* MUST have enough space for all attributes to be added to * hotkey_dev_attributes */ hotkey_dev_attributes = create_attr_set( ARRAY_SIZE(hotkey_attributes) + 2, NULL); if (!hotkey_dev_attributes) return -ENOMEM; res = add_many_to_attr_set(hotkey_dev_attributes, hotkey_attributes, ARRAY_SIZE(hotkey_attributes)); if (res) goto err_exit; /* mask not supported on 600e/x, 770e, 770x, A21e, A2xm/p, A30, R30, R31, T20-22, X20-21, X22-24. Detected by checking for HKEY interface version 0x100 */ if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) { if ((hkeyv >> 8) != 1) { pr_err("unknown version of the HKEY interface: 0x%x\n", hkeyv); pr_err("please report this to %s\n", TPACPI_MAIL); } else { /* * MHKV 0x100 in A31, R40, R40e, * T4x, X31, and later */ vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "firmware HKEY interface version: 0x%x\n", hkeyv); /* Paranoia check AND init hotkey_all_mask */ if (!acpi_evalf(hkey_handle, &hotkey_all_mask, "MHKA", "qd")) { pr_err("missing MHKA handler, " "please report this to %s\n", TPACPI_MAIL); /* Fallback: pre-init for FN+F3,F4,F12 */ hotkey_all_mask = 0x080cU; } else { tp_features.hotkey_mask = 1; } } } vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "hotkey masks are %s\n", str_supported(tp_features.hotkey_mask)); /* Init hotkey_all_mask if not initialized yet */ if (!tp_features.hotkey_mask && !hotkey_all_mask && (quirks & TPACPI_HK_Q_INIMASK)) hotkey_all_mask = 0x080cU; /* FN+F12, FN+F4, FN+F3 */ /* Init hotkey_acpi_mask and hotkey_orig_mask */ if (tp_features.hotkey_mask) { /* hotkey_source_mask *must* be zero for * the first hotkey_mask_get to return hotkey_orig_mask */ res = hotkey_mask_get(); if (res) goto err_exit; hotkey_orig_mask = hotkey_acpi_mask; } else { hotkey_orig_mask = hotkey_all_mask; hotkey_acpi_mask = hotkey_all_mask; } #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_wlswemul) { tp_features.hotkey_wlsw = 1; radiosw_state = !!tpacpi_wlsw_emulstate; pr_info("radio switch emulation enabled\n"); } else #endif /* Not all thinkpads have a hardware radio switch */ if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) { tp_features.hotkey_wlsw = 1; radiosw_state = !!status; pr_info("radio switch found; radios are %s\n", enabled(status, 0)); } if (tp_features.hotkey_wlsw) res = add_to_attr_set(hotkey_dev_attributes, &dev_attr_hotkey_radio_sw.attr); /* For X41t, X60t, X61t Tablets... */ if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) { tp_features.hotkey_tablet = 1; tabletsw_state = !!(status & TP_HOTKEY_TABLET_MASK); pr_info("possible tablet mode switch found; " "ThinkPad in %s mode\n", (tabletsw_state) ? "tablet" : "laptop"); res = add_to_attr_set(hotkey_dev_attributes, &dev_attr_hotkey_tablet_mode.attr); } if (!res) res = register_attr_set_with_sysfs( hotkey_dev_attributes, &tpacpi_pdev->dev.kobj); if (res) goto err_exit; /* Set up key map */ hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE, GFP_KERNEL); if (!hotkey_keycode_map) { pr_err("failed to allocate memory for key map\n"); res = -ENOMEM; goto err_exit; } keymap_id = tpacpi_check_quirks(tpacpi_keymap_qtable, ARRAY_SIZE(tpacpi_keymap_qtable)); BUG_ON(keymap_id >= ARRAY_SIZE(tpacpi_keymaps)); dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "using keymap number %lu\n", keymap_id); memcpy(hotkey_keycode_map, &tpacpi_keymaps[keymap_id], TPACPI_HOTKEY_MAP_SIZE); input_set_capability(tpacpi_inputdev, EV_MSC, MSC_SCAN); tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE; tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN; tpacpi_inputdev->keycode = hotkey_keycode_map; for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) { if (hotkey_keycode_map[i] != KEY_RESERVED) { input_set_capability(tpacpi_inputdev, EV_KEY, hotkey_keycode_map[i]); } else { if (i < sizeof(hotkey_reserved_mask)*8) hotkey_reserved_mask |= 1 << i; } } if (tp_features.hotkey_wlsw) { input_set_capability(tpacpi_inputdev, EV_SW, SW_RFKILL_ALL); input_report_switch(tpacpi_inputdev, SW_RFKILL_ALL, radiosw_state); } if (tp_features.hotkey_tablet) { input_set_capability(tpacpi_inputdev, EV_SW, SW_TABLET_MODE); input_report_switch(tpacpi_inputdev, SW_TABLET_MODE, tabletsw_state); } /* Do not issue duplicate brightness change events to * userspace. tpacpi_detect_brightness_capabilities() must have * been called before this point */ if (tp_features.bright_acpimode && acpi_video_backlight_support()) { pr_info("This ThinkPad has standard ACPI backlight " "brightness control, supported by the ACPI " "video driver\n"); pr_notice("Disabling thinkpad-acpi brightness events " "by default...\n"); /* Disable brightness up/down on Lenovo thinkpads when * ACPI is handling them, otherwise it is plain impossible * for userspace to do something even remotely sane */ hotkey_reserved_mask |= (1 << TP_ACPI_HOTKEYSCAN_FNHOME) | (1 << TP_ACPI_HOTKEYSCAN_FNEND); hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNHOME); hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNEND); } #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK & ~hotkey_all_mask & ~hotkey_reserved_mask; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "hotkey source mask 0x%08x, polling freq %u\n", hotkey_source_mask, hotkey_poll_freq); #endif dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "enabling firmware HKEY event interface...\n"); res = hotkey_status_set(true); if (res) { hotkey_exit(); return res; } res = hotkey_mask_set(((hotkey_all_mask & ~hotkey_reserved_mask) | hotkey_driver_mask) & ~hotkey_source_mask); if (res < 0 && res != -ENXIO) { hotkey_exit(); return res; } hotkey_user_mask = (hotkey_acpi_mask | hotkey_source_mask) & ~hotkey_reserved_mask; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "initial masks: user=0x%08x, fw=0x%08x, poll=0x%08x\n", hotkey_user_mask, hotkey_acpi_mask, hotkey_source_mask); dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY, "legacy ibm/hotkey event reporting over procfs %s\n", (hotkey_report_mode < 2) ? "enabled" : "disabled"); tpacpi_inputdev->open = &hotkey_inputdev_open; tpacpi_inputdev->close = &hotkey_inputdev_close; hotkey_poll_setup_safe(true); return 0; err_exit: delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj); hotkey_dev_attributes = NULL; return (res < 0)? res : 1; } static bool hotkey_notify_hotkey(const u32 hkey, bool *send_acpi_ev, bool *ignore_acpi_ev) { /* 0x1000-0x1FFF: key presses */ unsigned int scancode = hkey & 0xfff; *send_acpi_ev = true; *ignore_acpi_ev = false; /* HKEY event 0x1001 is scancode 0x00 */ if (scancode > 0 && scancode <= TPACPI_HOTKEY_MAP_LEN) { scancode--; if (!(hotkey_source_mask & (1 << scancode))) { tpacpi_input_send_key_masked(scancode); *send_acpi_ev = false; } else { *ignore_acpi_ev = true; } return true; } return false; } static bool hotkey_notify_wakeup(const u32 hkey, bool *send_acpi_ev, bool *ignore_acpi_ev) { /* 0x2000-0x2FFF: Wakeup reason */ *send_acpi_ev = true; *ignore_acpi_ev = false; switch (hkey) { case TP_HKEY_EV_WKUP_S3_UNDOCK: /* suspend, undock */ case TP_HKEY_EV_WKUP_S4_UNDOCK: /* hibernation, undock */ hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK; *ignore_acpi_ev = true; break; case TP_HKEY_EV_WKUP_S3_BAYEJ: /* suspend, bay eject */ case TP_HKEY_EV_WKUP_S4_BAYEJ: /* hibernation, bay eject */ hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ; *ignore_acpi_ev = true; break; case TP_HKEY_EV_WKUP_S3_BATLOW: /* Battery on critical low level/S3 */ case TP_HKEY_EV_WKUP_S4_BATLOW: /* Battery on critical low level/S4 */ pr_alert("EMERGENCY WAKEUP: battery almost empty\n"); /* how to auto-heal: */ /* 2313: woke up from S3, go to S4/S5 */ /* 2413: woke up from S4, go to S5 */ break; default: return false; } if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) { pr_info("woke up due to a hot-unplug request...\n"); hotkey_wakeup_reason_notify_change(); } return true; } static bool hotkey_notify_usrevent(const u32 hkey, bool *send_acpi_ev, bool *ignore_acpi_ev) { /* 0x5000-0x5FFF: human interface helpers */ *send_acpi_ev = true; *ignore_acpi_ev = false; switch (hkey) { case TP_HKEY_EV_PEN_INSERTED: /* X61t: tablet pen inserted into bay */ case TP_HKEY_EV_PEN_REMOVED: /* X61t: tablet pen removed from bay */ return true; case TP_HKEY_EV_TABLET_TABLET: /* X41t-X61t: tablet mode */ case TP_HKEY_EV_TABLET_NOTEBOOK: /* X41t-X61t: normal mode */ tpacpi_input_send_tabletsw(); hotkey_tablet_mode_notify_change(); *send_acpi_ev = false; return true; case TP_HKEY_EV_LID_CLOSE: /* Lid closed */ case TP_HKEY_EV_LID_OPEN: /* Lid opened */ case TP_HKEY_EV_BRGHT_CHANGED: /* brightness changed */ /* do not propagate these events */ *ignore_acpi_ev = true; return true; default: return false; } } static void thermal_dump_all_sensors(void); static bool hotkey_notify_thermal(const u32 hkey, bool *send_acpi_ev, bool *ignore_acpi_ev) { bool known = true; /* 0x6000-0x6FFF: thermal alarms */ *send_acpi_ev = true; *ignore_acpi_ev = false; switch (hkey) { case TP_HKEY_EV_THM_TABLE_CHANGED: pr_info("EC reports that Thermal Table has changed\n"); /* recommended action: do nothing, we don't have * Lenovo ATM information */ return true; case TP_HKEY_EV_ALARM_BAT_HOT: pr_crit("THERMAL ALARM: battery is too hot!\n"); /* recommended action: warn user through gui */ break; case TP_HKEY_EV_ALARM_BAT_XHOT: pr_alert("THERMAL EMERGENCY: battery is extremely hot!\n"); /* recommended action: immediate sleep/hibernate */ break; case TP_HKEY_EV_ALARM_SENSOR_HOT: pr_crit("THERMAL ALARM: " "a sensor reports something is too hot!\n"); /* recommended action: warn user through gui, that */ /* some internal component is too hot */ break; case TP_HKEY_EV_ALARM_SENSOR_XHOT: pr_alert("THERMAL EMERGENCY: " "a sensor reports something is extremely hot!\n"); /* recommended action: immediate sleep/hibernate */ break; default: pr_alert("THERMAL ALERT: unknown thermal alarm received\n"); known = false; } thermal_dump_all_sensors(); return known; } static void hotkey_notify(struct ibm_struct *ibm, u32 event) { u32 hkey; bool send_acpi_ev; bool ignore_acpi_ev; bool known_ev; if (event != 0x80) { pr_err("unknown HKEY notification event %d\n", event); /* forward it to userspace, maybe it knows how to handle it */ acpi_bus_generate_netlink_event( ibm->acpi->device->pnp.device_class, dev_name(&ibm->acpi->device->dev), event, 0); return; } while (1) { if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) { pr_err("failed to retrieve HKEY event\n"); return; } if (hkey == 0) { /* queue empty */ return; } send_acpi_ev = true; ignore_acpi_ev = false; switch (hkey >> 12) { case 1: /* 0x1000-0x1FFF: key presses */ known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev, &ignore_acpi_ev); break; case 2: /* 0x2000-0x2FFF: Wakeup reason */ known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev, &ignore_acpi_ev); break; case 3: /* 0x3000-0x3FFF: bay-related wakeups */ switch (hkey) { case TP_HKEY_EV_BAYEJ_ACK: hotkey_autosleep_ack = 1; pr_info("bay ejected\n"); hotkey_wakeup_hotunplug_complete_notify_change(); known_ev = true; break; case TP_HKEY_EV_OPTDRV_EJ: /* FIXME: kick libata if SATA link offline */ known_ev = true; break; default: known_ev = false; } break; case 4: /* 0x4000-0x4FFF: dock-related wakeups */ if (hkey == TP_HKEY_EV_UNDOCK_ACK) { hotkey_autosleep_ack = 1; pr_info("undocked\n"); hotkey_wakeup_hotunplug_complete_notify_change(); known_ev = true; } else { known_ev = false; } break; case 5: /* 0x5000-0x5FFF: human interface helpers */ known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev, &ignore_acpi_ev); break; case 6: /* 0x6000-0x6FFF: thermal alarms */ known_ev = hotkey_notify_thermal(hkey, &send_acpi_ev, &ignore_acpi_ev); break; case 7: /* 0x7000-0x7FFF: misc */ if (tp_features.hotkey_wlsw && hkey == TP_HKEY_EV_RFKILL_CHANGED) { tpacpi_send_radiosw_update(); send_acpi_ev = 0; known_ev = true; break; } /* fallthrough to default */ default: known_ev = false; } if (!known_ev) { pr_notice("unhandled HKEY event 0x%04x\n", hkey); pr_notice("please report the conditions when this " "event happened to %s\n", TPACPI_MAIL); } /* Legacy events */ if (!ignore_acpi_ev && (send_acpi_ev || hotkey_report_mode < 2)) { acpi_bus_generate_proc_event(ibm->acpi->device, event, hkey); } /* netlink events */ if (!ignore_acpi_ev && send_acpi_ev) { acpi_bus_generate_netlink_event( ibm->acpi->device->pnp.device_class, dev_name(&ibm->acpi->device->dev), event, hkey); } } } static void hotkey_suspend(pm_message_t state) { /* Do these on suspend, we get the events on early resume! */ hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE; hotkey_autosleep_ack = 0; } static void hotkey_resume(void) { tpacpi_disable_brightness_delay(); if (hotkey_status_set(true) < 0 || hotkey_mask_set(hotkey_acpi_mask) < 0) pr_err("error while attempting to reset the event " "firmware interface\n"); tpacpi_send_radiosw_update(); hotkey_tablet_mode_notify_change(); hotkey_wakeup_reason_notify_change(); hotkey_wakeup_hotunplug_complete_notify_change(); hotkey_poll_setup_safe(false); } /* procfs -------------------------------------------------------------- */ static int hotkey_read(struct seq_file *m) { int res, status; if (!tp_features.hotkey) { seq_printf(m, "status:\t\tnot supported\n"); return 0; } if (mutex_lock_killable(&hotkey_mutex)) return -ERESTARTSYS; res = hotkey_status_get(&status); if (!res) res = hotkey_mask_get(); mutex_unlock(&hotkey_mutex); if (res) return res; seq_printf(m, "status:\t\t%s\n", enabled(status, 0)); if (hotkey_all_mask) { seq_printf(m, "mask:\t\t0x%08x\n", hotkey_user_mask); seq_printf(m, "commands:\tenable, disable, reset, <mask>\n"); } else { seq_printf(m, "mask:\t\tnot supported\n"); seq_printf(m, "commands:\tenable, disable, reset\n"); } return 0; } static void hotkey_enabledisable_warn(bool enable) { tpacpi_log_usertask("procfs hotkey enable/disable"); if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable), pr_fmt("hotkey enable/disable functionality has been " "removed from the driver. " "Hotkeys are always enabled.\n"))) pr_err("Please remove the hotkey=enable module " "parameter, it is deprecated. " "Hotkeys are always enabled.\n"); } static int hotkey_write(char *buf) { int res; u32 mask; char *cmd; if (!tp_features.hotkey) return -ENODEV; if (mutex_lock_killable(&hotkey_mutex)) return -ERESTARTSYS; mask = hotkey_user_mask; res = 0; while ((cmd = next_cmd(&buf))) { if (strlencmp(cmd, "enable") == 0) { hotkey_enabledisable_warn(1); } else if (strlencmp(cmd, "disable") == 0) { hotkey_enabledisable_warn(0); res = -EPERM; } else if (strlencmp(cmd, "reset") == 0) { mask = (hotkey_all_mask | hotkey_source_mask) & ~hotkey_reserved_mask; } else if (sscanf(cmd, "0x%x", &mask) == 1) { /* mask set */ } else if (sscanf(cmd, "%x", &mask) == 1) { /* mask set */ } else { res = -EINVAL; goto errexit; } } if (!res) { tpacpi_disclose_usertask("procfs hotkey", "set mask to 0x%08x\n", mask); res = hotkey_user_mask_set(mask); } errexit: mutex_unlock(&hotkey_mutex); return res; } static const struct acpi_device_id ibm_htk_device_ids[] = { {TPACPI_ACPI_IBM_HKEY_HID, 0}, {TPACPI_ACPI_LENOVO_HKEY_HID, 0}, {"", 0}, }; static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = { .hid = ibm_htk_device_ids, .notify = hotkey_notify, .handle = &hkey_handle, .type = ACPI_DEVICE_NOTIFY, }; static struct ibm_struct hotkey_driver_data = { .name = "hotkey", .read = hotkey_read, .write = hotkey_write, .exit = hotkey_exit, .resume = hotkey_resume, .suspend = hotkey_suspend, .acpi = &ibm_hotkey_acpidriver, }; /************************************************************************* * Bluetooth subdriver */ enum { /* ACPI GBDC/SBDC bits */ TP_ACPI_BLUETOOTH_HWPRESENT = 0x01, /* Bluetooth hw available */ TP_ACPI_BLUETOOTH_RADIOSSW = 0x02, /* Bluetooth radio enabled */ TP_ACPI_BLUETOOTH_RESUMECTRL = 0x04, /* Bluetooth state at resume: 0 = disable, 1 = enable */ }; enum { /* ACPI \BLTH commands */ TP_ACPI_BLTH_GET_ULTRAPORT_ID = 0x00, /* Get Ultraport BT ID */ TP_ACPI_BLTH_GET_PWR_ON_RESUME = 0x01, /* Get power-on-resume state */ TP_ACPI_BLTH_PWR_ON_ON_RESUME = 0x02, /* Resume powered on */ TP_ACPI_BLTH_PWR_OFF_ON_RESUME = 0x03, /* Resume powered off */ TP_ACPI_BLTH_SAVE_STATE = 0x05, /* Save state for S4/S5 */ }; #define TPACPI_RFK_BLUETOOTH_SW_NAME "tpacpi_bluetooth_sw" static int bluetooth_get_status(void) { int status; #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_bluetoothemul) return (tpacpi_bluetooth_emulstate) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; #endif if (!acpi_evalf(hkey_handle, &status, "GBDC", "d")) return -EIO; return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; } static int bluetooth_set_status(enum tpacpi_rfkill_state state) { int status; vdbg_printk(TPACPI_DBG_RFKILL, "will attempt to %s bluetooth\n", (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable"); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_bluetoothemul) { tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON); return 0; } #endif if (state == TPACPI_RFK_RADIO_ON) status = TP_ACPI_BLUETOOTH_RADIOSSW | TP_ACPI_BLUETOOTH_RESUMECTRL; else status = 0; if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status)) return -EIO; return 0; } /* sysfs bluetooth enable ---------------------------------------------- */ static ssize_t bluetooth_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID, attr, buf); } static ssize_t bluetooth_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID, attr, buf, count); } static struct device_attribute dev_attr_bluetooth_enable = __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO, bluetooth_enable_show, bluetooth_enable_store); /* --------------------------------------------------------------------- */ static struct attribute *bluetooth_attributes[] = { &dev_attr_bluetooth_enable.attr, NULL }; static const struct attribute_group bluetooth_attr_group = { .attrs = bluetooth_attributes, }; static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = { .get_status = bluetooth_get_status, .set_status = bluetooth_set_status, }; static void bluetooth_shutdown(void) { /* Order firmware to save current state to NVRAM */ if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd", TP_ACPI_BLTH_SAVE_STATE)) pr_notice("failed to save bluetooth state to NVRAM\n"); else vdbg_printk(TPACPI_DBG_RFKILL, "bluestooth state saved to NVRAM\n"); } static void bluetooth_exit(void) { sysfs_remove_group(&tpacpi_pdev->dev.kobj, &bluetooth_attr_group); tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID); bluetooth_shutdown(); } static int __init bluetooth_init(struct ibm_init_struct *iibm) { int res; int status = 0; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "initializing bluetooth subdriver\n"); TPACPI_ACPIHANDLE_INIT(hkey); /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p, G4x, R30, R31, R40e, R50e, T20-22, X20-21 */ tp_features.bluetooth = hkey_handle && acpi_evalf(hkey_handle, &status, "GBDC", "qd"); vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "bluetooth is %s, status 0x%02x\n", str_supported(tp_features.bluetooth), status); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_bluetoothemul) { tp_features.bluetooth = 1; pr_info("bluetooth switch emulation enabled\n"); } else #endif if (tp_features.bluetooth && !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) { /* no bluetooth hardware present in system */ tp_features.bluetooth = 0; dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "bluetooth hardware not installed\n"); } if (!tp_features.bluetooth) return 1; res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID, &bluetooth_tprfk_ops, RFKILL_TYPE_BLUETOOTH, TPACPI_RFK_BLUETOOTH_SW_NAME, true); if (res) return res; res = sysfs_create_group(&tpacpi_pdev->dev.kobj, &bluetooth_attr_group); if (res) { tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID); return res; } return 0; } /* procfs -------------------------------------------------------------- */ static int bluetooth_read(struct seq_file *m) { return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, m); } static int bluetooth_write(char *buf) { return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf); } static struct ibm_struct bluetooth_driver_data = { .name = "bluetooth", .read = bluetooth_read, .write = bluetooth_write, .exit = bluetooth_exit, .shutdown = bluetooth_shutdown, }; /************************************************************************* * Wan subdriver */ enum { /* ACPI GWAN/SWAN bits */ TP_ACPI_WANCARD_HWPRESENT = 0x01, /* Wan hw available */ TP_ACPI_WANCARD_RADIOSSW = 0x02, /* Wan radio enabled */ TP_ACPI_WANCARD_RESUMECTRL = 0x04, /* Wan state at resume: 0 = disable, 1 = enable */ }; #define TPACPI_RFK_WWAN_SW_NAME "tpacpi_wwan_sw" static int wan_get_status(void) { int status; #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_wwanemul) return (tpacpi_wwan_emulstate) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; #endif if (!acpi_evalf(hkey_handle, &status, "GWAN", "d")) return -EIO; return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; } static int wan_set_status(enum tpacpi_rfkill_state state) { int status; vdbg_printk(TPACPI_DBG_RFKILL, "will attempt to %s wwan\n", (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable"); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_wwanemul) { tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON); return 0; } #endif if (state == TPACPI_RFK_RADIO_ON) status = TP_ACPI_WANCARD_RADIOSSW | TP_ACPI_WANCARD_RESUMECTRL; else status = 0; if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status)) return -EIO; return 0; } /* sysfs wan enable ---------------------------------------------------- */ static ssize_t wan_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID, attr, buf); } static ssize_t wan_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID, attr, buf, count); } static struct device_attribute dev_attr_wan_enable = __ATTR(wwan_enable, S_IWUSR | S_IRUGO, wan_enable_show, wan_enable_store); /* --------------------------------------------------------------------- */ static struct attribute *wan_attributes[] = { &dev_attr_wan_enable.attr, NULL }; static const struct attribute_group wan_attr_group = { .attrs = wan_attributes, }; static const struct tpacpi_rfk_ops wan_tprfk_ops = { .get_status = wan_get_status, .set_status = wan_set_status, }; static void wan_shutdown(void) { /* Order firmware to save current state to NVRAM */ if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd", TP_ACPI_WGSV_SAVE_STATE)) pr_notice("failed to save WWAN state to NVRAM\n"); else vdbg_printk(TPACPI_DBG_RFKILL, "WWAN state saved to NVRAM\n"); } static void wan_exit(void) { sysfs_remove_group(&tpacpi_pdev->dev.kobj, &wan_attr_group); tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID); wan_shutdown(); } static int __init wan_init(struct ibm_init_struct *iibm) { int res; int status = 0; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "initializing wan subdriver\n"); TPACPI_ACPIHANDLE_INIT(hkey); tp_features.wan = hkey_handle && acpi_evalf(hkey_handle, &status, "GWAN", "qd"); vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "wan is %s, status 0x%02x\n", str_supported(tp_features.wan), status); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_wwanemul) { tp_features.wan = 1; pr_info("wwan switch emulation enabled\n"); } else #endif if (tp_features.wan && !(status & TP_ACPI_WANCARD_HWPRESENT)) { /* no wan hardware present in system */ tp_features.wan = 0; dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "wan hardware not installed\n"); } if (!tp_features.wan) return 1; res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID, &wan_tprfk_ops, RFKILL_TYPE_WWAN, TPACPI_RFK_WWAN_SW_NAME, true); if (res) return res; res = sysfs_create_group(&tpacpi_pdev->dev.kobj, &wan_attr_group); if (res) { tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID); return res; } return 0; } /* procfs -------------------------------------------------------------- */ static int wan_read(struct seq_file *m) { return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, m); } static int wan_write(char *buf) { return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf); } static struct ibm_struct wan_driver_data = { .name = "wan", .read = wan_read, .write = wan_write, .exit = wan_exit, .shutdown = wan_shutdown, }; /************************************************************************* * UWB subdriver */ enum { /* ACPI GUWB/SUWB bits */ TP_ACPI_UWB_HWPRESENT = 0x01, /* UWB hw available */ TP_ACPI_UWB_RADIOSSW = 0x02, /* UWB radio enabled */ }; #define TPACPI_RFK_UWB_SW_NAME "tpacpi_uwb_sw" static int uwb_get_status(void) { int status; #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_uwbemul) return (tpacpi_uwb_emulstate) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; #endif if (!acpi_evalf(hkey_handle, &status, "GUWB", "d")) return -EIO; return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF; } static int uwb_set_status(enum tpacpi_rfkill_state state) { int status; vdbg_printk(TPACPI_DBG_RFKILL, "will attempt to %s UWB\n", (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable"); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_uwbemul) { tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON); return 0; } #endif if (state == TPACPI_RFK_RADIO_ON) status = TP_ACPI_UWB_RADIOSSW; else status = 0; if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status)) return -EIO; return 0; } /* --------------------------------------------------------------------- */ static const struct tpacpi_rfk_ops uwb_tprfk_ops = { .get_status = uwb_get_status, .set_status = uwb_set_status, }; static void uwb_exit(void) { tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID); } static int __init uwb_init(struct ibm_init_struct *iibm) { int res; int status = 0; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "initializing uwb subdriver\n"); TPACPI_ACPIHANDLE_INIT(hkey); tp_features.uwb = hkey_handle && acpi_evalf(hkey_handle, &status, "GUWB", "qd"); vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL, "uwb is %s, status 0x%02x\n", str_supported(tp_features.uwb), status); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES if (dbg_uwbemul) { tp_features.uwb = 1; pr_info("uwb switch emulation enabled\n"); } else #endif if (tp_features.uwb && !(status & TP_ACPI_UWB_HWPRESENT)) { /* no uwb hardware present in system */ tp_features.uwb = 0; dbg_printk(TPACPI_DBG_INIT, "uwb hardware not installed\n"); } if (!tp_features.uwb) return 1; res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID, &uwb_tprfk_ops, RFKILL_TYPE_UWB, TPACPI_RFK_UWB_SW_NAME, false); return res; } static struct ibm_struct uwb_driver_data = { .name = "uwb", .exit = uwb_exit, .flags.experimental = 1, }; /************************************************************************* * Video subdriver */ #ifdef CONFIG_THINKPAD_ACPI_VIDEO enum video_access_mode { TPACPI_VIDEO_NONE = 0, TPACPI_VIDEO_570, /* 570 */ TPACPI_VIDEO_770, /* 600e/x, 770e, 770x */ TPACPI_VIDEO_NEW, /* all others */ }; enum { /* video status flags, based on VIDEO_570 */ TP_ACPI_VIDEO_S_LCD = 0x01, /* LCD output enabled */ TP_ACPI_VIDEO_S_CRT = 0x02, /* CRT output enabled */ TP_ACPI_VIDEO_S_DVI = 0x08, /* DVI output enabled */ }; enum { /* TPACPI_VIDEO_570 constants */ TP_ACPI_VIDEO_570_PHSCMD = 0x87, /* unknown magic constant :( */ TP_ACPI_VIDEO_570_PHSMASK = 0x03, /* PHS bits that map to * video_status_flags */ TP_ACPI_VIDEO_570_PHS2CMD = 0x8b, /* unknown magic constant :( */ TP_ACPI_VIDEO_570_PHS2SET = 0x80, /* unknown magic constant :( */ }; static enum video_access_mode video_supported; static int video_orig_autosw; static int video_autosw_get(void); static int video_autosw_set(int enable); TPACPI_HANDLE(vid, root, "\\_SB.PCI.AGP.VGA", /* 570 */ "\\_SB.PCI0.AGP0.VID0", /* 600e/x, 770x */ "\\_SB.PCI0.VID0", /* 770e */ "\\_SB.PCI0.VID", /* A21e, G4x, R50e, X30, X40 */ "\\_SB.PCI0.AGP.VGA", /* X100e and a few others */ "\\_SB.PCI0.AGP.VID", /* all others */ ); /* R30, R31 */ TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID"); /* G41 */ static int __init video_init(struct ibm_init_struct *iibm) { int ivga; vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n"); TPACPI_ACPIHANDLE_INIT(vid); if (tpacpi_is_ibm()) TPACPI_ACPIHANDLE_INIT(vid2); if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga) /* G41, assume IVGA doesn't change */ vid_handle = vid2_handle; if (!vid_handle) /* video switching not supported on R30, R31 */ video_supported = TPACPI_VIDEO_NONE; else if (tpacpi_is_ibm() && acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd")) /* 570 */ video_supported = TPACPI_VIDEO_570; else if (tpacpi_is_ibm() && acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd")) /* 600e/x, 770e, 770x */ video_supported = TPACPI_VIDEO_770; else /* all others */ video_supported = TPACPI_VIDEO_NEW; vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n", str_supported(video_supported != TPACPI_VIDEO_NONE), video_supported); return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1; } static void video_exit(void) { dbg_printk(TPACPI_DBG_EXIT, "restoring original video autoswitch mode\n"); if (video_autosw_set(video_orig_autosw)) pr_err("error while trying to restore original " "video autoswitch mode\n"); } static int video_outputsw_get(void) { int status = 0; int i; switch (video_supported) { case TPACPI_VIDEO_570: if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd", TP_ACPI_VIDEO_570_PHSCMD)) return -EIO; status = i & TP_ACPI_VIDEO_570_PHSMASK; break; case TPACPI_VIDEO_770: if (!acpi_evalf(NULL, &i, "\\VCDL", "d")) return -EIO; if (i) status |= TP_ACPI_VIDEO_S_LCD; if (!acpi_evalf(NULL, &i, "\\VCDC", "d")) return -EIO; if (i) status |= TP_ACPI_VIDEO_S_CRT; break; case TPACPI_VIDEO_NEW: if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) || !acpi_evalf(NULL, &i, "\\VCDC", "d")) return -EIO; if (i) status |= TP_ACPI_VIDEO_S_CRT; if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) || !acpi_evalf(NULL, &i, "\\VCDL", "d")) return -EIO; if (i) status |= TP_ACPI_VIDEO_S_LCD; if (!acpi_evalf(NULL, &i, "\\VCDD", "d")) return -EIO; if (i) status |= TP_ACPI_VIDEO_S_DVI; break; default: return -ENOSYS; } return status; } static int video_outputsw_set(int status) { int autosw; int res = 0; switch (video_supported) { case TPACPI_VIDEO_570: res = acpi_evalf(NULL, NULL, "\\_SB.PHS2", "vdd", TP_ACPI_VIDEO_570_PHS2CMD, status | TP_ACPI_VIDEO_570_PHS2SET); break; case TPACPI_VIDEO_770: autosw = video_autosw_get(); if (autosw < 0) return autosw; res = video_autosw_set(1); if (res) return res; res = acpi_evalf(vid_handle, NULL, "ASWT", "vdd", status * 0x100, 0); if (!autosw && video_autosw_set(autosw)) { pr_err("video auto-switch left enabled due to error\n"); return -EIO; } break; case TPACPI_VIDEO_NEW: res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) && acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1); break; default: return -ENOSYS; } return (res)? 0 : -EIO; } static int video_autosw_get(void) { int autosw = 0; switch (video_supported) { case TPACPI_VIDEO_570: if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d")) return -EIO; break; case TPACPI_VIDEO_770: case TPACPI_VIDEO_NEW: if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d")) return -EIO; break; default: return -ENOSYS; } return autosw & 1; } static int video_autosw_set(int enable) { if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0)) return -EIO; return 0; } static int video_outputsw_cycle(void) { int autosw = video_autosw_get(); int res; if (autosw < 0) return autosw; switch (video_supported) { case TPACPI_VIDEO_570: res = video_autosw_set(1); if (res) return res; res = acpi_evalf(ec_handle, NULL, "_Q16", "v"); break; case TPACPI_VIDEO_770: case TPACPI_VIDEO_NEW: res = video_autosw_set(1); if (res) return res; res = acpi_evalf(vid_handle, NULL, "VSWT", "v"); break; default: return -ENOSYS; } if (!autosw && video_autosw_set(autosw)) { pr_err("video auto-switch left enabled due to error\n"); return -EIO; } return (res)? 0 : -EIO; } static int video_expand_toggle(void) { switch (video_supported) { case TPACPI_VIDEO_570: return acpi_evalf(ec_handle, NULL, "_Q17", "v")? 0 : -EIO; case TPACPI_VIDEO_770: return acpi_evalf(vid_handle, NULL, "VEXP", "v")? 0 : -EIO; case TPACPI_VIDEO_NEW: return acpi_evalf(NULL, NULL, "\\VEXP", "v")? 0 : -EIO; default: return -ENOSYS; } /* not reached */ } static int video_read(struct seq_file *m) { int status, autosw; if (video_supported == TPACPI_VIDEO_NONE) { seq_printf(m, "status:\t\tnot supported\n"); return 0; } /* Even reads can crash X.org, so... */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; status = video_outputsw_get(); if (status < 0) return status; autosw = video_autosw_get(); if (autosw < 0) return autosw; seq_printf(m, "status:\t\tsupported\n"); seq_printf(m, "lcd:\t\t%s\n", enabled(status, 0)); seq_printf(m, "crt:\t\t%s\n", enabled(status, 1)); if (video_supported == TPACPI_VIDEO_NEW) seq_printf(m, "dvi:\t\t%s\n", enabled(status, 3)); seq_printf(m, "auto:\t\t%s\n", enabled(autosw, 0)); seq_printf(m, "commands:\tlcd_enable, lcd_disable\n"); seq_printf(m, "commands:\tcrt_enable, crt_disable\n"); if (video_supported == TPACPI_VIDEO_NEW) seq_printf(m, "commands:\tdvi_enable, dvi_disable\n"); seq_printf(m, "commands:\tauto_enable, auto_disable\n"); seq_printf(m, "commands:\tvideo_switch, expand_toggle\n"); return 0; } static int video_write(char *buf) { char *cmd; int enable, disable, status; int res; if (video_supported == TPACPI_VIDEO_NONE) return -ENODEV; /* Even reads can crash X.org, let alone writes... */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; enable = 0; disable = 0; while ((cmd = next_cmd(&buf))) { if (strlencmp(cmd, "lcd_enable") == 0) { enable |= TP_ACPI_VIDEO_S_LCD; } else if (strlencmp(cmd, "lcd_disable") == 0) { disable |= TP_ACPI_VIDEO_S_LCD; } else if (strlencmp(cmd, "crt_enable") == 0) { enable |= TP_ACPI_VIDEO_S_CRT; } else if (strlencmp(cmd, "crt_disable") == 0) { disable |= TP_ACPI_VIDEO_S_CRT; } else if (video_supported == TPACPI_VIDEO_NEW && strlencmp(cmd, "dvi_enable") == 0) { enable |= TP_ACPI_VIDEO_S_DVI; } else if (video_supported == TPACPI_VIDEO_NEW && strlencmp(cmd, "dvi_disable") == 0) { disable |= TP_ACPI_VIDEO_S_DVI; } else if (strlencmp(cmd, "auto_enable") == 0) { res = video_autosw_set(1); if (res) return res; } else if (strlencmp(cmd, "auto_disable") == 0) { res = video_autosw_set(0); if (res) return res; } else if (strlencmp(cmd, "video_switch") == 0) { res = video_outputsw_cycle(); if (res) return res; } else if (strlencmp(cmd, "expand_toggle") == 0) { res = video_expand_toggle(); if (res) return res; } else return -EINVAL; } if (enable || disable) { status = video_outputsw_get(); if (status < 0) return status; res = video_outputsw_set((status & ~disable) | enable); if (res) return res; } return 0; } static struct ibm_struct video_driver_data = { .name = "video", .read = video_read, .write = video_write, .exit = video_exit, }; #endif /* CONFIG_THINKPAD_ACPI_VIDEO */ /************************************************************************* * Light (thinklight) subdriver */ TPACPI_HANDLE(lght, root, "\\LGHT"); /* A21e, A2xm/p, T20-22, X20-21 */ TPACPI_HANDLE(ledb, ec, "LEDB"); /* G4x */ static int light_get_status(void) { int status = 0; if (tp_features.light_status) { if (!acpi_evalf(ec_handle, &status, "KBLT", "d")) return -EIO; return (!!status); } return -ENXIO; } static int light_set_status(int status) { int rc; if (tp_features.light) { if (cmos_handle) { rc = acpi_evalf(cmos_handle, NULL, NULL, "vd", (status)? TP_CMOS_THINKLIGHT_ON : TP_CMOS_THINKLIGHT_OFF); } else { rc = acpi_evalf(lght_handle, NULL, NULL, "vd", (status)? 1 : 0); } return (rc)? 0 : -EIO; } return -ENXIO; } static void light_set_status_worker(struct work_struct *work) { struct tpacpi_led_classdev *data = container_of(work, struct tpacpi_led_classdev, work); if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING)) light_set_status((data->new_state != TPACPI_LED_OFF)); } static void light_sysfs_set(struct led_classdev *led_cdev, enum led_brightness brightness) { struct tpacpi_led_classdev *data = container_of(led_cdev, struct tpacpi_led_classdev, led_classdev); data->new_state = (brightness != LED_OFF) ? TPACPI_LED_ON : TPACPI_LED_OFF; queue_work(tpacpi_wq, &data->work); } static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev) { return (light_get_status() == 1)? LED_FULL : LED_OFF; } static struct tpacpi_led_classdev tpacpi_led_thinklight = { .led_classdev = { .name = "tpacpi::thinklight", .brightness_set = &light_sysfs_set, .brightness_get = &light_sysfs_get, } }; static int __init light_init(struct ibm_init_struct *iibm) { int rc; vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n"); if (tpacpi_is_ibm()) { TPACPI_ACPIHANDLE_INIT(ledb); TPACPI_ACPIHANDLE_INIT(lght); } TPACPI_ACPIHANDLE_INIT(cmos); INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker); /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */ tp_features.light = (cmos_handle || lght_handle) && !ledb_handle; if (tp_features.light) /* light status not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */ tp_features.light_status = acpi_evalf(ec_handle, NULL, "KBLT", "qv"); vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n", str_supported(tp_features.light), str_supported(tp_features.light_status)); if (!tp_features.light) return 1; rc = led_classdev_register(&tpacpi_pdev->dev, &tpacpi_led_thinklight.led_classdev); if (rc < 0) { tp_features.light = 0; tp_features.light_status = 0; } else { rc = 0; } return rc; } static void light_exit(void) { led_classdev_unregister(&tpacpi_led_thinklight.led_classdev); if (work_pending(&tpacpi_led_thinklight.work)) flush_workqueue(tpacpi_wq); } static int light_read(struct seq_file *m) { int status; if (!tp_features.light) { seq_printf(m, "status:\t\tnot supported\n"); } else if (!tp_features.light_status) { seq_printf(m, "status:\t\tunknown\n"); seq_printf(m, "commands:\ton, off\n"); } else { status = light_get_status(); if (status < 0) return status; seq_printf(m, "status:\t\t%s\n", onoff(status, 0)); seq_printf(m, "commands:\ton, off\n"); } return 0; } static int light_write(char *buf) { char *cmd; int newstatus = 0; if (!tp_features.light) return -ENODEV; while ((cmd = next_cmd(&buf))) { if (strlencmp(cmd, "on") == 0) { newstatus = 1; } else if (strlencmp(cmd, "off") == 0) { newstatus = 0; } else return -EINVAL; } return light_set_status(newstatus); } static struct ibm_struct light_driver_data = { .name = "light", .read = light_read, .write = light_write, .exit = light_exit, }; /************************************************************************* * CMOS subdriver */ /* sysfs cmos_command -------------------------------------------------- */ static ssize_t cmos_command_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long cmos_cmd; int res; if (parse_strtoul(buf, 21, &cmos_cmd)) return -EINVAL; res = issue_thinkpad_cmos_command(cmos_cmd); return (res)? res : count; } static struct device_attribute dev_attr_cmos_command = __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store); /* --------------------------------------------------------------------- */ static int __init cmos_init(struct ibm_init_struct *iibm) { int res; vdbg_printk(TPACPI_DBG_INIT, "initializing cmos commands subdriver\n"); TPACPI_ACPIHANDLE_INIT(cmos); vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n", str_supported(cmos_handle != NULL)); res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command); if (res) return res; return (cmos_handle)? 0 : 1; } static void cmos_exit(void) { device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command); } static int cmos_read(struct seq_file *m) { /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p, R30, R31, T20-22, X20-21 */ if (!cmos_handle) seq_printf(m, "status:\t\tnot supported\n"); else { seq_printf(m, "status:\t\tsupported\n"); seq_printf(m, "commands:\t<cmd> (<cmd> is 0-21)\n"); } return 0; } static int cmos_write(char *buf) { char *cmd; int cmos_cmd, res; while ((cmd = next_cmd(&buf))) { if (sscanf(cmd, "%u", &cmos_cmd) == 1 && cmos_cmd >= 0 && cmos_cmd <= 21) { /* cmos_cmd set */ } else return -EINVAL; res = issue_thinkpad_cmos_command(cmos_cmd); if (res) return res; } return 0; } static struct ibm_struct cmos_driver_data = { .name = "cmos", .read = cmos_read, .write = cmos_write, .exit = cmos_exit, }; /************************************************************************* * LED subdriver */ enum led_access_mode { TPACPI_LED_NONE = 0, TPACPI_LED_570, /* 570 */ TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */ TPACPI_LED_NEW, /* all others */ }; enum { /* For TPACPI_LED_OLD */ TPACPI_LED_EC_HLCL = 0x0c, /* EC reg to get led to power on */ TPACPI_LED_EC_HLBL = 0x0d, /* EC reg to blink a lit led */ TPACPI_LED_EC_HLMS = 0x0e, /* EC reg to select led to command */ }; static enum led_access_mode led_supported; static acpi_handle led_handle; #define TPACPI_LED_NUMLEDS 16 static struct tpacpi_led_classdev *tpacpi_leds; static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS]; static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = { /* there's a limit of 19 chars + NULL before 2.6.26 */ "tpacpi::power", "tpacpi:orange:batt", "tpacpi:green:batt", "tpacpi::dock_active", "tpacpi::bay_active", "tpacpi::dock_batt", "tpacpi::unknown_led", "tpacpi::standby", "tpacpi::dock_status1", "tpacpi::dock_status2", "tpacpi::unknown_led2", "tpacpi::unknown_led3", "tpacpi::thinkvantage", }; #define TPACPI_SAFE_LEDS 0x1081U static inline bool tpacpi_is_led_restricted(const unsigned int led) { #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS return false; #else return (1U & (TPACPI_SAFE_LEDS >> led)) == 0; #endif } static int led_get_status(const unsigned int led) { int status; enum led_status_t led_s; switch (led_supported) { case TPACPI_LED_570: if (!acpi_evalf(ec_handle, &status, "GLED", "dd", 1 << led)) return -EIO; led_s = (status == 0)? TPACPI_LED_OFF : ((status == 1)? TPACPI_LED_ON : TPACPI_LED_BLINK); tpacpi_led_state_cache[led] = led_s; return led_s; default: return -ENXIO; } /* not reached */ } static int led_set_status(const unsigned int led, const enum led_status_t ledstatus) { /* off, on, blink. Index is led_status_t */ static const unsigned int led_sled_arg1[] = { 0, 1, 3 }; static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 }; int rc = 0; switch (led_supported) { case TPACPI_LED_570: /* 570 */ if (unlikely(led > 7)) return -EINVAL; if (unlikely(tpacpi_is_led_restricted(led))) return -EPERM; if (!acpi_evalf(led_handle, NULL, NULL, "vdd", (1 << led), led_sled_arg1[ledstatus])) rc = -EIO; break; case TPACPI_LED_OLD: /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */ if (unlikely(led > 7)) return -EINVAL; if (unlikely(tpacpi_is_led_restricted(led))) return -EPERM; rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led)); if (rc >= 0) rc = ec_write(TPACPI_LED_EC_HLBL, (ledstatus == TPACPI_LED_BLINK) << led); if (rc >= 0) rc = ec_write(TPACPI_LED_EC_HLCL, (ledstatus != TPACPI_LED_OFF) << led); break; case TPACPI_LED_NEW: /* all others */ if (unlikely(led >= TPACPI_LED_NUMLEDS)) return -EINVAL; if (unlikely(tpacpi_is_led_restricted(led))) return -EPERM; if (!acpi_evalf(led_handle, NULL, NULL, "vdd", led, led_led_arg1[ledstatus])) rc = -EIO; break; default: rc = -ENXIO; } if (!rc) tpacpi_led_state_cache[led] = ledstatus; return rc; } static void led_set_status_worker(struct work_struct *work) { struct tpacpi_led_classdev *data = container_of(work, struct tpacpi_led_classdev, work); if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING)) led_set_status(data->led, data->new_state); } static void led_sysfs_set(struct led_classdev *led_cdev, enum led_brightness brightness) { struct tpacpi_led_classdev *data = container_of(led_cdev, struct tpacpi_led_classdev, led_classdev); if (brightness == LED_OFF) data->new_state = TPACPI_LED_OFF; else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK) data->new_state = TPACPI_LED_ON; else data->new_state = TPACPI_LED_BLINK; queue_work(tpacpi_wq, &data->work); } static int led_sysfs_blink_set(struct led_classdev *led_cdev, unsigned long *delay_on, unsigned long *delay_off) { struct tpacpi_led_classdev *data = container_of(led_cdev, struct tpacpi_led_classdev, led_classdev); /* Can we choose the flash rate? */ if (*delay_on == 0 && *delay_off == 0) { /* yes. set them to the hardware blink rate (1 Hz) */ *delay_on = 500; /* ms */ *delay_off = 500; /* ms */ } else if ((*delay_on != 500) || (*delay_off != 500)) return -EINVAL; data->new_state = TPACPI_LED_BLINK; queue_work(tpacpi_wq, &data->work); return 0; } static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev) { int rc; struct tpacpi_led_classdev *data = container_of(led_cdev, struct tpacpi_led_classdev, led_classdev); rc = led_get_status(data->led); if (rc == TPACPI_LED_OFF || rc < 0) rc = LED_OFF; /* no error handling in led class :( */ else rc = LED_FULL; return rc; } static void led_exit(void) { unsigned int i; for (i = 0; i < TPACPI_LED_NUMLEDS; i++) { if (tpacpi_leds[i].led_classdev.name) led_classdev_unregister(&tpacpi_leds[i].led_classdev); } kfree(tpacpi_leds); } static int __init tpacpi_init_led(unsigned int led) { int rc; tpacpi_leds[led].led = led; /* LEDs with no name don't get registered */ if (!tpacpi_led_names[led]) return 0; tpacpi_leds[led].led_classdev.brightness_set = &led_sysfs_set; tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set; if (led_supported == TPACPI_LED_570) tpacpi_leds[led].led_classdev.brightness_get = &led_sysfs_get; tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led]; INIT_WORK(&tpacpi_leds[led].work, led_set_status_worker); rc = led_classdev_register(&tpacpi_pdev->dev, &tpacpi_leds[led].led_classdev); if (rc < 0) tpacpi_leds[led].led_classdev.name = NULL; return rc; } static const struct tpacpi_quirk led_useful_qtable[] __initconst = { TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */ TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */ TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */ TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */ TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */ TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */ TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */ TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */ TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */ TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */ TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */ TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */ TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */ TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */ TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */ TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */ TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */ TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */ TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */ TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */ /* (1) - may have excess leds enabled on MSB */ /* Defaults (order matters, keep last, don't reorder!) */ { /* Lenovo */ .vendor = PCI_VENDOR_ID_LENOVO, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY, .quirks = 0x1fffU, }, { /* IBM ThinkPads with no EC version string */ .vendor = PCI_VENDOR_ID_IBM, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN, .quirks = 0x00ffU, }, { /* IBM ThinkPads with EC version string */ .vendor = PCI_VENDOR_ID_IBM, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY, .quirks = 0x00bfU, }, }; #undef TPACPI_LEDQ_IBM #undef TPACPI_LEDQ_LNV static enum led_access_mode __init led_init_detect_mode(void) { acpi_status status; if (tpacpi_is_ibm()) { /* 570 */ status = acpi_get_handle(ec_handle, "SLED", &led_handle); if (ACPI_SUCCESS(status)) return TPACPI_LED_570; /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */ status = acpi_get_handle(ec_handle, "SYSL", &led_handle); if (ACPI_SUCCESS(status)) return TPACPI_LED_OLD; } /* most others */ status = acpi_get_handle(ec_handle, "LED", &led_handle); if (ACPI_SUCCESS(status)) return TPACPI_LED_NEW; /* R30, R31, and unknown firmwares */ led_handle = NULL; return TPACPI_LED_NONE; } static int __init led_init(struct ibm_init_struct *iibm) { unsigned int i; int rc; unsigned long useful_leds; vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n"); led_supported = led_init_detect_mode(); vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n", str_supported(led_supported), led_supported); if (led_supported == TPACPI_LED_NONE) return 1; tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS, GFP_KERNEL); if (!tpacpi_leds) { pr_err("Out of memory for LED data\n"); return -ENOMEM; } useful_leds = tpacpi_check_quirks(led_useful_qtable, ARRAY_SIZE(led_useful_qtable)); for (i = 0; i < TPACPI_LED_NUMLEDS; i++) { if (!tpacpi_is_led_restricted(i) && test_bit(i, &useful_leds)) { rc = tpacpi_init_led(i); if (rc < 0) { led_exit(); return rc; } } } #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS pr_notice("warning: userspace override of important " "firmware LEDs is enabled\n"); #endif return 0; } #define str_led_status(s) \ ((s) == TPACPI_LED_OFF ? "off" : \ ((s) == TPACPI_LED_ON ? "on" : "blinking")) static int led_read(struct seq_file *m) { if (!led_supported) { seq_printf(m, "status:\t\tnot supported\n"); return 0; } seq_printf(m, "status:\t\tsupported\n"); if (led_supported == TPACPI_LED_570) { /* 570 */ int i, status; for (i = 0; i < 8; i++) { status = led_get_status(i); if (status < 0) return -EIO; seq_printf(m, "%d:\t\t%s\n", i, str_led_status(status)); } } seq_printf(m, "commands:\t" "<led> on, <led> off, <led> blink (<led> is 0-15)\n"); return 0; } static int led_write(char *buf) { char *cmd; int led, rc; enum led_status_t s; if (!led_supported) return -ENODEV; while ((cmd = next_cmd(&buf))) { if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 15) return -EINVAL; if (strstr(cmd, "off")) { s = TPACPI_LED_OFF; } else if (strstr(cmd, "on")) { s = TPACPI_LED_ON; } else if (strstr(cmd, "blink")) { s = TPACPI_LED_BLINK; } else { return -EINVAL; } rc = led_set_status(led, s); if (rc < 0) return rc; } return 0; } static struct ibm_struct led_driver_data = { .name = "led", .read = led_read, .write = led_write, .exit = led_exit, }; /************************************************************************* * Beep subdriver */ TPACPI_HANDLE(beep, ec, "BEEP"); /* all except R30, R31 */ #define TPACPI_BEEP_Q1 0x0001 static const struct tpacpi_quirk beep_quirk_table[] __initconst = { TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */ TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */ }; static int __init beep_init(struct ibm_init_struct *iibm) { unsigned long quirks; vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n"); TPACPI_ACPIHANDLE_INIT(beep); vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n", str_supported(beep_handle != NULL)); quirks = tpacpi_check_quirks(beep_quirk_table, ARRAY_SIZE(beep_quirk_table)); tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1); return (beep_handle)? 0 : 1; } static int beep_read(struct seq_file *m) { if (!beep_handle) seq_printf(m, "status:\t\tnot supported\n"); else { seq_printf(m, "status:\t\tsupported\n"); seq_printf(m, "commands:\t<cmd> (<cmd> is 0-17)\n"); } return 0; } static int beep_write(char *buf) { char *cmd; int beep_cmd; if (!beep_handle) return -ENODEV; while ((cmd = next_cmd(&buf))) { if (sscanf(cmd, "%u", &beep_cmd) == 1 && beep_cmd >= 0 && beep_cmd <= 17) { /* beep_cmd set */ } else return -EINVAL; if (tp_features.beep_needs_two_args) { if (!acpi_evalf(beep_handle, NULL, NULL, "vdd", beep_cmd, 0)) return -EIO; } else { if (!acpi_evalf(beep_handle, NULL, NULL, "vd", beep_cmd)) return -EIO; } } return 0; } static struct ibm_struct beep_driver_data = { .name = "beep", .read = beep_read, .write = beep_write, }; /************************************************************************* * Thermal subdriver */ enum thermal_access_mode { TPACPI_THERMAL_NONE = 0, /* No thermal support */ TPACPI_THERMAL_ACPI_TMP07, /* Use ACPI TMP0-7 */ TPACPI_THERMAL_ACPI_UPDT, /* Use ACPI TMP0-7 with UPDT */ TPACPI_THERMAL_TPEC_8, /* Use ACPI EC regs, 8 sensors */ TPACPI_THERMAL_TPEC_16, /* Use ACPI EC regs, 16 sensors */ }; enum { /* TPACPI_THERMAL_TPEC_* */ TP_EC_THERMAL_TMP0 = 0x78, /* ACPI EC regs TMP 0..7 */ TP_EC_THERMAL_TMP8 = 0xC0, /* ACPI EC regs TMP 8..15 */ TP_EC_THERMAL_TMP_NA = -128, /* ACPI EC sensor not available */ TPACPI_THERMAL_SENSOR_NA = -128000, /* Sensor not available */ }; #define TPACPI_MAX_THERMAL_SENSORS 16 /* Max thermal sensors supported */ struct ibm_thermal_sensors_struct { s32 temp[TPACPI_MAX_THERMAL_SENSORS]; }; static enum thermal_access_mode thermal_read_mode; /* idx is zero-based */ static int thermal_get_sensor(int idx, s32 *value) { int t; s8 tmp; char tmpi[5]; t = TP_EC_THERMAL_TMP0; switch (thermal_read_mode) { #if TPACPI_MAX_THERMAL_SENSORS >= 16 case TPACPI_THERMAL_TPEC_16: if (idx >= 8 && idx <= 15) { t = TP_EC_THERMAL_TMP8; idx -= 8; } /* fallthrough */ #endif case TPACPI_THERMAL_TPEC_8: if (idx <= 7) { if (!acpi_ec_read(t + idx, &tmp)) return -EIO; *value = tmp * 1000; return 0; } break; case TPACPI_THERMAL_ACPI_UPDT: if (idx <= 7) { snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx); if (!acpi_evalf(ec_handle, NULL, "UPDT", "v")) return -EIO; if (!acpi_evalf(ec_handle, &t, tmpi, "d")) return -EIO; *value = (t - 2732) * 100; return 0; } break; case TPACPI_THERMAL_ACPI_TMP07: if (idx <= 7) { snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx); if (!acpi_evalf(ec_handle, &t, tmpi, "d")) return -EIO; if (t > 127 || t < -127) t = TP_EC_THERMAL_TMP_NA; *value = t * 1000; return 0; } break; case TPACPI_THERMAL_NONE: default: return -ENOSYS; } return -EINVAL; } static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s) { int res, i; int n; n = 8; i = 0; if (!s) return -EINVAL; if (thermal_read_mode == TPACPI_THERMAL_TPEC_16) n = 16; for (i = 0 ; i < n; i++) { res = thermal_get_sensor(i, &s->temp[i]); if (res) return res; } return n; } static void thermal_dump_all_sensors(void) { int n, i; struct ibm_thermal_sensors_struct t; n = thermal_get_sensors(&t); if (n <= 0) return; pr_notice("temperatures (Celsius):"); for (i = 0; i < n; i++) { if (t.temp[i] != TPACPI_THERMAL_SENSOR_NA) pr_cont(" %d", (int)(t.temp[i] / 1000)); else pr_cont(" N/A"); } pr_cont("\n"); } /* sysfs temp##_input -------------------------------------------------- */ static ssize_t thermal_temp_input_show(struct device *dev, struct device_attribute *attr, char *buf) { struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr); int idx = sensor_attr->index; s32 value; int res; res = thermal_get_sensor(idx, &value); if (res) return res; if (value == TPACPI_THERMAL_SENSOR_NA) return -ENXIO; return snprintf(buf, PAGE_SIZE, "%d\n", value); } #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \ SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \ thermal_temp_input_show, NULL, _idxB) static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = { THERMAL_SENSOR_ATTR_TEMP(1, 0), THERMAL_SENSOR_ATTR_TEMP(2, 1), THERMAL_SENSOR_ATTR_TEMP(3, 2), THERMAL_SENSOR_ATTR_TEMP(4, 3), THERMAL_SENSOR_ATTR_TEMP(5, 4), THERMAL_SENSOR_ATTR_TEMP(6, 5), THERMAL_SENSOR_ATTR_TEMP(7, 6), THERMAL_SENSOR_ATTR_TEMP(8, 7), THERMAL_SENSOR_ATTR_TEMP(9, 8), THERMAL_SENSOR_ATTR_TEMP(10, 9), THERMAL_SENSOR_ATTR_TEMP(11, 10), THERMAL_SENSOR_ATTR_TEMP(12, 11), THERMAL_SENSOR_ATTR_TEMP(13, 12), THERMAL_SENSOR_ATTR_TEMP(14, 13), THERMAL_SENSOR_ATTR_TEMP(15, 14), THERMAL_SENSOR_ATTR_TEMP(16, 15), }; #define THERMAL_ATTRS(X) \ &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr static struct attribute *thermal_temp_input_attr[] = { THERMAL_ATTRS(8), THERMAL_ATTRS(9), THERMAL_ATTRS(10), THERMAL_ATTRS(11), THERMAL_ATTRS(12), THERMAL_ATTRS(13), THERMAL_ATTRS(14), THERMAL_ATTRS(15), THERMAL_ATTRS(0), THERMAL_ATTRS(1), THERMAL_ATTRS(2), THERMAL_ATTRS(3), THERMAL_ATTRS(4), THERMAL_ATTRS(5), THERMAL_ATTRS(6), THERMAL_ATTRS(7), NULL }; static const struct attribute_group thermal_temp_input16_group = { .attrs = thermal_temp_input_attr }; static const struct attribute_group thermal_temp_input8_group = { .attrs = &thermal_temp_input_attr[8] }; #undef THERMAL_SENSOR_ATTR_TEMP #undef THERMAL_ATTRS /* --------------------------------------------------------------------- */ static int __init thermal_init(struct ibm_init_struct *iibm) { u8 t, ta1, ta2; int i; int acpi_tmp7; int res; vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n"); acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv"); if (thinkpad_id.ec_model) { /* * Direct EC access mode: sensors at registers * 0x78-0x7F, 0xC0-0xC7. Registers return 0x00 for * non-implemented, thermal sensors return 0x80 when * not available */ ta1 = ta2 = 0; for (i = 0; i < 8; i++) { if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) { ta1 |= t; } else { ta1 = 0; break; } if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) { ta2 |= t; } else { ta1 = 0; break; } } if (ta1 == 0) { /* This is sheer paranoia, but we handle it anyway */ if (acpi_tmp7) { pr_err("ThinkPad ACPI EC access misbehaving, " "falling back to ACPI TMPx access " "mode\n"); thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07; } else { pr_err("ThinkPad ACPI EC access misbehaving, " "disabling thermal sensors access\n"); thermal_read_mode = TPACPI_THERMAL_NONE; } } else { thermal_read_mode = (ta2 != 0) ? TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8; } } else if (acpi_tmp7) { if (tpacpi_is_ibm() && acpi_evalf(ec_handle, NULL, "UPDT", "qv")) { /* 600e/x, 770e, 770x */ thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT; } else { /* IBM/LENOVO DSDT EC.TMPx access, max 8 sensors */ thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07; } } else { /* temperatures not supported on 570, G4x, R30, R31, R32 */ thermal_read_mode = TPACPI_THERMAL_NONE; } vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n", str_supported(thermal_read_mode != TPACPI_THERMAL_NONE), thermal_read_mode); switch (thermal_read_mode) { case TPACPI_THERMAL_TPEC_16: res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj, &thermal_temp_input16_group); if (res) return res; break; case TPACPI_THERMAL_TPEC_8: case TPACPI_THERMAL_ACPI_TMP07: case TPACPI_THERMAL_ACPI_UPDT: res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj, &thermal_temp_input8_group); if (res) return res; break; case TPACPI_THERMAL_NONE: default: return 1; } return 0; } static void thermal_exit(void) { switch (thermal_read_mode) { case TPACPI_THERMAL_TPEC_16: sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &thermal_temp_input16_group); break; case TPACPI_THERMAL_TPEC_8: case TPACPI_THERMAL_ACPI_TMP07: case TPACPI_THERMAL_ACPI_UPDT: sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &thermal_temp_input8_group); break; case TPACPI_THERMAL_NONE: default: break; } } static int thermal_read(struct seq_file *m) { int n, i; struct ibm_thermal_sensors_struct t; n = thermal_get_sensors(&t); if (unlikely(n < 0)) return n; seq_printf(m, "temperatures:\t"); if (n > 0) { for (i = 0; i < (n - 1); i++) seq_printf(m, "%d ", t.temp[i] / 1000); seq_printf(m, "%d\n", t.temp[i] / 1000); } else seq_printf(m, "not supported\n"); return 0; } static struct ibm_struct thermal_driver_data = { .name = "thermal", .read = thermal_read, .exit = thermal_exit, }; /************************************************************************* * Backlight/brightness subdriver */ #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen" /* * ThinkPads can read brightness from two places: EC HBRV (0x31), or * CMOS NVRAM byte 0x5E, bits 0-3. * * EC HBRV (0x31) has the following layout * Bit 7: unknown function * Bit 6: unknown function * Bit 5: Z: honour scale changes, NZ: ignore scale changes * Bit 4: must be set to zero to avoid problems * Bit 3-0: backlight brightness level * * brightness_get_raw returns status data in the HBRV layout * * WARNING: The X61 has been verified to use HBRV for something else, so * this should be used _only_ on IBM ThinkPads, and maybe with some careful * testing on the very early *60 Lenovo models... */ enum { TP_EC_BACKLIGHT = 0x31, /* TP_EC_BACKLIGHT bitmasks */ TP_EC_BACKLIGHT_LVLMSK = 0x1F, TP_EC_BACKLIGHT_CMDMSK = 0xE0, TP_EC_BACKLIGHT_MAPSW = 0x20, }; enum tpacpi_brightness_access_mode { TPACPI_BRGHT_MODE_AUTO = 0, /* Not implemented yet */ TPACPI_BRGHT_MODE_EC, /* EC control */ TPACPI_BRGHT_MODE_UCMS_STEP, /* UCMS step-based control */ TPACPI_BRGHT_MODE_ECNVRAM, /* EC control w/ NVRAM store */ TPACPI_BRGHT_MODE_MAX }; static struct backlight_device *ibm_backlight_device; static enum tpacpi_brightness_access_mode brightness_mode = TPACPI_BRGHT_MODE_MAX; static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */ static struct mutex brightness_mutex; /* NVRAM brightness access, * call with brightness_mutex held! */ static unsigned int tpacpi_brightness_nvram_get(void) { u8 lnvram; lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS) & TP_NVRAM_MASK_LEVEL_BRIGHTNESS) >> TP_NVRAM_POS_LEVEL_BRIGHTNESS; lnvram &= bright_maxlvl; return lnvram; } static void tpacpi_brightness_checkpoint_nvram(void) { u8 lec = 0; u8 b_nvram; if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM) return; vdbg_printk(TPACPI_DBG_BRGHT, "trying to checkpoint backlight level to NVRAM...\n"); if (mutex_lock_killable(&brightness_mutex) < 0) return; if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec))) goto unlock; lec &= TP_EC_BACKLIGHT_LVLMSK; b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS); if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS) >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) { /* NVRAM needs update */ b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS << TP_NVRAM_POS_LEVEL_BRIGHTNESS); b_nvram |= lec; nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS); dbg_printk(TPACPI_DBG_BRGHT, "updated NVRAM backlight level to %u (0x%02x)\n", (unsigned int) lec, (unsigned int) b_nvram); } else vdbg_printk(TPACPI_DBG_BRGHT, "NVRAM backlight level already is %u (0x%02x)\n", (unsigned int) lec, (unsigned int) b_nvram); unlock: mutex_unlock(&brightness_mutex); } /* call with brightness_mutex held! */ static int tpacpi_brightness_get_raw(int *status) { u8 lec = 0; switch (brightness_mode) { case TPACPI_BRGHT_MODE_UCMS_STEP: *status = tpacpi_brightness_nvram_get(); return 0; case TPACPI_BRGHT_MODE_EC: case TPACPI_BRGHT_MODE_ECNVRAM: if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec))) return -EIO; *status = lec; return 0; default: return -ENXIO; } } /* call with brightness_mutex held! */ /* do NOT call with illegal backlight level value */ static int tpacpi_brightness_set_ec(unsigned int value) { u8 lec = 0; if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec))) return -EIO; if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT, (lec & TP_EC_BACKLIGHT_CMDMSK) | (value & TP_EC_BACKLIGHT_LVLMSK)))) return -EIO; return 0; } /* call with brightness_mutex held! */ static int tpacpi_brightness_set_ucmsstep(unsigned int value) { int cmos_cmd, inc; unsigned int current_value, i; current_value = tpacpi_brightness_nvram_get(); if (value == current_value) return 0; cmos_cmd = (value > current_value) ? TP_CMOS_BRIGHTNESS_UP : TP_CMOS_BRIGHTNESS_DOWN; inc = (value > current_value) ? 1 : -1; for (i = current_value; i != value; i += inc) if (issue_thinkpad_cmos_command(cmos_cmd)) return -EIO; return 0; } /* May return EINTR which can always be mapped to ERESTARTSYS */ static int brightness_set(unsigned int value) { int res; if (value > bright_maxlvl || value < 0) return -EINVAL; vdbg_printk(TPACPI_DBG_BRGHT, "set backlight level to %d\n", value); res = mutex_lock_killable(&brightness_mutex); if (res < 0) return res; switch (brightness_mode) { case TPACPI_BRGHT_MODE_EC: case TPACPI_BRGHT_MODE_ECNVRAM: res = tpacpi_brightness_set_ec(value); break; case TPACPI_BRGHT_MODE_UCMS_STEP: res = tpacpi_brightness_set_ucmsstep(value); break; default: res = -ENXIO; } mutex_unlock(&brightness_mutex); return res; } /* sysfs backlight class ----------------------------------------------- */ static int brightness_update_status(struct backlight_device *bd) { unsigned int level = (bd->props.fb_blank == FB_BLANK_UNBLANK && bd->props.power == FB_BLANK_UNBLANK) ? bd->props.brightness : 0; dbg_printk(TPACPI_DBG_BRGHT, "backlight: attempt to set level to %d\n", level); /* it is the backlight class's job (caller) to handle * EINTR and other errors properly */ return brightness_set(level); } static int brightness_get(struct backlight_device *bd) { int status, res; res = mutex_lock_killable(&brightness_mutex); if (res < 0) return 0; res = tpacpi_brightness_get_raw(&status); mutex_unlock(&brightness_mutex); if (res < 0) return 0; return status & TP_EC_BACKLIGHT_LVLMSK; } static void tpacpi_brightness_notify_change(void) { backlight_force_update(ibm_backlight_device, BACKLIGHT_UPDATE_HOTKEY); } static const struct backlight_ops ibm_backlight_data = { .get_brightness = brightness_get, .update_status = brightness_update_status, }; /* --------------------------------------------------------------------- */ /* * Call _BCL method of video device. On some ThinkPads this will * switch the firmware to the ACPI brightness control mode. */ static int __init tpacpi_query_bcl_levels(acpi_handle handle) { struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; union acpi_object *obj; int rc; if (ACPI_SUCCESS(acpi_evaluate_object(handle, "_BCL", NULL, &buffer))) { obj = (union acpi_object *)buffer.pointer; if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) { pr_err("Unknown _BCL data, please report this to %s\n", TPACPI_MAIL); rc = 0; } else { rc = obj->package.count; } } else { return 0; } kfree(buffer.pointer); return rc; } /* * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map */ static unsigned int __init tpacpi_check_std_acpi_brightness_support(void) { acpi_handle video_device; int bcl_levels = 0; tpacpi_acpi_handle_locate("video", ACPI_VIDEO_HID, &video_device); if (video_device) bcl_levels = tpacpi_query_bcl_levels(video_device); tp_features.bright_acpimode = (bcl_levels > 0); return (bcl_levels > 2) ? (bcl_levels - 2) : 0; } /* * These are only useful for models that have only one possibility * of GPU. If the BIOS model handles both ATI and Intel, don't use * these quirks. */ #define TPACPI_BRGHT_Q_NOEC 0x0001 /* Must NOT use EC HBRV */ #define TPACPI_BRGHT_Q_EC 0x0002 /* Should or must use EC HBRV */ #define TPACPI_BRGHT_Q_ASK 0x8000 /* Ask for user report */ static const struct tpacpi_quirk brightness_quirk_table[] __initconst = { /* Models with ATI GPUs known to require ECNVRAM mode */ TPACPI_Q_IBM('1', 'Y', TPACPI_BRGHT_Q_EC), /* T43/p ATI */ /* Models with ATI GPUs that can use ECNVRAM */ TPACPI_Q_IBM('1', 'R', TPACPI_BRGHT_Q_EC), /* R50,51 T40-42 */ TPACPI_Q_IBM('1', 'Q', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC), TPACPI_Q_IBM('7', '6', TPACPI_BRGHT_Q_EC), /* R52 */ TPACPI_Q_IBM('7', '8', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC), /* Models with Intel Extreme Graphics 2 */ TPACPI_Q_IBM('1', 'U', TPACPI_BRGHT_Q_NOEC), /* X40 */ TPACPI_Q_IBM('1', 'V', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC), TPACPI_Q_IBM('1', 'W', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC), /* Models with Intel GMA900 */ TPACPI_Q_IBM('7', '0', TPACPI_BRGHT_Q_NOEC), /* T43, R52 */ TPACPI_Q_IBM('7', '4', TPACPI_BRGHT_Q_NOEC), /* X41 */ TPACPI_Q_IBM('7', '5', TPACPI_BRGHT_Q_NOEC), /* X41 Tablet */ }; /* * Returns < 0 for error, otherwise sets tp_features.bright_* * and bright_maxlvl. */ static void __init tpacpi_detect_brightness_capabilities(void) { unsigned int b; vdbg_printk(TPACPI_DBG_INIT, "detecting firmware brightness interface capabilities\n"); /* we could run a quirks check here (same table used by * brightness_init) if needed */ /* * We always attempt to detect acpi support, so as to switch * Lenovo Vista BIOS to ACPI brightness mode even if we are not * going to publish a backlight interface */ b = tpacpi_check_std_acpi_brightness_support(); switch (b) { case 16: bright_maxlvl = 15; pr_info("detected a 16-level brightness capable ThinkPad\n"); break; case 8: case 0: bright_maxlvl = 7; pr_info("detected a 8-level brightness capable ThinkPad\n"); break; default: pr_err("Unsupported brightness interface, " "please contact %s\n", TPACPI_MAIL); tp_features.bright_unkfw = 1; bright_maxlvl = b - 1; } } static int __init brightness_init(struct ibm_init_struct *iibm) { struct backlight_properties props; int b; unsigned long quirks; vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n"); mutex_init(&brightness_mutex); quirks = tpacpi_check_quirks(brightness_quirk_table, ARRAY_SIZE(brightness_quirk_table)); /* tpacpi_detect_brightness_capabilities() must have run already */ /* if it is unknown, we don't handle it: it wouldn't be safe */ if (tp_features.bright_unkfw) return 1; if (!brightness_enable) { dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT, "brightness support disabled by " "module parameter\n"); return 1; } if (acpi_video_backlight_support()) { if (brightness_enable > 1) { pr_info("Standard ACPI backlight interface " "available, not loading native one\n"); return 1; } else if (brightness_enable == 1) { pr_warn("Cannot enable backlight brightness support, " "ACPI is already handling it. Refer to the " "acpi_backlight kernel parameter.\n"); return 1; } } else if (tp_features.bright_acpimode && brightness_enable > 1) { pr_notice("Standard ACPI backlight interface not " "available, thinkpad_acpi native " "brightness control enabled\n"); } /* * Check for module parameter bogosity, note that we * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be * able to detect "unspecified" */ if (brightness_mode > TPACPI_BRGHT_MODE_MAX) return -EINVAL; /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */ if (brightness_mode == TPACPI_BRGHT_MODE_AUTO || brightness_mode == TPACPI_BRGHT_MODE_MAX) { if (quirks & TPACPI_BRGHT_Q_EC) brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM; else brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP; dbg_printk(TPACPI_DBG_BRGHT, "driver auto-selected brightness_mode=%d\n", brightness_mode); } /* Safety */ if (!tpacpi_is_ibm() && (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM || brightness_mode == TPACPI_BRGHT_MODE_EC)) return -EINVAL; if (tpacpi_brightness_get_raw(&b) < 0) return 1; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_PLATFORM; props.max_brightness = bright_maxlvl; props.brightness = b & TP_EC_BACKLIGHT_LVLMSK; ibm_backlight_device = backlight_device_register(TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL, &ibm_backlight_data, &props); if (IS_ERR(ibm_backlight_device)) { int rc = PTR_ERR(ibm_backlight_device); ibm_backlight_device = NULL; pr_err("Could not register backlight device\n"); return rc; } vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT, "brightness is supported\n"); if (quirks & TPACPI_BRGHT_Q_ASK) { pr_notice("brightness: will use unverified default: " "brightness_mode=%d\n", brightness_mode); pr_notice("brightness: please report to %s whether it works well " "or not on your ThinkPad\n", TPACPI_MAIL); } /* Added by mistake in early 2007. Probably useless, but it could * be working around some unknown firmware problem where the value * read at startup doesn't match the real hardware state... so leave * it in place just in case */ backlight_update_status(ibm_backlight_device); vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT, "brightness: registering brightness hotkeys " "as change notification\n"); tpacpi_hotkey_driver_mask_set(hotkey_driver_mask | TP_ACPI_HKEY_BRGHTUP_MASK | TP_ACPI_HKEY_BRGHTDWN_MASK); return 0; } static void brightness_suspend(pm_message_t state) { tpacpi_brightness_checkpoint_nvram(); } static void brightness_shutdown(void) { tpacpi_brightness_checkpoint_nvram(); } static void brightness_exit(void) { if (ibm_backlight_device) { vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT, "calling backlight_device_unregister()\n"); backlight_device_unregister(ibm_backlight_device); } tpacpi_brightness_checkpoint_nvram(); } static int brightness_read(struct seq_file *m) { int level; level = brightness_get(NULL); if (level < 0) { seq_printf(m, "level:\t\tunreadable\n"); } else { seq_printf(m, "level:\t\t%d\n", level); seq_printf(m, "commands:\tup, down\n"); seq_printf(m, "commands:\tlevel <level> (<level> is 0-%d)\n", bright_maxlvl); } return 0; } static int brightness_write(char *buf) { int level; int rc; char *cmd; level = brightness_get(NULL); if (level < 0) return level; while ((cmd = next_cmd(&buf))) { if (strlencmp(cmd, "up") == 0) { if (level < bright_maxlvl) level++; } else if (strlencmp(cmd, "down") == 0) { if (level > 0) level--; } else if (sscanf(cmd, "level %d", &level) == 1 && level >= 0 && level <= bright_maxlvl) { /* new level set */ } else return -EINVAL; } tpacpi_disclose_usertask("procfs brightness", "set level to %d\n", level); /* * Now we know what the final level should be, so we try to set it. * Doing it this way makes the syscall restartable in case of EINTR */ rc = brightness_set(level); if (!rc && ibm_backlight_device) backlight_force_update(ibm_backlight_device, BACKLIGHT_UPDATE_SYSFS); return (rc == -EINTR)? -ERESTARTSYS : rc; } static struct ibm_struct brightness_driver_data = { .name = "brightness", .read = brightness_read, .write = brightness_write, .exit = brightness_exit, .suspend = brightness_suspend, .shutdown = brightness_shutdown, }; /************************************************************************* * Volume subdriver */ /* * IBM ThinkPads have a simple volume controller with MUTE gating. * Very early Lenovo ThinkPads follow the IBM ThinkPad spec. * * Since the *61 series (and probably also the later *60 series), Lenovo * ThinkPads only implement the MUTE gate. * * EC register 0x30 * Bit 6: MUTE (1 mutes sound) * Bit 3-0: Volume * Other bits should be zero as far as we know. * * This is also stored in CMOS NVRAM, byte 0x60, bit 6 (MUTE), and * bits 3-0 (volume). Other bits in NVRAM may have other functions, * such as bit 7 which is used to detect repeated presses of MUTE, * and we leave them unchanged. */ #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT #define TPACPI_ALSA_DRVNAME "ThinkPad EC" #define TPACPI_ALSA_SHRTNAME "ThinkPad Console Audio Control" #define TPACPI_ALSA_MIXERNAME TPACPI_ALSA_SHRTNAME static int alsa_index = ~((1 << (SNDRV_CARDS - 3)) - 1); /* last three slots */ static char *alsa_id = "ThinkPadEC"; static int alsa_enable = SNDRV_DEFAULT_ENABLE1; struct tpacpi_alsa_data { struct snd_card *card; struct snd_ctl_elem_id *ctl_mute_id; struct snd_ctl_elem_id *ctl_vol_id; }; static struct snd_card *alsa_card; enum { TP_EC_AUDIO = 0x30, /* TP_EC_AUDIO bits */ TP_EC_AUDIO_MUTESW = 6, /* TP_EC_AUDIO bitmasks */ TP_EC_AUDIO_LVL_MSK = 0x0F, TP_EC_AUDIO_MUTESW_MSK = (1 << TP_EC_AUDIO_MUTESW), /* Maximum volume */ TP_EC_VOLUME_MAX = 14, }; enum tpacpi_volume_access_mode { TPACPI_VOL_MODE_AUTO = 0, /* Not implemented yet */ TPACPI_VOL_MODE_EC, /* Pure EC control */ TPACPI_VOL_MODE_UCMS_STEP, /* UCMS step-based control: N/A */ TPACPI_VOL_MODE_ECNVRAM, /* EC control w/ NVRAM store */ TPACPI_VOL_MODE_MAX }; enum tpacpi_volume_capabilities { TPACPI_VOL_CAP_AUTO = 0, /* Use white/blacklist */ TPACPI_VOL_CAP_VOLMUTE, /* Output vol and mute */ TPACPI_VOL_CAP_MUTEONLY, /* Output mute only */ TPACPI_VOL_CAP_MAX }; static enum tpacpi_volume_access_mode volume_mode = TPACPI_VOL_MODE_MAX; static enum tpacpi_volume_capabilities volume_capabilities; static int volume_control_allowed; /* * Used to syncronize writers to TP_EC_AUDIO and * TP_NVRAM_ADDR_MIXER, as we need to do read-modify-write */ static struct mutex volume_mutex; static void tpacpi_volume_checkpoint_nvram(void) { u8 lec = 0; u8 b_nvram; u8 ec_mask; if (volume_mode != TPACPI_VOL_MODE_ECNVRAM) return; if (!volume_control_allowed) return; vdbg_printk(TPACPI_DBG_MIXER, "trying to checkpoint mixer state to NVRAM...\n"); if (tp_features.mixer_no_level_control) ec_mask = TP_EC_AUDIO_MUTESW_MSK; else ec_mask = TP_EC_AUDIO_MUTESW_MSK | TP_EC_AUDIO_LVL_MSK; if (mutex_lock_killable(&volume_mutex) < 0) return; if (unlikely(!acpi_ec_read(TP_EC_AUDIO, &lec))) goto unlock; lec &= ec_mask; b_nvram = nvram_read_byte(TP_NVRAM_ADDR_MIXER); if (lec != (b_nvram & ec_mask)) { /* NVRAM needs update */ b_nvram &= ~ec_mask; b_nvram |= lec; nvram_write_byte(b_nvram, TP_NVRAM_ADDR_MIXER); dbg_printk(TPACPI_DBG_MIXER, "updated NVRAM mixer status to 0x%02x (0x%02x)\n", (unsigned int) lec, (unsigned int) b_nvram); } else { vdbg_printk(TPACPI_DBG_MIXER, "NVRAM mixer status already is 0x%02x (0x%02x)\n", (unsigned int) lec, (unsigned int) b_nvram); } unlock: mutex_unlock(&volume_mutex); } static int volume_get_status_ec(u8 *status) { u8 s; if (!acpi_ec_read(TP_EC_AUDIO, &s)) return -EIO; *status = s; dbg_printk(TPACPI_DBG_MIXER, "status 0x%02x\n", s); return 0; } static int volume_get_status(u8 *status) { return volume_get_status_ec(status); } static int volume_set_status_ec(const u8 status) { if (!acpi_ec_write(TP_EC_AUDIO, status)) return -EIO; dbg_printk(TPACPI_DBG_MIXER, "set EC mixer to 0x%02x\n", status); return 0; } static int volume_set_status(const u8 status) { return volume_set_status_ec(status); } /* returns < 0 on error, 0 on no change, 1 on change */ static int __volume_set_mute_ec(const bool mute) { int rc; u8 s, n; if (mutex_lock_killable(&volume_mutex) < 0) return -EINTR; rc = volume_get_status_ec(&s); if (rc) goto unlock; n = (mute) ? s | TP_EC_AUDIO_MUTESW_MSK : s & ~TP_EC_AUDIO_MUTESW_MSK; if (n != s) { rc = volume_set_status_ec(n); if (!rc) rc = 1; } unlock: mutex_unlock(&volume_mutex); return rc; } static int volume_alsa_set_mute(const bool mute) { dbg_printk(TPACPI_DBG_MIXER, "ALSA: trying to %smute\n", (mute) ? "" : "un"); return __volume_set_mute_ec(mute); } static int volume_set_mute(const bool mute) { int rc; dbg_printk(TPACPI_DBG_MIXER, "trying to %smute\n", (mute) ? "" : "un"); rc = __volume_set_mute_ec(mute); return (rc < 0) ? rc : 0; } /* returns < 0 on error, 0 on no change, 1 on change */ static int __volume_set_volume_ec(const u8 vol) { int rc; u8 s, n; if (vol > TP_EC_VOLUME_MAX) return -EINVAL; if (mutex_lock_killable(&volume_mutex) < 0) return -EINTR; rc = volume_get_status_ec(&s); if (rc) goto unlock; n = (s & ~TP_EC_AUDIO_LVL_MSK) | vol; if (n != s) { rc = volume_set_status_ec(n); if (!rc) rc = 1; } unlock: mutex_unlock(&volume_mutex); return rc; } static int volume_alsa_set_volume(const u8 vol) { dbg_printk(TPACPI_DBG_MIXER, "ALSA: trying to set volume level to %hu\n", vol); return __volume_set_volume_ec(vol); } static void volume_alsa_notify_change(void) { struct tpacpi_alsa_data *d; if (alsa_card && alsa_card->private_data) { d = alsa_card->private_data; if (d->ctl_mute_id) snd_ctl_notify(alsa_card, SNDRV_CTL_EVENT_MASK_VALUE, d->ctl_mute_id); if (d->ctl_vol_id) snd_ctl_notify(alsa_card, SNDRV_CTL_EVENT_MASK_VALUE, d->ctl_vol_id); } } static int volume_alsa_vol_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = TP_EC_VOLUME_MAX; return 0; } static int volume_alsa_vol_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { u8 s; int rc; rc = volume_get_status(&s); if (rc < 0) return rc; ucontrol->value.integer.value[0] = s & TP_EC_AUDIO_LVL_MSK; return 0; } static int volume_alsa_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { tpacpi_disclose_usertask("ALSA", "set volume to %ld\n", ucontrol->value.integer.value[0]); return volume_alsa_set_volume(ucontrol->value.integer.value[0]); } #define volume_alsa_mute_info snd_ctl_boolean_mono_info static int volume_alsa_mute_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { u8 s; int rc; rc = volume_get_status(&s); if (rc < 0) return rc; ucontrol->value.integer.value[0] = (s & TP_EC_AUDIO_MUTESW_MSK) ? 0 : 1; return 0; } static int volume_alsa_mute_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { tpacpi_disclose_usertask("ALSA", "%smute\n", ucontrol->value.integer.value[0] ? "un" : ""); return volume_alsa_set_mute(!ucontrol->value.integer.value[0]); } static struct snd_kcontrol_new volume_alsa_control_vol __devinitdata = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Console Playback Volume", .index = 0, .access = SNDRV_CTL_ELEM_ACCESS_READ, .info = volume_alsa_vol_info, .get = volume_alsa_vol_get, }; static struct snd_kcontrol_new volume_alsa_control_mute __devinitdata = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Console Playback Switch", .index = 0, .access = SNDRV_CTL_ELEM_ACCESS_READ, .info = volume_alsa_mute_info, .get = volume_alsa_mute_get, }; static void volume_suspend(pm_message_t state) { tpacpi_volume_checkpoint_nvram(); } static void volume_resume(void) { volume_alsa_notify_change(); } static void volume_shutdown(void) { tpacpi_volume_checkpoint_nvram(); } static void volume_exit(void) { if (alsa_card) { snd_card_free(alsa_card); alsa_card = NULL; } tpacpi_volume_checkpoint_nvram(); } static int __init volume_create_alsa_mixer(void) { struct snd_card *card; struct tpacpi_alsa_data *data; struct snd_kcontrol *ctl_vol; struct snd_kcontrol *ctl_mute; int rc; rc = snd_card_create(alsa_index, alsa_id, THIS_MODULE, sizeof(struct tpacpi_alsa_data), &card); if (rc < 0 || !card) { pr_err("Failed to create ALSA card structures: %d\n", rc); return 1; } BUG_ON(!card->private_data); data = card->private_data; data->card = card; strlcpy(card->driver, TPACPI_ALSA_DRVNAME, sizeof(card->driver)); strlcpy(card->shortname, TPACPI_ALSA_SHRTNAME, sizeof(card->shortname)); snprintf(card->mixername, sizeof(card->mixername), "ThinkPad EC %s", (thinkpad_id.ec_version_str) ? thinkpad_id.ec_version_str : "(unknown)"); snprintf(card->longname, sizeof(card->longname), "%s at EC reg 0x%02x, fw %s", card->shortname, TP_EC_AUDIO, (thinkpad_id.ec_version_str) ? thinkpad_id.ec_version_str : "unknown"); if (volume_control_allowed) { volume_alsa_control_vol.put = volume_alsa_vol_put; volume_alsa_control_vol.access = SNDRV_CTL_ELEM_ACCESS_READWRITE; volume_alsa_control_mute.put = volume_alsa_mute_put; volume_alsa_control_mute.access = SNDRV_CTL_ELEM_ACCESS_READWRITE; } if (!tp_features.mixer_no_level_control) { ctl_vol = snd_ctl_new1(&volume_alsa_control_vol, NULL); rc = snd_ctl_add(card, ctl_vol); if (rc < 0) { pr_err("Failed to create ALSA volume control: %d\n", rc); goto err_exit; } data->ctl_vol_id = &ctl_vol->id; } ctl_mute = snd_ctl_new1(&volume_alsa_control_mute, NULL); rc = snd_ctl_add(card, ctl_mute); if (rc < 0) { pr_err("Failed to create ALSA mute control: %d\n", rc); goto err_exit; } data->ctl_mute_id = &ctl_mute->id; snd_card_set_dev(card, &tpacpi_pdev->dev); rc = snd_card_register(card); if (rc < 0) { pr_err("Failed to register ALSA card: %d\n", rc); goto err_exit; } alsa_card = card; return 0; err_exit: snd_card_free(card); return 1; } #define TPACPI_VOL_Q_MUTEONLY 0x0001 /* Mute-only control available */ #define TPACPI_VOL_Q_LEVEL 0x0002 /* Volume control available */ static const struct tpacpi_quirk volume_quirk_table[] __initconst = { /* Whitelist volume level on all IBM by default */ { .vendor = PCI_VENDOR_ID_IBM, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY, .quirks = TPACPI_VOL_Q_LEVEL }, /* Lenovo models with volume control (needs confirmation) */ TPACPI_QEC_LNV('7', 'C', TPACPI_VOL_Q_LEVEL), /* R60/i */ TPACPI_QEC_LNV('7', 'E', TPACPI_VOL_Q_LEVEL), /* R60e/i */ TPACPI_QEC_LNV('7', '9', TPACPI_VOL_Q_LEVEL), /* T60/p */ TPACPI_QEC_LNV('7', 'B', TPACPI_VOL_Q_LEVEL), /* X60/s */ TPACPI_QEC_LNV('7', 'J', TPACPI_VOL_Q_LEVEL), /* X60t */ TPACPI_QEC_LNV('7', '7', TPACPI_VOL_Q_LEVEL), /* Z60 */ TPACPI_QEC_LNV('7', 'F', TPACPI_VOL_Q_LEVEL), /* Z61 */ /* Whitelist mute-only on all Lenovo by default */ { .vendor = PCI_VENDOR_ID_LENOVO, .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY, .quirks = TPACPI_VOL_Q_MUTEONLY } }; static int __init volume_init(struct ibm_init_struct *iibm) { unsigned long quirks; int rc; vdbg_printk(TPACPI_DBG_INIT, "initializing volume subdriver\n"); mutex_init(&volume_mutex); /* * Check for module parameter bogosity, note that we * init volume_mode to TPACPI_VOL_MODE_MAX in order to be * able to detect "unspecified" */ if (volume_mode > TPACPI_VOL_MODE_MAX) return -EINVAL; if (volume_mode == TPACPI_VOL_MODE_UCMS_STEP) { pr_err("UCMS step volume mode not implemented, " "please contact %s\n", TPACPI_MAIL); return 1; } if (volume_capabilities >= TPACPI_VOL_CAP_MAX) return -EINVAL; /* * The ALSA mixer is our primary interface. * When disabled, don't install the subdriver at all */ if (!alsa_enable) { vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER, "ALSA mixer disabled by parameter, " "not loading volume subdriver...\n"); return 1; } quirks = tpacpi_check_quirks(volume_quirk_table, ARRAY_SIZE(volume_quirk_table)); switch (volume_capabilities) { case TPACPI_VOL_CAP_AUTO: if (quirks & TPACPI_VOL_Q_MUTEONLY) tp_features.mixer_no_level_control = 1; else if (quirks & TPACPI_VOL_Q_LEVEL) tp_features.mixer_no_level_control = 0; else return 1; /* no mixer */ break; case TPACPI_VOL_CAP_VOLMUTE: tp_features.mixer_no_level_control = 0; break; case TPACPI_VOL_CAP_MUTEONLY: tp_features.mixer_no_level_control = 1; break; default: return 1; } if (volume_capabilities != TPACPI_VOL_CAP_AUTO) dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER, "using user-supplied volume_capabilities=%d\n", volume_capabilities); if (volume_mode == TPACPI_VOL_MODE_AUTO || volume_mode == TPACPI_VOL_MODE_MAX) { volume_mode = TPACPI_VOL_MODE_ECNVRAM; dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER, "driver auto-selected volume_mode=%d\n", volume_mode); } else { dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER, "using user-supplied volume_mode=%d\n", volume_mode); } vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER, "mute is supported, volume control is %s\n", str_supported(!tp_features.mixer_no_level_control)); rc = volume_create_alsa_mixer(); if (rc) { pr_err("Could not create the ALSA mixer interface\n"); return rc; } pr_info("Console audio control enabled, mode: %s\n", (volume_control_allowed) ? "override (read/write)" : "monitor (read only)"); vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER, "registering volume hotkeys as change notification\n"); tpacpi_hotkey_driver_mask_set(hotkey_driver_mask | TP_ACPI_HKEY_VOLUP_MASK | TP_ACPI_HKEY_VOLDWN_MASK | TP_ACPI_HKEY_MUTE_MASK); return 0; } static int volume_read(struct seq_file *m) { u8 status; if (volume_get_status(&status) < 0) { seq_printf(m, "level:\t\tunreadable\n"); } else { if (tp_features.mixer_no_level_control) seq_printf(m, "level:\t\tunsupported\n"); else seq_printf(m, "level:\t\t%d\n", status & TP_EC_AUDIO_LVL_MSK); seq_printf(m, "mute:\t\t%s\n", onoff(status, TP_EC_AUDIO_MUTESW)); if (volume_control_allowed) { seq_printf(m, "commands:\tunmute, mute\n"); if (!tp_features.mixer_no_level_control) { seq_printf(m, "commands:\tup, down\n"); seq_printf(m, "commands:\tlevel <level>" " (<level> is 0-%d)\n", TP_EC_VOLUME_MAX); } } } return 0; } static int volume_write(char *buf) { u8 s; u8 new_level, new_mute; int l; char *cmd; int rc; /* * We do allow volume control at driver startup, so that the * user can set initial state through the volume=... parameter hack. */ if (!volume_control_allowed && tpacpi_lifecycle != TPACPI_LIFE_INIT) { if (unlikely(!tp_warned.volume_ctrl_forbidden)) { tp_warned.volume_ctrl_forbidden = 1; pr_notice("Console audio control in monitor mode, " "changes are not allowed\n"); pr_notice("Use the volume_control=1 module parameter " "to enable volume control\n"); } return -EPERM; } rc = volume_get_status(&s); if (rc < 0) return rc; new_level = s & TP_EC_AUDIO_LVL_MSK; new_mute = s & TP_EC_AUDIO_MUTESW_MSK; while ((cmd = next_cmd(&buf))) { if (!tp_features.mixer_no_level_control) { if (strlencmp(cmd, "up") == 0) { if (new_mute) new_mute = 0; else if (new_level < TP_EC_VOLUME_MAX) new_level++; continue; } else if (strlencmp(cmd, "down") == 0) { if (new_mute) new_mute = 0; else if (new_level > 0) new_level--; continue; } else if (sscanf(cmd, "level %u", &l) == 1 && l >= 0 && l <= TP_EC_VOLUME_MAX) { new_level = l; continue; } } if (strlencmp(cmd, "mute") == 0) new_mute = TP_EC_AUDIO_MUTESW_MSK; else if (strlencmp(cmd, "unmute") == 0) new_mute = 0; else return -EINVAL; } if (tp_features.mixer_no_level_control) { tpacpi_disclose_usertask("procfs volume", "%smute\n", new_mute ? "" : "un"); rc = volume_set_mute(!!new_mute); } else { tpacpi_disclose_usertask("procfs volume", "%smute and set level to %d\n", new_mute ? "" : "un", new_level); rc = volume_set_status(new_mute | new_level); } volume_alsa_notify_change(); return (rc == -EINTR) ? -ERESTARTSYS : rc; } static struct ibm_struct volume_driver_data = { .name = "volume", .read = volume_read, .write = volume_write, .exit = volume_exit, .suspend = volume_suspend, .resume = volume_resume, .shutdown = volume_shutdown, }; #else /* !CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */ #define alsa_card NULL static void inline volume_alsa_notify_change(void) { } static int __init volume_init(struct ibm_init_struct *iibm) { pr_info("volume: disabled as there is no ALSA support in this kernel\n"); return 1; } static struct ibm_struct volume_driver_data = { .name = "volume", }; #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */ /************************************************************************* * Fan subdriver */ /* * FAN ACCESS MODES * * TPACPI_FAN_RD_ACPI_GFAN: * ACPI GFAN method: returns fan level * * see TPACPI_FAN_WR_ACPI_SFAN * EC 0x2f (HFSP) not available if GFAN exists * * TPACPI_FAN_WR_ACPI_SFAN: * ACPI SFAN method: sets fan level, 0 (stop) to 7 (max) * * EC 0x2f (HFSP) might be available *for reading*, but do not use * it for writing. * * TPACPI_FAN_WR_TPEC: * ThinkPad EC register 0x2f (HFSP): fan control loop mode * Supported on almost all ThinkPads * * Fan speed changes of any sort (including those caused by the * disengaged mode) are usually done slowly by the firmware as the * maximum amount of fan duty cycle change per second seems to be * limited. * * Reading is not available if GFAN exists. * Writing is not available if SFAN exists. * * Bits * 7 automatic mode engaged; * (default operation mode of the ThinkPad) * fan level is ignored in this mode. * 6 full speed mode (takes precedence over bit 7); * not available on all thinkpads. May disable * the tachometer while the fan controller ramps up * the speed (which can take up to a few *minutes*). * Speeds up fan to 100% duty-cycle, which is far above * the standard RPM levels. It is not impossible that * it could cause hardware damage. * 5-3 unused in some models. Extra bits for fan level * in others, but still useless as all values above * 7 map to the same speed as level 7 in these models. * 2-0 fan level (0..7 usually) * 0x00 = stop * 0x07 = max (set when temperatures critical) * Some ThinkPads may have other levels, see * TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41) * * FIRMWARE BUG: on some models, EC 0x2f might not be initialized at * boot. Apparently the EC does not initialize it, so unless ACPI DSDT * does so, its initial value is meaningless (0x07). * * For firmware bugs, refer to: * http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues * * ---- * * ThinkPad EC register 0x84 (LSB), 0x85 (MSB): * Main fan tachometer reading (in RPM) * * This register is present on all ThinkPads with a new-style EC, and * it is known not to be present on the A21m/e, and T22, as there is * something else in offset 0x84 according to the ACPI DSDT. Other * ThinkPads from this same time period (and earlier) probably lack the * tachometer as well. * * Unfortunately a lot of ThinkPads with new-style ECs but whose firmware * was never fixed by IBM to report the EC firmware version string * probably support the tachometer (like the early X models), so * detecting it is quite hard. We need more data to know for sure. * * FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings * might result. * * FIRMWARE BUG: may go stale while the EC is switching to full speed * mode. * * For firmware bugs, refer to: * http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues * * ---- * * ThinkPad EC register 0x31 bit 0 (only on select models) * * When bit 0 of EC register 0x31 is zero, the tachometer registers * show the speed of the main fan. When bit 0 of EC register 0x31 * is one, the tachometer registers show the speed of the auxiliary * fan. * * Fan control seems to affect both fans, regardless of the state * of this bit. * * So far, only the firmware for the X60/X61 non-tablet versions * seem to support this (firmware TP-7M). * * TPACPI_FAN_WR_ACPI_FANS: * ThinkPad X31, X40, X41. Not available in the X60. * * FANS ACPI handle: takes three arguments: low speed, medium speed, * high speed. ACPI DSDT seems to map these three speeds to levels * as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH * (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3") * * The speeds are stored on handles * (FANA:FAN9), (FANC:FANB), (FANE:FAND). * * There are three default speed sets, accessible as handles: * FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H * * ACPI DSDT switches which set is in use depending on various * factors. * * TPACPI_FAN_WR_TPEC is also available and should be used to * command the fan. The X31/X40/X41 seems to have 8 fan levels, * but the ACPI tables just mention level 7. */ enum { /* Fan control constants */ fan_status_offset = 0x2f, /* EC register 0x2f */ fan_rpm_offset = 0x84, /* EC register 0x84: LSB, 0x85 MSB (RPM) * 0x84 must be read before 0x85 */ fan_select_offset = 0x31, /* EC register 0x31 (Firmware 7M) bit 0 selects which fan is active */ TP_EC_FAN_FULLSPEED = 0x40, /* EC fan mode: full speed */ TP_EC_FAN_AUTO = 0x80, /* EC fan mode: auto fan control */ TPACPI_FAN_LAST_LEVEL = 0x100, /* Use cached last-seen fan level */ }; enum fan_status_access_mode { TPACPI_FAN_NONE = 0, /* No fan status or control */ TPACPI_FAN_RD_ACPI_GFAN, /* Use ACPI GFAN */ TPACPI_FAN_RD_TPEC, /* Use ACPI EC regs 0x2f, 0x84-0x85 */ }; enum fan_control_access_mode { TPACPI_FAN_WR_NONE = 0, /* No fan control */ TPACPI_FAN_WR_ACPI_SFAN, /* Use ACPI SFAN */ TPACPI_FAN_WR_TPEC, /* Use ACPI EC reg 0x2f */ TPACPI_FAN_WR_ACPI_FANS, /* Use ACPI FANS and EC reg 0x2f */ }; enum fan_control_commands { TPACPI_FAN_CMD_SPEED = 0x0001, /* speed command */ TPACPI_FAN_CMD_LEVEL = 0x0002, /* level command */ TPACPI_FAN_CMD_ENABLE = 0x0004, /* enable/disable cmd, * and also watchdog cmd */ }; static int fan_control_allowed; static enum fan_status_access_mode fan_status_access_mode; static enum fan_control_access_mode fan_control_access_mode; static enum fan_control_commands fan_control_commands; static u8 fan_control_initial_status; static u8 fan_control_desired_level; static u8 fan_control_resume_level; static int fan_watchdog_maxinterval; static struct mutex fan_mutex; static void fan_watchdog_fire(struct work_struct *ignored); static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire); TPACPI_HANDLE(fans, ec, "FANS"); /* X31, X40, X41 */ TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */ "\\FSPD", /* 600e/x, 770e, 770x */ ); /* all others */ TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */ "JFNS", /* 770x-JL */ ); /* all others */ /* * Unitialized HFSP quirk: ACPI DSDT and EC fail to initialize the * HFSP register at boot, so it contains 0x07 but the Thinkpad could * be in auto mode (0x80). * * This is corrected by any write to HFSP either by the driver, or * by the firmware. * * We assume 0x07 really means auto mode while this quirk is active, * as this is far more likely than the ThinkPad being in level 7, * which is only used by the firmware during thermal emergencies. * * Enable for TP-1Y (T43), TP-78 (R51e), TP-76 (R52), * TP-70 (T43, R52), which are known to be buggy. */ static void fan_quirk1_setup(void) { if (fan_control_initial_status == 0x07) { pr_notice("fan_init: initial fan status is unknown, " "assuming it is in auto mode\n"); tp_features.fan_ctrl_status_undef = 1; } } static void fan_quirk1_handle(u8 *fan_status) { if (unlikely(tp_features.fan_ctrl_status_undef)) { if (*fan_status != fan_control_initial_status) { /* something changed the HFSP regisnter since * driver init time, so it is not undefined * anymore */ tp_features.fan_ctrl_status_undef = 0; } else { /* Return most likely status. In fact, it * might be the only possible status */ *fan_status = TP_EC_FAN_AUTO; } } } /* Select main fan on X60/X61, NOOP on others */ static bool fan_select_fan1(void) { if (tp_features.second_fan) { u8 val; if (ec_read(fan_select_offset, &val) < 0) return false; val &= 0xFEU; if (ec_write(fan_select_offset, val) < 0) return false; } return true; } /* Select secondary fan on X60/X61 */ static bool fan_select_fan2(void) { u8 val; if (!tp_features.second_fan) return false; if (ec_read(fan_select_offset, &val) < 0) return false; val |= 0x01U; if (ec_write(fan_select_offset, val) < 0) return false; return true; } /* * Call with fan_mutex held */ static void fan_update_desired_level(u8 status) { if ((status & (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) { if (status > 7) fan_control_desired_level = 7; else fan_control_desired_level = status; } } static int fan_get_status(u8 *status) { u8 s; /* TODO: * Add TPACPI_FAN_RD_ACPI_FANS ? */ switch (fan_status_access_mode) { case TPACPI_FAN_RD_ACPI_GFAN: /* 570, 600e/x, 770e, 770x */ if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d"))) return -EIO; if (likely(status)) *status = s & 0x07; break; case TPACPI_FAN_RD_TPEC: /* all except 570, 600e/x, 770e, 770x */ if (unlikely(!acpi_ec_read(fan_status_offset, &s))) return -EIO; if (likely(status)) { *status = s; fan_quirk1_handle(status); } break; default: return -ENXIO; } return 0; } static int fan_get_status_safe(u8 *status) { int rc; u8 s; if (mutex_lock_killable(&fan_mutex)) return -ERESTARTSYS; rc = fan_get_status(&s); if (!rc) fan_update_desired_level(s); mutex_unlock(&fan_mutex); if (status) *status = s; return rc; } static int fan_get_speed(unsigned int *speed) { u8 hi, lo; switch (fan_status_access_mode) { case TPACPI_FAN_RD_TPEC: /* all except 570, 600e/x, 770e, 770x */ if (unlikely(!fan_select_fan1())) return -EIO; if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) || !acpi_ec_read(fan_rpm_offset + 1, &hi))) return -EIO; if (likely(speed)) *speed = (hi << 8) | lo; break; default: return -ENXIO; } return 0; } static int fan2_get_speed(unsigned int *speed) { u8 hi, lo; bool rc; switch (fan_status_access_mode) { case TPACPI_FAN_RD_TPEC: /* all except 570, 600e/x, 770e, 770x */ if (unlikely(!fan_select_fan2())) return -EIO; rc = !acpi_ec_read(fan_rpm_offset, &lo) || !acpi_ec_read(fan_rpm_offset + 1, &hi); fan_select_fan1(); /* play it safe */ if (rc) return -EIO; if (likely(speed)) *speed = (hi << 8) | lo; break; default: return -ENXIO; } return 0; } static int fan_set_level(int level) { if (!fan_control_allowed) return -EPERM; switch (fan_control_access_mode) { case TPACPI_FAN_WR_ACPI_SFAN: if (level >= 0 && level <= 7) { if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level)) return -EIO; } else return -EINVAL; break; case TPACPI_FAN_WR_ACPI_FANS: case TPACPI_FAN_WR_TPEC: if (!(level & TP_EC_FAN_AUTO) && !(level & TP_EC_FAN_FULLSPEED) && ((level < 0) || (level > 7))) return -EINVAL; /* safety net should the EC not support AUTO * or FULLSPEED mode bits and just ignore them */ if (level & TP_EC_FAN_FULLSPEED) level |= 7; /* safety min speed 7 */ else if (level & TP_EC_FAN_AUTO) level |= 4; /* safety min speed 4 */ if (!acpi_ec_write(fan_status_offset, level)) return -EIO; else tp_features.fan_ctrl_status_undef = 0; break; default: return -ENXIO; } vdbg_printk(TPACPI_DBG_FAN, "fan control: set fan control register to 0x%02x\n", level); return 0; } static int fan_set_level_safe(int level) { int rc; if (!fan_control_allowed) return -EPERM; if (mutex_lock_killable(&fan_mutex)) return -ERESTARTSYS; if (level == TPACPI_FAN_LAST_LEVEL) level = fan_control_desired_level; rc = fan_set_level(level); if (!rc) fan_update_desired_level(level); mutex_unlock(&fan_mutex); return rc; } static int fan_set_enable(void) { u8 s; int rc; if (!fan_control_allowed) return -EPERM; if (mutex_lock_killable(&fan_mutex)) return -ERESTARTSYS; switch (fan_control_access_mode) { case TPACPI_FAN_WR_ACPI_FANS: case TPACPI_FAN_WR_TPEC: rc = fan_get_status(&s); if (rc < 0) break; /* Don't go out of emergency fan mode */ if (s != 7) { s &= 0x07; s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */ } if (!acpi_ec_write(fan_status_offset, s)) rc = -EIO; else { tp_features.fan_ctrl_status_undef = 0; rc = 0; } break; case TPACPI_FAN_WR_ACPI_SFAN: rc = fan_get_status(&s); if (rc < 0) break; s &= 0x07; /* Set fan to at least level 4 */ s |= 4; if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s)) rc = -EIO; else rc = 0; break; default: rc = -ENXIO; } mutex_unlock(&fan_mutex); if (!rc) vdbg_printk(TPACPI_DBG_FAN, "fan control: set fan control register to 0x%02x\n", s); return rc; } static int fan_set_disable(void) { int rc; if (!fan_control_allowed) return -EPERM; if (mutex_lock_killable(&fan_mutex)) return -ERESTARTSYS; rc = 0; switch (fan_control_access_mode) { case TPACPI_FAN_WR_ACPI_FANS: case TPACPI_FAN_WR_TPEC: if (!acpi_ec_write(fan_status_offset, 0x00)) rc = -EIO; else { fan_control_desired_level = 0; tp_features.fan_ctrl_status_undef = 0; } break; case TPACPI_FAN_WR_ACPI_SFAN: if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00)) rc = -EIO; else fan_control_desired_level = 0; break; default: rc = -ENXIO; } if (!rc) vdbg_printk(TPACPI_DBG_FAN, "fan control: set fan control register to 0\n"); mutex_unlock(&fan_mutex); return rc; } static int fan_set_speed(int speed) { int rc; if (!fan_control_allowed) return -EPERM; if (mutex_lock_killable(&fan_mutex)) return -ERESTARTSYS; rc = 0; switch (fan_control_access_mode) { case TPACPI_FAN_WR_ACPI_FANS: if (speed >= 0 && speed <= 65535) { if (!acpi_evalf(fans_handle, NULL, NULL, "vddd", speed, speed, speed)) rc = -EIO; } else rc = -EINVAL; break; default: rc = -ENXIO; } mutex_unlock(&fan_mutex); return rc; } static void fan_watchdog_reset(void) { static int fan_watchdog_active; if (fan_control_access_mode == TPACPI_FAN_WR_NONE) return; if (fan_watchdog_active) cancel_delayed_work(&fan_watchdog_task); if (fan_watchdog_maxinterval > 0 && tpacpi_lifecycle != TPACPI_LIFE_EXITING) { fan_watchdog_active = 1; if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task, msecs_to_jiffies(fan_watchdog_maxinterval * 1000))) { pr_err("failed to queue the fan watchdog, " "watchdog will not trigger\n"); } } else fan_watchdog_active = 0; } static void fan_watchdog_fire(struct work_struct *ignored) { int rc; if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING) return; pr_notice("fan watchdog: enabling fan\n"); rc = fan_set_enable(); if (rc < 0) { pr_err("fan watchdog: error %d while enabling fan, " "will try again later...\n", -rc); /* reschedule for later */ fan_watchdog_reset(); } } /* * SYSFS fan layout: hwmon compatible (device) * * pwm*_enable: * 0: "disengaged" mode * 1: manual mode * 2: native EC "auto" mode (recommended, hardware default) * * pwm*: set speed in manual mode, ignored otherwise. * 0 is level 0; 255 is level 7. Intermediate points done with linear * interpolation. * * fan*_input: tachometer reading, RPM * * * SYSFS fan layout: extensions * * fan_watchdog (driver): * fan watchdog interval in seconds, 0 disables (default), max 120 */ /* sysfs fan pwm1_enable ----------------------------------------------- */ static ssize_t fan_pwm1_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { int res, mode; u8 status; res = fan_get_status_safe(&status); if (res) return res; if (status & TP_EC_FAN_FULLSPEED) { mode = 0; } else if (status & TP_EC_FAN_AUTO) { mode = 2; } else mode = 1; return snprintf(buf, PAGE_SIZE, "%d\n", mode); } static ssize_t fan_pwm1_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long t; int res, level; if (parse_strtoul(buf, 2, &t)) return -EINVAL; tpacpi_disclose_usertask("hwmon pwm1_enable", "set fan mode to %lu\n", t); switch (t) { case 0: level = TP_EC_FAN_FULLSPEED; break; case 1: level = TPACPI_FAN_LAST_LEVEL; break; case 2: level = TP_EC_FAN_AUTO; break; case 3: /* reserved for software-controlled auto mode */ return -ENOSYS; default: return -EINVAL; } res = fan_set_level_safe(level); if (res == -ENXIO) return -EINVAL; else if (res < 0) return res; fan_watchdog_reset(); return count; } static struct device_attribute dev_attr_fan_pwm1_enable = __ATTR(pwm1_enable, S_IWUSR | S_IRUGO, fan_pwm1_enable_show, fan_pwm1_enable_store); /* sysfs fan pwm1 ------------------------------------------------------ */ static ssize_t fan_pwm1_show(struct device *dev, struct device_attribute *attr, char *buf) { int res; u8 status; res = fan_get_status_safe(&status); if (res) return res; if ((status & (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0) status = fan_control_desired_level; if (status > 7) status = 7; return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7); } static ssize_t fan_pwm1_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long s; int rc; u8 status, newlevel; if (parse_strtoul(buf, 255, &s)) return -EINVAL; tpacpi_disclose_usertask("hwmon pwm1", "set fan speed to %lu\n", s); /* scale down from 0-255 to 0-7 */ newlevel = (s >> 5) & 0x07; if (mutex_lock_killable(&fan_mutex)) return -ERESTARTSYS; rc = fan_get_status(&status); if (!rc && (status & (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) { rc = fan_set_level(newlevel); if (rc == -ENXIO) rc = -EINVAL; else if (!rc) { fan_update_desired_level(newlevel); fan_watchdog_reset(); } } mutex_unlock(&fan_mutex); return (rc)? rc : count; } static struct device_attribute dev_attr_fan_pwm1 = __ATTR(pwm1, S_IWUSR | S_IRUGO, fan_pwm1_show, fan_pwm1_store); /* sysfs fan fan1_input ------------------------------------------------ */ static ssize_t fan_fan1_input_show(struct device *dev, struct device_attribute *attr, char *buf) { int res; unsigned int speed; res = fan_get_speed(&speed); if (res < 0) return res; return snprintf(buf, PAGE_SIZE, "%u\n", speed); } static struct device_attribute dev_attr_fan_fan1_input = __ATTR(fan1_input, S_IRUGO, fan_fan1_input_show, NULL); /* sysfs fan fan2_input ------------------------------------------------ */ static ssize_t fan_fan2_input_show(struct device *dev, struct device_attribute *attr, char *buf) { int res; unsigned int speed; res = fan2_get_speed(&speed); if (res < 0) return res; return snprintf(buf, PAGE_SIZE, "%u\n", speed); } static struct device_attribute dev_attr_fan_fan2_input = __ATTR(fan2_input, S_IRUGO, fan_fan2_input_show, NULL); /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */ static ssize_t fan_fan_watchdog_show(struct device_driver *drv, char *buf) { return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval); } static ssize_t fan_fan_watchdog_store(struct device_driver *drv, const char *buf, size_t count) { unsigned long t; if (parse_strtoul(buf, 120, &t)) return -EINVAL; if (!fan_control_allowed) return -EPERM; fan_watchdog_maxinterval = t; fan_watchdog_reset(); tpacpi_disclose_usertask("fan_watchdog", "set to %lu\n", t); return count; } static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO, fan_fan_watchdog_show, fan_fan_watchdog_store); /* --------------------------------------------------------------------- */ static struct attribute *fan_attributes[] = { &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr, &dev_attr_fan_fan1_input.attr, NULL, /* for fan2_input */ NULL }; static const struct attribute_group fan_attr_group = { .attrs = fan_attributes, }; #define TPACPI_FAN_Q1 0x0001 /* Unitialized HFSP */ #define TPACPI_FAN_2FAN 0x0002 /* EC 0x31 bit 0 selects fan2 */ #define TPACPI_FAN_QI(__id1, __id2, __quirks) \ { .vendor = PCI_VENDOR_ID_IBM, \ .bios = TPACPI_MATCH_ANY, \ .ec = TPID(__id1, __id2), \ .quirks = __quirks } #define TPACPI_FAN_QL(__id1, __id2, __quirks) \ { .vendor = PCI_VENDOR_ID_LENOVO, \ .bios = TPACPI_MATCH_ANY, \ .ec = TPID(__id1, __id2), \ .quirks = __quirks } static const struct tpacpi_quirk fan_quirk_table[] __initconst = { TPACPI_FAN_QI('1', 'Y', TPACPI_FAN_Q1), TPACPI_FAN_QI('7', '8', TPACPI_FAN_Q1), TPACPI_FAN_QI('7', '6', TPACPI_FAN_Q1), TPACPI_FAN_QI('7', '0', TPACPI_FAN_Q1), TPACPI_FAN_QL('7', 'M', TPACPI_FAN_2FAN), }; #undef TPACPI_FAN_QL #undef TPACPI_FAN_QI static int __init fan_init(struct ibm_init_struct *iibm) { int rc; unsigned long quirks; vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN, "initializing fan subdriver\n"); mutex_init(&fan_mutex); fan_status_access_mode = TPACPI_FAN_NONE; fan_control_access_mode = TPACPI_FAN_WR_NONE; fan_control_commands = 0; fan_watchdog_maxinterval = 0; tp_features.fan_ctrl_status_undef = 0; tp_features.second_fan = 0; fan_control_desired_level = 7; if (tpacpi_is_ibm()) { TPACPI_ACPIHANDLE_INIT(fans); TPACPI_ACPIHANDLE_INIT(gfan); TPACPI_ACPIHANDLE_INIT(sfan); } quirks = tpacpi_check_quirks(fan_quirk_table, ARRAY_SIZE(fan_quirk_table)); if (gfan_handle) { /* 570, 600e/x, 770e, 770x */ fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN; } else { /* all other ThinkPads: note that even old-style * ThinkPad ECs supports the fan control register */ if (likely(acpi_ec_read(fan_status_offset, &fan_control_initial_status))) { fan_status_access_mode = TPACPI_FAN_RD_TPEC; if (quirks & TPACPI_FAN_Q1) fan_quirk1_setup(); if (quirks & TPACPI_FAN_2FAN) { tp_features.second_fan = 1; dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN, "secondary fan support enabled\n"); } } else { pr_err("ThinkPad ACPI EC access misbehaving, " "fan status and control unavailable\n"); return 1; } } if (sfan_handle) { /* 570, 770x-JL */ fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN; fan_control_commands |= TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE; } else { if (!gfan_handle) { /* gfan without sfan means no fan control */ /* all other models implement TP EC 0x2f control */ if (fans_handle) { /* X31, X40, X41 */ fan_control_access_mode = TPACPI_FAN_WR_ACPI_FANS; fan_control_commands |= TPACPI_FAN_CMD_SPEED | TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE; } else { fan_control_access_mode = TPACPI_FAN_WR_TPEC; fan_control_commands |= TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE; } } } vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN, "fan is %s, modes %d, %d\n", str_supported(fan_status_access_mode != TPACPI_FAN_NONE || fan_control_access_mode != TPACPI_FAN_WR_NONE), fan_status_access_mode, fan_control_access_mode); /* fan control master switch */ if (!fan_control_allowed) { fan_control_access_mode = TPACPI_FAN_WR_NONE; fan_control_commands = 0; dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN, "fan control features disabled by parameter\n"); } /* update fan_control_desired_level */ if (fan_status_access_mode != TPACPI_FAN_NONE) fan_get_status_safe(NULL); if (fan_status_access_mode != TPACPI_FAN_NONE || fan_control_access_mode != TPACPI_FAN_WR_NONE) { if (tp_features.second_fan) { /* attach second fan tachometer */ fan_attributes[ARRAY_SIZE(fan_attributes)-2] = &dev_attr_fan_fan2_input.attr; } rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group); if (rc < 0) return rc; rc = driver_create_file(&tpacpi_hwmon_pdriver.driver, &driver_attr_fan_watchdog); if (rc < 0) { sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group); return rc; } return 0; } else return 1; } static void fan_exit(void) { vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_FAN, "cancelling any pending fan watchdog tasks\n"); /* FIXME: can we really do this unconditionally? */ sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group); driver_remove_file(&tpacpi_hwmon_pdriver.driver, &driver_attr_fan_watchdog); cancel_delayed_work(&fan_watchdog_task); flush_workqueue(tpacpi_wq); } static void fan_suspend(pm_message_t state) { int rc; if (!fan_control_allowed) return; /* Store fan status in cache */ fan_control_resume_level = 0; rc = fan_get_status_safe(&fan_control_resume_level); if (rc < 0) pr_notice("failed to read fan level for later " "restore during resume: %d\n", rc); /* if it is undefined, don't attempt to restore it. * KEEP THIS LAST */ if (tp_features.fan_ctrl_status_undef) fan_control_resume_level = 0; } static void fan_resume(void) { u8 current_level = 7; bool do_set = false; int rc; /* DSDT *always* updates status on resume */ tp_features.fan_ctrl_status_undef = 0; if (!fan_control_allowed || !fan_control_resume_level || (fan_get_status_safe(&current_level) < 0)) return; switch (fan_control_access_mode) { case TPACPI_FAN_WR_ACPI_SFAN: /* never decrease fan level */ do_set = (fan_control_resume_level > current_level); break; case TPACPI_FAN_WR_ACPI_FANS: case TPACPI_FAN_WR_TPEC: /* never decrease fan level, scale is: * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO * * We expect the firmware to set either 7 or AUTO, but we * handle FULLSPEED out of paranoia. * * So, we can safely only restore FULLSPEED or 7, anything * else could slow the fan. Restoring AUTO is useless, at * best that's exactly what the DSDT already set (it is the * slower it uses). * * Always keep in mind that the DSDT *will* have set the * fans to what the vendor supposes is the best level. We * muck with it only to speed the fan up. */ if (fan_control_resume_level != 7 && !(fan_control_resume_level & TP_EC_FAN_FULLSPEED)) return; else do_set = !(current_level & TP_EC_FAN_FULLSPEED) && (current_level != fan_control_resume_level); break; default: return; } if (do_set) { pr_notice("restoring fan level to 0x%02x\n", fan_control_resume_level); rc = fan_set_level_safe(fan_control_resume_level); if (rc < 0) pr_notice("failed to restore fan level: %d\n", rc); } } static int fan_read(struct seq_file *m) { int rc; u8 status; unsigned int speed = 0; switch (fan_status_access_mode) { case TPACPI_FAN_RD_ACPI_GFAN: /* 570, 600e/x, 770e, 770x */ rc = fan_get_status_safe(&status); if (rc < 0) return rc; seq_printf(m, "status:\t\t%s\n" "level:\t\t%d\n", (status != 0) ? "enabled" : "disabled", status); break; case TPACPI_FAN_RD_TPEC: /* all except 570, 600e/x, 770e, 770x */ rc = fan_get_status_safe(&status); if (rc < 0) return rc; seq_printf(m, "status:\t\t%s\n", (status != 0) ? "enabled" : "disabled"); rc = fan_get_speed(&speed); if (rc < 0) return rc; seq_printf(m, "speed:\t\t%d\n", speed); if (status & TP_EC_FAN_FULLSPEED) /* Disengaged mode takes precedence */ seq_printf(m, "level:\t\tdisengaged\n"); else if (status & TP_EC_FAN_AUTO) seq_printf(m, "level:\t\tauto\n"); else seq_printf(m, "level:\t\t%d\n", status); break; case TPACPI_FAN_NONE: default: seq_printf(m, "status:\t\tnot supported\n"); } if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) { seq_printf(m, "commands:\tlevel <level>"); switch (fan_control_access_mode) { case TPACPI_FAN_WR_ACPI_SFAN: seq_printf(m, " (<level> is 0-7)\n"); break; default: seq_printf(m, " (<level> is 0-7, " "auto, disengaged, full-speed)\n"); break; } } if (fan_control_commands & TPACPI_FAN_CMD_ENABLE) seq_printf(m, "commands:\tenable, disable\n" "commands:\twatchdog <timeout> (<timeout> " "is 0 (off), 1-120 (seconds))\n"); if (fan_control_commands & TPACPI_FAN_CMD_SPEED) seq_printf(m, "commands:\tspeed <speed>" " (<speed> is 0-65535)\n"); return 0; } static int fan_write_cmd_level(const char *cmd, int *rc) { int level; if (strlencmp(cmd, "level auto") == 0) level = TP_EC_FAN_AUTO; else if ((strlencmp(cmd, "level disengaged") == 0) | (strlencmp(cmd, "level full-speed") == 0)) level = TP_EC_FAN_FULLSPEED; else if (sscanf(cmd, "level %d", &level) != 1) return 0; *rc = fan_set_level_safe(level); if (*rc == -ENXIO) pr_err("level command accepted for unsupported access mode %d\n", fan_control_access_mode); else if (!*rc) tpacpi_disclose_usertask("procfs fan", "set level to %d\n", level); return 1; } static int fan_write_cmd_enable(const char *cmd, int *rc) { if (strlencmp(cmd, "enable") != 0) return 0; *rc = fan_set_enable(); if (*rc == -ENXIO) pr_err("enable command accepted for unsupported access mode %d\n", fan_control_access_mode); else if (!*rc) tpacpi_disclose_usertask("procfs fan", "enable\n"); return 1; } static int fan_write_cmd_disable(const char *cmd, int *rc) { if (strlencmp(cmd, "disable") != 0) return 0; *rc = fan_set_disable(); if (*rc == -ENXIO) pr_err("disable command accepted for unsupported access mode %d\n", fan_control_access_mode); else if (!*rc) tpacpi_disclose_usertask("procfs fan", "disable\n"); return 1; } static int fan_write_cmd_speed(const char *cmd, int *rc) { int speed; /* TODO: * Support speed <low> <medium> <high> ? */ if (sscanf(cmd, "speed %d", &speed) != 1) return 0; *rc = fan_set_speed(speed); if (*rc == -ENXIO) pr_err("speed command accepted for unsupported access mode %d\n", fan_control_access_mode); else if (!*rc) tpacpi_disclose_usertask("procfs fan", "set speed to %d\n", speed); return 1; } static int fan_write_cmd_watchdog(const char *cmd, int *rc) { int interval; if (sscanf(cmd, "watchdog %d", &interval) != 1) return 0; if (interval < 0 || interval > 120) *rc = -EINVAL; else { fan_watchdog_maxinterval = interval; tpacpi_disclose_usertask("procfs fan", "set watchdog timer to %d\n", interval); } return 1; } static int fan_write(char *buf) { char *cmd; int rc = 0; while (!rc && (cmd = next_cmd(&buf))) { if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) && fan_write_cmd_level(cmd, &rc)) && !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) && (fan_write_cmd_enable(cmd, &rc) || fan_write_cmd_disable(cmd, &rc) || fan_write_cmd_watchdog(cmd, &rc))) && !((fan_control_commands & TPACPI_FAN_CMD_SPEED) && fan_write_cmd_speed(cmd, &rc)) ) rc = -EINVAL; else if (!rc) fan_watchdog_reset(); } return rc; } static struct ibm_struct fan_driver_data = { .name = "fan", .read = fan_read, .write = fan_write, .exit = fan_exit, .suspend = fan_suspend, .resume = fan_resume, }; /**************************************************************************** **************************************************************************** * * Infrastructure * **************************************************************************** ****************************************************************************/ /* * HKEY event callout for other subdrivers go here * (yes, it is ugly, but it is quick, safe, and gets the job done */ static void tpacpi_driver_event(const unsigned int hkey_event) { if (ibm_backlight_device) { switch (hkey_event) { case TP_HKEY_EV_BRGHT_UP: case TP_HKEY_EV_BRGHT_DOWN: tpacpi_brightness_notify_change(); } } if (alsa_card) { switch (hkey_event) { case TP_HKEY_EV_VOL_UP: case TP_HKEY_EV_VOL_DOWN: case TP_HKEY_EV_VOL_MUTE: volume_alsa_notify_change(); } } } static void hotkey_driver_event(const unsigned int scancode) { tpacpi_driver_event(TP_HKEY_EV_HOTKEY_BASE + scancode); } /* sysfs name ---------------------------------------------------------- */ static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME); } static struct device_attribute dev_attr_thinkpad_acpi_pdev_name = __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL); /* --------------------------------------------------------------------- */ /* /proc support */ static struct proc_dir_entry *proc_dir; /* * Module and infrastructure proble, init and exit handling */ static int force_load; #ifdef CONFIG_THINKPAD_ACPI_DEBUG static const char * __init str_supported(int is_supported) { static char text_unsupported[] __initdata = "not supported"; return (is_supported)? &text_unsupported[4] : &text_unsupported[0]; } #endif /* CONFIG_THINKPAD_ACPI_DEBUG */ static void ibm_exit(struct ibm_struct *ibm) { dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name); list_del_init(&ibm->all_drivers); if (ibm->flags.acpi_notify_installed) { dbg_printk(TPACPI_DBG_EXIT, "%s: acpi_remove_notify_handler\n", ibm->name); BUG_ON(!ibm->acpi); acpi_remove_notify_handler(*ibm->acpi->handle, ibm->acpi->type, dispatch_acpi_notify); ibm->flags.acpi_notify_installed = 0; } if (ibm->flags.proc_created) { dbg_printk(TPACPI_DBG_EXIT, "%s: remove_proc_entry\n", ibm->name); remove_proc_entry(ibm->name, proc_dir); ibm->flags.proc_created = 0; } if (ibm->flags.acpi_driver_registered) { dbg_printk(TPACPI_DBG_EXIT, "%s: acpi_bus_unregister_driver\n", ibm->name); BUG_ON(!ibm->acpi); acpi_bus_unregister_driver(ibm->acpi->driver); kfree(ibm->acpi->driver); ibm->acpi->driver = NULL; ibm->flags.acpi_driver_registered = 0; } if (ibm->flags.init_called && ibm->exit) { ibm->exit(); ibm->flags.init_called = 0; } dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name); } static int __init ibm_init(struct ibm_init_struct *iibm) { int ret; struct ibm_struct *ibm = iibm->data; struct proc_dir_entry *entry; BUG_ON(ibm == NULL); INIT_LIST_HEAD(&ibm->all_drivers); if (ibm->flags.experimental && !experimental) return 0; dbg_printk(TPACPI_DBG_INIT, "probing for %s\n", ibm->name); if (iibm->init) { ret = iibm->init(iibm); if (ret > 0) return 0; /* probe failed */ if (ret) return ret; ibm->flags.init_called = 1; } if (ibm->acpi) { if (ibm->acpi->hid) { ret = register_tpacpi_subdriver(ibm); if (ret) goto err_out; } if (ibm->acpi->notify) { ret = setup_acpi_notify(ibm); if (ret == -ENODEV) { pr_notice("disabling subdriver %s\n", ibm->name); ret = 0; goto err_out; } if (ret < 0) goto err_out; } } dbg_printk(TPACPI_DBG_INIT, "%s installed\n", ibm->name); if (ibm->read) { mode_t mode = iibm->base_procfs_mode; if (!mode) mode = S_IRUGO; if (ibm->write) mode |= S_IWUSR; entry = proc_create_data(ibm->name, mode, proc_dir, &dispatch_proc_fops, ibm); if (!entry) { pr_err("unable to create proc entry %s\n", ibm->name); ret = -ENODEV; goto err_out; } ibm->flags.proc_created = 1; } list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers); return 0; err_out: dbg_printk(TPACPI_DBG_INIT, "%s: at error exit path with result %d\n", ibm->name, ret); ibm_exit(ibm); return (ret < 0)? ret : 0; } /* Probing */ static bool __pure __init tpacpi_is_fw_digit(const char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z'); } /* Most models: xxyTkkWW (#.##c); Ancient 570/600 and -SL lacks (#.##c) */ static bool __pure __init tpacpi_is_valid_fw_id(const char* const s, const char t) { return s && strlen(s) >= 8 && tpacpi_is_fw_digit(s[0]) && tpacpi_is_fw_digit(s[1]) && s[2] == t && s[3] == 'T' && tpacpi_is_fw_digit(s[4]) && tpacpi_is_fw_digit(s[5]); } /* returns 0 - probe ok, or < 0 - probe error. * Probe ok doesn't mean thinkpad found. * On error, kfree() cleanup on tp->* is not performed, caller must do it */ static int __must_check __init get_thinkpad_model_data( struct thinkpad_id_data *tp) { const struct dmi_device *dev = NULL; char ec_fw_string[18]; char const *s; if (!tp) return -EINVAL; memset(tp, 0, sizeof(*tp)); if (dmi_name_in_vendors("IBM")) tp->vendor = PCI_VENDOR_ID_IBM; else if (dmi_name_in_vendors("LENOVO")) tp->vendor = PCI_VENDOR_ID_LENOVO; else return 0; s = dmi_get_system_info(DMI_BIOS_VERSION); tp->bios_version_str = kstrdup(s, GFP_KERNEL); if (s && !tp->bios_version_str) return -ENOMEM; /* Really ancient ThinkPad 240X will fail this, which is fine */ if (!tpacpi_is_valid_fw_id(tp->bios_version_str, 'E')) return 0; tp->bios_model = tp->bios_version_str[0] | (tp->bios_version_str[1] << 8); tp->bios_release = (tp->bios_version_str[4] << 8) | tp->bios_version_str[5]; /* * ThinkPad T23 or newer, A31 or newer, R50e or newer, * X32 or newer, all Z series; Some models must have an * up-to-date BIOS or they will not be detected. * * See http://thinkwiki.org/wiki/List_of_DMI_IDs */ while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) { if (sscanf(dev->name, "IBM ThinkPad Embedded Controller -[%17c", ec_fw_string) == 1) { ec_fw_string[sizeof(ec_fw_string) - 1] = 0; ec_fw_string[strcspn(ec_fw_string, " ]")] = 0; tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL); if (!tp->ec_version_str) return -ENOMEM; if (tpacpi_is_valid_fw_id(ec_fw_string, 'H')) { tp->ec_model = ec_fw_string[0] | (ec_fw_string[1] << 8); tp->ec_release = (ec_fw_string[4] << 8) | ec_fw_string[5]; } else { pr_notice("ThinkPad firmware release %s " "doesn't match the known patterns\n", ec_fw_string); pr_notice("please report this to %s\n", TPACPI_MAIL); } break; } } s = dmi_get_system_info(DMI_PRODUCT_VERSION); if (s && !strnicmp(s, "ThinkPad", 8)) { tp->model_str = kstrdup(s, GFP_KERNEL); if (!tp->model_str) return -ENOMEM; } s = dmi_get_system_info(DMI_PRODUCT_NAME); tp->nummodel_str = kstrdup(s, GFP_KERNEL); if (s && !tp->nummodel_str) return -ENOMEM; return 0; } static int __init probe_for_thinkpad(void) { int is_thinkpad; if (acpi_disabled) return -ENODEV; /* It would be dangerous to run the driver in this case */ if (!tpacpi_is_ibm() && !tpacpi_is_lenovo()) return -ENODEV; /* * Non-ancient models have better DMI tagging, but very old models * don't. tpacpi_is_fw_known() is a cheat to help in that case. */ is_thinkpad = (thinkpad_id.model_str != NULL) || (thinkpad_id.ec_model != 0) || tpacpi_is_fw_known(); /* The EC handler is required */ tpacpi_acpi_handle_locate("ec", TPACPI_ACPI_EC_HID, &ec_handle); if (!ec_handle) { if (is_thinkpad) pr_err("Not yet supported ThinkPad detected!\n"); return -ENODEV; } if (!is_thinkpad && !force_load) return -ENODEV; return 0; } static void __init thinkpad_acpi_init_banner(void) { pr_info("%s v%s\n", TPACPI_DESC, TPACPI_VERSION); pr_info("%s\n", TPACPI_URL); pr_info("ThinkPad BIOS %s, EC %s\n", (thinkpad_id.bios_version_str) ? thinkpad_id.bios_version_str : "unknown", (thinkpad_id.ec_version_str) ? thinkpad_id.ec_version_str : "unknown"); BUG_ON(!thinkpad_id.vendor); if (thinkpad_id.model_str) pr_info("%s %s, model %s\n", (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ? "IBM" : ((thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) ? "Lenovo" : "Unknown vendor"), thinkpad_id.model_str, (thinkpad_id.nummodel_str) ? thinkpad_id.nummodel_str : "unknown"); } /* Module init, exit, parameters */ static struct ibm_init_struct ibms_init[] __initdata = { { .data = &thinkpad_acpi_driver_data, }, { .init = hotkey_init, .data = &hotkey_driver_data, }, { .init = bluetooth_init, .data = &bluetooth_driver_data, }, { .init = wan_init, .data = &wan_driver_data, }, { .init = uwb_init, .data = &uwb_driver_data, }, #ifdef CONFIG_THINKPAD_ACPI_VIDEO { .init = video_init, .base_procfs_mode = S_IRUSR, .data = &video_driver_data, }, #endif { .init = light_init, .data = &light_driver_data, }, { .init = cmos_init, .data = &cmos_driver_data, }, { .init = led_init, .data = &led_driver_data, }, { .init = beep_init, .data = &beep_driver_data, }, { .init = thermal_init, .data = &thermal_driver_data, }, { .init = brightness_init, .data = &brightness_driver_data, }, { .init = volume_init, .data = &volume_driver_data, }, { .init = fan_init, .data = &fan_driver_data, }, }; static int __init set_ibm_param(const char *val, struct kernel_param *kp) { unsigned int i; struct ibm_struct *ibm; if (!kp || !kp->name || !val) return -EINVAL; for (i = 0; i < ARRAY_SIZE(ibms_init); i++) { ibm = ibms_init[i].data; WARN_ON(ibm == NULL); if (!ibm || !ibm->name) continue; if (strcmp(ibm->name, kp->name) == 0 && ibm->write) { if (strlen(val) > sizeof(ibms_init[i].param) - 2) return -ENOSPC; strcpy(ibms_init[i].param, val); strcat(ibms_init[i].param, ","); return 0; } } return -EINVAL; } module_param(experimental, int, 0444); MODULE_PARM_DESC(experimental, "Enables experimental features when non-zero"); module_param_named(debug, dbg_level, uint, 0); MODULE_PARM_DESC(debug, "Sets debug level bit-mask"); module_param(force_load, bool, 0444); MODULE_PARM_DESC(force_load, "Attempts to load the driver even on a " "mis-identified ThinkPad when true"); module_param_named(fan_control, fan_control_allowed, bool, 0444); MODULE_PARM_DESC(fan_control, "Enables setting fan parameters features when true"); module_param_named(brightness_mode, brightness_mode, uint, 0444); MODULE_PARM_DESC(brightness_mode, "Selects brightness control strategy: " "0=auto, 1=EC, 2=UCMS, 3=EC+NVRAM"); module_param(brightness_enable, uint, 0444); MODULE_PARM_DESC(brightness_enable, "Enables backlight control when 1, disables when 0"); module_param(hotkey_report_mode, uint, 0444); MODULE_PARM_DESC(hotkey_report_mode, "used for backwards compatibility with userspace, " "see documentation"); #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT module_param_named(volume_mode, volume_mode, uint, 0444); MODULE_PARM_DESC(volume_mode, "Selects volume control strategy: " "0=auto, 1=EC, 2=N/A, 3=EC+NVRAM"); module_param_named(volume_capabilities, volume_capabilities, uint, 0444); MODULE_PARM_DESC(volume_capabilities, "Selects the mixer capabilites: " "0=auto, 1=volume and mute, 2=mute only"); module_param_named(volume_control, volume_control_allowed, bool, 0444); MODULE_PARM_DESC(volume_control, "Enables software override for the console audio " "control when true"); /* ALSA module API parameters */ module_param_named(index, alsa_index, int, 0444); MODULE_PARM_DESC(index, "ALSA index for the ACPI EC Mixer"); module_param_named(id, alsa_id, charp, 0444); MODULE_PARM_DESC(id, "ALSA id for the ACPI EC Mixer"); module_param_named(enable, alsa_enable, bool, 0444); MODULE_PARM_DESC(enable, "Enable the ALSA interface for the ACPI EC Mixer"); #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */ #define TPACPI_PARAM(feature) \ module_param_call(feature, set_ibm_param, NULL, NULL, 0); \ MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \ "at module load, see documentation") TPACPI_PARAM(hotkey); TPACPI_PARAM(bluetooth); TPACPI_PARAM(video); TPACPI_PARAM(light); TPACPI_PARAM(cmos); TPACPI_PARAM(led); TPACPI_PARAM(beep); TPACPI_PARAM(brightness); TPACPI_PARAM(volume); TPACPI_PARAM(fan); #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES module_param(dbg_wlswemul, uint, 0444); MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation"); module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0); MODULE_PARM_DESC(wlsw_state, "Initial state of the emulated WLSW switch"); module_param(dbg_bluetoothemul, uint, 0444); MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation"); module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0); MODULE_PARM_DESC(bluetooth_state, "Initial state of the emulated bluetooth switch"); module_param(dbg_wwanemul, uint, 0444); MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation"); module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0); MODULE_PARM_DESC(wwan_state, "Initial state of the emulated WWAN switch"); module_param(dbg_uwbemul, uint, 0444); MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation"); module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0); MODULE_PARM_DESC(uwb_state, "Initial state of the emulated UWB switch"); #endif static void thinkpad_acpi_module_exit(void) { struct ibm_struct *ibm, *itmp; tpacpi_lifecycle = TPACPI_LIFE_EXITING; list_for_each_entry_safe_reverse(ibm, itmp, &tpacpi_all_drivers, all_drivers) { ibm_exit(ibm); } dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n"); if (tpacpi_inputdev) { if (tp_features.input_device_registered) input_unregister_device(tpacpi_inputdev); else input_free_device(tpacpi_inputdev); } if (tpacpi_hwmon) hwmon_device_unregister(tpacpi_hwmon); if (tp_features.sensors_pdev_attrs_registered) device_remove_file(&tpacpi_sensors_pdev->dev, &dev_attr_thinkpad_acpi_pdev_name); if (tpacpi_sensors_pdev) platform_device_unregister(tpacpi_sensors_pdev); if (tpacpi_pdev) platform_device_unregister(tpacpi_pdev); if (tp_features.sensors_pdrv_attrs_registered) tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver); if (tp_features.platform_drv_attrs_registered) tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver); if (tp_features.sensors_pdrv_registered) platform_driver_unregister(&tpacpi_hwmon_pdriver); if (tp_features.platform_drv_registered) platform_driver_unregister(&tpacpi_pdriver); if (proc_dir) remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir); if (tpacpi_wq) destroy_workqueue(tpacpi_wq); kfree(thinkpad_id.bios_version_str); kfree(thinkpad_id.ec_version_str); kfree(thinkpad_id.model_str); } static int __init thinkpad_acpi_module_init(void) { int ret, i; tpacpi_lifecycle = TPACPI_LIFE_INIT; /* Parameter checking */ if (hotkey_report_mode > 2) return -EINVAL; /* Driver-level probe */ ret = get_thinkpad_model_data(&thinkpad_id); if (ret) { pr_err("unable to get DMI data: %d\n", ret); thinkpad_acpi_module_exit(); return ret; } ret = probe_for_thinkpad(); if (ret) { thinkpad_acpi_module_exit(); return ret; } /* Driver initialization */ thinkpad_acpi_init_banner(); tpacpi_check_outdated_fw(); TPACPI_ACPIHANDLE_INIT(ecrd); TPACPI_ACPIHANDLE_INIT(ecwr); tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME); if (!tpacpi_wq) { thinkpad_acpi_module_exit(); return -ENOMEM; } proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir); if (!proc_dir) { pr_err("unable to create proc dir " TPACPI_PROC_DIR "\n"); thinkpad_acpi_module_exit(); return -ENODEV; } ret = platform_driver_register(&tpacpi_pdriver); if (ret) { pr_err("unable to register main platform driver\n"); thinkpad_acpi_module_exit(); return ret; } tp_features.platform_drv_registered = 1; ret = platform_driver_register(&tpacpi_hwmon_pdriver); if (ret) { pr_err("unable to register hwmon platform driver\n"); thinkpad_acpi_module_exit(); return ret; } tp_features.sensors_pdrv_registered = 1; ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver); if (!ret) { tp_features.platform_drv_attrs_registered = 1; ret = tpacpi_create_driver_attributes( &tpacpi_hwmon_pdriver.driver); } if (ret) { pr_err("unable to create sysfs driver attributes\n"); thinkpad_acpi_module_exit(); return ret; } tp_features.sensors_pdrv_attrs_registered = 1; /* Device initialization */ tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1, NULL, 0); if (IS_ERR(tpacpi_pdev)) { ret = PTR_ERR(tpacpi_pdev); tpacpi_pdev = NULL; pr_err("unable to register platform device\n"); thinkpad_acpi_module_exit(); return ret; } tpacpi_sensors_pdev = platform_device_register_simple( TPACPI_HWMON_DRVR_NAME, -1, NULL, 0); if (IS_ERR(tpacpi_sensors_pdev)) { ret = PTR_ERR(tpacpi_sensors_pdev); tpacpi_sensors_pdev = NULL; pr_err("unable to register hwmon platform device\n"); thinkpad_acpi_module_exit(); return ret; } ret = device_create_file(&tpacpi_sensors_pdev->dev, &dev_attr_thinkpad_acpi_pdev_name); if (ret) { pr_err("unable to create sysfs hwmon device attributes\n"); thinkpad_acpi_module_exit(); return ret; } tp_features.sensors_pdev_attrs_registered = 1; tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev); if (IS_ERR(tpacpi_hwmon)) { ret = PTR_ERR(tpacpi_hwmon); tpacpi_hwmon = NULL; pr_err("unable to register hwmon device\n"); thinkpad_acpi_module_exit(); return ret; } mutex_init(&tpacpi_inputdev_send_mutex); tpacpi_inputdev = input_allocate_device(); if (!tpacpi_inputdev) { pr_err("unable to allocate input device\n"); thinkpad_acpi_module_exit(); return -ENOMEM; } else { /* Prepare input device, but don't register */ tpacpi_inputdev->name = "ThinkPad Extra Buttons"; tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0"; tpacpi_inputdev->id.bustype = BUS_HOST; tpacpi_inputdev->id.vendor = thinkpad_id.vendor; tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT; tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION; tpacpi_inputdev->dev.parent = &tpacpi_pdev->dev; } /* Init subdriver dependencies */ tpacpi_detect_brightness_capabilities(); /* Init subdrivers */ for (i = 0; i < ARRAY_SIZE(ibms_init); i++) { ret = ibm_init(&ibms_init[i]); if (ret >= 0 && *ibms_init[i].param) ret = ibms_init[i].data->write(ibms_init[i].param); if (ret < 0) { thinkpad_acpi_module_exit(); return ret; } } tpacpi_lifecycle = TPACPI_LIFE_RUNNING; ret = input_register_device(tpacpi_inputdev); if (ret < 0) { pr_err("unable to register input device\n"); thinkpad_acpi_module_exit(); return ret; } else { tp_features.input_device_registered = 1; } return 0; } MODULE_ALIAS(TPACPI_DRVR_SHORTNAME); /* * This will autoload the driver in almost every ThinkPad * in widespread use. * * Only _VERY_ old models, like the 240, 240x and 570 lack * the HKEY event interface. */ MODULE_DEVICE_TABLE(acpi, ibm_htk_device_ids); /* * DMI matching for module autoloading * * See http://thinkwiki.org/wiki/List_of_DMI_IDs * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads * * Only models listed in thinkwiki will be supported, so add yours * if it is not there yet. */ #define IBM_BIOS_MODULE_ALIAS(__type) \ MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW*") /* Ancient thinkpad BIOSes have to be identified by * BIOS type or model number, and there are far less * BIOS types than model numbers... */ IBM_BIOS_MODULE_ALIAS("I[MU]"); /* 570, 570e */ MODULE_AUTHOR("Borislav Deianov <borislav@users.sf.net>"); MODULE_AUTHOR("Henrique de Moraes Holschuh <hmh@hmh.eng.br>"); MODULE_DESCRIPTION(TPACPI_DESC); MODULE_VERSION(TPACPI_VERSION); MODULE_LICENSE("GPL"); module_init(thinkpad_acpi_module_init); module_exit(thinkpad_acpi_module_exit);
naota/hfsplus
drivers/platform/x86/thinkpad_acpi.c
C
gpl-2.0
235,029
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Test that the header defines the PROT_EXEC protection option. * * @pt:MF * @pt:SHM * @pt:ADV */ #include <sys/mman.h> #ifndef PROT_EXEC #error PROT_EXEC not defined #endif
ycui1984/posixtestsuite
posixtestsuite/conformance/definitions/sys/mman_h/2-3.c
C
gpl-2.0
584
(function ($) { providers_small.mailru = { name: 'mail.ru', url: "javascript: $('#mail_ru_auth_login a').click();" }; openid.getBoxHTML__mailru = openid.getBoxHTML; openid.getBoxHTML = function (box_id, provider, box_size, index) { if (box_id == 'mailru') { var no_sprite = this.no_sprite; this.no_sprite = true; var result = this.getBoxHTML__mailru(box_id, provider, box_size, index); this.no_sprite = no_sprite; return result; } return this.getBoxHTML__mailru(box_id, provider, box_size, index); } Drupal.behaviors.openid_selector_mailru = { attach: function (context) { $('#mail_ru_auth_login').hide(); }} })(jQuery);
janicak/C-Db
sites/all/modules/openid_selector/openid_selector_mailru.js
JavaScript
gpl-2.0
650
/* $OpenBSD: libcrypto.h,v 1.17 2005/04/05 20:46:20 cloder Exp $ */ /* $EOM: libcrypto.h,v 1.16 2000/09/28 12:53:27 niklas Exp $ */ /* * Copyright (c) 1999, 2000 Niklas Hallqvist. All rights reserved. * Copyright (c) 1999, 2000 Angelos D. Keromytis. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This code was written under funding by Ericsson Radio Systems. */ #ifndef _LIBCRYPTO_H_ #define _LIBCRYPTO_H_ #include <stdio.h> /* XXX I want #include <ssl/cryptall.h> but we appear to not install meth.h */ #include <openssl/ssl.h> #include <openssl/bio.h> #include <openssl/md5.h> #include <openssl/pem.h> #include <openssl/x509_vfy.h> #include <openssl/x509.h> extern void libcrypto_init(void); #endif /* _LIBCRYPTO_H_ */
mohammadhamad/mhhgen
repos/libports/src/test/isakmp_rpc_lwip/libcrypto.h
C
gpl-2.0
1,978
/* * Broadcom Dongle Host Driver (DHD), Linux-specific network interface * Basically selected code segments from usb-cdc.c and usb-rndis.c * * Copyright (C) 1999-2012, Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * * $Id: dhd_linux.c 324874 2012-03-30 18:29:52Z $ */ #include <typedefs.h> #include <linuxver.h> #include <osl.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/inetdevice.h> #include <linux/rtnetlink.h> #include <linux/etherdevice.h> #include <linux/random.h> #include <linux/spinlock.h> #include <linux/ethtool.h> #include <linux/fcntl.h> #include <linux/fs.h> #include <linux/ioprio.h> #include <asm/uaccess.h> #include <asm/unaligned.h> #include <epivers.h> #include <bcmutils.h> #include <bcmendian.h> #include <bcmdevs.h> #include <proto/ethernet.h> #include <dngl_stats.h> #include <dhd.h> #include <dhd_bus.h> #include <dhd_proto.h> #include <dhd_dbg.h> #ifdef CONFIG_HAS_WAKELOCK #include <linux/wakelock.h> #endif #ifdef WL_CFG80211 #include <wl_cfg80211.h> #endif #ifdef WLBTAMP #include <proto/802.11_bta.h> #include <proto/bt_amp_hci.h> #include <dhd_bta.h> #endif extern int bcm_chip_is_4330b1; extern int bcm_chip_is_4330; dhd_pub_t *priv_dhdp = NULL; #define htod32(i) i #define htod16(i) i #define dtoh32(i) i #define dtoh16(i) i static int module_insert = 0; int module_remove = 0; #ifdef WLMEDIA_HTSF #include <linux/time.h> #include <htsf.h> #define HTSF_MINLEN 200 #define HTSF_BUS_DELAY 150 #define TSMAX 1000 #define NUMBIN 34 static uint32 tsidx = 0; static uint32 htsf_seqnum = 0; uint32 tsfsync; struct timeval tsync; static uint32 tsport = 5010; typedef struct histo_ { uint32 bin[NUMBIN]; } histo_t; #if !ISPOWEROF2(DHD_SDALIGN) #error DHD_SDALIGN is not a power of 2! #endif static histo_t vi_d1, vi_d2, vi_d3, vi_d4; #endif #ifndef DTIM_COUNT #define DTIM_COUNT 3 #endif #define HTC_DUMP_PACKLEN 0 #if defined(PKT_FILTER_SUPPORT) #if defined(BLOCK_IPV6_PACKET) #define HEX_PREF_STR "0x" #define UNI_FILTER_STR "010000000000" #define ZERO_ADDR_STR "000000000000" #define ETHER_TYPE_STR "0000" #define IPV6_FILTER_STR "20" #define ZERO_TYPE_STR "00" #endif #endif #if defined(SOFTAP) extern bool ap_cfg_running; extern bool ap_fw_loaded; #endif bool wifi_fail_retry = false; #define AOE_IP_ALIAS_SUPPORT 1 #ifdef BCM_FD_AGGR #include <bcm_rpc.h> #include <bcm_rpc_tp.h> #endif #ifdef PROP_TXSTATUS #include <wlfc_proto.h> #include <dhd_wlfc.h> #endif #include <wl_android.h> #ifdef ARP_OFFLOAD_SUPPORT void aoe_update_host_ipv4_table(dhd_pub_t *dhd_pub, u32 ipa, bool add); static int dhd_device_event(struct notifier_block *this, unsigned long event, void *ptr); static struct notifier_block dhd_notifier = { .notifier_call = dhd_device_event }; #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && defined(CONFIG_PM_SLEEP) #include <linux/suspend.h> volatile bool dhd_mmc_suspend = FALSE; DECLARE_WAIT_QUEUE_HEAD(dhd_dpc_wait); #endif #if defined(OOB_INTR_ONLY) extern void dhd_enable_oob_intr(struct dhd_bus *bus, bool enable); #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && (1) static void dhd_hang_process(struct work_struct *work); #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) MODULE_LICENSE("GPL v2"); #endif #include <dhd_bus.h> #ifdef BCM_FD_AGGR #define DBUS_RX_BUFFER_SIZE_DHD(net) (BCM_RPC_TP_DNGL_AGG_MAX_BYTE) #else #ifndef PROP_TXSTATUS #define DBUS_RX_BUFFER_SIZE_DHD(net) (net->mtu + net->hard_header_len + dhd->pub.hdrlen) #else #define DBUS_RX_BUFFER_SIZE_DHD(net) (net->mtu + net->hard_header_len + dhd->pub.hdrlen + 128) #endif #endif #if LINUX_VERSION_CODE == KERNEL_VERSION(2, 6, 15) const char * print_tainted() { return ""; } #endif #if defined(CONFIG_WIRELESS_EXT) #include <wl_iw.h> extern wl_iw_extra_params_t g_wl_iw_params; #endif #if defined(CONFIG_HAS_EARLYSUSPEND) #include <linux/earlysuspend.h> extern int dhdcdc_set_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len); extern int dhd_get_dtim_skip(dhd_pub_t *dhd); #endif #ifdef PKT_FILTER_SUPPORT extern void dhd_pktfilter_offload_set(dhd_pub_t * dhd, char *arg); extern void dhd_pktfilter_offload_enable(dhd_pub_t * dhd, char *arg, int enable, int master_mode); #endif #ifdef READ_MACADDR extern int dhd_read_macaddr(struct dhd_info *dhd, struct ether_addr *mac); #endif #ifdef RDWR_MACADDR extern int dhd_check_rdwr_macaddr(struct dhd_info *dhd, dhd_pub_t *dhdp, struct ether_addr *mac); extern int dhd_write_rdwr_macaddr(struct ether_addr *mac); #endif #ifdef WRITE_MACADDR extern int dhd_write_macaddr(struct ether_addr *mac); #endif #ifdef USE_CID_CHECK extern int dhd_check_module_cid(dhd_pub_t *dhd); #endif #ifdef GET_MAC_FROM_OTP extern int dhd_check_module_mac(dhd_pub_t *dhd); #endif #ifdef MIMO_ANT_SETTING extern int dhd_sel_ant_from_file(dhd_pub_t *dhd); #endif #ifdef CUSTOMER_SET_COUNTRY int dhd_customer_set_country(dhd_pub_t *dhd); #endif typedef struct dhd_if { struct dhd_info *info; struct net_device *net; struct net_device_stats stats; int idx; dhd_if_state_t state; uint subunit; uint8 mac_addr[ETHER_ADDR_LEN]; bool attached; bool txflowcontrol; char name[IFNAMSIZ+1]; uint8 bssidx; bool set_multicast; bool event2cfg80211; } dhd_if_t; #ifdef WLMEDIA_HTSF typedef struct { uint32 low; uint32 high; } tsf_t; typedef struct { uint32 last_cycle; uint32 last_sec; uint32 last_tsf; uint32 coef; uint32 coefdec1; uint32 coefdec2; } htsf_t; typedef struct { uint32 t1; uint32 t2; uint32 t3; uint32 t4; } tstamp_t; static tstamp_t ts[TSMAX]; static tstamp_t maxdelayts; static uint32 maxdelay = 0, tspktcnt = 0, maxdelaypktno = 0; #endif #if defined(CUSTOMER_HW4) && defined(CONFIG_PM_SLEEP) && defined(PLATFORM_SLP) extern struct device *pm_dev; #endif typedef struct dhd_info { #if defined(CONFIG_WIRELESS_EXT) wl_iw_t iw; #endif dhd_pub_t pub; dhd_if_t *iflist[DHD_MAX_IFS]; struct semaphore proto_sem; #ifdef PROP_TXSTATUS spinlock_t wlfc_spinlock; #endif #ifdef WLMEDIA_HTSF htsf_t htsf; #endif wait_queue_head_t ioctl_resp_wait; struct timer_list timer; bool wd_timer_valid; struct tasklet_struct tasklet; spinlock_t sdlock; spinlock_t txqlock; spinlock_t dhd_lock; #ifdef DHDTHREAD bool threads_only; struct semaphore sdsem; tsk_ctl_t thr_dpc_ctl; tsk_ctl_t thr_wdt_ctl; #endif bool dhd_tasklet_create; tsk_ctl_t thr_sysioc_ctl; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) struct work_struct work_hang; #endif #if defined(CONFIG_HAS_WAKELOCK) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) struct wake_lock wl_wifi; struct wake_lock wl_rxwake; struct wake_lock wl_ctrlwake; struct wake_lock wl_htc; #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 struct mutex dhd_net_if_mutex; struct mutex dhd_suspend_mutex; #endif spinlock_t wakelock_spinlock; int wakelock_counter; int wakelock_rx_timeout_enable; int wakelock_ctrl_timeout_enable; unsigned char set_macaddress; struct ether_addr macvalue; wait_queue_head_t ctrl_wait; atomic_t pend_8021x_cnt; dhd_attach_states_t dhd_state; #ifdef CONFIG_HAS_EARLYSUSPEND struct early_suspend early_suspend; #endif #ifdef ARP_OFFLOAD_SUPPORT u32 pend_ipaddr; #endif bool dhd_force_exit; #ifdef BCM_FD_AGGR void *rpc_th; void *rpc_osh; struct timer_list rpcth_timer; bool rpcth_timer_active; bool fdaggr; #endif } dhd_info_t; char firmware_path[MOD_PARAM_PATHLEN]; char fwb1_path[MOD_PARAM_PATHLEN]; char fwb2_path[MOD_PARAM_PATHLEN]; char nvram_path[MOD_PARAM_PATHLEN]; char info_string[MOD_PARAM_INFOLEN]; module_param_string(info_string, info_string, MOD_PARAM_INFOLEN, 0444); int op_mode = 0; int disable_proptx = 0; module_param(op_mode, int, 0644); extern int wl_control_wl_start(struct net_device *dev); extern int net_os_send_hang_message(struct net_device *dev); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) struct semaphore dhd_registration_sem; struct semaphore dhd_chipup_sem; int dhd_registration_check = FALSE; #define DHD_REGISTRATION_TIMEOUT 12000 #endif uint dhd_sysioc = TRUE; module_param(dhd_sysioc, uint, 0); module_param(dhd_msg_level, int, 0); module_param(disable_proptx, int, 0644); module_param_string(firmware_path, firmware_path, MOD_PARAM_PATHLEN, 0660); module_param_string(fwb1_path, fwb1_path, MOD_PARAM_PATHLEN, 0); module_param_string(fwb2_path, fwb2_path, MOD_PARAM_PATHLEN, 0); module_param_string(nvram_path, nvram_path, MOD_PARAM_PATHLEN, 0); uint dhd_watchdog_ms = 10; module_param(dhd_watchdog_ms, uint, 0); #if defined(DHD_DEBUG) uint dhd_console_ms = 0; module_param(dhd_console_ms, uint, 0644); #endif uint dhd_slpauto = TRUE; module_param(dhd_slpauto, uint, 0); uint dhd_arp_mode = 0xb; module_param(dhd_arp_mode, uint, 0); uint dhd_arp_enable = TRUE; module_param(dhd_arp_enable, uint, 0); #ifdef PKT_FILTER_SUPPORT uint dhd_pkt_filter_enable = TRUE; module_param(dhd_pkt_filter_enable, uint, 0); #endif uint dhd_pkt_filter_init = 0; module_param(dhd_pkt_filter_init, uint, 0); #ifdef GAN_LITE_NAT_KEEPALIVE_FILTER uint dhd_master_mode = FALSE; #else uint dhd_master_mode = TRUE; #endif module_param(dhd_master_mode, uint, 0); #ifdef DHDTHREAD int dhd_watchdog_prio = 102; module_param(dhd_watchdog_prio, int, 0); int dhd_dpc_prio = 0; module_param(dhd_dpc_prio, int, 0); extern int dhd_dongle_memsize; module_param(dhd_dongle_memsize, int, 0); #endif #ifdef CUSTOMER_HW2 uint dhd_roam_disable = 0; #else uint dhd_roam_disable = 1; #endif uint dhd_radio_up = 1; char iface_name[IFNAMSIZ] = {'\0'}; module_param_string(iface_name, iface_name, IFNAMSIZ, 0); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) #define DAEMONIZE(a) daemonize(a); \ allow_signal(SIGKILL); \ allow_signal(SIGTERM); #else #define RAISE_RX_SOFTIRQ() \ cpu_raise_softirq(smp_processor_id(), NET_RX_SOFTIRQ) #define DAEMONIZE(a) daemonize(); \ do { if (a) \ strncpy(current->comm, a, MIN(sizeof(current->comm), (strlen(a) + 1))); \ } while (0); #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) #define BLOCKABLE() (!in_atomic()) #else #define BLOCKABLE() (!in_interrupt()) #endif int dhd_ioctl_timeout_msec = IOCTL_RESP_TIMEOUT; int dhd_idletime = DHD_IDLETIME_TICKS; module_param(dhd_idletime, int, 0); uint dhd_poll = FALSE; module_param(dhd_poll, uint, 0); uint dhd_intr = TRUE; module_param(dhd_intr, uint, 0); uint dhd_sdiod_drive_strength = 12; module_param(dhd_sdiod_drive_strength, uint, 0); extern uint dhd_txbound; extern uint dhd_rxbound; module_param(dhd_txbound, uint, 0); module_param(dhd_rxbound, uint, 0); extern uint dhd_deferred_tx; module_param(dhd_deferred_tx, uint, 0); #ifdef BCMDBGFS extern void dhd_dbg_init(dhd_pub_t *dhdp); extern void dhd_dbg_remove(void); #endif #ifdef SDTEST uint dhd_pktgen = 0; module_param(dhd_pktgen, uint, 0); uint dhd_pktgen_len = 0; module_param(dhd_pktgen_len, uint, 0); #endif #ifdef DHD_DEBUG #ifndef SRCBASE #define SRCBASE "drivers/net/wireless/bcmdhd" #endif #define DHD_COMPILED "\nCompiled in " SRCBASE #else #define DHD_COMPILED #endif static char dhd_version[] = "Dongle Host Driver, version " EPI_VERSION_STR #ifdef DHD_DEBUG "\nCompiled in " SRCBASE " on " __DATE__ " at " __TIME__ #endif ; static void dhd_net_if_lock_local(dhd_info_t *dhd); static void dhd_net_if_unlock_local(dhd_info_t *dhd); #if 0 static void dhd_suspend_lock(dhd_pub_t *dhdp); static void dhd_suspend_unlock(dhd_pub_t *dhdp); #endif #ifdef WLMEDIA_HTSF void htsf_update(dhd_info_t *dhd, void *data); tsf_t prev_tsf, cur_tsf; uint32 dhd_get_htsf(dhd_info_t *dhd, int ifidx); static int dhd_ioctl_htsf_get(dhd_info_t *dhd, int ifidx); static void dhd_dump_latency(void); static void dhd_htsf_addtxts(dhd_pub_t *dhdp, void *pktbuf); static void dhd_htsf_addrxts(dhd_pub_t *dhdp, void *pktbuf); static void dhd_dump_htsfhisto(histo_t *his, char *s); #endif int dhd_monitor_init(void *dhd_pub); int dhd_monitor_uninit(void); #ifdef CONFIG_CONTROL_PM bool g_pm_control; void sec_control_pm(dhd_pub_t *dhd, uint *); #endif #if defined(CONFIG_WIRELESS_EXT) struct iw_statistics *dhd_get_wireless_stats(struct net_device *dev); #endif static void dhd_dpc(ulong data); extern int dhd_wait_pend8021x(struct net_device *dev); #ifdef TOE #ifndef BDC #error TOE requires BDC #endif static int dhd_toe_get(dhd_info_t *dhd, int idx, uint32 *toe_ol); static int dhd_toe_set(dhd_info_t *dhd, int idx, uint32 toe_ol); #endif static int dhd_wl_host_event(dhd_info_t *dhd, int *ifidx, void *pktdata, wl_event_msg_t *event_ptr, void **data_ptr); #define WLC_HT_TKIP_RESTRICT 0x02 #define WLC_HT_WEP_RESTRICT 0x01 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && defined(CONFIG_PM_SLEEP) static int dhd_sleep_pm_callback(struct notifier_block *nfb, unsigned long action, void *ignored) { int ret = NOTIFY_DONE; switch (action) { case PM_HIBERNATION_PREPARE: case PM_SUSPEND_PREPARE: dhd_mmc_suspend = TRUE; ret = NOTIFY_OK; break; case PM_POST_HIBERNATION: case PM_POST_SUSPEND: dhd_mmc_suspend = FALSE; ret = NOTIFY_OK; break; } smp_mb(); return ret; } static struct notifier_block dhd_sleep_pm_notifier = { .notifier_call = dhd_sleep_pm_callback, .priority = 10 }; extern int register_pm_notifier(struct notifier_block *nb); extern int unregister_pm_notifier(struct notifier_block *nb); #endif static void dhd_set_packet_filter(int value, dhd_pub_t *dhd) { #ifdef PKT_FILTER_SUPPORT DHD_TRACE(("%s: %d\n", __FUNCTION__, value)); if ((dhd_pkt_filter_enable && !dhd->dhcp_in_progress) && (!value || (dhd_check_ap_wfd_mode_set(dhd) == FALSE))) { int i; for (i = 0; i < dhd->pktfilter_count; i++) { dhd_pktfilter_offload_set(dhd, dhd->pktfilter[i]); dhd_pktfilter_offload_enable(dhd, dhd->pktfilter[i], value, dhd_master_mode); } } #endif } #if defined(CONFIG_HAS_EARLYSUSPEND) void wl_android_set_screen_off(int off); dhd_pub_t *pdhd = NULL; #ifdef BCM4329_LOW_POWER int LowPowerMode = 1; extern char gatewaybuf[8+1]; char ip_str[32]; bool hasDLNA = false; bool allowMulticast = false; #endif int dhd_set_keepalive(int value); extern int wl_pattern_atoh(char *src, char *dst); int is_screen_off = 0; static int dhd_set_suspend(int value, dhd_pub_t *dhd) { #ifdef BCM4329_LOW_POWER int ignore_bcmc = 1; #endif char iovbuf[32]; #ifdef CUSTOMER_HW2 #endif char eventmask[WL_EVENTING_MASK_LEN]; int ret = 0; is_screen_off = value; DHD_TRACE(("%s: enter, value = %d in_suspend=%d\n", __FUNCTION__, value, dhd->in_suspend)); wl_android_set_screen_off(is_screen_off); if (is_screen_off) { bcm_mkiovar("event_msgs", eventmask, WL_EVENTING_MASK_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, iovbuf, sizeof(iovbuf), FALSE, 0)) < 0) { DHD_ERROR(("%s read Event mask failed %d\n", __FUNCTION__, ret)); } bcopy(iovbuf, eventmask, WL_EVENTING_MASK_LEN); clrbit(eventmask, WLC_E_ACTION_FRAME_RX); clrbit(eventmask, WLC_E_ACTION_FRAME_COMPLETE); clrbit(eventmask, WLC_E_ACTION_FRAME_OFF_CHAN_COMPLETE); clrbit(eventmask, WLC_E_P2P_PROBREQ_MSG); clrbit(eventmask, WLC_E_P2P_DISC_LISTEN_COMPLETE); bcm_mkiovar("event_msgs", eventmask, WL_EVENTING_MASK_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s Set Event mask failed %d\n", __FUNCTION__, ret)); } } else { bcm_mkiovar("event_msgs", eventmask, WL_EVENTING_MASK_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, iovbuf, sizeof(iovbuf), FALSE, 0)) < 0) { DHD_ERROR(("%s read Event mask failed %d\n", __FUNCTION__, ret)); } bcopy(iovbuf, eventmask, WL_EVENTING_MASK_LEN); setbit(eventmask, WLC_E_ACTION_FRAME_RX); setbit(eventmask, WLC_E_ACTION_FRAME_COMPLETE); setbit(eventmask, WLC_E_ACTION_FRAME_OFF_CHAN_COMPLETE); setbit(eventmask, WLC_E_P2P_PROBREQ_MSG); setbit(eventmask, WLC_E_P2P_DISC_LISTEN_COMPLETE); bcm_mkiovar("event_msgs", eventmask, WL_EVENTING_MASK_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s Set Event mask failed %d\n", __FUNCTION__, ret)); } } if (dhd && dhd->up) { if (value && dhd->in_suspend) { #ifdef PKT_FILTER_SUPPORT dhd->early_suspended = 1; #endif #ifdef BCM4329_LOW_POWER if (LowPowerMode == 1) { if (!hasDLNA && !allowMulticast) { printf("set ignore_bcmc = %d",ignore_bcmc); bcm_mkiovar("pm_ignore_bcmc", (char *)&ignore_bcmc, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); } } #endif dhd_set_keepalive(1); DHD_TRACE(("%s: force extra Suspend setting \n", __FUNCTION__)); #ifdef PNO_SUPPORT dhd_set_pfn(dhd, 1); #endif dhdhtc_set_power_control(0, DHDHTC_POWER_CTRL_BROWSER_LOAD_PAGE); dhdhtc_update_wifi_power_mode(is_screen_off); dhdhtc_update_dtim_listen_interval(is_screen_off); } else { #ifdef PKT_FILTER_SUPPORT dhd->early_suspended = 0; #endif dhdhtc_update_wifi_power_mode(is_screen_off); dhdhtc_update_dtim_listen_interval(is_screen_off); DHD_TRACE(("%s: Remove extra suspend setting \n", __FUNCTION__)); #ifdef PNO_SUPPORT dhd_set_pfn(dhd, 0); #endif #ifdef BCM4329_LOW_POWER if (LowPowerMode == 1) { ignore_bcmc = 0; printf("set ignore_bcmc = %d",ignore_bcmc); bcm_mkiovar("pm_ignore_bcmc", (char *)&ignore_bcmc, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); } dhd_set_keepalive(0); #endif } } return 0; } int dhd_set_keepalive(int value) { char *str; int str_len; int buf_len; char buf[256]; wl_keep_alive_pkt_t keep_alive_pkt; wl_keep_alive_pkt_t *keep_alive_pktp; dhd_pub_t *dhd = pdhd; #ifdef HTC_KlocWork memset(&keep_alive_pkt, 0, sizeof(keep_alive_pkt)); #endif str = "keep_alive"; str_len = strlen(str); strncpy(buf, str, str_len); buf[str_len] = '\0'; buf_len = str_len + 1; keep_alive_pktp = (wl_keep_alive_pkt_t *) (buf + str_len + 1); keep_alive_pkt.period_msec = htod32(30000); keep_alive_pkt.len_bytes = 0; buf_len += WL_KEEP_ALIVE_FIXED_LEN; bzero(keep_alive_pkt.data, sizeof(keep_alive_pkt.data)); memcpy((char*)keep_alive_pktp, &keep_alive_pkt, WL_KEEP_ALIVE_FIXED_LEN); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, buf_len, TRUE, 0); return 0; } static unsigned int dhdhtc_power_ctrl_mask = 0; int dhdcdc_power_active_while_plugin = 1; int dhdcdc_wifiLock = 0; extern int usb_get_connect_type(void); int dhdhtc_update_wifi_power_mode(int is_screen_off) { int pm_type; dhd_pub_t *dhd = pdhd; if (!dhd) { printf("dhd is not attached\n"); return -1; } if (dhdhtc_power_ctrl_mask) { printf("power active. ctrl_mask: 0x%x\n", dhdhtc_power_ctrl_mask); pm_type = PM_OFF; dhd_wl_ioctl_cmd(dhd, WLC_SET_PM, (char *)&pm_type, sizeof(pm_type), TRUE, 0); } else if (dhdcdc_power_active_while_plugin && usb_get_connect_type()) { printf("update pm: PM_FAST. usb_type:%d\n", usb_get_connect_type()); pm_type = PM_FAST; dhd_wl_ioctl_cmd(dhd, WLC_SET_PM, (char *)&pm_type, sizeof(pm_type), TRUE, 0); } else { if (is_screen_off && !dhdcdc_wifiLock) pm_type = PM_MAX; else pm_type = PM_FAST; printf("update pm: %s, wifiLock: %d\n", pm_type==1?"PM_MAX":"PM_FAST", dhdcdc_wifiLock); dhd_wl_ioctl_cmd(dhd, WLC_SET_PM, (char *)&pm_type, sizeof(pm_type), TRUE, 0); } return 0; } int dhdhtc_set_power_control(int power_mode, unsigned int reason) { if (reason < DHDHTC_POWER_CTRL_MAX_NUM) { if (power_mode) { dhdhtc_power_ctrl_mask |= 0x1<<reason; } else { dhdhtc_power_ctrl_mask &= ~(0x1<<reason); } } else { printf("%s: Error reason: %u", __func__, reason); return -1; } return 0; } unsigned int dhdhtc_get_cur_pwr_ctrl(void) { return dhdhtc_power_ctrl_mask; } extern int wl_android_is_during_wifi_call(void); int dhdhtc_update_dtim_listen_interval(int is_screen_off) { char iovbuf[32]; int bcn_li_dtim; int ret = 0; dhd_pub_t *dhd = pdhd; if (!dhd) { printf("dhd is not attached\n"); return -1; } if (wl_android_is_during_wifi_call() || !is_screen_off || dhdcdc_wifiLock) bcn_li_dtim = 0; else bcn_li_dtim = 3; bcm_mkiovar("bcn_li_dtim", (char *)&bcn_li_dtim, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); printf("update dtim listern interval: %d\n", bcn_li_dtim); return ret; } static int dhd_suspend_resume_helper(struct dhd_info *dhd, int val, int force) { dhd_pub_t *dhdp = &dhd->pub; int ret = 0; DHD_OS_WAKE_LOCK(dhdp); dhdp->in_suspend = val; if ((force || !dhdp->suspend_disable_flag) && (dhd_check_ap_wfd_mode_set(dhdp) == FALSE)) { ret = dhd_set_suspend(val, dhdp); } DHD_OS_WAKE_UNLOCK(dhdp); return ret; } static void dhd_early_suspend(struct early_suspend *h) { struct dhd_info *dhd = container_of(h, struct dhd_info, early_suspend); DHD_TRACE(("%s: enter\n", __FUNCTION__)); if (dhd) dhd_suspend_resume_helper(dhd, 1, 0); } static void dhd_late_resume(struct early_suspend *h) { struct dhd_info *dhd = container_of(h, struct dhd_info, early_suspend); DHD_TRACE(("%s: enter\n", __FUNCTION__)); if (dhd) dhd_suspend_resume_helper(dhd, 0, 0); } #endif void dhd_timeout_start(dhd_timeout_t *tmo, uint usec) { tmo->limit = usec; tmo->increment = 0; tmo->elapsed = 0; tmo->tick = 1000000 / HZ; } int dhd_timeout_expired(dhd_timeout_t *tmo) { if (tmo->increment == 0) { tmo->increment = 1; return 0; } if (tmo->elapsed >= tmo->limit) return 1; tmo->elapsed += tmo->increment; if (tmo->increment < tmo->tick) { OSL_DELAY(tmo->increment); tmo->increment *= 2; if (tmo->increment > tmo->tick) tmo->increment = tmo->tick; } else { wait_queue_head_t delay_wait; DECLARE_WAITQUEUE(wait, current); int pending; init_waitqueue_head(&delay_wait); add_wait_queue(&delay_wait, &wait); set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(1); pending = signal_pending(current); remove_wait_queue(&delay_wait, &wait); set_current_state(TASK_RUNNING); if (pending) return 1; } return 0; } int dhd_net2idx(dhd_info_t *dhd, struct net_device *net) { int i = 0; ASSERT(dhd); while (i < DHD_MAX_IFS) { if (dhd->iflist[i] && (dhd->iflist[i]->net == net)) return i; i++; } return DHD_BAD_IF; } struct net_device * dhd_idx2net(void *pub, int ifidx) { struct dhd_pub *dhd_pub = (struct dhd_pub *)pub; struct dhd_info *dhd_info; if (!dhd_pub || ifidx < 0 || ifidx >= DHD_MAX_IFS) return NULL; dhd_info = dhd_pub->info; if (dhd_info && dhd_info->iflist[ifidx]) return dhd_info->iflist[ifidx]->net; return NULL; } int dhd_ifname2idx(dhd_info_t *dhd, char *name) { int i = DHD_MAX_IFS; ASSERT(dhd); if (name == NULL || *name == '\0') return 0; while (--i > 0) if (dhd->iflist[i] && !strncmp(dhd->iflist[i]->name, name, IFNAMSIZ)) break; DHD_TRACE(("%s: return idx %d for \"%s\"\n", __FUNCTION__, i, name)); return i; } char * dhd_ifname(dhd_pub_t *dhdp, int ifidx) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; ASSERT(dhd); if (ifidx < 0 || ifidx >= DHD_MAX_IFS) { DHD_ERROR(("%s: ifidx %d out of range\n", __FUNCTION__, ifidx)); return "<if_bad>"; } if (dhd->iflist[ifidx] == NULL) { DHD_ERROR(("%s: null i/f %d\n", __FUNCTION__, ifidx)); return "<if_null>"; } if (dhd->iflist[ifidx]->net) return dhd->iflist[ifidx]->net->name; return "<if_none>"; } uint8 * dhd_bssidx2bssid(dhd_pub_t *dhdp, int idx) { int i; dhd_info_t *dhd = (dhd_info_t *)dhdp; ASSERT(dhd); for (i = 0; i < DHD_MAX_IFS; i++) if (dhd->iflist[i] && dhd->iflist[i]->bssidx == idx) return dhd->iflist[i]->mac_addr; return NULL; } void dhd_state_set_flags(dhd_pub_t *dhdp, dhd_attach_states_t flags, int add) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; ASSERT(dhd); if (add) { DHD_INFO(("%s: add flags %x to dhd_state(%x).\n", __FUNCTION__, flags, dhd->dhd_state)); dhd->dhd_state |= flags; } else { DHD_INFO(("%s: remove flags %x to dhd_state(%x).\n", __FUNCTION__, flags, dhd->dhd_state)); dhd->dhd_state &= (~flags); } DHD_INFO(("%s: dhd_state=%x.\n", __FUNCTION__, dhd->dhd_state)); } static void _dhd_set_multicast_list(dhd_info_t *dhd, int ifidx) { struct net_device *dev; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35) struct netdev_hw_addr *ha; #else struct dev_mc_list *mclist; #endif uint32 allmulti, cnt; wl_ioctl_t ioc; char *buf, *bufp; uint buflen; int ret; #ifdef MCAST_LIST_ACCUMULATION int i; uint32 cnt_iface[DHD_MAX_IFS]; cnt = 0; allmulti = 0; for (i = 0; i < DHD_MAX_IFS; i++) { if (dhd->iflist[i]) { dev = dhd->iflist[i]->net; #else ASSERT(dhd && dhd->iflist[ifidx]); dev = dhd->iflist[ifidx]->net; #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27) netif_addr_lock_bh(dev); #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35) #ifdef MCAST_LIST_ACCUMULATION cnt_iface[i] = netdev_mc_count(dev); cnt += cnt_iface[i]; #else cnt = netdev_mc_count(dev); #endif #else #ifdef MCAST_LIST_ACCUMULATION cnt += dev->mc_count; #else cnt = dev->mc_count; #endif #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27) netif_addr_unlock_bh(dev); #endif #ifdef MCAST_LIST_ACCUMULATION allmulti |= (dev->flags & IFF_ALLMULTI) ? TRUE : FALSE; } } #else allmulti = (dev->flags & IFF_ALLMULTI) ? TRUE : FALSE; #endif #ifdef PASS_ALL_MCAST_PKTS #ifdef PKT_FILTER_SUPPORT if (!dhd->pub.early_suspended) #endif allmulti = TRUE; #endif buflen = sizeof("mcast_list") + sizeof(cnt) + (cnt * ETHER_ADDR_LEN); if (!(bufp = buf = MALLOC(dhd->pub.osh, buflen))) { DHD_ERROR(("%s: out of memory for mcast_list, cnt %d\n", dhd_ifname(&dhd->pub, ifidx), cnt)); return; } strncpy(bufp, "mcast_list", sizeof("mcast_list")); bufp += sizeof("mcast_list"); cnt = htol32(cnt); memcpy(bufp, &cnt, sizeof(cnt)); bufp += sizeof(cnt); #ifdef MCAST_LIST_ACCUMULATION for (i = 0; i < DHD_MAX_IFS; i++) { if (dhd->iflist[i]) { DHD_TRACE(("_dhd_set_multicast_list: ifidx %d\n", i)); dev = dhd->iflist[i]->net; #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27) netif_addr_lock_bh(dev); #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35) netdev_for_each_mc_addr(ha, dev) { #ifdef MCAST_LIST_ACCUMULATION if (!cnt_iface[i]) #else if (!cnt) #endif break; memcpy(bufp, ha->addr, ETHER_ADDR_LEN); bufp += ETHER_ADDR_LEN; #ifdef MCAST_LIST_ACCUMULATION DHD_TRACE(("_dhd_set_multicast_list: cnt " "%d %02x:%02x:%02x:%02x:%02x:%02x\n", cnt_iface[i], ha->addr[0], ha->addr[1], ha->addr[2], ha->addr[3], ha->addr[4], ha->addr[5])); cnt_iface[i]--; #else cnt--; #endif } #else #ifdef MCAST_LIST_ACCUMULATION for (mclist = dev->mc_list; (mclist && (cnt_iface[i] > 0)); cnt_iface[i]--, mclist = mclist->next) { #else for (mclist = dev->mc_list; (mclist && (cnt > 0)); cnt--, mclist = mclist->next) { #endif memcpy(bufp, (void *)mclist->dmi_addr, ETHER_ADDR_LEN); bufp += ETHER_ADDR_LEN; } #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27) netif_addr_unlock_bh(dev); #endif #ifdef MCAST_LIST_ACCUMULATION } } #endif memset(&ioc, 0, sizeof(ioc)); ioc.cmd = WLC_SET_VAR; ioc.buf = buf; ioc.len = buflen; ioc.set = TRUE; ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len); if (ret < 0) { DHD_ERROR(("%s: set mcast_list failed, cnt %d\n", dhd_ifname(&dhd->pub, ifidx), cnt)); allmulti = cnt ? TRUE : allmulti; } MFREE(dhd->pub.osh, buf, buflen); buflen = sizeof("allmulti") + sizeof(allmulti); if (!(buf = MALLOC(dhd->pub.osh, buflen))) { DHD_ERROR(("%s: out of memory for allmulti\n", dhd_ifname(&dhd->pub, ifidx))); return; } allmulti = htol32(allmulti); if (!bcm_mkiovar("allmulti", (void*)&allmulti, sizeof(allmulti), buf, buflen)) { DHD_ERROR(("%s: mkiovar failed for allmulti, datalen %d buflen %u\n", dhd_ifname(&dhd->pub, ifidx), (int)sizeof(allmulti), buflen)); MFREE(dhd->pub.osh, buf, buflen); return; } memset(&ioc, 0, sizeof(ioc)); ioc.cmd = WLC_SET_VAR; ioc.buf = buf; ioc.len = buflen; ioc.set = TRUE; ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len); if (ret < 0) { DHD_ERROR(("%s: set allmulti %d failed\n", dhd_ifname(&dhd->pub, ifidx), ltoh32(allmulti))); } MFREE(dhd->pub.osh, buf, buflen); #ifdef MCAST_LIST_ACCUMULATION allmulti = 0; for (i = 0; i < DHD_MAX_IFS; i++) { if (dhd->iflist[i]) { dev = dhd->iflist[i]->net; allmulti |= (dev->flags & IFF_PROMISC) ? TRUE : FALSE; } } #else allmulti = (dev->flags & IFF_PROMISC) ? TRUE : FALSE; #endif allmulti = htol32(allmulti); memset(&ioc, 0, sizeof(ioc)); ioc.cmd = WLC_SET_PROMISC; ioc.buf = &allmulti; ioc.len = sizeof(allmulti); ioc.set = TRUE; ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len); if (ret < 0) { DHD_ERROR(("%s: set promisc %d failed\n", dhd_ifname(&dhd->pub, ifidx), ltoh32(allmulti))); } } #ifdef CUSTOMER_HW4 int #else static int #endif _dhd_set_mac_address(dhd_info_t *dhd, int ifidx, struct ether_addr *addr) { char buf[32]; wl_ioctl_t ioc; int ret; if (module_remove) { printf("%s: module removed.\n", __FUNCTION__); return -1; } if (!bcm_mkiovar("cur_etheraddr", (char*)addr, ETHER_ADDR_LEN, buf, 32)) { DHD_ERROR(("%s: mkiovar failed for cur_etheraddr\n", dhd_ifname(&dhd->pub, ifidx))); return -1; } memset(&ioc, 0, sizeof(ioc)); ioc.cmd = WLC_SET_VAR; ioc.buf = buf; ioc.len = 32; ioc.set = TRUE; ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len); if (ret < 0) { DHD_ERROR(("%s: set cur_etheraddr failed\n", dhd_ifname(&dhd->pub, ifidx))); } else { memcpy(dhd->iflist[ifidx]->net->dev_addr, addr, ETHER_ADDR_LEN); memcpy(dhd->pub.mac.octet, addr, ETHER_ADDR_LEN); } return ret; } #ifdef SOFTAP extern struct net_device *ap_net_dev; extern tsk_ctl_t ap_eth_ctl; #endif static void dhd_op_if(dhd_if_t *ifp) { dhd_info_t *dhd; int ret = 0, err = 0; #ifdef SOFTAP unsigned long flags; #endif if (!ifp || !ifp->info || !ifp->idx) return; ASSERT(ifp && ifp->info && ifp->idx); dhd = ifp->info; DHD_TRACE(("%s: idx %d, state %d\n", __FUNCTION__, ifp->idx, ifp->state)); #ifdef WL_CFG80211 if (wl_cfg80211_is_progress_ifchange()) return; #endif switch (ifp->state) { case DHD_IF_ADD: if (ifp->net != NULL) { DHD_ERROR(("%s: ERROR: netdev:%s already exists, try free & unregister \n", __FUNCTION__, ifp->net->name)); netif_stop_queue(ifp->net); unregister_netdev(ifp->net); free_netdev(ifp->net); } if (!(ifp->net = alloc_etherdev(sizeof(dhd)))) { DHD_ERROR(("%s: OOM - alloc_etherdev\n", __FUNCTION__)); ret = -ENOMEM; } if (ret == 0) { strncpy(ifp->net->name, ifp->name, IFNAMSIZ); ifp->net->name[IFNAMSIZ - 1] = '\0'; memcpy(netdev_priv(ifp->net), &dhd, sizeof(dhd)); #ifdef WL_CFG80211 if (dhd->dhd_state & DHD_ATTACH_STATE_CFG80211) if (!wl_cfg80211_notify_ifadd(ifp->net, ifp->idx, ifp->bssidx, (void*)dhd_net_attach)) { ifp->state = DHD_IF_NONE; ifp->event2cfg80211 = TRUE; return; } #endif if ((err = dhd_net_attach(&dhd->pub, ifp->idx)) != 0) { DHD_ERROR(("%s: dhd_net_attach failed, err %d\n", __FUNCTION__, err)); ret = -EOPNOTSUPP; } else { #if defined(SOFTAP) #ifndef APSTA_CONCURRENT if (ap_fw_loaded && !(dhd->dhd_state & DHD_ATTACH_STATE_CFG80211)) { #endif flags = dhd_os_spin_lock(&dhd->pub); printf("%s save ptr to wl0.1 netdev for use in wl_iw.c \n",__FUNCTION__); ap_net_dev = ifp->net; up(&ap_eth_ctl.sema); dhd_os_spin_unlock(&dhd->pub, flags); #ifndef APSTA_CONCURRENT } #endif #endif DHD_TRACE(("\n ==== pid:%x, net_device for if:%s created ===\n\n", current->pid, ifp->net->name)); ifp->state = DHD_IF_NONE; } } break; case DHD_IF_DEL: ifp->state = DHD_IF_DELETING; if (ifp->net != NULL) { DHD_TRACE(("\n%s: got 'DHD_IF_DEL' state\n", __FUNCTION__)); netif_stop_queue(ifp->net); #ifdef WL_CFG80211 if (dhd->dhd_state & DHD_ATTACH_STATE_CFG80211) { wl_cfg80211_ifdel_ops(ifp->net); } #endif msleep(300); unregister_netdev(ifp->net); ret = DHD_DEL_IF; #ifdef WL_CFG80211 if (dhd->dhd_state & DHD_ATTACH_STATE_CFG80211) { wl_cfg80211_notify_ifdel(); } #endif } break; case DHD_IF_DELETING: break; default: DHD_ERROR(("%s: bad op %d\n", __FUNCTION__, ifp->state)); ASSERT(!ifp->state); break; } if (ret < 0) { ifp->set_multicast = FALSE; if (ifp->net) { #ifdef SOFTAP flags = dhd_os_spin_lock(&dhd->pub); if (ifp->net == ap_net_dev) ap_net_dev = NULL; dhd_os_spin_unlock(&dhd->pub, flags); #endif free_netdev(ifp->net); ifp->net = NULL; } dhd->iflist[ifp->idx] = NULL; MFREE(dhd->pub.osh, ifp, sizeof(*ifp)); } } static int _dhd_sysioc_thread(void *data) { tsk_ctl_t *tsk = (tsk_ctl_t *)data; dhd_info_t *dhd = (dhd_info_t *)tsk->parent; int i; #ifdef SOFTAP bool in_ap = FALSE; unsigned long flags; #endif #ifndef USE_KTHREAD_API DAEMONIZE("dhd_sysioc"); complete(&tsk->completed); #endif while (down_interruptible(&tsk->sema) == 0) { #ifdef MCAST_LIST_ACCUMULATION bool set_multicast = FALSE; #endif if (dhd->dhd_force_exit== TRUE) break; SMP_RD_BARRIER_DEPENDS(); if (tsk->terminated) { break; } dhd_net_if_lock_local(dhd); DHD_OS_WAKE_LOCK(&dhd->pub); for (i = 0; i < DHD_MAX_IFS; i++) { if (dhd->iflist[i]) { DHD_TRACE(("%s: interface %d\n", __FUNCTION__, i)); #ifdef SOFTAP flags = dhd_os_spin_lock(&dhd->pub); in_ap = (ap_net_dev != NULL); dhd_os_spin_unlock(&dhd->pub, flags); #endif if (dhd->iflist[i] && dhd->iflist[i]->state) dhd_op_if(dhd->iflist[i]); if (dhd->iflist[i] == NULL) { DHD_TRACE(("\n\n %s: interface %d just been removed," "!\n\n", __FUNCTION__, i)); continue; } #ifdef SOFTAP if (in_ap && dhd->set_macaddress == i+1) { DHD_TRACE(("attempt to set MAC for %s in AP Mode," "blocked. \n", dhd->iflist[i]->net->name)); dhd->set_macaddress = 0; continue; } if (in_ap && dhd->iflist[i]->set_multicast) { DHD_TRACE(("attempt to set MULTICAST list for %s" "in AP Mode, blocked. \n", dhd->iflist[i]->net->name)); dhd->iflist[i]->set_multicast = FALSE; continue; } #endif if (dhd->pub.up == 0) continue; if (dhd->iflist[i]->set_multicast) { dhd->iflist[i]->set_multicast = FALSE; #ifdef MCAST_LIST_ACCUMULATION set_multicast = TRUE; #else _dhd_set_multicast_list(dhd, i); #endif } if (dhd->set_macaddress == i+1) { dhd->set_macaddress = 0; if (_dhd_set_mac_address(dhd, i, &dhd->macvalue) == 0) { DHD_INFO(( "dhd_sysioc_thread: MACID is overwritten\n")); } else { DHD_ERROR(( "dhd_sysioc_thread: _dhd_set_mac_address() failed\n")); } } } } #ifdef MCAST_LIST_ACCUMULATION if (set_multicast) _dhd_set_multicast_list(dhd, 0); #endif DHD_OS_WAKE_UNLOCK(&dhd->pub); dhd_net_if_unlock_local(dhd); } DHD_TRACE(("%s: stopped\n", __FUNCTION__)); complete_and_exit(&tsk->completed, 0); } static int dhd_set_mac_address(struct net_device *dev, void *addr) { int ret = 0; dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); struct sockaddr *sa = (struct sockaddr *)addr; int ifidx; printf("enter %s\n", __func__); if ( !dhd->pub.up || (dhd->pub.busstate == DHD_BUS_DOWN)) { printf("%s: dhd is down. skip it.\n", __func__); return -ENODEV; } ifidx = dhd_net2idx(dhd, dev); if (ifidx == DHD_BAD_IF) return -1; ASSERT(dhd->thr_sysioc_ctl.thr_pid >= 0); memcpy(&dhd->macvalue, sa->sa_data, ETHER_ADDR_LEN); dhd->set_macaddress = ifidx+1; up(&dhd->thr_sysioc_ctl.sema); return ret; } static void dhd_set_multicast_list(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ifidx; printf("enter %s\n", __func__); if ( !dhd->pub.up || (dhd->pub.busstate == DHD_BUS_DOWN) || module_remove) { printf("%s: dhd is down module_remove[%d]. skip it.\n", __func__,module_remove); return; } ifidx = dhd_net2idx(dhd, dev); if (ifidx == DHD_BAD_IF) return; ASSERT(dhd->thr_sysioc_ctl.thr_pid >= 0); dhd->iflist[ifidx]->set_multicast = TRUE; up(&dhd->thr_sysioc_ctl.sema); } #ifdef PROP_TXSTATUS int dhd_os_wlfc_block(dhd_pub_t *pub) { dhd_info_t *di = (dhd_info_t *)(pub->info); ASSERT(di != NULL); spin_lock_bh(&di->wlfc_spinlock); return 1; } int dhd_os_wlfc_unblock(dhd_pub_t *pub) { dhd_info_t *di = (dhd_info_t *)(pub->info); (void)di; ASSERT(di != NULL); spin_unlock_bh(&di->wlfc_spinlock); return 1; } const uint8 wme_fifo2ac[] = { 0, 1, 2, 3, 1, 1 }; uint8 prio2fifo[8] = { 1, 0, 0, 1, 2, 2, 3, 3 }; #define WME_PRIO2AC(prio) wme_fifo2ac[prio2fifo[(prio)]] #endif int dhd_sendpkt(dhd_pub_t *dhdp, int ifidx, void *pktbuf) { int ret; dhd_info_t *dhd = (dhd_info_t *)(dhdp->info); struct ether_header *eh = NULL; if (!dhdp->up || (dhdp->busstate == DHD_BUS_DOWN)) { PKTFREE(dhdp->osh, pktbuf, TRUE); return -ENODEV; } if (PKTLEN(dhdp->osh, pktbuf) >= ETHER_HDR_LEN) { uint8 *pktdata = (uint8 *)PKTDATA(dhdp->osh, pktbuf); eh = (struct ether_header *)pktdata; if (ETHER_ISMULTI(eh->ether_dhost)) dhdp->tx_multicast++; if (ntoh16(eh->ether_type) == ETHER_TYPE_802_1X) atomic_inc(&dhd->pend_8021x_cnt); } else { PKTFREE(dhd->pub.osh, pktbuf, TRUE); return BCME_ERROR; } if (PKTPRIO(pktbuf) == 0) pktsetprio(pktbuf, FALSE); #ifdef PROP_TXSTATUS if (dhdp->wlfc_state) { DHD_PKTTAG_SETIF(PKTTAG(pktbuf), ifidx); DHD_PKTTAG_SETDSTN(PKTTAG(pktbuf), eh->ether_dhost); if (ETHER_ISMULTI(eh->ether_dhost)) DHD_PKTTAG_SETFIFO(PKTTAG(pktbuf), AC_COUNT); else DHD_PKTTAG_SETFIFO(PKTTAG(pktbuf), WME_PRIO2AC(PKTPRIO(pktbuf))); } else #endif dhd_prot_hdrpush(dhdp, ifidx, pktbuf); #ifdef WLMEDIA_HTSF dhd_htsf_addtxts(dhdp, pktbuf); #endif #ifdef PROP_TXSTATUS if (dhdp->wlfc_state && ((athost_wl_status_info_t*)dhdp->wlfc_state)->proptxstatus_mode != WLFC_FCMODE_NONE) { dhd_os_wlfc_block(dhdp); ret = dhd_wlfc_enque_sendq(dhdp->wlfc_state, DHD_PKTTAG_FIFO(PKTTAG(pktbuf)), pktbuf); dhd_wlfc_commit_packets(dhdp->wlfc_state, (f_commitpkt_t)dhd_bus_txdata, dhdp->bus); if (((athost_wl_status_info_t*)dhdp->wlfc_state)->toggle_host_if) { ((athost_wl_status_info_t*)dhdp->wlfc_state)->toggle_host_if = 0; } dhd_os_wlfc_unblock(dhdp); } else ret = dhd_bus_txdata(dhdp->bus, pktbuf); #else ret = dhd_bus_txdata(dhdp->bus, pktbuf); #endif return ret; } static int txq_full_event_num = 0; int dhd_start_xmit(struct sk_buff *skb, struct net_device *net) { int ret; void *pktbuf; dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); int ifidx; #ifdef WLMEDIA_HTSF uint8 htsfdlystat_sz = dhd->pub.htsfdlystat_sz; #else uint8 htsfdlystat_sz = 0; #endif DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (module_remove) { printf("%s: module removed.", __FUNCTION__); dev_kfree_skb(skb); netif_stop_queue(net); return -ENODEV; } DHD_OS_WAKE_LOCK(&dhd->pub); if (dhd->pub.busstate == DHD_BUS_DOWN || dhd->pub.hang_was_sent) { DHD_ERROR(("%s: xmit rejected pub.up=%d busstate=%d \n", __FUNCTION__, dhd->pub.up, dhd->pub.busstate)); netif_stop_queue(net); if (dhd->pub.up) { DHD_ERROR(("%s: Event HANG sent up\n", __FUNCTION__)); net_os_send_hang_message(net); } DHD_OS_WAKE_UNLOCK(&dhd->pub); #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)) return -ENODEV; #else return NETDEV_TX_BUSY; #endif } ifidx = dhd_net2idx(dhd, net); if (ifidx == DHD_BAD_IF) { DHD_ERROR(("%s: bad ifidx %d\n", __FUNCTION__, ifidx)); netif_stop_queue(net); dev_kfree_skb(skb); DHD_OS_WAKE_UNLOCK(&dhd->pub); #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)) return -ENODEV; #else return NETDEV_TX_BUSY; #endif } if (skb_headroom(skb) < dhd->pub.hdrlen + htsfdlystat_sz) { struct sk_buff *skb2; DHD_INFO(("%s: insufficient headroom\n", dhd_ifname(&dhd->pub, ifidx))); dhd->pub.tx_realloc++; skb2 = skb_realloc_headroom(skb, dhd->pub.hdrlen + htsfdlystat_sz); dev_kfree_skb(skb); if ((skb = skb2) == NULL) { DHD_ERROR(("%s: skb_realloc_headroom failed\n", dhd_ifname(&dhd->pub, ifidx))); ret = -ENOMEM; goto done; } } if (!(pktbuf = PKTFRMNATIVE(dhd->pub.osh, skb))) { DHD_ERROR(("%s: PKTFRMNATIVE failed\n", dhd_ifname(&dhd->pub, ifidx))); dev_kfree_skb_any(skb); ret = -ENOMEM; goto done; } #ifdef WLMEDIA_HTSF if (htsfdlystat_sz && PKTLEN(dhd->pub.osh, pktbuf) >= ETHER_ADDR_LEN) { uint8 *pktdata = (uint8 *)PKTDATA(dhd->pub.osh, pktbuf); struct ether_header *eh = (struct ether_header *)pktdata; if (!ETHER_ISMULTI(eh->ether_dhost) && (ntoh16(eh->ether_type) == ETHER_TYPE_IP)) { eh->ether_type = hton16(ETHER_TYPE_BRCM_PKTDLYSTATS); } } #endif #if HTC_DUMP_PACKLEN if (PKTLEN(dhd->pub.osh, pktbuf) >= 1500) { printf("startx: send pkt len = %d\n", PKTLEN(dhd->pub.osh, pktbuf)); } #endif ret = dhd_sendpkt(&dhd->pub, ifidx, pktbuf); if ( ret == BCME_NORESOURCE ) { txq_full_event_num++; if ( txq_full_event_num >= MAX_TXQ_FULL_EVENT ) { txq_full_event_num = 0; net_os_send_hang_message(net); } } else { txq_full_event_num = 0; } done: if (ret) dhd->pub.dstats.tx_dropped++; else dhd->pub.tx_packets++; DHD_OS_WAKE_UNLOCK(&dhd->pub); #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)) return 0; #else return NETDEV_TX_OK; #endif } void dhd_txflowcontrol(dhd_pub_t *dhdp, int ifidx, bool state) { struct net_device *net; dhd_info_t *dhd = dhdp->info; int i; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); dhdp->txoff = state; ASSERT(dhd); if (ifidx == ALL_INTERFACES) { for (i = 0; i < DHD_MAX_IFS; i++) { if (dhd->iflist[i]) { net = dhd->iflist[i]->net; if (state == ON) netif_stop_queue(net); else netif_wake_queue(net); } } } else { if (dhd->iflist[ifidx]) { net = dhd->iflist[ifidx]->net; if (state == ON) netif_stop_queue(net); else netif_wake_queue(net); } } } #ifdef DHD_RX_DUMP typedef struct { uint16 type; const char *str; } PKTTYPE_INFO; static const PKTTYPE_INFO packet_type_info[] = { { ETHER_TYPE_IP, "IP" }, { ETHER_TYPE_ARP, "ARP" }, { ETHER_TYPE_BRCM, "BRCM" }, { ETHER_TYPE_802_1X, "802.1X" }, { ETHER_TYPE_WAI, "WAPI" }, { 0, ""} }; static const char *_get_packet_type_str(uint16 type) { int i; int n = sizeof(packet_type_info)/sizeof(packet_type_info[1]) - 1; for (i = 0; i < n; i++) { if (packet_type_info[i].type == type) return packet_type_info[i].str; } return packet_type_info[n].str; } #endif void dhd_rx_frame(dhd_pub_t *dhdp, int ifidx, void *pktbuf, int numpkt, uint8 chan) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; struct sk_buff *skb; uchar *eth; uint len; void *data = NULL, *pnext = NULL; int i; dhd_if_t *ifp; wl_event_msg_t event; int tout_rx = 0; int tout_ctrl = 0; #ifdef DHD_RX_DUMP #ifdef DHD_RX_FULL_DUMP int k; #endif char *dump_data; uint16 protocol; #endif #ifdef HTC_KlocWork memset(&event,0,sizeof(event)); #endif DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (module_remove || (!module_insert)) { for (i = 0; pktbuf && i < numpkt; i++, pktbuf = pnext) { pnext = PKTNEXT(dhdp->osh, pktbuf); PKTSETNEXT(wl->sh.osh, pktbuf, NULL); skb = PKTTONATIVE(dhdp->osh, pktbuf); dev_kfree_skb_any(skb); } if (!module_insert) DHD_ERROR(("%s: module not insert, skip\n", __FUNCTION__)); else DHD_ERROR(("%s: module removed. skip rx frame\n", __FUNCTION__)); return; } for (i = 0; pktbuf && i < numpkt; i++, pktbuf = pnext) { #ifdef WLBTAMP struct ether_header *eh; struct dot11_llc_snap_header *lsh; #endif pnext = PKTNEXT(dhdp->osh, pktbuf); PKTSETNEXT(wl->sh.osh, pktbuf, NULL); ifp = dhd->iflist[ifidx]; if (ifp == NULL) { DHD_ERROR(("%s: ifp is NULL. drop packet\n", __FUNCTION__)); PKTFREE(dhdp->osh, pktbuf, TRUE); continue; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) if (!ifp->net || ifp->net->reg_state != NETREG_REGISTERED || !dhd->pub.up) { DHD_ERROR(("%s: net device is NOT registered yet. drop packet\n", __FUNCTION__)); PKTFREE(dhdp->osh, pktbuf, TRUE); continue; } #endif #ifdef WLBTAMP eh = (struct ether_header *)PKTDATA(wl->sh.osh, pktbuf); lsh = (struct dot11_llc_snap_header *)&eh[1]; if ((ntoh16(eh->ether_type) < ETHER_TYPE_MIN) && (PKTLEN(wl->sh.osh, pktbuf) >= RFC1042_HDR_LEN) && bcmp(lsh, BT_SIG_SNAP_MPROT, DOT11_LLC_SNAP_HDR_LEN - 2) == 0 && lsh->type == HTON16(BTA_PROT_L2CAP)) { amp_hci_ACL_data_t *ACL_data = (amp_hci_ACL_data_t *) ((uint8 *)eh + RFC1042_HDR_LEN); ACL_data = NULL; } #endif #ifdef PROP_TXSTATUS if (dhdp->wlfc_state && PKTLEN(wl->sh.osh, pktbuf) == 0) { ((athost_wl_status_info_t*)dhdp->wlfc_state)->stats.wlfc_header_only_pkt++; PKTFREE(dhdp->osh, pktbuf, TRUE); continue; } #endif skb = PKTTONATIVE(dhdp->osh, pktbuf); eth = skb->data; len = skb->len; #ifdef DHD_RX_DUMP dump_data = skb->data; protocol = (dump_data[12] << 8) | dump_data[13]; DHD_ERROR(("RX DUMP - %s\n", _get_packet_type_str(protocol))); #ifdef DHD_RX_FULL_DUMP if (protocol != ETHER_TYPE_BRCM) { for (k = 0; k < skb->len; k++) { DHD_ERROR(("%02X ", dump_data[k])); if ((k & 15) == 15) DHD_ERROR(("\n")); } DHD_ERROR(("\n")); } #endif if (protocol != ETHER_TYPE_BRCM) { if (dump_data[0] == 0xFF) { DHD_ERROR(("%s: BROADCAST\n", __FUNCTION__)); if ((dump_data[12] == 8) && (dump_data[13] == 6)) { DHD_ERROR(("%s: ARP %d\n", __FUNCTION__, dump_data[0x15])); } } else if (dump_data[0] & 1) { DHD_ERROR(("%s: MULTICAST: " "%02X:%02X:%02X:%02X:%02X:%02X\n", __FUNCTION__, dump_data[0], dump_data[1], dump_data[2], dump_data[3], dump_data[4], dump_data[5])); } if (protocol == ETHER_TYPE_802_1X) { DHD_ERROR(("ETHER_TYPE_802_1X: " "ver %d, type %d, replay %d\n", dump_data[14], dump_data[15], dump_data[30])); } } #endif ifp = dhd->iflist[ifidx]; if (ifp == NULL) ifp = dhd->iflist[0]; ASSERT(ifp); skb->dev = ifp->net; skb->protocol = eth_type_trans(skb, skb->dev); if (skb->pkt_type == PACKET_MULTICAST) { dhd->pub.rx_multicast++; } skb->data = eth; skb->len = len; #ifdef WLMEDIA_HTSF dhd_htsf_addrxts(dhdp, pktbuf); #endif skb_pull(skb, ETH_HLEN); #ifdef BRCM_WPSAP if (ntoh16(skb->protocol) == ETHER_TYPE_802_1X){ #if 0 int plen = 0; printk("@@@ got eap packet start! \n"); for(plen = 0; plen<len ; plen++){ printk("%02x ",eth[plen]); if((plen + 1 )%8 == 0) printk("\n"); } printk("\n"); printk("@@@ got eap packet End! \n"); #endif if(eth[22] == 0x01) { ASSERT(dhd->iflist[ifidx]->net != NULL); if (dhd->iflist[ifidx]->net) wl_iw_send_priv_event(dhd->iflist[ifidx]->net, "WPS_START"); } } #endif if (ntoh16(skb->protocol) == ETHER_TYPE_BRCM) { dhd_wl_host_event(dhd, &ifidx, #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 22) skb->mac_header, #else skb->mac.raw, #endif &event, &data); wl_event_to_host_order(&event); if (!tout_ctrl) tout_ctrl = DHD_PACKET_TIMEOUT_MS; #ifdef WLBTAMP if (event.event_type == WLC_E_BTA_HCI_EVENT) { #ifdef HTC_KlocWork if(!data) { printf("[HTCKW] dhd_rx_frame: data=NULL\n"); } else #endif dhd_bta_doevt(dhdp, data, event.datalen); } tout = DHD_EVENT_TIMEOUT_MS; #endif #if defined(PNO_SUPPORT) if (event.event_type == WLC_E_PFN_NET_FOUND) { tout_ctrl *= 2; } #endif } else { tout_rx = DHD_PACKET_TIMEOUT_MS; } ASSERT(ifidx < DHD_MAX_IFS && dhd->iflist[ifidx]); if (dhd->iflist[ifidx] && !dhd->iflist[ifidx]->state) ifp = dhd->iflist[ifidx]; if (ifp->net) ifp->net->last_rx = jiffies; dhdp->dstats.rx_bytes += skb->len; dhdp->rx_packets++; if (in_interrupt()) { netif_rx(skb); } else { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) netif_rx_ni(skb); #else ulong flags; netif_rx(skb); local_irq_save(flags); RAISE_RX_SOFTIRQ(); local_irq_restore(flags); #endif } } DHD_OS_WAKE_LOCK_RX_TIMEOUT_ENABLE(dhdp, tout_rx); DHD_OS_WAKE_LOCK_CTRL_TIMEOUT_ENABLE(dhdp, tout_ctrl); } void dhd_event(struct dhd_info *dhd, char *evpkt, int evlen, int ifidx) { return; } void dhd_txcomplete(dhd_pub_t *dhdp, void *txp, bool success) { uint ifidx; dhd_info_t *dhd = (dhd_info_t *)(dhdp->info); struct ether_header *eh; uint16 type; #ifdef WLBTAMP uint len; #endif dhd_prot_hdrpull(dhdp, &ifidx, txp, NULL, NULL); eh = (struct ether_header *)PKTDATA(dhdp->osh, txp); type = ntoh16(eh->ether_type); if (type == ETHER_TYPE_802_1X) atomic_dec(&dhd->pend_8021x_cnt); #ifdef WLBTAMP len = PKTLEN(dhdp->osh, txp); if ((type < ETHER_TYPE_MIN) && (len >= RFC1042_HDR_LEN)) { struct dot11_llc_snap_header *lsh = (struct dot11_llc_snap_header *)&eh[1]; if (bcmp(lsh, BT_SIG_SNAP_MPROT, DOT11_LLC_SNAP_HDR_LEN - 2) == 0 && ntoh16(lsh->type) == BTA_PROT_L2CAP) { dhd_bta_tx_hcidata_complete(dhdp, txp, success); } } #endif } static struct net_device_stats * dhd_get_stats(struct net_device *net) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); dhd_if_t *ifp; int ifidx; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); ifidx = dhd_net2idx(dhd, net); if (ifidx == DHD_BAD_IF) { DHD_ERROR(("%s: BAD_IF\n", __FUNCTION__)); return NULL; } ifp = dhd->iflist[ifidx]; ASSERT(dhd && ifp); if (dhd->pub.up) { if (module_remove) { printf("%s: module removed. return old value. ifp=%p, dhd=%p\n", __FUNCTION__, ifp, dhd); } else dhd_prot_dstats(&dhd->pub); } ifp->stats.rx_packets = dhd->pub.dstats.rx_packets; ifp->stats.tx_packets = dhd->pub.dstats.tx_packets; ifp->stats.rx_bytes = dhd->pub.dstats.rx_bytes; ifp->stats.tx_bytes = dhd->pub.dstats.tx_bytes; ifp->stats.rx_errors = dhd->pub.dstats.rx_errors; ifp->stats.tx_errors = dhd->pub.dstats.tx_errors; ifp->stats.rx_dropped = dhd->pub.dstats.rx_dropped; ifp->stats.tx_dropped = dhd->pub.dstats.tx_dropped; ifp->stats.multicast = dhd->pub.dstats.multicast; return &ifp->stats; } #ifdef DHDTHREAD static int dhd_watchdog_thread(void *data) { tsk_ctl_t *tsk = (tsk_ctl_t *)data; dhd_info_t *dhd = (dhd_info_t *)tsk->parent; if (dhd_watchdog_prio > 0) { struct sched_param param; param.sched_priority = (dhd_watchdog_prio < MAX_RT_PRIO)? dhd_watchdog_prio:(MAX_RT_PRIO-1); setScheduler(current, SCHED_FIFO, &param); } #ifndef USE_KTHREAD_API DAEMONIZE("dhd_watchdog"); complete(&tsk->completed); #endif while (1) if (down_interruptible (&tsk->sema) == 0) { unsigned long flags; if (dhd->dhd_force_exit== TRUE) break; SMP_RD_BARRIER_DEPENDS(); if (tsk->terminated) { break; } dhd_os_sdlock(&dhd->pub); if (dhd->pub.dongle_reset == FALSE) { DHD_TIMER(("%s:\n", __FUNCTION__)); dhd_bus_watchdog(&dhd->pub); flags = dhd_os_spin_lock(&dhd->pub); dhd->pub.tickcnt++; if (dhd->wd_timer_valid) mod_timer(&dhd->timer, jiffies + dhd_watchdog_ms * HZ / 1000); dhd_os_spin_unlock(&dhd->pub, flags); } dhd_os_sdunlock(&dhd->pub); DHD_OS_WAKE_UNLOCK(&dhd->pub); } else { break; } complete_and_exit(&tsk->completed, 0); } #endif static void dhd_watchdog(ulong data) { dhd_info_t *dhd = (dhd_info_t *)data; unsigned long flags; DHD_OS_WAKE_LOCK(&dhd->pub); if (dhd->pub.dongle_reset) { DHD_OS_WAKE_UNLOCK(&dhd->pub); return; } #ifdef DHDTHREAD if (dhd->thr_wdt_ctl.thr_pid >= 0) { up(&dhd->thr_wdt_ctl.sema); return; } else { DHD_ERROR(("watch_dog thr stopped, ignore\n")); return; } #endif dhd_os_sdlock(&dhd->pub); dhd_bus_watchdog(&dhd->pub); flags = dhd_os_spin_lock(&dhd->pub); dhd->pub.tickcnt++; if (dhd->wd_timer_valid) mod_timer(&dhd->timer, jiffies + dhd_watchdog_ms * HZ / 1000); dhd_os_spin_unlock(&dhd->pub, flags); dhd_os_sdunlock(&dhd->pub); DHD_OS_WAKE_UNLOCK(&dhd->pub); } int wlan_ioprio_idle = 0; static int prev_wlan_ioprio_idle=0; static inline void set_wlan_ioprio(void) { int ret, prio; if(wlan_ioprio_idle == 1){ prio = ((IOPRIO_CLASS_IDLE << IOPRIO_CLASS_SHIFT) | 0); } else { prio = ((IOPRIO_CLASS_NONE << IOPRIO_CLASS_SHIFT) | 4); } ret = set_task_ioprio(current, prio); DHD_DEFAULT(("set_wlan_ioprio: prio=0x%X, ret=%d\n", prio, ret)); } #ifdef DHDTHREAD #include <linux/sched.h> extern int multi_core_locked; static int rt_class(int priority) { return ((dhd_dpc_prio < MAX_RT_PRIO) && (dhd_dpc_prio != 0))? 1: 0; } static void adjust_thread_priority(void) { struct sched_param param; int ret = 0; if (multi_core_locked) { if ((current->on_cpu > 0) && !rt_class(dhd_dpc_prio)) { param.sched_priority = dhd_dpc_prio = (MAX_RT_PRIO-1); ret = setScheduler(current, SCHED_FIFO, &param); printf("change dhd_dpc to SCHED_FIFO priority: %d, ret: %d", param.sched_priority, ret); { cpumask_t mask; cpumask_clear(&mask); cpumask_set_cpu(1, &mask); cpumask_set_cpu(2, &mask); cpumask_set_cpu(3, &mask); if (sched_setaffinity(0, &mask) < 0) { printf("sched_setaffinity failed"); } else { printf("[adjust_thread_priority]sched_setaffinity ok"); } } } } else { if (rt_class(dhd_dpc_prio)) { param.sched_priority = dhd_dpc_prio = 0; ret = setScheduler(current, SCHED_NORMAL, &param); printf("change dhd_dpc to SCHED_NORMAL priority: %d, ret: %d", param.sched_priority, ret); } } } static int dhd_dpc_thread(void *data) { tsk_ctl_t *tsk = (tsk_ctl_t *)data; dhd_info_t *dhd = (dhd_info_t *)tsk->parent; if (dhd_dpc_prio > 0) { struct sched_param param; param.sched_priority = dhd_dpc_prio; setScheduler(current, SCHED_FIFO, &param); } #ifndef USE_KTHREAD_API DAEMONIZE("dhd_dpc"); complete(&tsk->completed); #endif while (1) { if(prev_wlan_ioprio_idle != wlan_ioprio_idle){ set_wlan_ioprio(); prev_wlan_ioprio_idle = wlan_ioprio_idle; } if (down_interruptible(&tsk->sema) == 0) { adjust_thread_priority(); if (dhd->dhd_force_exit== TRUE) break; SMP_RD_BARRIER_DEPENDS(); if (tsk->terminated) { break; } if (dhd->pub.busstate != DHD_BUS_DOWN) { if (dhd_bus_dpc(dhd->pub.bus)) { up(&tsk->sema); } else { DHD_OS_WAKE_UNLOCK(&dhd->pub); } } else { if (dhd->pub.up) dhd_bus_stop(dhd->pub.bus, TRUE); DHD_OS_WAKE_UNLOCK(&dhd->pub); } } else break; } complete_and_exit(&tsk->completed, 0); } #endif static void dhd_dpc(ulong data) { dhd_info_t *dhd; dhd = (dhd_info_t *)data; if (dhd->pub.busstate != DHD_BUS_DOWN) { if (dhd_bus_dpc(dhd->pub.bus)) tasklet_schedule(&dhd->tasklet); else DHD_OS_WAKE_UNLOCK(&dhd->pub); } else { dhd_bus_stop(dhd->pub.bus, TRUE); DHD_OS_WAKE_UNLOCK(&dhd->pub); } } void dhd_sched_dpc(dhd_pub_t *dhdp) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; DHD_OS_WAKE_LOCK(dhdp); #ifdef DHDTHREAD if (dhd->thr_dpc_ctl.thr_pid >= 0) { up(&dhd->thr_dpc_ctl.sema); return; } #endif if (dhd->dhd_tasklet_create) tasklet_schedule(&dhd->tasklet); } #ifdef TOE static int dhd_toe_get(dhd_info_t *dhd, int ifidx, uint32 *toe_ol) { wl_ioctl_t ioc; char buf[32]; int ret; memset(&ioc, 0, sizeof(ioc)); ioc.cmd = WLC_GET_VAR; ioc.buf = buf; ioc.len = (uint)sizeof(buf); ioc.set = FALSE; strncpy(buf, "toe_ol", sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; if ((ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len)) < 0) { if (ret == -EIO) { DHD_ERROR(("%s: toe not supported by device\n", dhd_ifname(&dhd->pub, ifidx))); return -EOPNOTSUPP; } DHD_INFO(("%s: could not get toe_ol: ret=%d\n", dhd_ifname(&dhd->pub, ifidx), ret)); return ret; } memcpy(toe_ol, buf, sizeof(uint32)); return 0; } static int dhd_toe_set(dhd_info_t *dhd, int ifidx, uint32 toe_ol) { wl_ioctl_t ioc; char buf[32]; int toe, ret; memset(&ioc, 0, sizeof(ioc)); ioc.cmd = WLC_SET_VAR; ioc.buf = buf; ioc.len = (uint)sizeof(buf); ioc.set = TRUE; strncpy(buf, "toe_ol", sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; memcpy(&buf[sizeof("toe_ol")], &toe_ol, sizeof(uint32)); if ((ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len)) < 0) { DHD_ERROR(("%s: could not set toe_ol: ret=%d\n", dhd_ifname(&dhd->pub, ifidx), ret)); return ret; } toe = (toe_ol != 0); strcpy(buf, "toe"); memcpy(&buf[sizeof("toe")], &toe, sizeof(uint32)); if ((ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len)) < 0) { DHD_ERROR(("%s: could not set toe: ret=%d\n", dhd_ifname(&dhd->pub, ifidx), ret)); return ret; } return 0; } #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24) static void dhd_ethtool_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *info) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); snprintf(info->driver, sizeof(info->driver), "wl"); snprintf(info->version, sizeof(info->version), "%lu", dhd->pub.drv_version); } struct ethtool_ops dhd_ethtool_ops = { .get_drvinfo = dhd_ethtool_get_drvinfo }; #endif #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 4, 2) static int dhd_ethtool(dhd_info_t *dhd, void *uaddr) { struct ethtool_drvinfo info; char drvname[sizeof(info.driver)]; uint32 cmd; #ifdef TOE struct ethtool_value edata; uint32 toe_cmpnt, csum_dir; int ret; #endif DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (copy_from_user(&cmd, uaddr, sizeof (uint32))) return -EFAULT; switch (cmd) { case ETHTOOL_GDRVINFO: if (copy_from_user(&info, uaddr, sizeof(info))) return -EFAULT; strncpy(drvname, info.driver, sizeof(info.driver)); drvname[sizeof(info.driver)-1] = '\0'; memset(&info, 0, sizeof(info)); info.cmd = cmd; if (strcmp(drvname, "?dhd") == 0) { snprintf(info.driver, sizeof(info.driver), "dhd"); strncpy(info.version, EPI_VERSION_STR, sizeof(info.version) - 1); info.version[sizeof(info.version) - 1] = '\0'; } else if (!dhd->pub.up) { DHD_ERROR(("%s: dongle is not up\n", __FUNCTION__)); return -ENODEV; } else if (dhd->pub.iswl) snprintf(info.driver, sizeof(info.driver), "wl"); else snprintf(info.driver, sizeof(info.driver), "xx"); snprintf(info.version, sizeof(info.version), "%lu", dhd->pub.drv_version); if (copy_to_user(uaddr, &info, sizeof(info))) return -EFAULT; DHD_CTL(("%s: given %*s, returning %s\n", __FUNCTION__, (int)sizeof(drvname), drvname, info.driver)); break; #ifdef TOE case ETHTOOL_GRXCSUM: case ETHTOOL_GTXCSUM: if ((ret = dhd_toe_get(dhd, 0, &toe_cmpnt)) < 0) return ret; csum_dir = (cmd == ETHTOOL_GTXCSUM) ? TOE_TX_CSUM_OL : TOE_RX_CSUM_OL; edata.cmd = cmd; edata.data = (toe_cmpnt & csum_dir) ? 1 : 0; if (copy_to_user(uaddr, &edata, sizeof(edata))) return -EFAULT; break; case ETHTOOL_SRXCSUM: case ETHTOOL_STXCSUM: if (copy_from_user(&edata, uaddr, sizeof(edata))) return -EFAULT; if ((ret = dhd_toe_get(dhd, 0, &toe_cmpnt)) < 0) return ret; csum_dir = (cmd == ETHTOOL_STXCSUM) ? TOE_TX_CSUM_OL : TOE_RX_CSUM_OL; if (edata.data != 0) toe_cmpnt |= csum_dir; else toe_cmpnt &= ~csum_dir; if ((ret = dhd_toe_set(dhd, 0, toe_cmpnt)) < 0) return ret; if (cmd == ETHTOOL_STXCSUM) { if (edata.data) dhd->iflist[0]->net->features |= NETIF_F_IP_CSUM; else dhd->iflist[0]->net->features &= ~NETIF_F_IP_CSUM; } break; #endif default: return -EOPNOTSUPP; } return 0; } #endif static bool dhd_check_hang(struct net_device *net, dhd_pub_t *dhdp, int error) { dhd_info_t * dhd; if (!dhdp) return FALSE; dhd = (dhd_info_t *)dhdp->info; if (dhd->thr_sysioc_ctl.thr_pid < 0) { DHD_ERROR(("%s : skipped due to negative pid - unloading?\n", __FUNCTION__)); return FALSE; } if ((error == -ETIMEDOUT) || (error == -EREMOTEIO) || ((dhdp->busstate == DHD_BUS_DOWN) && (!dhdp->dongle_reset))) { DHD_ERROR(("%s: Event HANG send up due to re=%d te=%d e=%d s=%d\n", __FUNCTION__, dhdp->rxcnt_timeout, dhdp->txcnt_timeout, error, dhdp->busstate)); net_os_send_hang_message(net); return TRUE; } return FALSE; } static int dhd_ioctl_entry(struct net_device *net, struct ifreq *ifr, int cmd) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); dhd_ioctl_t ioc; int bcmerror = 0; int buflen = 0; void *buf = NULL; uint driver = 0; int ifidx; int ret; if (module_remove) { printf("%s: module removed. cmd 0x%04x\n", __FUNCTION__, cmd); return -1; } if ( !dhd->pub.up || (dhd->pub.busstate == DHD_BUS_DOWN)){ printf("%s: dhd is down. skip it.\n", __func__); return -ENODEV; } DHD_OS_WAKE_LOCK(&dhd->pub); if (dhd->pub.hang_was_sent) { DHD_ERROR(("%s: HANG was sent up earlier\n", __FUNCTION__)); DHD_OS_WAKE_LOCK_CTRL_TIMEOUT_ENABLE(&dhd->pub, DHD_EVENT_TIMEOUT_MS); DHD_OS_WAKE_UNLOCK(&dhd->pub); return OSL_ERROR(BCME_DONGLE_DOWN); } ifidx = dhd_net2idx(dhd, net); DHD_TRACE(("%s: ifidx %d, cmd 0x%04x\n", __FUNCTION__, ifidx, cmd)); if (ifidx == DHD_BAD_IF) { DHD_ERROR(("%s: BAD IF\n", __FUNCTION__)); DHD_OS_WAKE_UNLOCK(&dhd->pub); return -1; } #if defined(CONFIG_WIRELESS_EXT) if ((cmd >= SIOCIWFIRST) && (cmd <= SIOCIWLAST)) { ret = wl_iw_ioctl(net, ifr, cmd); DHD_OS_WAKE_UNLOCK(&dhd->pub); return ret; } #endif #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 4, 2) if (cmd == SIOCETHTOOL) { ret = dhd_ethtool(dhd, (void*)ifr->ifr_data); DHD_OS_WAKE_UNLOCK(&dhd->pub); return ret; } #endif if (cmd == SIOCDEVPRIVATE+1) { ret = wl_android_priv_cmd(net, ifr, cmd); dhd_check_hang(net, &dhd->pub, ret); DHD_OS_WAKE_UNLOCK(&dhd->pub); return ret; } if (cmd != SIOCDEVPRIVATE) { DHD_OS_WAKE_UNLOCK(&dhd->pub); return -EOPNOTSUPP; } memset(&ioc, 0, sizeof(ioc)); if (copy_from_user(&ioc, ifr->ifr_data, sizeof(wl_ioctl_t))) { bcmerror = -BCME_BADADDR; goto done; } if (ioc.buf) { if (ioc.len == 0) { DHD_TRACE(("%s: ioc.len=0, returns BCME_BADARG \n", __FUNCTION__)); bcmerror = -BCME_BADARG; goto done; } buflen = MIN(ioc.len, DHD_IOCTL_MAXLEN); { if (!(buf = (char*)MALLOC(dhd->pub.osh, buflen))) { bcmerror = -BCME_NOMEM; goto done; } if (copy_from_user(buf, ioc.buf, buflen)) { bcmerror = -BCME_BADADDR; goto done; } } } if ((copy_from_user(&driver, (char *)ifr->ifr_data + sizeof(wl_ioctl_t), sizeof(uint)) != 0)) { bcmerror = -BCME_BADADDR; goto done; } if (!capable(CAP_NET_ADMIN)) { bcmerror = -BCME_EPERM; goto done; } if (driver == DHD_IOCTL_MAGIC) { bcmerror = dhd_ioctl((void *)&dhd->pub, &ioc, buf, buflen); if (bcmerror) dhd->pub.bcmerror = bcmerror; goto done; } if (dhd->pub.busstate != DHD_BUS_DATA) { bcmerror = BCME_DONGLE_DOWN; goto done; } if (!dhd->pub.iswl) { bcmerror = BCME_DONGLE_DOWN; goto done; } if (ioc.cmd == WLC_SET_KEY || (ioc.cmd == WLC_SET_VAR && ioc.buf != NULL && strncmp("wsec_key", ioc.buf, 9) == 0) || (ioc.cmd == WLC_SET_VAR && ioc.buf != NULL && strncmp("bsscfg:wsec_key", ioc.buf, 15) == 0) || ioc.cmd == WLC_DISASSOC) dhd_wait_pend8021x(net); #ifdef WLMEDIA_HTSF if (ioc.buf) { if (strcmp("htsf", ioc.buf) == 0) { dhd_ioctl_htsf_get(dhd, 0); return BCME_OK; } if (strcmp("htsflate", ioc.buf) == 0) { if (ioc.set) { memset(ts, 0, sizeof(tstamp_t)*TSMAX); memset(&maxdelayts, 0, sizeof(tstamp_t)); maxdelay = 0; tspktcnt = 0; maxdelaypktno = 0; memset(&vi_d1.bin, 0, sizeof(uint32)*NUMBIN); memset(&vi_d2.bin, 0, sizeof(uint32)*NUMBIN); memset(&vi_d3.bin, 0, sizeof(uint32)*NUMBIN); memset(&vi_d4.bin, 0, sizeof(uint32)*NUMBIN); } else { dhd_dump_latency(); } return BCME_OK; } if (strcmp("htsfclear", ioc.buf) == 0) { memset(&vi_d1.bin, 0, sizeof(uint32)*NUMBIN); memset(&vi_d2.bin, 0, sizeof(uint32)*NUMBIN); memset(&vi_d3.bin, 0, sizeof(uint32)*NUMBIN); memset(&vi_d4.bin, 0, sizeof(uint32)*NUMBIN); htsf_seqnum = 0; return BCME_OK; } if (strcmp("htsfhis", ioc.buf) == 0) { dhd_dump_htsfhisto(&vi_d1, "H to D"); dhd_dump_htsfhisto(&vi_d2, "D to D"); dhd_dump_htsfhisto(&vi_d3, "D to H"); dhd_dump_htsfhisto(&vi_d4, "H to H"); return BCME_OK; } if (strcmp("tsport", ioc.buf) == 0) { if (ioc.set) { memcpy(&tsport, ioc.buf + 7, 4); } else { DHD_ERROR(("current timestamp port: %d \n", tsport)); } return BCME_OK; } } #endif if ((ioc.cmd == WLC_SET_VAR || ioc.cmd == WLC_GET_VAR) && ioc.buf != NULL && strncmp("rpc_", ioc.buf, 4) == 0) { #ifdef BCM_FD_AGGR bcmerror = dhd_fdaggr_ioctl(&dhd->pub, ifidx, (wl_ioctl_t *)&ioc, buf, buflen); #else bcmerror = BCME_UNSUPPORTED; #endif goto done; } bcmerror = dhd_wl_ioctl(&dhd->pub, ifidx, (wl_ioctl_t *)&ioc, buf, buflen); done: dhd_check_hang(net, &dhd->pub, bcmerror); if (!bcmerror && buf && ioc.buf) { if (copy_to_user(ioc.buf, buf, buflen)) bcmerror = -EFAULT; } if (buf) MFREE(dhd->pub.osh, buf, buflen); DHD_OS_WAKE_UNLOCK(&dhd->pub); return OSL_ERROR(bcmerror); } #ifdef WL_CFG80211 static int dhd_cleanup_virt_ifaces(dhd_info_t *dhd) { int i = 1; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) int rollback_lock = FALSE; #endif DHD_TRACE(("%s: Enter \n", __func__)); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if (rtnl_is_locked()) { rtnl_unlock(); rollback_lock = TRUE; } #endif for (i = 1; i < DHD_MAX_IFS; i++) { dhd_net_if_lock_local(dhd); if (dhd->iflist[i]) { DHD_TRACE(("Deleting IF: %d \n", i)); if ((dhd->iflist[i]->state != DHD_IF_DEL) && (dhd->iflist[i]->state != DHD_IF_DELETING)) { dhd->iflist[i]->state = DHD_IF_DEL; dhd->iflist[i]->idx = i; dhd_op_if(dhd->iflist[i]); } } dhd_net_if_unlock_local(dhd); } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if (rollback_lock) rtnl_lock(); #endif return 0; } #endif #if defined(WL_CFG80211) && defined(SUPPORT_DEEP_SLEEP) int sleep_never = 0; #endif static int dhd_stop(struct net_device *net) { int ifidx = 0; dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); DHD_OS_WAKE_LOCK(&dhd->pub); DHD_TRACE(("%s: Enter %p\n", __FUNCTION__, net)); if (dhd->pub.up == 0) { goto exit; } ifidx = dhd_net2idx(dhd, net); BCM_REFERENCE(ifidx); module_remove = 1; #if defined(HW_OOB) bcmsdh_oob_intr_set(FALSE); #endif #ifdef WL_CFG80211 if (ifidx == 0) { wl_cfg80211_down(NULL); #ifndef APSTA_CONCURRENT if ((dhd->dhd_state & DHD_ATTACH_STATE_ADD_IF) && (dhd->dhd_state & DHD_ATTACH_STATE_CFG80211)) { dhd_cleanup_virt_ifaces(dhd); } #else if (ap_net_dev || ((dhd->dhd_state & DHD_ATTACH_STATE_ADD_IF) && (dhd->dhd_state & DHD_ATTACH_STATE_CFG80211))) { printf("clean interface and free parameters"); dhd_cleanup_virt_ifaces(dhd); ap_net_dev = NULL; ap_cfg_running = FALSE; } } #endif #endif #ifdef PROP_TXSTATUS dhd_wlfc_cleanup(&dhd->pub); #endif dhd->pub.up = 0; netif_stop_queue(net); dhd_prot_stop(&dhd->pub); #if defined(WL_CFG80211) if (ifidx == 0 && !dhd_download_fw_on_driverload) wl_android_wifi_off(net); #endif dhd->pub.hang_was_sent = 0; dhd->pub.rxcnt_timeout = 0; dhd->pub.txcnt_timeout = 0; OLD_MOD_DEC_USE_COUNT; exit: DHD_OS_WAKE_UNLOCK(&dhd->pub); return 0; } #define BCM4330B1_STA_FW_PATH "/system/etc/firmware/fw_bcm4330_b1.bin" #define BCM4330B1_APSTA_FW_PATH "/system/etc/firmware/fw_bcm4330_apsta_b1.bin" #define BCM4330B1_P2P_FW_PATH "/system/etc/firmware/fw_bcm4330_p2p_b1.bin" #define BCM4330B1_MFG_FW_PATH "/system/etc/firmware/bcm_mfg.bin" #define BCM4330B2_STA_FW_PATH "/system/etc/firmware/fw_bcm4330_b2.bin" #define BCM4330B2_APSTA_FW_PATH "/system/etc/firmware/fw_bcm4330_apsta_b2.bin" #define BCM4330B2_P2P_FW_PATH "/system/etc/firmware/fw_bcm4330_p2p_b2.bin" #define BCM4330B2_MFG_FW_PATH "/system/etc/firmware/bcm_mfg2.bin" static int dhd_open(struct net_device *net) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); uint up = 0; #ifdef TOE uint32 toe_ol; #endif int ifidx; int32 ret = 0; int32 dhd_open_retry_count = 0; dhd_open_retry: DHD_OS_WAKE_LOCK(&dhd->pub); module_remove = 0; if (module_remove) { printf("%s: module removed. Just return.\n", __FUNCTION__); return -1; } printf(" firmware_path = %s\n", firmware_path); if (strlen(firmware_path) != 0) { if (bcm_chip_is_4330) { printf("chip is 4330!\n"); if (strstr(firmware_path, "_apsta") != NULL) { if (bcm_chip_is_4330b1) strcpy(fw_path, BCM4330B1_APSTA_FW_PATH); else strcpy(fw_path, BCM4330B2_APSTA_FW_PATH); } else if (strstr(firmware_path, "_p2p") != NULL) { if (bcm_chip_is_4330b1) strcpy(fw_path, BCM4330B1_P2P_FW_PATH); else strcpy(fw_path, BCM4330B2_P2P_FW_PATH); } else if (strstr(firmware_path, "mfg") != NULL) { if (bcm_chip_is_4330b1) strcpy(fw_path, BCM4330B1_MFG_FW_PATH); else strcpy(fw_path, BCM4330B2_MFG_FW_PATH); } else { if (bcm_chip_is_4330b1) strcpy(fw_path, BCM4330B1_STA_FW_PATH); else strcpy(fw_path, BCM4330B2_STA_FW_PATH); } } else { if (firmware_path[strlen(firmware_path)-1] == '\n') firmware_path[strlen(firmware_path)-1] = '\0'; strncpy(fw_path, firmware_path, sizeof(fw_path)-1); fw_path[sizeof(fw_path)-1] = '\0'; #if defined(SUPPORT_MULTIPLE_REVISION) ret = concate_revision(dhd->pub.bus, fw_path, MOD_PARAM_PATHLEN); if (ret != 0) { DHD_ERROR(("%s: fail to concatnate revison \n", __FUNCTION__)); goto exit; } #endif } firmware_path[0] = '\0'; } dhd->pub.dongle_trap_occured = 0; dhd->pub.hang_was_sent = 0; #if !defined(WL_CFG80211) ret = wl_control_wl_start(net); if (ret != 0) { DHD_ERROR(("%s: failed with code %d\n", __FUNCTION__, ret)); ret = -1; goto exit; } #endif ifidx = dhd_net2idx(dhd, net); DHD_TRACE(("%s: ifidx %d\n", __FUNCTION__, ifidx)); #ifdef HTC_KlocWork if (ifidx < 0) { DHD_ERROR(("%s: Error: called with invalid IF\n", __FUNCTION__)); ret = -1; goto exit; } #endif if (!dhd->iflist[ifidx] || dhd->iflist[ifidx]->state == DHD_IF_DEL) { DHD_ERROR(("%s: Error: called when IF already deleted\n", __FUNCTION__)); ret = -1; goto exit; } if (ifidx == 0) { atomic_set(&dhd->pend_8021x_cnt, 0); #if defined(WL_CFG80211) DHD_ERROR(("\n%s\n", dhd_version)); if (!dhd_download_fw_on_driverload) { ret = wl_android_wifi_on(net); if (ret != 0) { DHD_ERROR(("%s: failed with code %d\n", __FUNCTION__, ret)); ret = -1; goto exit; } } else { #ifdef SUPPORT_DEEP_SLEEP if (sleep_never) { dhd_deepsleep(net, 0); sleep_never = 0; } #endif } #endif if (dhd->pub.busstate != DHD_BUS_DATA) { if ((ret = dhd_bus_start(&dhd->pub)) != 0) { DHD_ERROR(("%s: failed with code %d\n", __FUNCTION__, ret)); ret = -1; goto exit; } } memcpy(net->dev_addr, dhd->pub.mac.octet, ETHER_ADDR_LEN); memcpy(dhd->iflist[ifidx]->mac_addr, dhd->pub.mac.octet, ETHER_ADDR_LEN); #ifdef TOE if (dhd_toe_get(dhd, ifidx, &toe_ol) >= 0 && (toe_ol & TOE_TX_CSUM_OL) != 0) dhd->iflist[ifidx]->net->features |= NETIF_F_IP_CSUM; else dhd->iflist[ifidx]->net->features &= ~NETIF_F_IP_CSUM; #endif #if defined(WL_CFG80211) if (unlikely(wl_cfg80211_up(NULL))) { DHD_ERROR(("%s: failed to bring up cfg80211\n", __FUNCTION__)); ret = -1; goto exit; } #endif } netif_start_queue(net); dhd->pub.up = 1; if (ifidx == 0) dhd_wl_ioctl_cmd(&dhd->pub, WLC_UP, (char *)&up, sizeof(up), TRUE, 0); #ifdef BCMDBGFS dhd_dbg_init(&dhd->pub); #endif OLD_MOD_INC_USE_COUNT; exit: if (ret) { wl_android_wifi_off(net); dhd_stop(net); } DHD_OS_WAKE_UNLOCK(&dhd->pub); if (ret&&(dhd_open_retry_count <3)) { dhd_open_retry_count++; goto dhd_open_retry; } return ret; } int dhd_do_driver_init(struct net_device *net) { dhd_info_t *dhd = NULL; if (!net) { DHD_ERROR(("Primary Interface not initialized \n")); return -EINVAL; } dhd = *(dhd_info_t **)netdev_priv(net); if (dhd->pub.busstate == DHD_BUS_DATA) { DHD_TRACE(("Driver already Inititalized. Nothing to do")); return 0; } if (dhd_open(net) < 0) { DHD_ERROR(("Driver Init Failed \n")); return -1; } return 0; } osl_t * dhd_osl_attach(void *pdev, uint bustype) { return osl_attach(pdev, bustype, TRUE); } void dhd_osl_detach(osl_t *osh) { if (MALLOCED(osh)) { DHD_ERROR(("%s: MEMORY LEAK %d bytes\n", __FUNCTION__, MALLOCED(osh))); } osl_detach(osh); wifi_fail_retry = true; #if 1 && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) dhd_registration_check = FALSE; up(&dhd_registration_sem); #if defined(BCMLXSDMMC) #if 0 up(&dhd_chipup_sem); #endif #endif #endif } int dhd_add_if(dhd_info_t *dhd, int ifidx, void *handle, char *name, uint8 *mac_addr, uint32 flags, uint8 bssidx) { dhd_if_t *ifp; DHD_TRACE(("%s: idx %d, handle->%p\n", __FUNCTION__, ifidx, handle)); ASSERT(dhd && (ifidx < DHD_MAX_IFS)); ifp = dhd->iflist[ifidx]; if (ifp != NULL) { if (ifp->net != NULL) { netif_stop_queue(ifp->net); unregister_netdev(ifp->net); free_netdev(ifp->net); } } else if ((ifp = MALLOC(dhd->pub.osh, sizeof(dhd_if_t))) == NULL) { DHD_ERROR(("%s: OOM - dhd_if_t\n", __FUNCTION__)); return -ENOMEM; } memset(ifp, 0, sizeof(dhd_if_t)); ifp->event2cfg80211 = FALSE; ifp->info = dhd; dhd->iflist[ifidx] = ifp; strncpy(ifp->name, name, IFNAMSIZ); ifp->name[IFNAMSIZ] = '\0'; if (mac_addr != NULL) memcpy(&ifp->mac_addr, mac_addr, ETHER_ADDR_LEN); if (handle == NULL) { ifp->state = DHD_IF_ADD; ifp->idx = ifidx; ifp->bssidx = bssidx; ASSERT(dhd->thr_sysioc_ctl.thr_pid >= 0); up(&dhd->thr_sysioc_ctl.sema); } else ifp->net = (struct net_device *)handle; if (ifidx == 0) { ifp->event2cfg80211 = TRUE; } return 0; } void dhd_del_if(dhd_info_t *dhd, int ifidx) { dhd_if_t *ifp; DHD_TRACE(("%s: idx %d\n", __FUNCTION__, ifidx)); ASSERT(dhd && ifidx && (ifidx < DHD_MAX_IFS)); ifp = dhd->iflist[ifidx]; if (!ifp) { DHD_ERROR(("%s: Null interface\n", __FUNCTION__)); return; } ifp->state = DHD_IF_DEL; ifp->idx = ifidx; ASSERT(dhd->thr_sysioc_ctl.thr_pid >= 0); up(&dhd->thr_sysioc_ctl.sema); } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 31)) static struct net_device_ops dhd_ops_pri = { .ndo_open = dhd_open, .ndo_stop = dhd_stop, .ndo_get_stats = dhd_get_stats, .ndo_do_ioctl = dhd_ioctl_entry, .ndo_start_xmit = dhd_start_xmit, .ndo_set_mac_address = dhd_set_mac_address, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 2, 0)) .ndo_set_rx_mode = dhd_set_multicast_list, #else .ndo_set_multicast_list = dhd_set_multicast_list, #endif }; static struct net_device_ops dhd_ops_virt = { .ndo_get_stats = dhd_get_stats, .ndo_do_ioctl = dhd_ioctl_entry, .ndo_start_xmit = dhd_start_xmit, .ndo_set_mac_address = dhd_set_mac_address, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 2, 0)) .ndo_set_rx_mode = dhd_set_multicast_list, #else .ndo_set_multicast_list = dhd_set_multicast_list, #endif }; #endif extern int system_rev; #define XA 0 #define XB 1 #define XC 2 #define XD 3 #define PVT 0x80 #define PVT_1 0x81 int dhd_change_nvram_path(void) { printf("Read PCBID = %x\n", system_rev); #ifdef CONFIG_MACH_MONARUDO if (system_rev >= PVT_1){ strcpy(nvram_path, "/system/etc/calibration.gpio4"); } #endif #ifdef CONFIG_MACH_DUMMY if (system_rev >= PVT){ strcpy(nvram_path, "/system/etc/calibration.gpio4"); } #endif #ifdef CONFIG_MACH_DUMMY if (system_rev >= PVT){ strcpy(nvram_path, "/system/etc/calibration.gpio4"); } #endif #ifdef CONFIG_MACH_DUMMY if (system_rev >= XC){ strcpy(nvram_path, "/system/etc/calibration.gpio4"); } #endif #ifdef CONFIG_MACH_DUMMY strcpy(nvram_path, "/system/etc/calibration.gpio4"); #endif #ifdef CONFIG_MACH_OPERAUL if (system_rev >= XC){ strcpy(nvram_path, "/system/etc/calibration.gpio4"); } #endif #ifdef CONFIG_MACH_DUMMY if (system_rev >= PVT){ strcpy(nvram_path, "/system/etc/calibration.gpio4"); } #endif return 0; } dhd_pub_t * dhd_attach(osl_t *osh, struct dhd_bus *bus, uint bus_hdrlen) { dhd_info_t *dhd = NULL; struct net_device *net = NULL; dhd_attach_states_t dhd_state = DHD_ATTACH_STATE_INIT; DHD_ERROR(("%s: Enter\n", __FUNCTION__)); if (strlen(firmware_path) != 0) { strncpy(fw_path, firmware_path, sizeof(fw_path) - 1); fw_path[sizeof(fw_path) - 1] = '\0'; } if (bcm_chip_is_4330) { if (bcm_chip_is_4330b1) { if ((fwb1_path != NULL) && (fwb1_path[0] != '\0')) strcpy(fw_path, fwb1_path); } else { if ((fwb2_path != NULL) && (fwb2_path[0] != '\0')) strcpy(fw_path, fwb2_path); } } dhd_change_nvram_path(); if (strlen(nvram_path) != 0) { strncpy(nv_path, nvram_path, sizeof(nv_path) -1); nv_path[sizeof(nv_path) -1] = '\0'; } #if defined(SUPPORT_MULTIPLE_REVISION) if (strlen(fw_path) != 0 && concate_revision(bus, fw_path, MOD_PARAM_PATHLEN) != 0) { DHD_ERROR(("%s: fail to concatnate revison \n", __FUNCTION__)); goto fail; } #endif if (!(net = alloc_etherdev(sizeof(dhd)))) { DHD_ERROR(("%s: OOM - alloc_etherdev\n", __FUNCTION__)); goto fail; } dhd_state |= DHD_ATTACH_STATE_NET_ALLOC; if (!(dhd = MALLOC(osh, sizeof(dhd_info_t)))) { DHD_ERROR(("%s: OOM - alloc dhd_info\n", __FUNCTION__)); goto fail; } memset(dhd, 0, sizeof(dhd_info_t)); #ifdef DHDTHREAD dhd->thr_dpc_ctl.thr_pid = DHD_PID_KT_TL_INVALID; dhd->thr_wdt_ctl.thr_pid = DHD_PID_KT_INVALID; #endif dhd->dhd_tasklet_create = FALSE; dhd->thr_sysioc_ctl.thr_pid = DHD_PID_KT_INVALID; dhd_state |= DHD_ATTACH_STATE_DHD_ALLOC; memcpy((void *)netdev_priv(net), &dhd, sizeof(dhd)); dhd->pub.osh = osh; dhd->pub.info = dhd; dhd->pub.bus = bus; dhd->pub.hdrlen = bus_hdrlen; if (iface_name[0]) { int len; char ch; strncpy(net->name, iface_name, IFNAMSIZ); net->name[IFNAMSIZ - 1] = 0; len = strlen(net->name); #ifdef HTC_KlocWork if(len > 0) { ch = net->name[len - 1]; if ((ch > '9' || ch < '0') && (len < IFNAMSIZ - 2)) strcat(net->name, "%d"); } #else ch = net->name[len - 1]; if ((ch > '9' || ch < '0') && (len < IFNAMSIZ - 2)) strcat(net->name, "%d"); #endif } if (dhd_add_if(dhd, 0, (void *)net, net->name, NULL, 0, 0) == DHD_BAD_IF) { printf("%s : dhd_add_if failed\n", __func__); goto fail; } dhd_state |= DHD_ATTACH_STATE_ADD_IF; #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)) net->open = NULL; #else net->netdev_ops = NULL; #endif sema_init(&dhd->proto_sem, 1); #ifdef PROP_TXSTATUS spin_lock_init(&dhd->wlfc_spinlock); #endif init_waitqueue_head(&dhd->ioctl_resp_wait); init_waitqueue_head(&dhd->ctrl_wait); spin_lock_init(&dhd->sdlock); spin_lock_init(&dhd->txqlock); spin_lock_init(&dhd->dhd_lock); spin_lock_init(&dhd->wakelock_spinlock); dhd->wakelock_counter = 0; dhd->wakelock_rx_timeout_enable = 0; dhd->wakelock_ctrl_timeout_enable = 0; #ifdef CONFIG_HAS_WAKELOCK wake_lock_init(&dhd->wl_wifi, WAKE_LOCK_SUSPEND, "wlan_wake"); wake_lock_init(&dhd->wl_rxwake, WAKE_LOCK_SUSPEND, "wlan_rx_wake"); wake_lock_init(&dhd->wl_ctrlwake, WAKE_LOCK_SUSPEND, "wlan_ctrl_wake"); wake_lock_init(&dhd->wl_htc, WAKE_LOCK_SUSPEND, "wlan_htc"); #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 mutex_init(&dhd->dhd_net_if_mutex); mutex_init(&dhd->dhd_suspend_mutex); #endif dhd_state |= DHD_ATTACH_STATE_WAKELOCKS_INIT; if (dhd_prot_attach(&dhd->pub) != 0) { DHD_ERROR(("dhd_prot_attach failed\n")); goto fail; } dhd_state |= DHD_ATTACH_STATE_PROT_ATTACH; #ifdef WL_CFG80211 if (unlikely(wl_cfg80211_attach(net, &dhd->pub))) { DHD_ERROR(("wl_cfg80211_attach failed\n")); goto fail; } dhd_monitor_init(&dhd->pub); dhd_state |= DHD_ATTACH_STATE_CFG80211; #endif #if defined(CONFIG_WIRELESS_EXT) if (wl_iw_attach(net, (void *)&dhd->pub) != 0) { DHD_ERROR(("wl_iw_attach failed\n")); printf("%s : wl_iw_attach failed\n", __func__); goto fail; } dhd_state |= DHD_ATTACH_STATE_WL_ATTACH; #endif init_timer(&dhd->timer); dhd->timer.data = (ulong)dhd; dhd->timer.function = dhd_watchdog; #ifdef DHDTHREAD sema_init(&dhd->sdsem, 1); if ((dhd_watchdog_prio >= 0) && (dhd_dpc_prio >= 0)) { dhd->threads_only = TRUE; } else { dhd->threads_only = FALSE; } dhd->dhd_force_exit = FALSE; if (dhd_dpc_prio >= 0) { #ifdef USE_KTHREAD_API printf("%s: Initialize watchdog thread\n",__func__); PROC_START2(dhd_watchdog_thread, dhd, &dhd->thr_wdt_ctl, 0, "dhd_watchdog_thread"); #else PROC_START(dhd_watchdog_thread, dhd, &dhd->thr_wdt_ctl, 0); #endif } else { dhd->thr_wdt_ctl.thr_pid = -1; } if (dhd_dpc_prio >= 0) { #ifdef USE_KTHREAD_API printf("%s: Initialize DPC thread\n",__func__); PROC_START2(dhd_dpc_thread, dhd, &dhd->thr_dpc_ctl, 0, "dhd_dpc"); #else PROC_START(dhd_dpc_thread, dhd, &dhd->thr_dpc_ctl, 0); #endif } else { tasklet_init(&dhd->tasklet, dhd_dpc, (ulong)dhd); dhd->thr_dpc_ctl.thr_pid = -1; } #else tasklet_init(&dhd->tasklet, dhd_dpc, (ulong)dhd); dhd->dhd_tasklet_create = TRUE; #endif if (dhd_sysioc) { #ifdef USE_KTHREAD_API printf("%s: Initialize sysioc thread\n",__func__); PROC_START2(_dhd_sysioc_thread, dhd, &dhd->thr_sysioc_ctl, 0, "dhd_sysioc"); #else PROC_START(_dhd_sysioc_thread, dhd, &dhd->thr_sysioc_ctl, 0); #endif } else { dhd->thr_sysioc_ctl.thr_pid = -1; } dhd_state |= DHD_ATTACH_STATE_THREADS_CREATED; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && (1) INIT_WORK(&dhd->work_hang, dhd_hang_process); #endif memcpy(netdev_priv(net), &dhd, sizeof(dhd)); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && defined(CONFIG_PM_SLEEP) register_pm_notifier(&dhd_sleep_pm_notifier); #endif #ifdef CONFIG_HAS_EARLYSUSPEND dhd->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 20; dhd->early_suspend.suspend = dhd_early_suspend; dhd->early_suspend.resume = dhd_late_resume; register_early_suspend(&dhd->early_suspend); dhd_state |= DHD_ATTACH_STATE_EARLYSUSPEND_DONE; #endif #ifdef ARP_OFFLOAD_SUPPORT dhd->pend_ipaddr = 0; register_inetaddr_notifier(&dhd_notifier); #endif dhd_state |= DHD_ATTACH_STATE_DONE; dhd->dhd_state = dhd_state; return &dhd->pub; fail: printf("%s : fail case\n", __func__); if (dhd_state < DHD_ATTACH_STATE_DHD_ALLOC) { printf("%s : dhd_state < DHD_ATTACH_STATE_DHD_ALLOC\n", __func__); if (net) free_netdev(net); } else { DHD_ERROR(("%s: Calling dhd_detach dhd_state 0x%x &dhd->pub %p\n", __FUNCTION__, dhd_state, &dhd->pub)); dhd->dhd_state = dhd_state; dhd_detach(&dhd->pub); dhd_free(&dhd->pub); } return NULL; } int dhd_bus_start(dhd_pub_t *dhdp) { int ret = -1; dhd_info_t *dhd = (dhd_info_t*)dhdp->info; unsigned long flags; #ifdef CUSTOMER_HW2 char mac_buf[16]; #endif ASSERT(dhd); DHD_TRACE(("Enter %s:\n", __FUNCTION__)); #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdlock(dhdp); #endif if ((dhd->pub.busstate == DHD_BUS_DOWN) && (fw_path != NULL) && (fw_path[0] != '\0') && (nv_path != NULL) && (nv_path[0] != '\0')) { printf("load firmware from %s, nvram %s\n", fw_path, nv_path); if (!(dhd_bus_download_firmware(dhd->pub.bus, dhd->pub.osh, fw_path, nv_path))) { DHD_ERROR(("%s: dhdsdio_probe_download failed. firmware = %s nvram = %s\n", __FUNCTION__, fw_path, nv_path)); #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdunlock(dhdp); #endif return -1; } } if (dhd->pub.busstate != DHD_BUS_LOAD) { #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdunlock(dhdp); #endif return -ENETDOWN; } dhd->pub.tickcnt = 0; dhd_os_wd_timer(&dhd->pub, dhd_watchdog_ms); if ((ret = dhd_bus_init(&dhd->pub, FALSE)) != 0) { DHD_ERROR(("%s, dhd_bus_init failed %d\n", __FUNCTION__, ret)); #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdunlock(dhdp); #endif return ret; } #if defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) if (bcmsdh_register_oob_intr(dhdp)) { flags = dhd_os_spin_lock(&dhd->pub); dhd->wd_timer_valid = FALSE; dhd_os_spin_unlock(&dhd->pub, flags); del_timer_sync(&dhd->timer); DHD_ERROR(("%s Host failed to register for OOB\n", __FUNCTION__)); #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdunlock(dhdp); #endif return -ENODEV; } #ifndef BCMSPI_ANDROID dhd_enable_oob_intr(dhd->pub.bus, TRUE); #endif #endif if (dhd->pub.busstate != DHD_BUS_DATA) { flags = dhd_os_spin_lock(&dhd->pub); dhd->wd_timer_valid = FALSE; dhd_os_spin_unlock(&dhd->pub, flags); del_timer_sync(&dhd->timer); DHD_ERROR(("%s failed bus is not ready\n", __FUNCTION__)); #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdunlock(dhdp); #endif return -ENODEV; } #ifdef DHDTHREAD if (dhd->threads_only) dhd_os_sdunlock(dhdp); #endif #ifdef BCMSDIOH_TXGLOM if ((dhd->pub.busstate == DHD_BUS_DATA) && bcmsdh_glom_enabled()) { dhd_txglom_enable(dhdp, TRUE); } #endif #ifdef READ_MACADDR dhd_read_macaddr(dhd); #endif if ((ret = dhd_prot_init(&dhd->pub)) < 0) return ret; #ifdef CUSTOMER_HW2 if (ap_fw_loaded == FALSE) { sprintf( mac_buf, "0x%02x%02x%02x%02x%02x%02x", dhdp->mac.octet[0], dhdp->mac.octet[1], dhdp->mac.octet[2], dhdp->mac.octet[3], dhdp->mac.octet[4], dhdp->mac.octet[5] ); dhdp->pktfilter_count = 3; #if 0 dhd_set_pktfilter(dhdp, 1, ALLOW_UNICAST, 0, "0xffffffffffff", mac_buf); dhd_set_pktfilter(dhdp, 1, ALLOW_DHCP, 0, "0xffffffffffff000000000000ffff00000000000000000000000000000000000000000000ffff", "0xffffffffffff0000000000000800000000000000000000000000000000000000000000000044"); dhd_set_pktfilter(dhdp, 1, ALLOW_IPV6_MULTICAST, 0, "0xffff", "0x3333"); #endif } #else dhdp->pktfilter_count = 1; dhdp->pktfilter[0] = "100 0 0 0 0x01 0x00"; #endif #ifdef WRITE_MACADDR dhd_write_macaddr(dhd->pub.mac.octet); #endif priv_dhdp = dhdp; #ifdef ARP_OFFLOAD_SUPPORT if (dhd->pend_ipaddr) { #ifdef AOE_IP_ALIAS_SUPPORT aoe_update_host_ipv4_table(&dhd->pub, dhd->pend_ipaddr, TRUE); #endif dhd->pend_ipaddr = 0; } #endif return 0; } #ifdef CONFIG_METRICO_TP #define TRAFFIC_HIGH_WATER_MARK 1 *(3000/1000) #define TRAFFIC_LOW_WATER_MARK 0 * (3000/1000) #define TRAFFIC_S_HIGH_WATER_MARK ((TRAFFIC_HIGH_WATER_MARK) * 20) #else #define TRAFFIC_HIGH_WATER_MARK 670 *(3000/1000) #define TRAFFIC_LOW_WATER_MARK 280 * (3000/1000) #define TRAFFIC_S_HIGH_WATER_MARK ((TRAFFIC_HIGH_WATER_MARK) * 20) #endif extern dhd_pub_t *pdhd; #if 1 bool dhd_concurrent_fw(dhd_pub_t *dhd) { #ifdef WL_ENABLE_P2P_IF if (strstr(fw_path, "_apsta") == NULL) return 1; else return 0; #else int i; int ret = 0; char buf[WLC_IOCTL_SMLEN]; char *cap[] = {"p2p", "mchan", "dsta", NULL}; if ((!op_mode) && (strstr(fw_path, "_p2p") == NULL) && (strstr(fw_path, "_apsta") == NULL)) { for (i = 0; cap[i] != NULL; ) { memset(buf, 0, sizeof(buf)); bcm_mkiovar(cap[i++], 0, 0, buf, sizeof(buf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, buf, sizeof(buf), FALSE, 0)) < 0) { DHD_TRACE(("%s: Get VSDB Capability(%s) failed (error=%d)\n", __FUNCTION__, cap[i-1], ret)); return 0; } else if (buf[0] != 1) { DHD_TRACE(("VSDB(%s) is not supported , ret : %d\n", cap[i-1], buf[0])); return 0; } } return 1; } return 0; #endif } #endif int dhd_preinit_ioctls(dhd_pub_t *dhd) { int ret = 0; char eventmask[WL_EVENTING_MASK_LEN]; char iovbuf[WL_EVENTING_MASK_LEN + 12]; char buf[256]; char *ptr; uint up = 0; uint power_mode = PM_FAST; uint32 dongle_align = DHD_SDALIGN; uint32 glom = CUSTOM_GLOM_SETTING; uint32 txlazydelay = 0; uint32 lvtrigtime = 250; #if defined(VSDB) || defined(ROAM_ENABLE) uint bcn_timeout = 8; #else uint bcn_timeout = 8; #endif uint retry_max = 10; #if defined(ARP_OFFLOAD_SUPPORT) int arpoe = 0; #endif int scan_assoc_time = 40; int scan_unassoc_time = 80; int scan_passive_time = 100; uint32 listen_interval = LISTEN_INTERVAL; uint16 chipID; #if defined(SOFTAP) uint dtim = 1; #endif #if (defined(AP) && !defined(WLP2P)) || (!defined(AP) && defined(WL_CFG80211)) uint32 mpc = 0; struct ether_addr p2p_ea; #endif int ht_wsec_restrict = WLC_HT_TKIP_RESTRICT | WLC_HT_WEP_RESTRICT; #ifdef CUSTOMER_HW2 uint dhd_roam = 0; #else uint dhd_roam = 1; #endif #if defined(AP) || defined(WLP2P) || defined(APSTA_CONCURRENT) uint32 apsta = 1; #endif #ifdef GET_CUSTOM_MAC_ENABLE struct ether_addr ea_addr; #endif #ifdef OKC_SUPPORT uint32 okc = 1; #endif uint srl = 15; uint lrl = 15; DHD_TRACE(("Enter %s\n", __FUNCTION__)); dhd->op_mode = 0; #ifdef GET_CUSTOM_MAC_ENABLE ret = dhd_custom_get_mac_address(ea_addr.octet); if (!ret) { memset(buf, 0, sizeof(buf)); bcm_mkiovar("cur_etheraddr", (void *)&ea_addr, ETHER_ADDR_LEN, buf, sizeof(buf)); ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, sizeof(buf), TRUE, 0); if (ret < 0) { DHD_ERROR(("%s: can't set MAC address , error=%d\n", __FUNCTION__, ret)); return BCME_NOTUP; } memcpy(dhd->mac.octet, ea_addr.octet, ETHER_ADDR_LEN); } else { #endif pdhd = dhd; #ifdef PNO_SUPPORT dhd_clear_pfn(); #endif strcpy(iovbuf, "cur_etheraddr"); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, iovbuf, sizeof(iovbuf), FALSE, 0)) < 0) { DHD_ERROR(("%s: can't get MAC address , error=%d\n", __FUNCTION__, ret)); return BCME_NOTUP; } memcpy(dhd->mac.octet, iovbuf, ETHER_ADDR_LEN); #ifdef GET_CUSTOM_MAC_ENABLE } #endif #ifdef SET_RANDOM_MAC_SOFTAP if ((!op_mode && strstr(fw_path, "_apsta") != NULL) || (op_mode == HOSTAPD_MASK)) { uint rand_mac; srandom32((uint)jiffies); rand_mac = random32(); iovbuf[0] = 0x02; iovbuf[1] = 0x1A; iovbuf[2] = 0x11; iovbuf[3] = (unsigned char)(rand_mac & 0x0F) | 0xF0; iovbuf[4] = (unsigned char)(rand_mac >> 8); iovbuf[5] = (unsigned char)(rand_mac >> 16); bcm_mkiovar("cur_etheraddr", (void *)iovbuf, ETHER_ADDR_LEN, buf, sizeof(buf)); ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, sizeof(buf), TRUE, 0); if (ret < 0) { DHD_ERROR(("%s: can't set MAC address , error=%d\n", __FUNCTION__, ret)); } else memcpy(dhd->mac.octet, iovbuf, ETHER_ADDR_LEN); } #endif DHD_TRACE(("Firmware = %s\n", fw_path)); #ifdef APSTA_CONCURRENT if (strstr(fw_path, "_apsta") == NULL) { bcm_mkiovar("apsta", (char *)&apsta, 4, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s APSTA for apsta_concurrent failed ret= %d\n", __FUNCTION__, ret)); } } #endif #if !defined(AP) && defined(WLP2P) if ((!op_mode && strstr(fw_path, "_p2p") != NULL) || (op_mode == 0x04) || (dhd_concurrent_fw(dhd))) { bcm_mkiovar("apsta", (char *)&apsta, 4, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s APSTA for WFD failed ret= %d\n", __FUNCTION__, ret)); } else if (!dhd_concurrent_fw(dhd)) { dhd->op_mode |= WFD_MASK; #if defined(ARP_OFFLOAD_SUPPORT) arpoe = 0; #endif #ifdef PKT_FILTER_SUPPORT dhd_pkt_filter_enable = FALSE; #endif } memcpy(&p2p_ea, &dhd->mac, ETHER_ADDR_LEN); ETHER_SET_LOCALADDR(&p2p_ea); bcm_mkiovar("p2p_da_override", (char *)&p2p_ea, ETHER_ADDR_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s p2p_da_override ret= %d\n", __FUNCTION__, ret)); } else { DHD_INFO(("dhd_preinit_ioctls: p2p_da_override succeeded\n")); } } #endif #if !defined(AP) && defined(WL_CFG80211) if ((!op_mode && strstr(fw_path, "_apsta") != NULL) || (op_mode == 0x02)) { #ifdef CONFIG_METRICO_TP dhd_bus_setidletime(dhd, 1000); #endif bcm_mkiovar("mpc", (char *)&mpc, 4, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s mpc for HostAPD failed %d\n", __FUNCTION__, ret)); } else { dhd->op_mode |= HOSTAPD_MASK; #if defined(ARP_OFFLOAD_SUPPORT) arpoe = 0; #endif #ifdef PKT_FILTER_SUPPORT dhd_pkt_filter_enable = FALSE; #endif } } #endif if ((dhd->op_mode != WFD_MASK) && (dhd->op_mode != HOSTAPD_MASK)) { dhd->op_mode |= STA_MASK; #ifdef PKT_FILTER_SUPPORT dhd_pkt_filter_enable = TRUE; #endif #if !defined(AP) && defined(WLP2P) if (dhd_concurrent_fw(dhd)) { dhd->op_mode |= WFD_MASK; } #endif } DHD_ERROR(("Firmware up: op_mode=%d, " "Broadcom Dongle Host Driver mac=%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", dhd->op_mode, dhd->mac.octet[0], dhd->mac.octet[1], dhd->mac.octet[2], dhd->mac.octet[3], dhd->mac.octet[4], dhd->mac.octet[5])); if (dhd->dhd_cspec.ccode[0] != 0) { bcm_mkiovar("country", (char *)&dhd->dhd_cspec, sizeof(wl_country_t), iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) DHD_ERROR(("%s: country code setting failed\n", __FUNCTION__)); } bcm_mkiovar("assoc_listen", (char *)&listen_interval, 4, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) DHD_ERROR(("%s assoc_listen failed %d\n", __FUNCTION__, ret)); #ifdef OKC_SUPPORT bcm_mkiovar("okc_enable", (char *)&okc, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); #endif memset(buf, 0, sizeof(buf)); ptr = buf; bcm_mkiovar("ver", (char *)&buf, 4, buf, sizeof(buf)); dhdcdc_query_ioctl(dhd, 0, WLC_GET_VAR, buf, sizeof(buf),WL_IOCTL_ACTION_SET); bcmstrtok(&ptr, "\n", 0); DHD_DEFAULT(("Firmware version = %s\n", buf)); #ifdef CONFIG_CONTROL_PM sec_control_pm(dhd, &power_mode); #else dhd_wl_ioctl_cmd(dhd, WLC_SET_PM, (char *)&power_mode, sizeof(power_mode), TRUE, 0); #endif bcm_mkiovar("bus:txglomalign", (char *)&dongle_align, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); chipID = (uint16)dhd_bus_chip_id(dhd); DHD_INFO(("%s disable glom for chipID=0x%X\n", __FUNCTION__, chipID)); bcm_mkiovar("bus:txglom", (char *)&glom, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("bus:txlazydelay", (char *)&txlazydelay, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("bus:lvtrigtime", (char *)&lvtrigtime, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("bcn_timeout", (char *)&bcn_timeout, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("roam_off", (char *)&dhd_roam, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); #if defined(AP) && !defined(WLP2P) bcm_mkiovar("mpc", (char *)&mpc, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("apsta", (char *)&apsta, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); #endif #if defined(SOFTAP) if (ap_fw_loaded == TRUE) { dhd_wl_ioctl_cmd(dhd, WLC_SET_DTIMPRD, (char *)&dtim, sizeof(dtim), TRUE, 0); } #endif if (dhd_roam == 0) { int roam_scan_period = 30; int roam_fullscan_period = 120; #ifdef CUSTOMER_HW2 int roam_trigger = -75; int roam_delta = 10; #else int roam_trigger = -85; int roam_delta = 15; #endif int band; int band_temp_set = WLC_BAND_2G; if (dhd_wl_ioctl_cmd(dhd, WLC_SET_ROAM_SCAN_PERIOD, \ (char *)&roam_scan_period, sizeof(roam_scan_period),TRUE,0) < 0) DHD_ERROR(("%s: roam scan setup failed\n", __FUNCTION__)); bcm_mkiovar("fullroamperiod", (char *)&roam_fullscan_period, \ 4, iovbuf, sizeof(iovbuf)); if (dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, \ iovbuf, sizeof(iovbuf), TRUE, 0) < 0) DHD_ERROR(("%s: roam fullscan setup failed\n", __FUNCTION__)); if (dhdcdc_query_ioctl(dhd, 0, WLC_GET_BAND, \ (char *)&band, sizeof(band),WL_IOCTL_ACTION_GET) < 0) DHD_ERROR(("%s: roam delta setting failed\n", __FUNCTION__)); else { if ((band == WLC_BAND_AUTO) || (band == WLC_BAND_ALL)) { if (dhd_wl_ioctl_cmd(dhd, WLC_SET_BAND, \ (char *)&band_temp_set, sizeof(band_temp_set), TRUE, 0) < 0) DHD_ERROR(("%s: local band seting failed\n", __FUNCTION__)); } if (dhd_wl_ioctl_cmd(dhd, WLC_SET_ROAM_DELTA, \ (char *)&roam_delta, sizeof(roam_delta), TRUE, 0) < 0) DHD_ERROR(("%s: roam delta setting failed\n", __FUNCTION__)); if (dhd_wl_ioctl_cmd(dhd, WLC_SET_ROAM_TRIGGER, \ (char *)&roam_trigger, sizeof(roam_trigger), TRUE, 0) < 0) DHD_ERROR(("%s: roam trigger setting failed\n", __FUNCTION__)); band_temp_set = WLC_BAND_5G; roam_delta = 10; roam_trigger = -75; if (dhd_wl_ioctl_cmd(dhd, WLC_SET_BAND, \ (char *)&band_temp_set, sizeof(band_temp_set), TRUE, 0) < 0) DHD_ERROR(("%s: local band seting failed\n", __FUNCTION__)); if (dhd_wl_ioctl_cmd(dhd, WLC_SET_ROAM_DELTA, \ (char *)&roam_delta, sizeof(roam_delta), TRUE, 0) < 0) DHD_ERROR(("%s: 5G roam delta setting failed\n", __FUNCTION__)); if (dhd_wl_ioctl_cmd(dhd, WLC_SET_ROAM_TRIGGER, \ (char *)&roam_trigger, sizeof(roam_trigger), TRUE, 0) < 0) DHD_ERROR(("%s: 5G roam trigger setting failed\n", __FUNCTION__)); if (dhd_wl_ioctl_cmd(dhd, WLC_SET_BAND, \ (char *)&band, sizeof(band), TRUE, 0) < 0) DHD_ERROR(("%s: Original band restore failed\n", __FUNCTION__)); } } #if defined(KEEP_ALIVE) { int res; #if defined(SOFTAP) if (ap_fw_loaded == FALSE) #endif if ((dhd->op_mode & HOSTAPD_MASK) != HOSTAPD_MASK) { if ((res = dhd_keep_alive_onoff(dhd)) < 0) DHD_ERROR(("%s set keeplive failed %d\n", __FUNCTION__, res)); } } #endif bcm_mkiovar("event_msgs", eventmask, WL_EVENTING_MASK_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, iovbuf, sizeof(iovbuf), FALSE, 0)) < 0) { DHD_ERROR(("%s read Event mask failed %d\n", __FUNCTION__, ret)); goto done; } bcopy(iovbuf, eventmask, WL_EVENTING_MASK_LEN); setbit(eventmask, WLC_E_SET_SSID); setbit(eventmask, WLC_E_PRUNE); setbit(eventmask, WLC_E_AUTH); setbit(eventmask, WLC_E_REASSOC); setbit(eventmask, WLC_E_REASSOC_IND); setbit(eventmask, WLC_E_DEAUTH); setbit(eventmask, WLC_E_DEAUTH_IND); setbit(eventmask, WLC_E_DISASSOC_IND); setbit(eventmask, WLC_E_DISASSOC); setbit(eventmask, WLC_E_JOIN); setbit(eventmask, WLC_E_ASSOC_IND); setbit(eventmask, WLC_E_PSK_SUP); setbit(eventmask, WLC_E_LINK); setbit(eventmask, WLC_E_NDIS_LINK); setbit(eventmask, WLC_E_MIC_ERROR); setbit(eventmask, WLC_E_ASSOC_REQ_IE); setbit(eventmask, WLC_E_ASSOC_RESP_IE); setbit(eventmask, WLC_E_PMKID_CACHE); setbit(eventmask, WLC_E_JOIN_START); setbit(eventmask, WLC_E_SCAN_COMPLETE); #ifdef WLMEDIA_HTSF setbit(eventmask, WLC_E_HTSFSYNC); #endif #ifdef PNO_SUPPORT setbit(eventmask, WLC_E_PFN_NET_FOUND); #endif #ifdef WLC_E_RSSI_LOW setbit(eventmask, WLC_E_RSSI_LOW); #endif setbit(eventmask, WLC_E_ROAM); setbit(eventmask, WLC_E_LOAD_IND); #if defined(HTC_TX_TRACKING) setbit(eventmask, WLC_E_TX_STAT_ERROR); #endif #ifdef WL_CFG80211 setbit(eventmask, WLC_E_ESCAN_RESULT); if(!is_screen_off) { setbit(eventmask, WLC_E_ACTION_FRAME_RX); setbit(eventmask, WLC_E_ACTION_FRAME_COMPLETE); setbit(eventmask, WLC_E_ACTION_FRAME_OFF_CHAN_COMPLETE); setbit(eventmask, WLC_E_P2P_PROBREQ_MSG); setbit(eventmask, WLC_E_P2P_DISC_LISTEN_COMPLETE); } else { printf("screen is off, don't register some events\n"); } #endif bcm_mkiovar("event_msgs", eventmask, WL_EVENTING_MASK_LEN, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0)) < 0) { DHD_ERROR(("%s Set Event mask failed %d\n", __FUNCTION__, ret)); goto done; } dhd_wl_ioctl_cmd(dhd, WLC_SET_SCAN_CHANNEL_TIME, (char *)&scan_assoc_time, sizeof(scan_assoc_time), TRUE, 0); dhd_wl_ioctl_cmd(dhd, WLC_SET_SCAN_UNASSOC_TIME, (char *)&scan_unassoc_time, sizeof(scan_unassoc_time), TRUE, 0); dhd_wl_ioctl_cmd(dhd, WLC_SET_SCAN_PASSIVE_TIME, (char *)&scan_passive_time, sizeof(scan_passive_time), TRUE, 0); bcm_mkiovar("ht_wsec_restrict", (char *)&ht_wsec_restrict, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd,WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("assoc_retry_max", (char *)&retry_max, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); #ifdef ARP_OFFLOAD_SUPPORT #if defined(SOFTAP) if (arpoe && !ap_fw_loaded) { #else if (arpoe) { #endif dhd_arp_offload_enable(dhd, TRUE); dhd_arp_offload_set(dhd, dhd_arp_mode); } else { dhd_arp_offload_enable(dhd, FALSE); dhd_arp_offload_set(dhd, 0); } #endif ret = 3; bcm_mkiovar("tc_period", (char *)&ret, 4, iovbuf, sizeof(iovbuf)); #if defined(DHD_BCM_WIFI_HDMI) if (dhd_bcm_whdmi_enable) { DHD_ERROR(("DHD WiFi HDMI is enabled\n")); #if !defined(AP) && !defined(WLP2P) bcm_mkiovar("mpc", (char *)&mpc, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("apsta", (char *)&apsta, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); #endif power_mode = PM_OFF; dhd_wl_ioctl_cmd(dhd, WLC_SET_PM, (char *)&power_mode, sizeof(power_mode), TRUE, 0); #ifdef ARP_OFFLOAD_SUPPORT dhd_arp_offload_set(dhd, 0); dhd_arp_offload_enable(dhd, FALSE); #endif } else { } #endif ret = dhd_wl_ioctl_cmd(dhd, WLC_UP, (char *)&up, sizeof(up), TRUE, 0); if (ret < 0) { DHD_ERROR(("%s Setting WL UP failed %d\n", __FUNCTION__, ret)); goto done; } dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); ret = TRAFFIC_LOW_WATER_MARK; bcm_mkiovar("tc_lo_wm", (char *)&ret, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); ret = TRAFFIC_HIGH_WATER_MARK; bcm_mkiovar("tc_hi_wm", (char *)&ret, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); ret = TRAFFIC_S_HIGH_WATER_MARK; bcm_mkiovar("tc_shi_wm", (char *)&ret, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); ret = 1; bcm_mkiovar("tc_enable", (char *)&ret, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); #if defined(HTC_TX_TRACKING) { uint tx_stat_chk = 0; uint tx_stat_chk_prd = 5; uint tx_stat_chk_ratio = 8; uint tx_stat_chk_num = 5; bcm_mkiovar("tx_stat_chk_num", (char *)&tx_stat_chk_num, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("tx_stat_chk_ratio", (char *)&tx_stat_chk_ratio, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("tx_stat_chk_prd", (char *)&tx_stat_chk_prd, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); bcm_mkiovar("tx_stat_chk", (char *)&tx_stat_chk, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); } #endif dhd_wl_ioctl_cmd(dhd, WLC_SET_SRL, (char *)&srl, sizeof(srl), TRUE, 0); dhd_wl_ioctl_cmd(dhd, WLC_SET_LRL, (char *)&lrl, sizeof(lrl), TRUE, 0); #ifdef GAN_LITE_NAT_KEEPALIVE_FILTER dhd->pktfilter[0] = "100 0 0 0 0xffffff 0xffffff"; dhd->pktfilter[1] = "102 0 0 36 0xffffffff 0x11940009"; dhd->pktfilter[2] = "104 0 0 38 0xffffffff 0x11940009"; dhd->pktfilter[3] = NULL; #endif done: return ret; } int dhd_iovar(dhd_pub_t *pub, int ifidx, char *name, char *cmd_buf, uint cmd_len, int set) { char buf[strlen(name) + 1 + cmd_len]; int len = sizeof(buf); wl_ioctl_t ioc; int ret; len = bcm_mkiovar(name, cmd_buf, cmd_len, buf, len); memset(&ioc, 0, sizeof(ioc)); ioc.cmd = set? WLC_SET_VAR : WLC_GET_VAR; ioc.buf = buf; ioc.len = len; ioc.set = TRUE; ret = dhd_wl_ioctl(pub, ifidx, &ioc, ioc.buf, ioc.len); if (!set && ret >= 0) memcpy(cmd_buf, buf, cmd_len); return ret; } int dhd_change_mtu(dhd_pub_t *dhdp, int new_mtu, int ifidx) { struct dhd_info *dhd = dhdp->info; struct net_device *dev = NULL; ASSERT(dhd && dhd->iflist[ifidx]); dev = dhd->iflist[ifidx]->net; ASSERT(dev); if (netif_running(dev)) { DHD_ERROR(("%s: Must be down to change its MTU", dev->name)); return BCME_NOTDOWN; } #define DHD_MIN_MTU 1500 #define DHD_MAX_MTU 1752 if ((new_mtu < DHD_MIN_MTU) || (new_mtu > DHD_MAX_MTU)) { DHD_ERROR(("%s: MTU size %d is invalid.\n", __FUNCTION__, new_mtu)); return BCME_BADARG; } dev->mtu = new_mtu; return 0; } #ifdef ARP_OFFLOAD_SUPPORT void aoe_update_host_ipv4_table(dhd_pub_t *dhd_pub, u32 ipa, bool add) { u32 ipv4_buf[MAX_IPV4_ENTRIES]; int i; int ret; bzero(ipv4_buf, sizeof(ipv4_buf)); ret = dhd_arp_get_arp_hostip_table(dhd_pub, ipv4_buf, sizeof(ipv4_buf)); DHD_ARPOE(("%s: hostip table read from Dongle:\n", __FUNCTION__)); #ifdef AOE_DBG dhd_print_buf(ipv4_buf, 32, 4); #endif dhd_aoe_hostip_clr(dhd_pub); if (ret) { DHD_ERROR(("%s failed\n", __FUNCTION__)); return; } for (i = 0; i < MAX_IPV4_ENTRIES; i++) { if (add && (ipv4_buf[i] == 0)) { ipv4_buf[i] = ipa; add = FALSE; DHD_ARPOE(("%s: Saved new IP in temp arp_hostip[%d]\n", __FUNCTION__, i)); } else if (ipv4_buf[i] == ipa) { ipv4_buf[i] = 0; DHD_ARPOE(("%s: removed IP:%x from temp table %d\n", __FUNCTION__, ipa, i)); } if (ipv4_buf[i] != 0) { dhd_arp_offload_add_ip(dhd_pub, ipv4_buf[i]); DHD_ARPOE(("%s: added IP:%x to dongle arp_hostip[%d]\n\n", __FUNCTION__, ipv4_buf[i], i)); } } #ifdef AOE_DBG dhd_arp_get_arp_hostip_table(dhd_pub, ipv4_buf, sizeof(ipv4_buf)); DHD_ARPOE(("%s: read back arp_hostip table:\n", __FUNCTION__)); dhd_print_buf(ipv4_buf, 32, 4); #endif } static int dhd_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct in_ifaddr *ifa = (struct in_ifaddr *)ptr; dhd_info_t *dhd; dhd_pub_t *dhd_pub; if (!ifa) return NOTIFY_DONE; dhd = *(dhd_info_t **)netdev_priv(ifa->ifa_dev->dev); dhd_pub = &dhd->pub; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 31)) if (ifa->ifa_dev->dev->netdev_ops == &dhd_ops_pri) { #else if (ifa->ifa_dev->dev) { #endif switch (event) { case NETDEV_UP: DHD_ARPOE(("%s: [%s] Up IP: 0x%x\n", __FUNCTION__, ifa->ifa_label, ifa->ifa_address)); if (dhd->pub.busstate != DHD_BUS_DATA) { DHD_ERROR(("%s: bus not ready, exit\n", __FUNCTION__)); if (dhd->pend_ipaddr) { DHD_ERROR(("%s: overwrite pending ipaddr: 0x%x\n", __FUNCTION__, dhd->pend_ipaddr)); } dhd->pend_ipaddr = ifa->ifa_address; break; } if (dhd->pub.busstate == DHD_BUS_DOWN) { DHD_ERROR(("%s: bus is down, exit\n", __FUNCTION__)); break; } #ifdef AOE_IP_ALIAS_SUPPORT if ((dhd_pub->op_mode & HOSTAPD_MASK) != HOSTAPD_MASK) { if (ifa->ifa_label[strlen(ifa->ifa_label)-2] == 0x3a) { DHD_ARPOE(("%s:add aliased IP to AOE hostip cache\n", __FUNCTION__)); aoe_update_host_ipv4_table(dhd_pub, ifa->ifa_address, TRUE); } else aoe_update_host_ipv4_table(dhd_pub, ifa->ifa_address, TRUE); } #endif break; case NETDEV_DOWN: DHD_ARPOE(("%s: [%s] Down IP: 0x%x\n", __FUNCTION__, ifa->ifa_label, ifa->ifa_address)); dhd->pend_ipaddr = 0; #ifdef AOE_IP_ALIAS_SUPPORT if ((dhd_pub->op_mode & HOSTAPD_MASK) != HOSTAPD_MASK) { if (!(ifa->ifa_label[strlen(ifa->ifa_label)-2] == 0x3a)) { DHD_ARPOE(("%s: primary interface is down, AOE clr all\n", __FUNCTION__)); dhd_aoe_hostip_clr(&dhd->pub); dhd_aoe_arp_clr(&dhd->pub); } else aoe_update_host_ipv4_table(dhd_pub, ifa->ifa_address, FALSE); } #else dhd_aoe_hostip_clr(&dhd->pub); dhd_aoe_arp_clr(&dhd->pub); #endif break; default: DHD_ARPOE(("%s: do noting for [%s] Event: %lu\n", __func__, ifa->ifa_label, event)); break; } } return NOTIFY_DONE; } #endif int dhd_net_attach(dhd_pub_t *dhdp, int ifidx) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; struct net_device *net = NULL; int err = 0; uint8 temp_addr[ETHER_ADDR_LEN] = { 0x00, 0x90, 0x4c, 0x11, 0x22, 0x33 }; DHD_TRACE(("%s: ifidx %d\n", __FUNCTION__, ifidx)); ASSERT(dhd && dhd->iflist[ifidx]); net = dhd->iflist[ifidx]->net; ASSERT(net); #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)) ASSERT(!net->open); net->get_stats = dhd_get_stats; net->do_ioctl = dhd_ioctl_entry; net->hard_start_xmit = dhd_start_xmit; net->set_mac_address = dhd_set_mac_address; net->set_multicast_list = dhd_set_multicast_list; net->open = net->stop = NULL; #else ASSERT(!net->netdev_ops); net->netdev_ops = &dhd_ops_virt; #endif if (ifidx == 0) { #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)) net->open = dhd_open; net->stop = dhd_stop; #else net->netdev_ops = &dhd_ops_pri; #endif memcpy(temp_addr, dhd->pub.mac.octet, ETHER_ADDR_LEN); } else { memcpy(temp_addr, dhd->iflist[ifidx]->mac_addr, ETHER_ADDR_LEN); if (!memcmp(temp_addr, dhd->iflist[0]->mac_addr, ETHER_ADDR_LEN)) { DHD_ERROR(("%s interface [%s]: set locally administered bit in MAC\n", __func__, net->name)); temp_addr[0] |= 0x02; } } net->hard_header_len = ETH_HLEN + dhd->pub.hdrlen; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24) net->ethtool_ops = &dhd_ethtool_ops; #endif #if defined(CONFIG_WIRELESS_EXT) #if WIRELESS_EXT < 19 net->get_wireless_stats = dhd_get_wireless_stats; #endif #if WIRELESS_EXT > 12 net->wireless_handlers = (struct iw_handler_def *)&wl_iw_handler_def; #endif #endif dhd->pub.rxsz = DBUS_RX_BUFFER_SIZE_DHD(net); memcpy(net->dev_addr, temp_addr, ETHER_ADDR_LEN); if ((err = register_netdev(net)) != 0) { DHD_ERROR(("couldn't register the net device, err %d\n", err)); goto fail; } printf("Broadcom Dongle Host Driver: register interface [%s]" " MAC: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", net->name, net->dev_addr[0], net->dev_addr[1], net->dev_addr[2], net->dev_addr[3], net->dev_addr[4], net->dev_addr[5]); #if defined(SOFTAP) && defined(CONFIG_WIRELESS_EXT) && !defined(WL_CFG80211) wl_iw_iscan_set_scan_broadcast_prep(net, 1); #endif #if 1 && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if (ifidx == 0) { dhd_registration_check = TRUE; up(&dhd_registration_sem); } #endif return 0; fail: #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31) net->open = NULL; #else net->netdev_ops = NULL; #endif return err; } void dhd_bus_detach(dhd_pub_t *dhdp) { dhd_info_t *dhd; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (dhdp) { dhd = (dhd_info_t *)dhdp->info; if (dhd) { if (dhd->pub.busstate != DHD_BUS_DOWN) { dhd_prot_stop(&dhd->pub); dhd_bus_stop(dhd->pub.bus, TRUE); } #if defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) bcmsdh_unregister_oob_intr(); #endif } } } void dhd_detach(dhd_pub_t *dhdp) { dhd_info_t *dhd; unsigned long flags; int timer_valid = FALSE; if (!dhdp) return; dhd = (dhd_info_t *)dhdp->info; if (!dhd) return; dhd->dhd_force_exit = TRUE; DHD_TRACE(("%s: Enter state 0x%x\n", __FUNCTION__, dhd->dhd_state)); dhd->pub.up = 0; if (!(dhd->dhd_state & DHD_ATTACH_STATE_DONE)) { osl_delay(1000*100); } if (dhd->dhd_state & DHD_ATTACH_STATE_PROT_ATTACH) { dhd_bus_detach(dhdp); if (dhdp->prot) dhd_prot_detach(dhdp); } #ifdef ARP_OFFLOAD_SUPPORT unregister_inetaddr_notifier(&dhd_notifier); #endif #if defined(CONFIG_HAS_EARLYSUSPEND) && defined(DHD_USE_EARLYSUSPEND) if (dhd->dhd_state & DHD_ATTACH_STATE_EARLYSUSPEND_DONE) { if (dhd->early_suspend.suspend) unregister_early_suspend(&dhd->early_suspend); } #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) cancel_work_sync(&dhd->work_hang); #endif #if defined(CONFIG_WIRELESS_EXT) if (dhd->dhd_state & DHD_ATTACH_STATE_WL_ATTACH) { wl_iw_detach(); } #endif if (dhd->thr_sysioc_ctl.thr_pid >= 0) { PROC_STOP(&dhd->thr_sysioc_ctl); } if (dhd->dhd_state & DHD_ATTACH_STATE_ADD_IF) { int i = 1; dhd_if_t *ifp; for (i = 1; i < DHD_MAX_IFS; i++) { dhd_net_if_lock_local(dhd); if (dhd->iflist[i]) { dhd->iflist[i]->state = DHD_IF_DEL; dhd->iflist[i]->idx = i; dhd_op_if(dhd->iflist[i]); } dhd_net_if_unlock_local(dhd); } ifp = dhd->iflist[0]; ASSERT(ifp); #ifdef HTC_KlocWork if (ifp && ifp->net) { #endif #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)) if (ifp->net->open) #else if (ifp->net->netdev_ops == &dhd_ops_pri) #endif { if (ifp->net) { unregister_netdev(ifp->net); free_netdev(ifp->net); ifp->net = NULL; } MFREE(dhd->pub.osh, ifp, sizeof(*ifp)); dhd->iflist[0] = NULL; } #ifdef HTC_KlocWork } #endif } flags = dhd_os_spin_lock(&dhd->pub); timer_valid = dhd->wd_timer_valid; dhd->wd_timer_valid = FALSE; dhd_os_spin_unlock(&dhd->pub, flags); if (timer_valid) del_timer_sync(&dhd->timer); if (dhd->dhd_state & DHD_ATTACH_STATE_THREADS_CREATED) { #ifdef DHDTHREAD if (dhd->thr_wdt_ctl.thr_pid >= 0) { PROC_STOP(&dhd->thr_wdt_ctl); } if (dhd->thr_dpc_ctl.thr_pid >= 0) { PROC_STOP(&dhd->thr_dpc_ctl); } if (dhd->thr_sysioc_ctl.thr_pid >= 0) { PROC_STOP(&dhd->thr_sysioc_ctl); } else #endif tasklet_kill(&dhd->tasklet); } if (dhd->dhd_state & DHD_ATTACH_STATE_PROT_ATTACH) { dhd_bus_detach(dhdp); if (dhdp->prot) dhd_prot_detach(dhdp); } #ifdef WL_CFG80211 if (dhd->dhd_state & DHD_ATTACH_STATE_CFG80211) { wl_cfg80211_detach(NULL); dhd_monitor_uninit(); } #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && defined(CONFIG_PM_SLEEP) unregister_pm_notifier(&dhd_sleep_pm_notifier); #endif if (dhd->dhd_state & DHD_ATTACH_STATE_WAKELOCKS_INIT) { #ifdef CONFIG_HAS_WAKELOCK dhd->wakelock_counter = 0; dhd->wakelock_rx_timeout_enable = 0; dhd->wakelock_ctrl_timeout_enable = 0; wake_lock_destroy(&dhd->wl_wifi); wake_lock_destroy(&dhd->wl_rxwake); wake_lock_destroy(&dhd->wl_ctrlwake); wake_lock_destroy(&dhd->wl_htc); #endif } dhd->dhd_force_exit = FALSE; } void dhd_free(dhd_pub_t *dhdp) { dhd_info_t *dhd; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (dhdp) { int i; for (i = 0; i < ARRAYSIZE(dhdp->reorder_bufs); i++) { if (dhdp->reorder_bufs[i]) { reorder_info_t *ptr; uint32 buf_size = sizeof(struct reorder_info); ptr = dhdp->reorder_bufs[i]; buf_size += ((ptr->max_idx + 1) * sizeof(void*)); DHD_REORDER(("free flow id buf %d, maxidx is %d, buf_size %d\n", i, ptr->max_idx, buf_size)); MFREE(dhdp->osh, dhdp->reorder_bufs[i], buf_size); dhdp->reorder_bufs[i] = NULL; } } dhd = (dhd_info_t *)dhdp->info; if (dhd) MFREE(dhd->pub.osh, dhd, sizeof(*dhd)); } } extern void disable_dev_wlc_ioctl(void); static void __exit dhd_module_cleanup(void) { DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (priv_dhdp) dhd_net_if_lock_local(priv_dhdp->info); #ifdef CONFIG_WIRELESS_EXT disable_dev_wlc_ioctl(); #endif module_remove = 1; module_insert = 0; if (priv_dhdp) dhd_net_if_unlock_local(priv_dhdp->info); msleep(1000); dhd_bus_unregister(); #if defined(CONFIG_WIFI_CONTROL_FUNC) wl_android_wifictrl_func_del(); #endif wl_android_exit(); dhd_customer_gpio_wlan_ctrl(WLAN_POWER_OFF); printf("[ATS][press_widget][turn_off]\n"); } static int __init dhd_module_init(void) { int error = 0; int retry = 0; wifi_fail_retry = false; #if 0 && defined(BCMLXSDMMC) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) int retry = POWERUP_MAX_RETRY; int chip_up = 0; #endif DHD_TRACE(("%s: Enter\n", __FUNCTION__)); wl_android_init(); init_retry: #if defined(DHDTHREAD) do { if ((dhd_watchdog_prio < 0) && (dhd_dpc_prio < 0)) break; if ((dhd_watchdog_prio >= 0) && (dhd_dpc_prio >= 0) && dhd_deferred_tx) break; DHD_ERROR(("Invalid module parameters.\n")); return -EINVAL; } while (0); #endif #if 0 && defined(BCMLXSDMMC) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) do { sema_init(&dhd_chipup_sem, 0); dhd_bus_reg_sdio_notify(&dhd_chipup_sem); dhd_customer_gpio_wlan_ctrl(WLAN_POWER_ON); #if defined(CONFIG_WIFI_CONTROL_FUNC) if (wl_android_wifictrl_func_add() < 0) { dhd_bus_unreg_sdio_notify(); goto fail_1; } #endif if (down_timeout(&dhd_chipup_sem, msecs_to_jiffies(POWERUP_WAIT_MS)) == 0) { dhd_bus_unreg_sdio_notify(); chip_up = 1; break; } DHD_ERROR(("\nfailed to power up wifi chip, retry again (%d left) **\n\n", retry+1)); dhd_bus_unreg_sdio_notify(); #if defined(CONFIG_WIFI_CONTROL_FUNC) wl_android_wifictrl_func_del(); #endif dhd_customer_gpio_wlan_ctrl(WLAN_POWER_OFF); } while (retry-- > 0); if (!chip_up) { DHD_ERROR(("\nfailed to power up wifi chip, max retry reached, exits **\n\n")); return -ENODEV; } #else dhd_customer_gpio_wlan_ctrl(WLAN_POWER_ON); #if defined(CONFIG_WIFI_CONTROL_FUNC) if (wl_android_wifictrl_func_add() < 0) goto fail_1; #endif #endif #if 1 && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) sema_init(&dhd_registration_sem, 0); #endif error = dhd_bus_register(); if (!error) printf("\n%s\n", dhd_version); else { DHD_ERROR(("%s: sdio_register_driver failed\n", __FUNCTION__)); goto fail_1; } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if ((down_timeout(&dhd_registration_sem, msecs_to_jiffies(DHD_REGISTRATION_TIMEOUT)) != 0) || (dhd_registration_check != TRUE)) { error = -ENODEV; DHD_ERROR(("%s: sdio_register_driver timeout or error \n", __FUNCTION__)); goto fail_2; } #endif if (wifi_fail_retry) { wifi_fail_retry = false; DHD_ERROR(("%s: wifi_fail_retry is true\n", __FUNCTION__)); goto fail_2; } #if defined(WL_CFG80211) wl_android_post_init(); #endif module_insert = 1; printf("[ATS][press_widget][launch]\n"); return error; #if 1 && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) fail_2: dhd_bus_unregister(); #endif fail_1: #if defined(CONFIG_WIFI_CONTROL_FUNC) wl_android_wifictrl_func_del(); #endif dhd_customer_gpio_wlan_ctrl(WLAN_POWER_OFF); if (!retry) { printf("module init fail, try again!\n"); retry = 1; goto init_retry; } return error; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) late_initcall(dhd_module_init); #else module_init(dhd_module_init); #endif module_exit(dhd_module_cleanup); int dhd_os_proto_block(dhd_pub_t *pub) { dhd_info_t * dhd = (dhd_info_t *)(pub->info); if (dhd) { down(&dhd->proto_sem); return 1; } return 0; } int dhd_os_proto_unblock(dhd_pub_t *pub) { dhd_info_t * dhd = (dhd_info_t *)(pub->info); if (dhd) { up(&dhd->proto_sem); return 1; } return 0; } unsigned int dhd_os_get_ioctl_resp_timeout(void) { return ((unsigned int)dhd_ioctl_timeout_msec); } void dhd_os_set_ioctl_resp_timeout(unsigned int timeout_msec) { dhd_ioctl_timeout_msec = (int)timeout_msec; } int dhd_os_ioctl_resp_wait(dhd_pub_t *pub, uint *condition, bool *pending) { dhd_info_t * dhd = (dhd_info_t *)(pub->info); int timeout; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) timeout = msecs_to_jiffies(dhd_ioctl_timeout_msec); #else timeout = timeout * HZ / 1000; #endif #if 0 add_wait_queue(&dhd->ioctl_resp_wait, &wait); set_current_state(TASK_INTERRUPTIBLE); smp_mb(); while (!(*condition) && (!signal_pending(current) && timeout)) { timeout = schedule_timeout(timeout); smp_mb(); } if (signal_pending(current)) *pending = TRUE; set_current_state(TASK_RUNNING); remove_wait_queue(&dhd->ioctl_resp_wait, &wait); #else timeout = wait_event_timeout(dhd->ioctl_resp_wait, (*condition), timeout); #endif return timeout; } int dhd_os_ioctl_resp_wake(dhd_pub_t *pub) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); if (waitqueue_active(&dhd->ioctl_resp_wait)) { wake_up(&dhd->ioctl_resp_wait); } return 0; } void dhd_os_wd_timer(void *bus, uint wdtick) { dhd_pub_t *pub = bus; dhd_info_t *dhd = (dhd_info_t *)pub->info; unsigned long flags; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (!dhd) return; flags = dhd_os_spin_lock(pub); if (pub->busstate == DHD_BUS_DOWN) { dhd_os_spin_unlock(pub, flags); return; } if (!wdtick && dhd->wd_timer_valid == TRUE) { dhd->wd_timer_valid = FALSE; dhd_os_spin_unlock(pub, flags); #ifdef DHDTHREAD del_timer_sync(&dhd->timer); #else del_timer(&dhd->timer); #endif return; } if (wdtick) { dhd_watchdog_ms = (uint)wdtick; mod_timer(&dhd->timer, jiffies + dhd_watchdog_ms * HZ / 1000); dhd->wd_timer_valid = TRUE; } dhd_os_spin_unlock(pub, flags); } void * dhd_os_open_image(char *filename) { struct file *fp; fp = filp_open(filename, O_RDONLY, 0); if (IS_ERR(fp)) fp = NULL; return fp; } int dhd_os_get_image_block(char *buf, int len, void *image) { struct file *fp = (struct file *)image; int rdlen; if (!image) return 0; rdlen = kernel_read(fp, fp->f_pos, buf, len); if (rdlen > 0) fp->f_pos += rdlen; return rdlen; } void dhd_os_close_image(void *image) { if (image) filp_close((struct file *)image, NULL); } void dhd_os_sdlock(dhd_pub_t *pub) { dhd_info_t *dhd; dhd = (dhd_info_t *)(pub->info); #ifdef DHDTHREAD if (dhd->threads_only) down(&dhd->sdsem); else #endif spin_lock_bh(&dhd->sdlock); } void dhd_os_sdunlock(dhd_pub_t *pub) { dhd_info_t *dhd; dhd = (dhd_info_t *)(pub->info); #ifdef DHDTHREAD if (dhd->threads_only) up(&dhd->sdsem); else #endif spin_unlock_bh(&dhd->sdlock); } void dhd_os_sdlock_txq(dhd_pub_t *pub) { dhd_info_t *dhd; dhd = (dhd_info_t *)(pub->info); spin_lock_bh(&dhd->txqlock); } void dhd_os_sdunlock_txq(dhd_pub_t *pub) { dhd_info_t *dhd; dhd = (dhd_info_t *)(pub->info); spin_unlock_bh(&dhd->txqlock); } void dhd_os_sdlock_rxq(dhd_pub_t *pub) { } void dhd_os_sdunlock_rxq(dhd_pub_t *pub) { } void dhd_os_sdtxlock(dhd_pub_t *pub) { dhd_os_sdlock(pub); } void dhd_os_sdtxunlock(dhd_pub_t *pub) { dhd_os_sdunlock(pub); } #if defined(DHD_USE_STATIC_BUF) uint8* dhd_os_prealloc(void *osh, int section, uint size) { return (uint8*)wl_android_prealloc(section, size); } void dhd_os_prefree(void *osh, void *addr, uint size) { } #endif #if defined(CONFIG_WIRELESS_EXT) struct iw_statistics * dhd_get_wireless_stats(struct net_device *dev) { int res = 0; dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (!dhd->pub.up) { return NULL; } res = wl_iw_get_wireless_stats(dev, &dhd->iw.wstats); if (res == 0) return &dhd->iw.wstats; else return NULL; } #endif static int dhd_wl_host_event(dhd_info_t *dhd, int *ifidx, void *pktdata, wl_event_msg_t *event, void **data) { int bcmerror = 0; ASSERT(dhd != NULL); bcmerror = wl_host_event(&dhd->pub, ifidx, pktdata, event, data); if (bcmerror != BCME_OK) return (bcmerror); #if defined(CONFIG_WIRELESS_EXT) if ( #if defined(APSTA_CONCURRENT) && defined(SOFTAP) !ap_net_dev && #endif event->bsscfgidx == 0) { ASSERT(dhd->iflist[*ifidx] != NULL); ASSERT(dhd->iflist[*ifidx]->net != NULL); if (dhd->iflist[*ifidx]->net) { wl_iw_event(dhd->iflist[*ifidx]->net, event, *data); } } #if defined(APSTA_CONCURRENT) && defined(SOFTAP) if ( dhd->iflist[*ifidx]->net && (dhd->iflist[*ifidx]->net == ap_net_dev)){ wl_iw_event(dhd->iflist[*ifidx]->net, event, *data); printf("%s: don't route event to wl_cfg80211 if the net_dev is ap_net_dev\n", __FUNCTION__); return BCME_OK; } #endif #endif #ifdef WL_CFG80211 if ((ntoh32(event->event_type) == WLC_E_IF) && (((dhd_if_event_t *)*data)->action == WLC_E_IF_ADD)) return (BCME_OK); if ((wl_cfg80211_is_progress_ifchange() || wl_cfg80211_is_progress_ifadd()) && (*ifidx != 0)) { return (BCME_OK); } ASSERT(dhd->iflist[*ifidx] != NULL); ASSERT(dhd->iflist[*ifidx]->net != NULL); if (dhd->iflist[*ifidx]->event2cfg80211 && dhd->iflist[*ifidx]->net) { wl_cfg80211_event(dhd->iflist[*ifidx]->net, event, *data); } #endif return (bcmerror); } void dhd_sendup_event(dhd_pub_t *dhdp, wl_event_msg_t *event, void *data) { switch (ntoh32(event->event_type)) { #ifdef WLBTAMP case WLC_E_BTA_HCI_EVENT: { struct sk_buff *p, *skb; bcm_event_t *msg; wl_event_msg_t *p_bcm_event; char *ptr; uint32 len; uint32 pktlen; dhd_if_t *ifp; dhd_info_t *dhd; uchar *eth; int ifidx; len = ntoh32(event->datalen); pktlen = sizeof(bcm_event_t) + len + 2; dhd = dhdp->info; ifidx = dhd_ifname2idx(dhd, event->ifname); if ((p = PKTGET(dhdp->osh, pktlen, FALSE))) { ASSERT(ISALIGNED((uintptr)PKTDATA(dhdp->osh, p), sizeof(uint32))); msg = (bcm_event_t *) PKTDATA(dhdp->osh, p); bcopy(&dhdp->mac, &msg->eth.ether_dhost, ETHER_ADDR_LEN); bcopy(&dhdp->mac, &msg->eth.ether_shost, ETHER_ADDR_LEN); ETHER_TOGGLE_LOCALADDR(&msg->eth.ether_shost); msg->eth.ether_type = hton16(ETHER_TYPE_BRCM); msg->bcm_hdr.subtype = hton16(BCMILCP_SUBTYPE_VENDOR_LONG); msg->bcm_hdr.version = BCMILCP_BCM_SUBTYPEHDR_VERSION; bcopy(BRCM_OUI, &msg->bcm_hdr.oui[0], DOT11_OUI_LEN); msg->bcm_hdr.length = hton16(BCMILCP_BCM_SUBTYPEHDR_MINLENGTH + BCM_MSG_LEN + sizeof(wl_event_msg_t) + (uint16)len); msg->bcm_hdr.usr_subtype = hton16(BCMILCP_BCM_SUBTYPE_EVENT); PKTSETLEN(dhdp->osh, p, (sizeof(bcm_event_t) + len + 2)); p_bcm_event = &msg->event; bcopy(event, p_bcm_event, sizeof(wl_event_msg_t)); bcopy(data, (p_bcm_event + 1), len); msg->bcm_hdr.length = hton16(sizeof(wl_event_msg_t) + ntoh16(msg->bcm_hdr.length)); PKTSETLEN(dhdp->osh, p, (sizeof(bcm_event_t) + len + 2)); ptr = (char *)(msg + 1); ptr[len+0] = 0x00; ptr[len+1] = 0x00; skb = PKTTONATIVE(dhdp->osh, p); eth = skb->data; len = skb->len; ifp = dhd->iflist[ifidx]; if (ifp == NULL) ifp = dhd->iflist[0]; ASSERT(ifp); skb->dev = ifp->net; skb->protocol = eth_type_trans(skb, skb->dev); skb->data = eth; skb->len = len; skb_pull(skb, ETH_HLEN); if (in_interrupt()) { netif_rx(skb); } else { netif_rx_ni(skb); } } else { DHD_ERROR(("%s: unable to alloc sk_buf", __FUNCTION__)); } break; } #endif default: break; } } void dhd_wait_for_event(dhd_pub_t *dhd, bool *lockvar) { #if 1 && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) struct dhd_info *dhdinfo = dhd->info; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) int timeout = msecs_to_jiffies(2000); #else int timeout = 2 * HZ; #endif dhd_os_sdunlock(dhd); wait_event_timeout(dhdinfo->ctrl_wait, (*lockvar == FALSE), timeout); dhd_os_sdlock(dhd); #endif return; } void dhd_wait_event_wakeup(dhd_pub_t *dhd) { #if 1 && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) struct dhd_info *dhdinfo = dhd->info; if (waitqueue_active(&dhdinfo->ctrl_wait)) wake_up(&dhdinfo->ctrl_wait); #endif return; } int dhd_dev_reset(struct net_device *dev, uint8 flag) { int ret; dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); ret = dhd_bus_devreset(&dhd->pub, flag); if (ret) { DHD_ERROR(("%s: dhd_bus_devreset: %d\n", __FUNCTION__, ret)); return ret; } return ret; } int net_os_set_suspend_disable(struct net_device *dev, int val) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd) { ret = dhd->pub.suspend_disable_flag; dhd->pub.suspend_disable_flag = val; } return ret; } int net_os_set_suspend(struct net_device *dev, int val, int force) { int ret = 0; dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (dhd) { #if defined(CONFIG_HAS_EARLYSUSPEND) ret = dhd_set_suspend(val, &dhd->pub); #else ret = dhd_suspend_resume_helper(dhd, val, force); #endif } return ret; } int net_os_set_dtim_skip(struct net_device *dev, int val) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (dhd) dhd->pub.dtim_skip = val; return 0; } #ifdef PKT_FILTER_SUPPORT int net_os_rxfilter_add_remove(struct net_device *dev, int add_remove, int num) { #ifndef GAN_LITE_NAT_KEEPALIVE_FILTER dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); char *filterp = NULL; int ret = 0; if (!dhd || (num == DHD_UNICAST_FILTER_NUM) || (num == DHD_MDNS_FILTER_NUM)) return ret; if (num >= dhd->pub.pktfilter_count) return -EINVAL; if (add_remove) { switch (num) { case DHD_BROADCAST_FILTER_NUM: filterp = "101 0 0 0 0xFFFFFFFFFFFF 0xFFFFFFFFFFFF"; break; case DHD_MULTICAST4_FILTER_NUM: filterp = "102 0 0 0 0xFFFFFF 0x01005E"; break; case DHD_MULTICAST6_FILTER_NUM: #if defined(BLOCK_IPV6_PACKET) return ret; #endif filterp = "103 0 0 0 0xFFFF 0x3333"; break; default: return -EINVAL; } } dhd->pub.pktfilter[num] = filterp; return ret; #else return 0; #endif } #endif int wl_android_set_pktfilter(struct net_device *dev, struct dd_pkt_filter_s *data) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); return dhd_set_pktfilter(&dhd->pub, data->add, data->id, data->offset, data->mask, data->pattern); } int net_os_set_packet_filter(struct net_device *dev, int val) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd && dhd->pub.up) { if (dhd->pub.in_suspend) { if (!val || (val && !dhd->pub.suspend_disable_flag)) dhd_set_packet_filter(val, &dhd->pub); } } return ret; } void dhd_dev_init_ioctl(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); dhd_preinit_ioctls(&dhd->pub); } #ifdef PNO_SUPPORT int dhd_dev_pno_reset(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); return (dhd_pno_clean(&dhd->pub)); } int dhd_dev_pno_enable(struct net_device *dev, int pfn_enabled) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); return (dhd_pno_enable(&dhd->pub, pfn_enabled)); } int dhd_dev_pno_set(struct net_device *dev, wlc_ssid_t* ssids_local, int nssid, ushort scan_fr, int pno_repeat, int pno_freq_expo_max) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); return (dhd_pno_set(&dhd->pub, ssids_local, nssid, scan_fr, pno_repeat, pno_freq_expo_max)); } int dhd_dev_get_pno_status(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); return (dhd_pno_get_status(&dhd->pub)); } #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) && (1) static void dhd_hang_process(struct work_struct *work) { dhd_info_t *dhd; struct net_device *dev; int ret; s32 updown = 0; dhd = (dhd_info_t *)container_of(work, dhd_info_t, work_hang); dev = dhd->iflist[0]->net; if (dev) { printf(" %s before send hang messages, do wlc down to prevent get additional event from firmware\n",__FUNCTION__); if ((ret = wldev_ioctl(dev, WLC_DOWN, &updown, sizeof(s32), false))) { WL_ERR(("fail to set wlc down")); } #if defined(WL_WIRELESS_EXT) wl_iw_send_priv_event(dev, "HANG"); #endif #if defined(WL_CFG80211) wl_cfg80211_hang(dev, WLAN_REASON_UNSPECIFIED); #endif } } int dhd_os_send_hang_message(dhd_pub_t *dhdp) { int ret = 0; if (dhdp) { if (!dhdp->hang_was_sent) { dhdp->hang_was_sent = 1; printf("%s: schedule hang event\n", __FUNCTION__); schedule_work(&dhdp->info->work_hang); } } return ret; } int net_os_send_hang_message(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (module_remove) { printf("%s: module removed. Do not send hang event.\n", __FUNCTION__); return ret; } if (dhd) ret = dhd_os_send_hang_message(&dhd->pub); return ret; } #endif bool check_hang_already(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (dhd->pub.hang_was_sent) return TRUE; else return FALSE; } #if defined(CONFIG_WIRELESS_EXT) void dhd_info_send_hang_message(dhd_pub_t *dhdp) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; struct net_device *dev = NULL; if ((dhd == NULL) || dhd->iflist[0]->net == NULL) { return; } dev = dhd->iflist[0]->net; net_os_send_hang_message(dev); return; } int net_os_send_rssilow_message(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (module_remove) { printf("%s: module removed. Do not send rssi_low event.\n", __FUNCTION__); return ret; } if (dhd) { ret = wl_cfg80211_rssilow(dev); } return ret; } #endif void dhd_bus_country_set(struct net_device *dev, wl_country_t *cspec) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (dhd && dhd->pub.up) memcpy(&dhd->pub.dhd_cspec, cspec, sizeof(wl_country_t)); } wl_country_t *dhd_bus_country_get(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (dhd && (dhd->pub.dhd_cspec.ccode[0] != 0)) return &dhd->pub.dhd_cspec; return NULL; } void dhd_net_if_lock(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); dhd_net_if_lock_local(dhd); } void dhd_net_if_unlock(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); dhd_net_if_unlock_local(dhd); } static void dhd_net_if_lock_local(dhd_info_t *dhd) { #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 if (dhd) mutex_lock(&dhd->dhd_net_if_mutex); #endif } static void dhd_net_if_unlock_local(dhd_info_t *dhd) { #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 if (dhd) mutex_unlock(&dhd->dhd_net_if_mutex); #endif } #if 0 static void dhd_suspend_lock(dhd_pub_t *pub) { #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 dhd_info_t *dhd = (dhd_info_t *)(pub->info); if (dhd) mutex_lock(&dhd->dhd_suspend_mutex); #endif } static void dhd_suspend_unlock(dhd_pub_t *pub) { #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 dhd_info_t *dhd = (dhd_info_t *)(pub->info); if (dhd) mutex_unlock(&dhd->dhd_suspend_mutex); #endif } #endif unsigned long dhd_os_spin_lock(dhd_pub_t *pub) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags = 0; if (dhd) spin_lock_irqsave(&dhd->dhd_lock, flags); return flags; } void dhd_os_spin_unlock(dhd_pub_t *pub, unsigned long flags) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); if (dhd) spin_unlock_irqrestore(&dhd->dhd_lock, flags); } static int dhd_get_pend_8021x_cnt(dhd_info_t *dhd) { return (atomic_read(&dhd->pend_8021x_cnt)); } #define MAX_WAIT_FOR_8021X_TX 25 int dhd_wait_pend8021x(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int timeout = 10 * HZ / 1000; int ntimes = MAX_WAIT_FOR_8021X_TX; int pend = dhd_get_pend_8021x_cnt(dhd); while (ntimes && pend) { if (pend) { set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(timeout); set_current_state(TASK_RUNNING); ntimes--; } pend = dhd_get_pend_8021x_cnt(dhd); } if (ntimes == 0) DHD_ERROR(("%s: TIMEOUT\n", __FUNCTION__)); return pend; } #ifdef DHD_DEBUG int write_to_file(dhd_pub_t *dhd, uint8 *buf, int size) { int ret = 0; struct file *fp; mm_segment_t old_fs; loff_t pos = 0; old_fs = get_fs(); set_fs(KERNEL_DS); fp = filp_open("/tmp/mem_dump", O_WRONLY|O_CREAT, 0640); if (!fp) { printf("%s: open file error\n", __FUNCTION__); ret = -1; goto exit; } fp->f_op->write(fp, buf, size, &pos); exit: MFREE(dhd->osh, buf, size); if (fp) filp_close(fp, current->files); set_fs(old_fs); return ret; } #endif void dhd_htc_wake_lock_timeout(dhd_pub_t *pub, int sec) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); #ifdef CONFIG_HAS_WAKELOCK wake_lock_timeout(&dhd->wl_htc, sec * HZ); #endif } int dhd_os_wake_lock_timeout(dhd_pub_t *pub) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags; int ret = 0; if (dhd) { spin_lock_irqsave(&dhd->wakelock_spinlock, flags); ret = dhd->wakelock_rx_timeout_enable > dhd->wakelock_ctrl_timeout_enable ? dhd->wakelock_rx_timeout_enable : dhd->wakelock_ctrl_timeout_enable; #ifdef CONFIG_HAS_WAKELOCK if (dhd->wakelock_rx_timeout_enable) wake_lock_timeout(&dhd->wl_rxwake, msecs_to_jiffies(dhd->wakelock_rx_timeout_enable)); if (dhd->wakelock_ctrl_timeout_enable) wake_lock_timeout(&dhd->wl_ctrlwake, msecs_to_jiffies(dhd->wakelock_ctrl_timeout_enable)); #endif dhd->wakelock_rx_timeout_enable = 0; dhd->wakelock_ctrl_timeout_enable = 0; spin_unlock_irqrestore(&dhd->wakelock_spinlock, flags); } return ret; } int net_os_wake_lock_timeout(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd) ret = dhd_os_wake_lock_timeout(&dhd->pub); return ret; } int dhd_os_wake_lock_rx_timeout_enable(dhd_pub_t *pub, int val) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags; if (dhd) { spin_lock_irqsave(&dhd->wakelock_spinlock, flags); if (val > dhd->wakelock_rx_timeout_enable) dhd->wakelock_rx_timeout_enable = val; spin_unlock_irqrestore(&dhd->wakelock_spinlock, flags); } return 0; } int dhd_os_wake_lock_ctrl_timeout_enable(dhd_pub_t *pub, int val) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags; if (dhd) { spin_lock_irqsave(&dhd->wakelock_spinlock, flags); if (val > dhd->wakelock_ctrl_timeout_enable) dhd->wakelock_ctrl_timeout_enable = val; spin_unlock_irqrestore(&dhd->wakelock_spinlock, flags); } return 0; } int net_os_wake_lock_rx_timeout_enable(struct net_device *dev, int val) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd) ret = dhd_os_wake_lock_rx_timeout_enable(&dhd->pub, val); return ret; } int net_os_wake_lock_ctrl_timeout_enable(struct net_device *dev, int val) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd) ret = dhd_os_wake_lock_ctrl_timeout_enable(&dhd->pub, val); return ret; } int dhd_os_wake_lock(dhd_pub_t *pub) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags; int ret = 0; if (dhd) { spin_lock_irqsave(&dhd->wakelock_spinlock, flags); #ifdef CONFIG_HAS_WAKELOCK if (!dhd->wakelock_counter) wake_lock(&dhd->wl_wifi); #elif defined(CUSTOMER_HW4) && defined(CONFIG_PM_SLEEP) && defined(PLATFORM_SLP) pm_stay_awake(pm_dev); #endif dhd->wakelock_counter++; ret = dhd->wakelock_counter; spin_unlock_irqrestore(&dhd->wakelock_spinlock, flags); } return ret; } int net_os_wake_lock(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd) ret = dhd_os_wake_lock(&dhd->pub); return ret; } int dhd_os_wake_unlock(dhd_pub_t *pub) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags; int ret = 0; dhd_os_wake_lock_timeout(pub); if (dhd) { spin_lock_irqsave(&dhd->wakelock_spinlock, flags); if (dhd->wakelock_counter) { dhd->wakelock_counter--; #ifdef CONFIG_HAS_WAKELOCK if (!dhd->wakelock_counter) wake_unlock(&dhd->wl_wifi); #elif defined(CUSTOMER_HW4) && defined(CONFIG_PM_SLEEP) && defined(PLATFORM_SLP) pm_relax(pm_dev); #endif ret = dhd->wakelock_counter; } spin_unlock_irqrestore(&dhd->wakelock_spinlock, flags); } return ret; } int net_os_wake_unlock(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); int ret = 0; if (dhd) ret = dhd_os_wake_unlock(&dhd->pub); return ret; } int dhd_os_wake_force_unlock(dhd_pub_t *pub) { dhd_info_t *dhd = (dhd_info_t *)(pub->info); unsigned long flags; int ret = 0; dhd_os_wake_lock_timeout(pub); if (dhd) { spin_lock_irqsave(&dhd->wakelock_spinlock, flags); if (dhd->wakelock_counter) { printf("wakelock_counter = %d, set to 0\n", dhd->wakelock_counter); dhd->wakelock_counter = 0; #ifdef CONFIG_HAS_WAKELOCK if (!dhd->wakelock_counter) wake_unlock(&dhd->wl_wifi); #endif ret = dhd->wakelock_counter; } spin_unlock_irqrestore(&dhd->wakelock_spinlock, flags); } return ret; } int dhd_os_check_wakelock(void *dhdp) { #ifdef CONFIG_HAS_WAKELOCK dhd_pub_t *pub = (dhd_pub_t *)dhdp; dhd_info_t *dhd; if (!pub) return 0; dhd = (dhd_info_t *)(pub->info); if (dhd && wake_lock_active(&dhd->wl_wifi)) return 1; #elif defined(CUSTOMER_HW4) && defined(CONFIG_PM_SLEEP) && defined(PLATFORM_SLP) dhd_pub_t *pub = (dhd_pub_t *)dhdp; dhd_info_t *dhd; if (!pub) return 0; dhd = (dhd_info_t *)(pub->info); DHD_ERROR(("%s : wakelock_count = %d\n", __func__, dhd->wakelock_counter)); if (dhd && (dhd->wakelock_counter > 0)) return 1; #endif return 0; } int dhd_os_check_if_up(void *dhdp) { dhd_pub_t *pub = (dhd_pub_t *)dhdp; if (!pub) return 0; return pub->up; } int dhd_ioctl_entry_local(struct net_device *net, wl_ioctl_t *ioc, int cmd) { int ifidx; int ret = 0; dhd_info_t *dhd = NULL; if (!net || !netdev_priv(net)) { DHD_ERROR(("%s invalid parameter\n", __FUNCTION__)); return -EINVAL; } dhd = *(dhd_info_t **)netdev_priv(net); ifidx = dhd_net2idx(dhd, net); if (ifidx == DHD_BAD_IF) { DHD_ERROR(("%s bad ifidx\n", __FUNCTION__)); return -ENODEV; } DHD_OS_WAKE_LOCK(&dhd->pub); ret = dhd_wl_ioctl(&dhd->pub, ifidx, ioc, ioc->buf, ioc->len); dhd_check_hang(net, &dhd->pub, ret); DHD_OS_WAKE_UNLOCK(&dhd->pub); return ret; } bool dhd_os_check_hang(dhd_pub_t *dhdp, int ifidx, int ret) { struct net_device *net; net = dhd_idx2net(dhdp, ifidx); return dhd_check_hang(net, dhdp, ret); } #if defined(WL_CFG80211) && defined(SUPPORT_DEEP_SLEEP) #define MAX_TRY_CNT 5 int dhd_deepsleep(struct net_device *dev, int flag) { char iovbuf[20]; uint powervar = 0; dhd_info_t *dhd; dhd_pub_t *dhdp; int cnt = 0; int ret = 0; dhd = *(dhd_info_t **)netdev_priv(dev); dhdp = &dhd->pub; switch (flag) { case 1 : DHD_ERROR(("[WiFi] Deepsleep On\n")); msleep(200); #ifdef PKT_FILTER_SUPPORT dhd_set_packet_filter(0, dhdp); #endif powervar = 0; memset(iovbuf, 0, sizeof(iovbuf)); bcm_mkiovar("mpc", (char *)&powervar, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhdp, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); powervar = 1; memset(iovbuf, 0, sizeof(iovbuf)); bcm_mkiovar("deepsleep", (char *)&powervar, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhdp, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); break; case 0: DHD_ERROR(("[WiFi] Deepsleep Off\n")); for (cnt = 0; cnt < MAX_TRY_CNT; cnt++) { powervar = 0; memset(iovbuf, 0, sizeof(iovbuf)); bcm_mkiovar("deepsleep", (char *)&powervar, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhdp, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); memset(iovbuf, 0, sizeof(iovbuf)); bcm_mkiovar("deepsleep", (char *)&powervar, 4, iovbuf, sizeof(iovbuf)); if ((ret = dhd_wl_ioctl_cmd(dhdp, WLC_GET_VAR, iovbuf, sizeof(iovbuf), FALSE, 0)) < 0) { DHD_ERROR(("the error of dhd deepsleep status ret value :%d\n", ret)); } else { if (!(*(int *)iovbuf)) { DHD_ERROR(("deepsleep mode is 0, ok , count : %d\n", cnt)); break; } } } powervar = 1; memset(iovbuf, 0, sizeof(iovbuf)); bcm_mkiovar("mpc", (char *)&powervar, 4, iovbuf, sizeof(iovbuf)); dhd_wl_ioctl_cmd(dhdp, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0); break; } return 0; } #endif #ifdef PROP_TXSTATUS extern int dhd_wlfc_interface_entry_update(void* state, ewlfc_mac_entry_action_t action, uint8 ifid, uint8 iftype, uint8* ea); extern int dhd_wlfc_FIFOcreditmap_update(void* state, uint8* credits); int dhd_wlfc_interface_event(struct dhd_info *dhd, ewlfc_mac_entry_action_t action, uint8 ifid, uint8 iftype, uint8* ea) { if (dhd->pub.wlfc_state == NULL) return BCME_OK; return dhd_wlfc_interface_entry_update(dhd->pub.wlfc_state, action, ifid, iftype, ea); } int dhd_wlfc_FIFOcreditmap_event(struct dhd_info *dhd, uint8* event_data) { if (dhd->pub.wlfc_state == NULL) return BCME_OK; return dhd_wlfc_FIFOcreditmap_update(dhd->pub.wlfc_state, event_data); } int dhd_wlfc_event(struct dhd_info *dhd) { return dhd_wlfc_enable(&dhd->pub); } #endif #ifdef BCMDBGFS #include <linux/debugfs.h> extern uint32 dhd_readregl(void *bp, uint32 addr); extern uint32 dhd_writeregl(void *bp, uint32 addr, uint32 data); typedef struct dhd_dbgfs { struct dentry *debugfs_dir; struct dentry *debugfs_mem; dhd_pub_t *dhdp; uint32 size; } dhd_dbgfs_t; dhd_dbgfs_t g_dbgfs; static int dhd_dbg_state_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t dhd_dbg_state_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { ssize_t rval; uint32 tmp; loff_t pos = *ppos; size_t ret; if (pos < 0) return -EINVAL; if (pos >= g_dbgfs.size || !count) return 0; if (count > g_dbgfs.size - pos) count = g_dbgfs.size - pos; tmp = dhd_readregl(g_dbgfs.dhdp->bus, file->f_pos & (~3)); ret = copy_to_user(ubuf, &tmp, 4); if (ret == count) return -EFAULT; count -= ret; *ppos = pos + count; rval = count; return rval; } static ssize_t dhd_debugfs_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { loff_t pos = *ppos; size_t ret; uint32 buf; if (pos < 0) return -EINVAL; if (pos >= g_dbgfs.size || !count) return 0; if (count > g_dbgfs.size - pos) count = g_dbgfs.size - pos; ret = copy_from_user(&buf, ubuf, sizeof(uint32)); if (ret == count) return -EFAULT; dhd_writeregl(g_dbgfs.dhdp->bus, file->f_pos & (~3), buf); return count; } loff_t dhd_debugfs_lseek(struct file *file, loff_t off, int whence) { loff_t pos = -1; switch (whence) { case 0: pos = off; break; case 1: pos = file->f_pos + off; break; case 2: pos = g_dbgfs.size - off; } return (pos < 0 || pos > g_dbgfs.size) ? -EINVAL : (file->f_pos = pos); } static const struct file_operations dhd_dbg_state_ops = { .read = dhd_dbg_state_read, .write = dhd_debugfs_write, .open = dhd_dbg_state_open, .llseek = dhd_debugfs_lseek }; static void dhd_dbg_create(void) { if (g_dbgfs.debugfs_dir) { g_dbgfs.debugfs_mem = debugfs_create_file("mem", 0644, g_dbgfs.debugfs_dir, NULL, &dhd_dbg_state_ops); } } void dhd_dbg_init(dhd_pub_t *dhdp) { int err; g_dbgfs.dhdp = dhdp; g_dbgfs.size = 0x20000000; g_dbgfs.debugfs_dir = debugfs_create_dir("dhd", 0); if (IS_ERR(g_dbgfs.debugfs_dir)) { err = PTR_ERR(g_dbgfs.debugfs_dir); g_dbgfs.debugfs_dir = NULL; return; } dhd_dbg_create(); return; } void dhd_dbg_remove(void) { debugfs_remove(g_dbgfs.debugfs_mem); debugfs_remove(g_dbgfs.debugfs_dir); bzero((unsigned char *) &g_dbgfs, sizeof(g_dbgfs)); } #endif #ifdef WLMEDIA_HTSF static void dhd_htsf_addtxts(dhd_pub_t *dhdp, void *pktbuf) { dhd_info_t *dhd = (dhd_info_t *)(dhdp->info); struct sk_buff *skb; uint32 htsf = 0; uint16 dport = 0, oldmagic = 0xACAC; char *p1; htsfts_t ts; p1 = (char*) PKTDATA(dhdp->osh, pktbuf); if (PKTLEN(dhdp->osh, pktbuf) > HTSF_MINLEN) { memcpy(&dport, p1+40, 2); dport = ntoh16(dport); } if (dport >= tsport && dport <= tsport + 20) { skb = (struct sk_buff *) pktbuf; htsf = dhd_get_htsf(dhd, 0); memset(skb->data + 44, 0, 2); memcpy(skb->data+82, &oldmagic, 2); memcpy(skb->data+84, &htsf, 4); memset(&ts, 0, sizeof(htsfts_t)); ts.magic = HTSFMAGIC; ts.prio = PKTPRIO(pktbuf); ts.seqnum = htsf_seqnum++; ts.c10 = get_cycles(); ts.t10 = htsf; ts.endmagic = HTSFENDMAGIC; memcpy(skb->data + HTSF_HOSTOFFSET, &ts, sizeof(ts)); } } static void dhd_dump_htsfhisto(histo_t *his, char *s) { int pktcnt = 0, curval = 0, i; for (i = 0; i < (NUMBIN-2); i++) { curval += 500; printf("%d ", his->bin[i]); pktcnt += his->bin[i]; } printf(" max: %d TotPkt: %d neg: %d [%s]\n", his->bin[NUMBIN-2], pktcnt, his->bin[NUMBIN-1], s); } static void sorttobin(int value, histo_t *histo) { int i, binval = 0; if (value < 0) { histo->bin[NUMBIN-1]++; return; } if (value > histo->bin[NUMBIN-2]) histo->bin[NUMBIN-2] = value; for (i = 0; i < (NUMBIN-2); i++) { binval += 500; if (value <= binval) { histo->bin[i]++; return; } } histo->bin[NUMBIN-3]++; } static void dhd_htsf_addrxts(dhd_pub_t *dhdp, void *pktbuf) { dhd_info_t *dhd = (dhd_info_t *)dhdp->info; struct sk_buff *skb; char *p1; uint16 old_magic; int d1, d2, d3, end2end; htsfts_t *htsf_ts; uint32 htsf; skb = PKTTONATIVE(dhdp->osh, pktbuf); p1 = (char*)PKTDATA(dhdp->osh, pktbuf); if (PKTLEN(osh, pktbuf) > HTSF_MINLEN) { memcpy(&old_magic, p1+78, 2); htsf_ts = (htsfts_t*) (p1 + HTSF_HOSTOFFSET - 4); } else return; if (htsf_ts->magic == HTSFMAGIC) { htsf_ts->tE0 = dhd_get_htsf(dhd, 0); htsf_ts->cE0 = get_cycles(); } if (old_magic == 0xACAC) { tspktcnt++; htsf = dhd_get_htsf(dhd, 0); memcpy(skb->data+92, &htsf, sizeof(uint32)); memcpy(&ts[tsidx].t1, skb->data+80, 16); d1 = ts[tsidx].t2 - ts[tsidx].t1; d2 = ts[tsidx].t3 - ts[tsidx].t2; d3 = ts[tsidx].t4 - ts[tsidx].t3; end2end = ts[tsidx].t4 - ts[tsidx].t1; sorttobin(d1, &vi_d1); sorttobin(d2, &vi_d2); sorttobin(d3, &vi_d3); sorttobin(end2end, &vi_d4); if (end2end > 0 && end2end > maxdelay) { maxdelay = end2end; maxdelaypktno = tspktcnt; memcpy(&maxdelayts, &ts[tsidx], 16); } if (++tsidx >= TSMAX) tsidx = 0; } } uint32 dhd_get_htsf(dhd_info_t *dhd, int ifidx) { uint32 htsf = 0, cur_cycle, delta, delta_us; uint32 factor, baseval, baseval2; cycles_t t; t = get_cycles(); cur_cycle = t; if (cur_cycle > dhd->htsf.last_cycle) delta = cur_cycle - dhd->htsf.last_cycle; else { delta = cur_cycle + (0xFFFFFFFF - dhd->htsf.last_cycle); } delta = delta >> 4; if (dhd->htsf.coef) { factor = (dhd->htsf.coef*10 + dhd->htsf.coefdec1); baseval = (delta*10)/factor; baseval2 = (delta*10)/(factor+1); delta_us = (baseval - (((baseval - baseval2) * dhd->htsf.coefdec2)) / 10); htsf = (delta_us << 4) + dhd->htsf.last_tsf + HTSF_BUS_DELAY; } else { DHD_ERROR(("-------dhd->htsf.coef = 0 -------\n")); } return htsf; } static void dhd_dump_latency(void) { int i, max = 0; int d1, d2, d3, d4, d5; printf("T1 T2 T3 T4 d1 d2 t4-t1 i \n"); for (i = 0; i < TSMAX; i++) { d1 = ts[i].t2 - ts[i].t1; d2 = ts[i].t3 - ts[i].t2; d3 = ts[i].t4 - ts[i].t3; d4 = ts[i].t4 - ts[i].t1; d5 = ts[max].t4-ts[max].t1; if (d4 > d5 && d4 > 0) { max = i; } printf("%08X %08X %08X %08X \t%d %d %d %d i=%d\n", ts[i].t1, ts[i].t2, ts[i].t3, ts[i].t4, d1, d2, d3, d4, i); } printf("current idx = %d \n", tsidx); printf("Highest latency %d pkt no.%d total=%d\n", maxdelay, maxdelaypktno, tspktcnt); printf("%08X %08X %08X %08X \t%d %d %d %d\n", maxdelayts.t1, maxdelayts.t2, maxdelayts.t3, maxdelayts.t4, maxdelayts.t2 - maxdelayts.t1, maxdelayts.t3 - maxdelayts.t2, maxdelayts.t4 - maxdelayts.t3, maxdelayts.t4 - maxdelayts.t1); } static int dhd_ioctl_htsf_get(dhd_info_t *dhd, int ifidx) { wl_ioctl_t ioc; char buf[32]; int ret; uint32 s1, s2; struct tsf { uint32 low; uint32 high; } tsf_buf; memset(&ioc, 0, sizeof(ioc)); memset(&tsf_buf, 0, sizeof(tsf_buf)); ioc.cmd = WLC_GET_VAR; ioc.buf = buf; ioc.len = (uint)sizeof(buf); ioc.set = FALSE; strncpy(buf, "tsf", sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; s1 = dhd_get_htsf(dhd, 0); if ((ret = dhd_wl_ioctl(&dhd->pub, ifidx, &ioc, ioc.buf, ioc.len)) < 0) { if (ret == -EIO) { DHD_ERROR(("%s: tsf is not supported by device\n", dhd_ifname(&dhd->pub, ifidx))); return -EOPNOTSUPP; } return ret; } s2 = dhd_get_htsf(dhd, 0); memcpy(&tsf_buf, buf, sizeof(tsf_buf)); printf(" TSF_h=%04X lo=%08X Calc:htsf=%08X, coef=%d.%d%d delta=%d ", tsf_buf.high, tsf_buf.low, s2, dhd->htsf.coef, dhd->htsf.coefdec1, dhd->htsf.coefdec2, s2-tsf_buf.low); printf("lasttsf=%08X lastcycle=%08X\n", dhd->htsf.last_tsf, dhd->htsf.last_cycle); return 0; } void htsf_update(dhd_info_t *dhd, void *data) { static ulong cur_cycle = 0, prev_cycle = 0; uint32 htsf, tsf_delta = 0; uint32 hfactor = 0, cyc_delta, dec1 = 0, dec2, dec3, tmp; ulong b, a; cycles_t t; t = get_cycles(); prev_cycle = cur_cycle; cur_cycle = t; if (cur_cycle > prev_cycle) cyc_delta = cur_cycle - prev_cycle; else { b = cur_cycle; a = prev_cycle; cyc_delta = cur_cycle + (0xFFFFFFFF - prev_cycle); } if (data == NULL) printf(" tsf update ata point er is null \n"); memcpy(&prev_tsf, &cur_tsf, sizeof(tsf_t)); memcpy(&cur_tsf, data, sizeof(tsf_t)); if (cur_tsf.low == 0) { DHD_INFO((" ---- 0 TSF, do not update, return\n")); return; } if (cur_tsf.low > prev_tsf.low) tsf_delta = (cur_tsf.low - prev_tsf.low); else { DHD_INFO((" ---- tsf low is smaller cur_tsf= %08X, prev_tsf=%08X, \n", cur_tsf.low, prev_tsf.low)); if (cur_tsf.high > prev_tsf.high) { tsf_delta = cur_tsf.low + (0xFFFFFFFF - prev_tsf.low); DHD_INFO((" ---- Wrap around tsf coutner adjusted TSF=%08X\n", tsf_delta)); } else return; } if (tsf_delta) { hfactor = cyc_delta / tsf_delta; tmp = (cyc_delta - (hfactor * tsf_delta))*10; dec1 = tmp/tsf_delta; dec2 = ((tmp - dec1*tsf_delta)*10) / tsf_delta; tmp = (tmp - (dec1*tsf_delta))*10; dec3 = ((tmp - dec2*tsf_delta)*10) / tsf_delta; if (dec3 > 4) { if (dec2 == 9) { dec2 = 0; if (dec1 == 9) { dec1 = 0; hfactor++; } else { dec1++; } } else dec2++; } } if (hfactor) { htsf = ((cyc_delta * 10) / (hfactor*10+dec1)) + prev_tsf.low; dhd->htsf.coef = hfactor; dhd->htsf.last_cycle = cur_cycle; dhd->htsf.last_tsf = cur_tsf.low; dhd->htsf.coefdec1 = dec1; dhd->htsf.coefdec2 = dec2; } else { htsf = prev_tsf.low; } } #endif void dhd_reset_hang_was_sent(struct net_device *dev) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(dev); if (dhd) dhd->pub.hang_was_sent = 0; } int dhd_get_txrx_stats(struct net_device *net, unsigned long *rx_packets, unsigned long *tx_packets) { dhd_info_t *dhd = *(dhd_info_t **)netdev_priv(net); dhd_pub_t *dhdp; if (!dhd) return -1; dhdp = &dhd->pub; if (!dhdp) return -1; *rx_packets = dhdp->rx_packets; *tx_packets = dhdp->tx_packets; return 0; }
htc-first/android_kernel_htc_msm8930aa
drivers/net/wireless/bcmdhd_4334/dhd_linux.c
C
gpl-2.0
156,615
/* * "$Id: tcpstream.cc,v 1.11 2007-03-01 01:09:39 rmf24 Exp $" * * TCP-on-UDP (tou) network interface for RetroShare. * * Copyright 2004-2006 by Robert Fernie. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License Version 2 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * Please report all bugs and problems to "retroshare@lunamutt.com". * */ #include <stdlib.h> #include <string.h> #include "tcpstream.h" #include <iostream> #include <iomanip> #include <assert.h> #include <errno.h> #include <math.h> #include <limits.h> #include <sys/time.h> #include <time.h> /* Debugging for STATE change, and Startup SYNs */ #include "util/rsdebug.h" #include "util/rsstring.h" #include "util/rsrandom.h" static struct RsLog::logInfo rstcpstreamzoneInfo = {RsLog::Default, "rstcpstream"}; #define rstcpstreamzone &rstcpstreamzoneInfo /* * #define DEBUG_TCP_STREAM 1 * #define DEBUG_TCP_STREAM_RETRANS 1 * #define DEBUG_TCP_STREAM_CLOSE 1 */ //#define DEBUG_TCP_STREAM_RETRANS 1 //#define DEBUG_TCP_STREAM_CLOSE 1 /* *#define DEBUG_TCP_STREAM_EXTRA 1 */ /* * #define TCP_NO_PARTIAL_READ 1 */ #ifdef DEBUG_TCP_STREAM int checkData(uint8 *data, int size, int idx); int setupBinaryCheck(std::string fname); #endif static const uint32 kMaxQueueSize = 300; // Was 100, which means max packet size of 100k (smaller than max packet size). static const uint32 kMaxPktRetransmit = 10; static const uint32 kMaxSynPktRetransmit = 100; // 100 => 200secs = over 3 minutes startup static const int TCP_STD_TTL = 64; static const int TCP_DEFAULT_FIREWALL_TTL = 4; static const double RTT_ALPHA = 0.875; int dumpPacket(std::ostream &out, unsigned char *pkt, uint32_t size); // platform independent fractional timestamp. static double getCurrentTS(); TcpStream::TcpStream(UdpSubReceiver *lyr) : tcpMtx("TcpStream"), inSize(0), outSizeRead(0), outSizeNet(0), state(TCP_CLOSED), inStreamActive(false), outStreamActive(false), outSeqno(0), outAcked(0), outWinSize(0), inAckno(0), inWinSize(0), maxWinSize(TCP_MAX_WIN), keepAliveTimeout(TCP_ALIVE_TIMEOUT), retransTimerOn(false), retransTimeout(TCP_RETRANS_TIMEOUT), retransTimerTs(0), keepAliveTimer(0), lastIncomingPkt(0), lastSentAck(0), lastSentWinSize(0), initOurSeqno(0), initPeerSeqno(0), lastWriteTF(0),lastReadTF(0), wcount(0), rcount(0), errorState(0), /* retranmission variables - init to large */ rtt_est(TCP_RETRANS_TIMEOUT), rtt_dev(0), congestThreshold(TCP_MAX_WIN), congestWinSize(MAX_SEG), congestUpdate(0), ttl(0), mTTL_period(0), mTTL_start(0), mTTL_end(0), peerKnown(false), udp(lyr) { sockaddr_clear(&peeraddr); return; } /* Stream Control! */ int TcpStream::connect(const struct sockaddr_in &raddr, uint32_t conn_period) { tcpMtx.lock(); /********** LOCK MUTEX *********/ setRemoteAddress(raddr); /* check state */ if (state != TCP_CLOSED) { if (state == TCP_ESTABLISHED) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; } else { // major issues! errorState = EFAULT; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } /* setup Seqnos */ outSeqno = genSequenceNo(); initOurSeqno = outSeqno; outAcked = outSeqno; /* min - 1 expected */ inWinSize = maxWinSize; congestThreshold = TCP_MAX_WIN; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; /* Init Connection */ /* send syn packet */ TcpPacket *pkt = new TcpPacket(); pkt -> setSyn(); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::connect() Send Init Pkt" << std::endl; #endif /* ********* SLOW START ************* * As this is the only place where a syn * is sent ..... we switch the ttl to 0, * and increment it as we retransmit the packet.... * This should help the firewalls along. */ setTTL(1); mTTL_start = getCurrentTS(); mTTL_period = conn_period; mTTL_end = mTTL_start + mTTL_period; toSend(pkt); /* change state */ state = TCP_SYN_SENT; errorState = EAGAIN; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_SYN_SENT" << std::endl; #endif { rslog(RSL_WARNING,rstcpstreamzone,"TcpStream::state => TCP_SYN_SENT (Connect)"); } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } int TcpStream::listenfor(const struct sockaddr_in &raddr) { tcpMtx.lock(); /********** LOCK MUTEX *********/ setRemoteAddress(raddr); /* check state */ if (state != TCP_CLOSED) { if (state == TCP_ESTABLISHED) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; } else { // major issues! errorState = EFAULT; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } errorState = EAGAIN; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } /* Stream Control! */ int TcpStream::close() { tcpMtx.lock(); /********** LOCK MUTEX *********/ cleanup(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } int TcpStream::closeWrite() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* check state */ /* will always close socket.... */ /* if in TCP_ESTABLISHED.... * -> to state: TCP_FIN_WAIT_1 * and shutdown outward stream. */ /* if in CLOSE_WAIT.... * -> to state: TCP_LAST_ACK * and shutdown outward stream. * do this one first!. */ outStreamActive = false; if (state == TCP_CLOSE_WAIT) { /* don't think we need to be * graceful at this point... * connection already closed by other end. * XXX might fix later with scheme * * flag stream closed, and when outqueue * emptied then fin will be sent. */ /* do nothing */ } if (state == TCP_ESTABLISHED) { /* fire off the damned thing. */ /* by changing state */ /* again this is handled by internals * the flag however indicates that * no more data can be send, * and once the queue empties * the FIN will be sent. */ } if (state == TCP_CLOSED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::close() Flag Set" << std::endl; #endif tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::close() pending" << std::endl; #endif errorState = EAGAIN; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } bool TcpStream::isConnected() { tcpMtx.lock(); /********** LOCK MUTEX *********/ bool isConn = (state == TCP_ESTABLISHED); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return isConn; } int TcpStream::status(std::ostream &out) { tcpMtx.lock(); /********** LOCK MUTEX *********/ int s = status_locked(out); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return s; } int TcpStream::status_locked(std::ostream &out) { int tmpstate = state; // can leave the timestamp here as time()... rough but okay. out << "TcpStream::status @ (" << time(NULL) << ")" << std::endl; out << "TcpStream::state = " << (int) state << std::endl; out << std::endl; out << "writeBuffer: " << inSize << " + MAX_SEG * " << inQueue.size(); out << " bytes Queued for transmission" << std::endl; out << "readBuffer: " << outSizeRead << " + MAX_SEG * "; out << outQueue.size() << " + " << outSizeNet; out << " incoming bytes waiting" << std::endl; out << std::endl; out << "inPkts: " << inPkt.size() << " packets waiting for processing"; out << std::endl; out << "outPkts: " << outPkt.size() << " packets waiting for acks"; out << std::endl; out << "us -> peer: nextSeqno: " << outSeqno << " lastAcked: " << outAcked; out << " winsize: " << outWinSize; out << std::endl; out << "peer -> us: Expected SeqNo: " << inAckno; out << " winsize: " << inWinSize; out << std::endl; out << std::endl; return tmpstate; } int TcpStream::write_allowed() { tcpMtx.lock(); /********** LOCK MUTEX *********/ int ret = 1; if (state == TCP_CLOSED) { errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; ret = -1; } else if (!outStreamActive) { errorState = EBADF; ret = -1; } if (ret < 1) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return ret; } int maxwrite = (kMaxQueueSize - inQueue.size()) * MAX_SEG; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return maxwrite; } int TcpStream::read_pending() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* error should be detected next time */ int maxread = int_read_pending(); if (state == TCP_CLOSED) { errorState = EBADF; maxread = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; maxread = -1; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return maxread; } /* INTERNAL */ int TcpStream::int_read_pending() { return outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; } /* stream Interface */ int TcpStream::write(char *dta, int size) /* write -> pkt -> net */ { tcpMtx.lock(); /********** LOCK MUTEX *********/ int ret = 1; /* initial error checking */ #ifdef DEBUG_TCP_STREAM_EXTRA static uint32 TMPtotalwrite = 0; #endif if (state == TCP_CLOSED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP_CLOSED" << std::endl; #endif errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP Not Established" << std::endl; #endif errorState = EAGAIN; ret = -1; } else if (inQueue.size() > kMaxQueueSize) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error EAGAIN" << std::endl; #endif errorState = EAGAIN; ret = -1; } else if (!outStreamActive) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP_CLOSED" << std::endl; #endif errorState = EBADF; ret = -1; } if (ret < 1) /* check for initial error */ { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return ret; } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() = Will Succeed " << size << std::endl; std::cerr << "TcpStream::write() Write Start: " << TMPtotalwrite << std::endl; std::cerr << printPktOffset(TMPtotalwrite, dta, size) << std::endl; TMPtotalwrite += size; #endif if (size + inSize < MAX_SEG) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() Add Itty Bit" << std::endl; std::cerr << "TcpStream::write() inData: " << (void *) inData; std::cerr << " inSize: " << inSize << " dta: " << (void *) dta; std::cerr << " size: " << size << " dest: " << (void *) &(inData[inSize]); std::cerr << std::endl; #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() = " << size << std::endl; #endif memcpy((void *) &(inData[inSize]), dta, size); inSize += size; //std::cerr << "Small Packet - write to net:" << std::endl; //std::cerr << printPkt(dta, size) << std::endl; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } /* otherwise must construct a dataBuffer. */ #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() filling 1 dataBuffer" << std::endl; std::cerr << "TcpStream::write() from inData(" << inSize << ")" << std::endl; std::cerr << "TcpStream::write() + dta(" << MAX_SEG - inSize; std::cerr << "/" << size << ")" << std::endl; #endif /* first create 1. */ dataBuffer *db = new dataBuffer; memcpy((void *) db->data, (void *) inData, inSize); int remSize = size; memcpy((void *) &(db->data[inSize]), dta, MAX_SEG - inSize); inQueue.push_back(db); remSize -= (MAX_SEG - inSize); #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() remaining " << remSize << " bytes to load" << std::endl; #endif while(remSize >= MAX_SEG) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() filling whole dataBuffer" << std::endl; std::cerr << "TcpStream::write() from dta[" << size-remSize << "]" << std::endl; #endif db = new dataBuffer; memcpy((void *) db->data, (void *) &(dta[size-remSize]), MAX_SEG); inQueue.push_back(db); remSize -= MAX_SEG; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() = " << size << std::endl; #endif if (remSize > 0) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() putting last bit in inData" << std::endl; std::cerr << "TcpStream::write() from dta[" << size-remSize << "] size: "; std::cerr << remSize << std::endl; #endif memcpy((void *) inData, (void *) &(dta[size-remSize]), remSize); inSize = remSize; } else { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() Data fitted exactly in dataBuffer!" << std::endl; #endif inSize = 0; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } int TcpStream::read(char *dta, int size) /* net -> pkt -> read */ { tcpMtx.lock(); /********** LOCK MUTEX *********/ #ifdef DEBUG_TCP_STREAM_EXTRA static uint32 TMPtotalread = 0; #endif /* max available data is * outDataRead + outQueue + outDataNet */ int maxread = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; int ret = 1; /* used only for initial errors */ if (state == TCP_CLOSED) { errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; ret = -1; } else if ((!inStreamActive) && (maxread == 0)) { // finished stream. ret = 0; } else if (maxread == 0) { /* must wait for more data */ errorState = EAGAIN; ret = -1; } if (ret < 1) /* if ret has been changed */ { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return ret; } if (maxread < size) { #ifdef TCP_NO_PARTIAL_READ if (inStreamActive) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::read() No Partial Read! "; std::cerr << "Can only supply " << maxread << " of "; std::cerr << size; std::cerr << std::endl; #endif errorState = EAGAIN; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } #endif /* TCP_NO_PARTIAL_READ */ size = maxread; } /* if less than outDataRead size */ if (((unsigned) (size) < outSizeRead) && (outSizeRead)) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Add Itty Bit" << std::endl; std::cerr << "TcpStream::read() outSizeRead: " << outSizeRead; std::cerr << " size: " << size << " remaining: " << outSizeRead - size; std::cerr << std::endl; #endif memcpy(dta,(void *) outDataRead, size); memmove((void *) outDataRead, (void *) &(outDataRead[size]), outSizeRead - (size)); outSizeRead -= size; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } /* move the whole of outDataRead. */ if (outSizeRead) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Move All outSizeRead" << std::endl; std::cerr << "TcpStream::read() outSizeRead: " << outSizeRead; std::cerr << " size: " << size; std::cerr << std::endl; #endif memcpy(dta,(void *) outDataRead, outSizeRead); } int remSize = size - outSizeRead; outSizeRead = 0; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() remaining size: " << remSize << std::endl; #endif while((outQueue.size() > 0) && (remSize > 0)) { dataBuffer *db = outQueue.front(); outQueue.pop_front(); /* remove */ #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Taking Data from outQueue" << std::endl; #endif /* load into outDataRead */ if (remSize < MAX_SEG) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Partially using Segment" << std::endl; std::cerr << "TcpStream::read() moving: " << remSize << " to dta @: " << size-remSize; std::cerr << std::endl; std::cerr << "TcpStream::read() rest to outDataRead: " << MAX_SEG - remSize; std::cerr << std::endl; #endif memcpy((void *) &(dta[(size)-remSize]), (void *) db->data, remSize); memcpy((void *) outDataRead, (void *) &(db->data[remSize]), MAX_SEG - remSize); outSizeRead = MAX_SEG - remSize; delete db; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Move Whole Segment to dta @ " << size-remSize << std::endl; #endif /* else copy whole segment */ memcpy((void *) &(dta[(size)-remSize]), (void *) db->data, MAX_SEG); remSize -= MAX_SEG; delete db; } /* assumes that outSizeNet >= remSize due to initial * constraint */ if ((remSize > 0)) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Using up : " << remSize; std::cerr << " last Bytes, leaving: " << outSizeNet - remSize << std::endl; #endif memcpy((void *) &(dta[(size)-remSize]),(void *) outDataNet, remSize); outSizeNet -= remSize; if (outSizeNet > 0) { /* move to the outDataRead */ memcpy((void *) outDataRead,(void *) &(outDataNet[remSize]), outSizeNet); outSizeRead = outSizeNet; outSizeNet = 0; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() moving last of outSizeNet to outSizeRead: " << outSizeRead; std::cerr << std::endl; #endif } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } /* Callback from lower Layers */ void TcpStream::recvPkt(void *data, int size) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recvPkt()"; std::cerr << std::endl; #endif tcpMtx.lock(); /********** LOCK MUTEX *********/ uint8 *input = (uint8 *) data; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recvPkt() Past Lock!"; std::cerr << std::endl; #endif #ifdef DEBUG_TCP_STREAM if (state > TCP_SYN_RCVD) { int availRead = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; std::cerr << "TcpStream::recvPkt() CC: "; std::cerr << " iWS: " << inWinSize; std::cerr << " aRead: " << availRead; std::cerr << " iAck: " << inAckno; std::cerr << std::endl; } else { std::cerr << "TcpStream::recv() Not Connected"; std::cerr << std::endl; } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recv() ReadPkt(" << size << ")" << std::endl; //std::cerr << printPkt(input, size); //std::cerr << std::endl; #endif TcpPacket *pkt = new TcpPacket(); if (0 < pkt -> readPacket(input, size)) { lastIncomingPkt = getCurrentTS(); handleIncoming(pkt); } else { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recv() Bad Packet Deleting!"; std::cerr << std::endl; #endif delete pkt; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return; } int TcpStream::tick() { tcpMtx.lock(); /********** LOCK MUTEX *********/ //std::cerr << "TcpStream::tick()" << std::endl; recv_check(); /* recv is async */ send(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 1; } bool TcpStream::getRemoteAddress(struct sockaddr_in &raddr) { tcpMtx.lock(); /********** LOCK MUTEX *********/ if (peerKnown) { raddr = peeraddr; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return peerKnown; } uint8 TcpStream::TcpState() { tcpMtx.lock(); /********** LOCK MUTEX *********/ uint8 err = state; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return err; } int TcpStream::TcpErrorState() { tcpMtx.lock(); /********** LOCK MUTEX *********/ int err = errorState; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return err; } /********************* SOME EXPOSED DEBUGGING FNS ******************/ static int ilevel = 100; bool TcpStream::widle() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* init */ if (!lastWriteTF) { lastWriteTF = int_wbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } if ((lastWriteTF == int_wbytes()) && (inSize == 0) && inQueue.empty()) { wcount++; if (wcount > ilevel) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return true; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } wcount = 0; lastWriteTF = int_wbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } bool TcpStream::ridle() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* init */ if (!lastReadTF) { lastReadTF = int_rbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } if ((lastReadTF == int_rbytes()) && (outSizeRead + outQueue.size() + outSizeNet== 0)) { rcount++; if (rcount > ilevel) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return true; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } rcount = 0; lastReadTF = int_rbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } uint32 TcpStream::wbytes() { tcpMtx.lock(); /********** LOCK MUTEX *********/ uint32 wb = int_wbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return wb; } uint32 TcpStream::rbytes() { tcpMtx.lock(); /********** LOCK MUTEX *********/ uint32 rb = int_rbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return rb; } /********************* ALL BELOW HERE IS INTERNAL ****************** ******************* AND ALWAYS PROTECTED BY A MUTEX ***************/ int TcpStream::recv_check() { double cts = getCurrentTS(); // fractional seconds. #ifdef DEBUG_TCP_STREAM if (state > TCP_SYN_RCVD) { int availRead = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; std::cerr << "TcpStream::recv_check() CC: "; std::cerr << " iWS: " << inWinSize; std::cerr << " aRead: " << availRead; std::cerr << " iAck: " << inAckno; std::cerr << std::endl; } else { std::cerr << "TcpStream::recv_check() Not Connected"; std::cerr << std::endl; } #endif // make sure we've rcvd something! if ((state > TCP_SYN_RCVD) && (cts - lastIncomingPkt > kNoPktTimeout)) { /* shut it all down */ /* this period should be equivalent * to the firewall timeouts ??? * * for max efficiency */ #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::recv_check() state = CLOSED (NoPktTimeout)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (kNoPktTimeout)"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; cleanup(); } return 1; } int TcpStream::cleanup() { // This shuts it all down! no matter what. rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::cleanup() state = TCP_CLOSED"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_CLOSED" << std::endl; #endif //peerKnown = false; //??? NOT SURE -> for a rapid reconnetion this might be key?? /* reset TTL */ setTTL(TCP_STD_TTL); // clear arrays. inSize = 0; while(inQueue.size() > 0) { dataBuffer *db = inQueue.front(); inQueue.pop_front(); delete db; } while(outPkt.size() > 0) { TcpPacket *pkt = outPkt.front(); outPkt.pop_front(); delete pkt; } // clear arrays. outSizeRead = 0; outSizeNet = 0; while(outQueue.size() > 0) { dataBuffer *db = outQueue.front(); outQueue.pop_front(); delete db; } while(inPkt.size() > 0) { TcpPacket *pkt = inPkt.front(); inPkt.pop_front(); delete pkt; } return 1; } int TcpStream::handleIncoming(TcpPacket *pkt) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::handleIncoming()" << std::endl; #endif switch(state) { case TCP_CLOSED: case TCP_LISTEN: /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * else Discard. */ return incoming_Closed(pkt); break; case TCP_SYN_SENT: /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * if receive SYN+ACK * -> respond ACK * To State: TCP_ESTABLISHED * * else Discard. */ return incoming_SynSent(pkt); break; case TCP_SYN_RCVD: /* if receive ACK * To State: TCP_ESTABLISHED */ return incoming_SynRcvd(pkt); break; case TCP_ESTABLISHED: /* if receive FIN * -> respond ACK * To State: TCP_CLOSE_WAIT * else Discard. */ return incoming_Established(pkt); break; case TCP_FIN_WAIT_1: /* state entered by close() call. * if receive FIN * -> respond ACK * To State: TCP_CLOSING * * if receive ACK * -> no response * To State: TCP_FIN_WAIT_2 * * if receive FIN+ACK * -> respond ACK * To State: TCP_TIMED_WAIT * */ return incoming_Established(pkt); //return incoming_FinWait1(pkt); break; case TCP_FIN_WAIT_2: /* if receive FIN * -> respond ACK * To State: TCP_TIMED_WAIT */ return incoming_Established(pkt); //return incoming_FinWait2(pkt); break; case TCP_CLOSING: /* if receive ACK * To State: TCP_TIMED_WAIT */ /* all handled in Established */ return incoming_Established(pkt); //return incoming_Closing(pkt); break; case TCP_CLOSE_WAIT: /* * wait for our close to be called. */ /* all handled in Established */ return incoming_Established(pkt); //return incoming_CloseWait(pkt); break; case TCP_LAST_ACK: /* entered by the local close() after sending FIN. * if receive ACK * To State: TCP_CLOSED */ /* all handled in Established */ return incoming_Established(pkt); /* return incoming_LastAck(pkt); */ break; /* this is actually the only * final state where packets not expected! */ case TCP_TIMED_WAIT: /* State: TCP_TIMED_WAIT * * discard all -> both connections FINed * timeout of this state. * */ #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::handleIncoming() state = CLOSED (TimedWait)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif state = TCP_CLOSED; // return incoming_TimedWait(pkt); { rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (recvd TCP_TIMED_WAIT?)"); } break; } delete pkt; return 1; } int TcpStream::incoming_Closed(TcpPacket *pkt) { /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * else Discard. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Closed()" << std::endl; #endif if ((pkt -> hasSyn()) && (!pkt -> hasAck())) { /* Init Connection */ /* save seqno */ initPeerSeqno = pkt -> seqno; inAckno = initPeerSeqno + 1; outWinSize = pkt -> winsize; inWinSize = maxWinSize; /* we can get from SynSent as well, * but only send one SYN packet */ /* start packet */ TcpPacket *rsp = new TcpPacket(); if (state == TCP_CLOSED) { outSeqno = genSequenceNo(); initOurSeqno = outSeqno; outAcked = outSeqno; /* min - 1 expected */ /* setup Congestion Charging */ congestThreshold = TCP_MAX_WIN; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; rsp -> setSyn(); } rsp -> setAck(inAckno); /* seq + winsize set in toSend() */ /* as we have received something ... we can up the TTL */ setTTL(TCP_STD_TTL); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Closed() Sending reply" << std::endl; std::cerr << "SeqNo: " << rsp->seqno << " Ack: " << rsp->ackno; std::cerr << std::endl; #endif toSend(rsp); /* change state */ state = TCP_SYN_RCVD; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_SYN_RCVD" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_SYN_RECVD (recvd SYN & !ACK)"); } delete pkt; return 1; } int TcpStream::incoming_SynSent(TcpPacket *pkt) { /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * if receive SYN+ACK * -> respond ACK * To State: TCP_ESTABLISHED * * else Discard. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynSent()" << std::endl; #endif if ((pkt -> hasSyn()) && (pkt -> hasAck())) { /* check stuff */ if (pkt -> getAck() != outSeqno) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynSent() Bad Ack - Deleting " << std::endl; #endif /* bad ignore */ delete pkt; return -1; } /* Complete Connection */ /* save seqno */ initPeerSeqno = pkt -> seqno; inAckno = initPeerSeqno + 1; outWinSize = pkt -> winsize; outAcked = pkt -> getAck(); /* before ACK, reset the TTL * As they have sent something, and we have received * through the firewall, set to STD. */ setTTL(TCP_STD_TTL); /* ack the Syn Packet */ sendAck(); /* change state */ state = TCP_ESTABLISHED; outStreamActive = true; inStreamActive = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_ESTABLISHED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_ESTABLISHED (recvd SUN & ACK)"); delete pkt; } else /* same as if closed! (simultaneous open) */ { return incoming_Closed(pkt); } return 1; } int TcpStream::incoming_SynRcvd(TcpPacket *pkt) { /* if receive ACK * To State: TCP_ESTABLISHED */ if (pkt -> hasRst()) { /* trouble */ state = TCP_CLOSED; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_CLOSED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (recvd RST)"); delete pkt; return 1; } bool ackWithData = false; if (pkt -> hasAck()) { if (pkt -> hasSyn()) { /* has resent syn -> check it matches */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Pkt with ACK + SYN" << std::endl; #endif } /* check stuff */ if (pkt -> getAck() != outSeqno) { /* bad ignore */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Ignoring Pkt with bad ACK" << std::endl; #endif delete pkt; return -1; } /* Complete Connection */ /* save seqno */ if (pkt -> datasize > 0) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynRcvd() ACK with Data!" << std::endl; std::cerr << "TcpStream::incoming_SynRcvd() Shoudn't recv ... unless initACK lost!" << std::endl; #endif // managed to trigger this under windows... // perhaps the initial Ack was lost, // believe we should just pass this packet // directly to the incoming_Established... once // the following has been done. // and it should all work! //exit(1); ackWithData = true; } inAckno = pkt -> seqno; /* + pkt -> datasize; */ outWinSize = pkt -> winsize; outAcked = pkt -> getAck(); /* As they have sent something, and we have received * through the firewall, set to STD. */ setTTL(TCP_STD_TTL); /* change state */ state = TCP_ESTABLISHED; outStreamActive = true; inStreamActive = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_ESTABLISHED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_ESTABLISHED (have SYN, recvd ACK)"); } if (ackWithData) { /* connection Established -> handle normally */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Handling Data with Ack Pkt!"; std::cerr << std::endl; #endif incoming_Established(pkt); } else { #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Ignoring Pkt!" << std::endl; #endif /* else nothing */ delete pkt; } return 1; } int TcpStream::incoming_Established(TcpPacket *pkt) { /* first handle the Ack ... * this must be done before the queue, * to keep the values as up-to-date as possible. * * must sanity check ..... * make sure that the sequence number is within the correct range. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() "; std::cerr << " Pkt->seqno: " << std::hex << pkt->seqno; std::cerr << " Pkt->datasize: " << std::hex << pkt->datasize; std::cerr << std::dec << std::endl; #endif if ((!isOldSequence(pkt->seqno, inAckno)) && // seq >= inAckno isOldSequence(pkt->seqno, inAckno + maxWinSize)) // seq < inAckno + maxWinSize. { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() valid Packet Seqno."; std::cerr << std::endl; #endif if (pkt->hasAck()) { #ifdef DEBUG_TCP_STREAM if (outAcked != pkt->ackno) { std::cerr << "TcpStream::incoming_Established() valid Packet Seqno & new Ackno."; std::cerr << std::endl; std::cerr << "\tUpdating OutAcked to: " << outAcked; std::cerr << std::endl; } #endif outAcked = pkt->ackno; } outWinSize = pkt->winsize; #ifdef DEBUG_TCP_STREAM std::cerr << "\tUpdating OutWinSize to: " << outWinSize; std::cerr << std::endl; #endif } else { /* what we do! (This is actually okay - and happens occasionally) */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() ERROR out-of-range Packet Seqno."; std::cerr << std::endl; std::cerr << "\t Pkt->SeqNo: " << std::hex << pkt->seqno; std::cerr << std::endl; std::cerr << "\t inAckno: " << std::hex << inAckno; std::cerr << std::endl; std::cerr << "\t inAckno + maxWinSize: " << std::hex << inAckno + maxWinSize; std::cerr << std::endl; std::cerr << "\t outAcked: " << std::hex << outAcked; std::cerr << std::endl; std::cerr << "\t Pkt->SeqNo: " << std::hex << pkt->seqno; std::cerr << std::dec << std::endl; std::cerr << "\t !isOldSequence(pkt->seqno, inAckno): " << (!isOldSequence(pkt->seqno, inAckno)); std::cerr << std::endl; std::cerr << "\t isOldSequence(pkt->seqno, inAckno + maxWinSize): " << isOldSequence(pkt->seqno, inAckno + maxWinSize); std::cerr << std::endl; std::cerr << std::endl; std::cerr << "TcpStream::incoming_Established() Sending Ack to update Peer"; std::cerr << std::endl; #endif sendAck(); } /* add to queue */ inPkt.push_back(pkt); if (inPkt.size() > kMaxQueueSize) { TcpPacket *pkt = inPkt.front(); inPkt.pop_front(); delete pkt; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() inPkt reached max size...Discarding Oldest Pkt"; std::cerr << std::endl; #endif } /* use as many packets as possible */ return check_InPkts(); } int TcpStream::check_InPkts() { bool found = true; TcpPacket *pkt; std::list<TcpPacket *>::iterator it; while(found) { found = false; for(it = inPkt.begin(); (!found) && (it != inPkt.end());) { #ifdef DEBUG_TCP_STREAM std::cerr << "Checking expInAck: " << std::hex << inAckno; std::cerr << " vs: " << std::hex << (*it)->seqno << std::dec << std::endl; #endif pkt = *it; if ((*it)->seqno == inAckno) { //std::cerr << "\tFOUND MATCH!"; //std::cerr << std::endl; found = true; it = inPkt.erase(it); } /* see if we can discard it */ /* if smaller seqno, and not wrapping around */ else if (isOldSequence((*it)->seqno, inAckno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "Discarding Old Packet expAck: " << std::hex << inAckno; std::cerr << " seqno: " << std::hex << (*it)->seqno; std::cerr << " pkt->size: " << std::hex << (*it)->datasize; std::cerr << " pkt->seqno+size: " << std::hex << (*it)->seqno + (*it)->datasize; std::cerr << std::dec << std::endl; #endif /* discard */ it = inPkt.erase(it); delete pkt; } else { ++it; } } if (found) { #ifdef DEBUG_TCP_STREAM_EXTRA if (pkt->datasize) { checkData(pkt->data, pkt->datasize, pkt->seqno-initPeerSeqno-1); } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() Updating inAckno from: " << std::hex << inAckno; #endif /* update ack number - let it rollover */ inAckno = pkt->seqno + pkt->datasize; #ifdef DEBUG_TCP_STREAM std::cerr << " to: " << std::hex << inAckno; std::cerr << std::dec << std::endl; #endif /* XXX This shouldn't be here, as it prevents * the Ack being used until the packet is. * This means that a dropped packet will stop traffic in both * directions.... * * Moved it to incoming_Established .... but extra * check here to be sure! */ if (pkt->hasAck()) { if (isOldSequence(outAcked, pkt->ackno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() ERROR Ack Not Already Used!"; std::cerr << std::endl; std::cerr << "\t Pkt->ackno: " << std::hex << pkt->ackno; std::cerr << std::endl; std::cerr << "\t outAcked: " << std::hex << outAcked; std::cerr << std::endl; std::cerr << "\t Pkt->winsize: " << std::hex << pkt->winsize; std::cerr << std::endl; std::cerr << "\t outWinSize: " << std::hex << outWinSize; std::cerr << std::endl; std::cerr << "\t isOldSequence(outAcked, pkt->ackno): " << isOldSequence(outAcked, pkt->ackno); std::cerr << std::endl; std::cerr << std::endl; #endif outAcked = pkt->ackno; outWinSize = pkt->winsize; #ifdef DEBUG_TCP_STREAM std::cerr << "\tUpdating OutAcked to: " << outAcked; std::cerr << std::endl; std::cerr << "\tUpdating OutWinSize to: " << outWinSize; std::cerr << std::endl; #endif } else { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() GOOD Ack Already Used!"; std::cerr << std::endl; #endif } } /* push onto queue */ if (outSizeNet + pkt->datasize < MAX_SEG) { /* move onto outSizeNet */ if (pkt->datasize) { memcpy((void *) &(outDataNet[outSizeNet]), pkt->data, pkt->datasize); outSizeNet += pkt->datasize; } } else { /* if it'll overflow the buffer. */ dataBuffer *db = new dataBuffer(); /* move outDatNet -> buffer */ memcpy((void *) db->data, (void *) outDataNet, outSizeNet); /* fill rest of space */ int remSpace = MAX_SEG - outSizeNet; memcpy((void *) &(db->data[outSizeNet]), (void *) pkt->data, remSpace); /* push packet onto queue */ outQueue.push_back(db); /* any big chunks that will take up a full dataBuffer */ int remData = pkt->datasize - remSpace; while(remData >= MAX_SEG) { db = new dataBuffer(); memcpy((void *) db->data, (void *) &(pkt->data[remSpace]), MAX_SEG); remData -= MAX_SEG; outQueue.push_back(db); } /* remove any remaining to outDataNet */ outSizeNet = remData; if (outSizeNet > 0) { memcpy((void *) outDataNet, (void *) &(pkt->data[pkt->datasize - remData]), outSizeNet); } } /* can allow more in! - update inWinSize */ UpdateInWinSize(); /* if pkt is FIN */ /* these must be here -> at the end of the reliable stream */ /* if the fin is set, ack it specially close stream */ if (pkt->hasFin()) { /* send final ack */ sendAck(); /* closedown stream */ inStreamActive = false; if (state == TCP_ESTABLISHED) { state = TCP_CLOSE_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_CLOSE_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSE_WAIT (recvd FIN)"); } else if (state == TCP_FIN_WAIT_1) { state = TCP_CLOSING; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_CLOSING"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSING (FIN_WAIT_1, recvd FIN)"); } else if (state == TCP_FIN_WAIT_2) { state = TCP_TIMED_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_TIMED_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_TIMED_WAIT (FIN_WAIT_2, recvd FIN)"); cleanup(); } } /* if ack for our FIN */ if ((pkt->hasAck()) && (!outStreamActive) && (pkt->ackno == outSeqno)) { if (state == TCP_FIN_WAIT_1) { state = TCP_FIN_WAIT_2; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_FIN_WAIT_2"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_FIN_WAIT_2 (FIN_WAIT_1, recvd ACK)"); } else if (state == TCP_LAST_ACK) { #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::state = TCP_CLOSED (LastAck)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif state = TCP_CLOSED; rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (LAST_ACK, recvd ACK)"); cleanup(); } else if (state == TCP_CLOSING) { state = TCP_TIMED_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_TIMED_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_TIMED_WAIT (TCP_CLOSING, recvd ACK)"); cleanup(); } } delete pkt; } /* end of found */ } /* while(found) */ return 1; } /* This Fn should be called after each read, or recvd data (thats added to the buffer) */ int TcpStream::UpdateInWinSize() { /* InWinSize = maxWinSze - QueuedData, * actually we can allow a lot more to queue up... * inWinSize = 65536, unless QueuedData > 65536. * inWinSize = 2 * maxWinSize - QueuedData; * */ uint32 queuedData = int_read_pending(); if (queuedData < maxWinSize) { inWinSize = maxWinSize; } else if (queuedData < 2 * maxWinSize) { inWinSize = 2 * maxWinSize - queuedData; } else { inWinSize = 0; } return inWinSize; } int TcpStream::sendAck() { /* simple -> toSend fills in ack/winsize * and the rest is history */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::sendAck()"; std::cerr << std::endl; #endif return toSend(new TcpPacket(), false); } void TcpStream::setRemoteAddress(const struct sockaddr_in &raddr) { peeraddr = raddr; peerKnown = true; } int TcpStream::toSend(TcpPacket *pkt, bool retrans) { int outPktSize = MAX_SEG + TCP_PSEUDO_HDR_SIZE; char tmpOutPkt[outPktSize]; if (!peerKnown) { /* Major Error! */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() peerUnknown ERROR!!!"; std::cerr << std::endl; #endif delete pkt; return 0; } /* get accurate timestamp */ double cts = getCurrentTS(); pkt -> winsize = inWinSize; pkt -> seqno = outSeqno; /* increment seq no */ if (pkt->datasize) { #ifdef DEBUG_TCP_STREAM_EXTRA checkData(pkt->data, pkt->datasize, outSeqno-initOurSeqno-1); #endif outSeqno += pkt->datasize; } if (pkt->hasSyn()) { /* should not have data! */ if (pkt->datasize) { #ifdef DEBUG_TCP_STREAM std::cerr << "SYN Packet shouldn't contain data!" << std::endl; #endif } outSeqno++; } else { /* cannot auto Ack SynPackets */ pkt -> setAck(inAckno); } pkt -> winsize = inWinSize; /* store old info */ lastSentAck = pkt -> ackno; lastSentWinSize = pkt -> winsize; keepAliveTimer = cts; pkt -> writePacket(tmpOutPkt, outPktSize); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << " Ackno: "; std::cerr << pkt->ackno << " winsize: " << pkt->winsize; std::cerr << std::endl; //std::cerr << printPkt(tmpOutPkt, outPktSize) << std::endl; #endif udp -> sendPkt(tmpOutPkt, outPktSize, peeraddr, ttl); if (retrans) { /* restart timers */ pkt -> ts = cts; pkt -> retrans = 0; startRetransmitTimer(); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() Adding to outPkt --> Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif outPkt.push_back(pkt); } else { delete pkt; } return 1; } /* single retransmit timer. * */ void TcpStream::startRetransmitTimer() { if (retransTimerOn) { return; } retransTimerTs = getCurrentTS(); retransTimerOn = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::startRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << retransTimeout; std::cerr << " retransTimerTs: " << std::setprecision(12) <<retransTimerTs; std::cerr << std::endl; #endif } void TcpStream::restartRetransmitTimer() { stopRetransmitTimer(); startRetransmitTimer(); } void TcpStream::stopRetransmitTimer() { if (!retransTimerOn) { return; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::stopRetransmitTimer() peer: " << peeraddr; std::cerr << std::endl; #endif retransTimerOn = false; } void TcpStream::resetRetransmitTimer() { retransTimerOn = false; retransTimeout = 2.0 * (rtt_est + 4.0 * rtt_dev); // happens too often for RETRANS debugging. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::resetRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; #endif } void TcpStream::incRetransmitTimeout() { retransTimeout = 2 * retransTimeout; if (retransTimeout > TCP_RETRANS_MAX_TIMEOUT) { retransTimeout = TCP_RETRANS_MAX_TIMEOUT; } #ifdef DEBUG_TCP_STREAM_RETRANS std::cerr << "TcpStream::incRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; #endif } int TcpStream::retrans() { int outPktSize = MAX_SEG + TCP_PSEUDO_HDR_SIZE; char tmpOutPkt[outPktSize]; if (!peerKnown) { /* Major Error! */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::retrans() peerUnknown ERROR!!!"; std::cerr << std::endl; #endif return 0; } if (!retransTimerOn) { return 0; } double cts = getCurrentTS(); if (cts - retransTimerTs < retransTimeout) { return 0; } if (outPkt.begin() == outPkt.end()) { resetRetransmitTimer(); return 0; } TcpPacket *pkt = outPkt.front(); if (!pkt) { /* error */ return 0; } /* retransmission -> adjust the congestWinSize and congestThreshold */ congestThreshold = congestWinSize / 2; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; // point when we can up the winSize. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::retrans() Adjusting Congestion Parameters: "; std::cerr << std::endl; std::cerr << "\tcongestWinSize: " << congestWinSize; std::cerr << " congestThreshold: " << congestThreshold; std::cerr << " congestUpdate: " << congestUpdate; std::cerr << std::endl; #endif /* update ackno and winsize */ if (!(pkt->hasSyn())) { pkt->setAck(inAckno); lastSentAck = pkt -> ackno; } pkt->winsize = inWinSize; lastSentWinSize = pkt -> winsize; keepAliveTimer = cts; pkt->writePacket(tmpOutPkt, outPktSize); #ifdef DEBUG_TCP_STREAM_RETRANS std::cerr << "TcpStream::retrans()"; std::cerr << " peer: " << peeraddr; std::cerr << " hasSyn: " << pkt->hasSyn(); std::cerr << " Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << " Ackno: "; std::cerr << pkt->ackno << " winsize: " << pkt->winsize; std::cerr << " retrans: " << (int) pkt->retrans; std::cerr << " timeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; //std::cerr << printPkt(tmpOutPkt, outPktSize) << std::endl; #endif /* if its a syn packet ** thats been * transmitting for a while, maybe * we should increase the ttl. */ if ((pkt->hasSyn()) && (getTTL() < TCP_STD_TTL)) { /* calculate a new TTL */ if (mTTL_end > cts) { setTTL(TCP_DEFAULT_FIREWALL_TTL); } else { setTTL(getTTL() + 1); } std::string out; rs_sprintf(out, "TcpStream::retrans() Startup SYNs retrans count: %u New TTL: %d", pkt->retrans, getTTL()); rslog(RSL_WARNING, rstcpstreamzone, out); #ifdef DEBUG_TCP_STREAM std::cerr << out.str() << std::endl; #endif } /* catch excessive retransmits * - Allow Syn case more.... * - if not SYN or TTL has reached STD then timeout quickly. * OLD 2nd Logic (below) has been replaced with lower logic. * (((!pkt->hasSyn()) || (TCP_STD_TTL == getTTL())) * && (pkt->retrans > kMaxPktRetransmit))) * Problem was that the retransmit of Syn packet had STD_TTL, and was triggering Close (and SeqNo change). * It seemed to work anyway.... But might cause coonnection failures. Will reduce the MaxSyn Retransmit * so something more reasonable as well. * ((!pkt->hasSyn()) && (pkt->retrans > kMaxPktRetransmit))) */ if ((pkt->hasSyn() && (pkt->retrans > kMaxSynPktRetransmit)) || ((!pkt->hasSyn()) && (pkt->retrans > kMaxPktRetransmit))) { /* too many attempts close stream */ #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::retrans() Too many Retransmission Attempts ("; std::cerr << (int) pkt->retrans << ") for Peer: " << peeraddr << std::endl; std::cerr << "TcpStream::retrans() Closing Socket Connection"; std::cerr << std::endl; //dumpPacket(std::cerr, (unsigned char *) tmpOutPkt, outPktSize); dumpstate_locked(std::cerr); #endif rslog(RSL_WARNING,rstcpstreamzone,"TcpStream::state => TCP_CLOSED (Too Many Retransmits)"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; cleanup(); return 0; } udp -> sendPkt(tmpOutPkt, outPktSize, peeraddr, ttl); /* restart timers */ pkt->ts = cts; pkt->retrans++; /* * finally - double the retransTimeout ... (Karn's Algorithm) * except if we are starting a connection... i.e. hasSyn() */ if (!pkt->hasSyn()) { incRetransmitTimeout(); restartRetransmitTimer(); } else { resetRetransmitTimer(); startRetransmitTimer(); } return 1; } void TcpStream::acknowledge() { /* cleans up acknowledge packets */ /* packets are pushed back in order */ std::list<TcpPacket *>::iterator it; double cts = getCurrentTS(); bool updateRTT = true; bool clearedPkts = false; for(it = outPkt.begin(); (it != outPkt.end()) && (isOldSequence((*it)->seqno, outAcked)); it = outPkt.erase(it)) { TcpPacket *pkt = (*it); clearedPkts = true; /* adjust the congestWinSize and congestThreshold * congestUpdate <= outAcked * ***/ if (!isOldSequence(outAcked, congestUpdate)) { if (congestWinSize < congestThreshold) { /* double it baby! */ congestWinSize *= 2; } else { /* linear increase */ congestWinSize += MAX_SEG; } if (congestWinSize > maxWinSize) { congestWinSize = maxWinSize; } congestUpdate = outAcked + congestWinSize; // point when we can up the winSize. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Adjusting Congestion Parameters: "; std::cerr << std::endl; std::cerr << "\tcongestWinSize: " << congestWinSize; std::cerr << " congestThreshold: " << congestThreshold; std::cerr << " congestUpdate: " << congestUpdate; std::cerr << std::endl; #endif } /* update the RoundTripTime, * using Jacobson's values. * RTT = a RTT + (1-a) M * where * RTT is RoundTripTime estimate. * a = 7/8, * M = time for ack. * * D = a D + (1 - a) | RTT - M | * where * D is approx Deviation. * a,RTT & M are the same as above. * * Timeout = RTT + 4 * D. * * And Karn's Algorithm... * which says * (1) do not update RTT or D for retransmitted packets. * + the ones that follow .... (the ones whos ack was * delayed by the retranmission) * (2) double timeout, when packets fail. (done in retrans). */ if (pkt->retrans) { updateRTT = false; } if (updateRTT) /* can use for RTT calc */ { double ack_time = cts - pkt->ts; rtt_est = RTT_ALPHA * rtt_est + (1.0 - RTT_ALPHA) * ack_time; rtt_dev = RTT_ALPHA * rtt_dev + (1.0 - RTT_ALPHA) * fabs(rtt_est - ack_time); retransTimeout = rtt_est + 4.0 * rtt_dev; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Updating RTT: "; std::cerr << std::endl; std::cerr << "\tAckTime: " << ack_time; std::cerr << std::endl; std::cerr << "\tRRT_est: " << rtt_est; std::cerr << std::endl; std::cerr << "\tRTT_dev: " << rtt_dev; std::cerr << std::endl; std::cerr << "\tTimeout: " << retransTimeout; std::cerr << std::endl; #endif } #ifdef DEBUG_TCP_STREAM else { std::cerr << "TcpStream::acknowledge() Not Updating RTT for retransmitted Pkt Sequence"; std::cerr << std::endl; } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Removing Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif delete pkt; } /* This is triggered if we have recieved acks for retransmitted packets.... * In this case we want to reset the timeout, and remove the doubling. * * If we don't do this, and there have been more dropped packets, * the the timeout gets continually doubled. which will virtually stop * all communication. * * This will effectively trigger the retransmission of the next dropped packet. */ /* * if have acked all data - resetRetransTimer() */ if (it == outPkt.end()) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() peer: " << peeraddr; std::cerr << " Backlog cleared, resetRetransmitTimer"; std::cerr << std::endl; #endif resetRetransmitTimer(); } else if (clearedPkts) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() peer: " << peeraddr; std::cerr << " Cleared some packets -> resetRetransmitTimer + start"; std::cerr << std::endl; #endif resetRetransmitTimer(); startRetransmitTimer(); } return; } int TcpStream::send() { /* handle network interface always */ /* clean up as much as possible */ acknowledge(); /* send any old packets */ retrans(); if (state < TCP_ESTABLISHED) { return -1; } /* get the inQueue, can send */ /* determine exactly how much we can send */ uint32 maxsend = congestWinSize; uint32 inTransit; if (outWinSize < congestWinSize) { maxsend = outWinSize; } if (outSeqno < outAcked) { inTransit = (TCP_MAX_SEQ - outAcked) + outSeqno; } else { inTransit = outSeqno - outAcked; } if (maxsend > inTransit) { maxsend -= inTransit; } else { maxsend = 0; } #ifdef DEBUG_TCP_STREAM int availSend = inQueue.size() * MAX_SEG + inSize; std::cerr << "TcpStream::send() CC: "; std::cerr << "oWS: " << outWinSize; std::cerr << " cWS: " << congestWinSize; std::cerr << " | inT: " << inTransit; std::cerr << " mSnd: " << maxsend; std::cerr << " aSnd: " << availSend; std::cerr << " | oSeq: " << outSeqno; std::cerr << " oAck: " << outAcked; std::cerr << " cUpd: " << congestUpdate; std::cerr << std::endl; #endif int sent = 0; while((inQueue.size() > 0) && (maxsend >= MAX_SEG)) { dataBuffer *db = inQueue.front(); inQueue.pop_front(); TcpPacket *pkt = new TcpPacket(db->data, MAX_SEG); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Segment ===> Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif sent++; maxsend -= MAX_SEG; toSend(pkt); delete db; } /* if inqueue empty, and enough window space, send partial stuff */ if ((!sent) && (inQueue.empty()) && (maxsend >= inSize) && (inSize)) { TcpPacket *pkt = new TcpPacket(inData, inSize); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Remaining ===>"; std::cerr << std::endl; #endif inSize = 0; sent++; maxsend -= inSize; toSend(pkt); } /* if send nothing */ bool needsAck = false; if (!sent) { double cts = getCurrentTS(); /* if needs ack */ if (isOldSequence(lastSentAck,inAckno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (Ackno)"; std::cerr << std::endl; #endif needsAck = true; } /* if needs window * if added enough space for packet, or * (this case is equivalent to persistence timer) * haven't sent anything for a while, and the * window size has drastically increased. * */ if (((lastSentWinSize < MAX_SEG) && (inWinSize > MAX_SEG)) || ((cts - keepAliveTimer > retransTimeout * 4) && (inWinSize > lastSentWinSize + 4 * MAX_SEG))) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (Window)"; std::cerr << std::endl; #endif needsAck = true; } /* if needs keepalive */ if (cts - keepAliveTimer > keepAliveTimeout) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (KAlive)"; std::cerr << std::endl; #endif needsAck = true; } /* if end of stream -> switch mode -> send fin (with ack) */ if ((!outStreamActive) && (inQueue.size() + inSize == 0) && ((state == TCP_ESTABLISHED) || (state == TCP_CLOSE_WAIT))) { /* finish the stream */ TcpPacket *pkt = new TcpPacket(); pkt -> setFin(); needsAck = false; toSend(pkt, false); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Fin Triggered"; std::cerr << std::endl; #endif if (state == TCP_ESTABLISHED) { state = TCP_FIN_WAIT_1; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_FIN_WAIT_1"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_FIN_WAIT_1 (End of Stream)"); } else if (state == TCP_CLOSE_WAIT) { state = TCP_LAST_ACK; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_LAST_ACK"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_LAST_ACK (CLOSE_WAIT, End of Stream)"); } } if (needsAck) { sendAck(); } #ifdef DEBUG_TCP_STREAM_EXTRA else { std::cerr << "TcpStream::send() No Ack"; std::cerr << std::endl; } #endif } #ifdef DEBUG_TCP_STREAM_EXTRA else { std::cerr << "TcpStream::send() Stuff Sent"; std::cerr << std::endl; } #endif return 1; } uint32 TcpStream::genSequenceNo() { return RSRandom::random_u32(); //return 1000; // TCP_MAX_SEQ - 1000; //1000; //(rand() - 100000) + time(NULL) % 100000; //return (rand() - 100000) + time(NULL) % 100000; } bool TcpStream::isOldSequence(uint32 tst, uint32 curr) { return ((int)((tst)-(curr)) < 0); std::cerr << "TcpStream::isOldSequence(): Case "; /* if tst < curr */ if ((int)((tst)-(curr)) < 0) { if (curr - tst < TCP_MAX_SEQ/2) /* diff less than half span -> old */ { std::cerr << "1T" << std::endl; return true; } std::cerr << "2F" << std::endl; return false; } else if ((tst - curr) > TCP_MAX_SEQ/2) { std::cerr << "3T: tst-curr:" << (tst-curr) << std::endl; return true; } std::cerr << "4F: tst-curr:" << (tst-curr) << std::endl; return false; } #ifdef WINDOWS_SYS #include <time.h> #include <sys/timeb.h> #endif // Little fn to get current timestamp in an independent manner. static double getCurrentTS() { #ifndef WINDOWS_SYS struct timeval cts_tmp; gettimeofday(&cts_tmp, NULL); double cts = (cts_tmp.tv_sec) + ((double) cts_tmp.tv_usec) / 1000000.0; #else struct _timeb timebuf; _ftime( &timebuf); double cts = (timebuf.time) + ((double) timebuf.millitm) / 1000.0; #endif return cts; } uint32 TcpStream::int_wbytes() { return outSeqno - initOurSeqno - 1; } uint32 TcpStream::int_rbytes() { return inAckno - initPeerSeqno - 1; } /********* Special debugging stuff *****/ #ifdef DEBUG_TCP_STREAM_EXTRA #include <stdio.h> static FILE *bc_fd = 0; int setupBinaryCheck(std::string fname) { bc_fd = RsDirUtil::rs_fopen(fname.c_str(), "r"); return 1; } /* uses seq number to track position -> ensure no rollover */ int checkData(uint8 *data, int size, int idx) { if (bc_fd <= 0) { return -1; } std::cerr << "checkData(" << idx << "+" << size << ")"; int tmpsize = size; uint8 tmpdata[tmpsize]; if (-1 == fseek(bc_fd, idx, SEEK_SET)) { std::cerr << "Fseek Issues!" << std::endl; exit(1); return -1; } if (1 != fread(tmpdata, tmpsize, 1, bc_fd)) { std::cerr << "Length Difference!" << std::endl; exit(1); return -1; } for(int i = 0; i < size; i++) { if (data[i] != tmpdata[i]) { std::cerr << "Byte Difference!" << std::endl; exit(1); return -1; } } std::cerr << "OK" << std::endl; return 1; } #endif /***** Dump state of TCP Stream - to workout why it was closed ****/ int TcpStream::dumpstate_locked(std::ostream &out) { out << "TcpStream::dumpstate()"; out << "======================================================="; out << std::endl; out << "state: " << (int) state; out << " errorState: " << (int) errorState; out << std::endl; out << "(Streams) inStreamActive: " << inStreamActive; out << " outStreamActive: " << outStreamActive; out << std::endl; out << "(Timeouts) maxWinSize: " << maxWinSize; out << " keepAliveTimeout: " << keepAliveTimeout; out << " retransTimeout: " << retransTimeout; out << std::endl; out << "(Timers) keepAliveTimer: " << std::setprecision(12) << keepAliveTimer; out << " lastIncomingPkt: " << std::setprecision(12) << lastIncomingPkt; out << std::endl; out << "(Tracking) lastSendAck: " << lastSentAck; out << " lastSendWinSize: " << lastSentWinSize; out << std::endl; out << "(Init) initOutSeqno: " << initOurSeqno; out << " initPeerSeqno: " << initPeerSeqno; out << std::endl; out << "(r/w) lastWriteTF: " << lastWriteTF; out << " lastReadTF: " << lastReadTF; out << " wcount: " << wcount; out << " rcount: " << rcount; out << std::endl; out << "(rtt) rtt_est: " << rtt_est; out << " rtt_dev: " << rtt_dev; out << std::endl; out << "(congestion) congestThreshold: " << congestThreshold; out << " congestWinSize: " << congestWinSize; out << " congestUpdate: " << congestUpdate; out << std::endl; out << "(TTL) mTTL_period: " << mTTL_period; out << " mTTL_start: " << std::setprecision(12) << mTTL_start; out << " mTTL_end: " << std::setprecision(12) << mTTL_end; out << std::endl; out << "(Peer) peerKnown: " << peerKnown; out << " peerAddr: " << peeraddr; out << std::endl; out << "-------------------------------------------------------"; out << std::endl; status_locked(out); out << "======================================================="; out << std::endl; return 1; } int TcpStream::dumpstate(std::ostream &out) { tcpMtx.lock(); /********** LOCK MUTEX *********/ dumpstate_locked(out); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 1; } int dumpPacket(std::ostream &out, unsigned char *pkt, uint32_t size) { uint32_t i; out << "dumpPacket() Size: " << size; out << std::endl; out << "------------------------------------------------------"; for(i = 0; i < size; i++) { if (i % 16 == 0) { out << std::endl; } out << std::hex << std::setfill('0') << std::setw(2) << (int) pkt[i] << ":"; } if ((i - 1) % 16 != 0) { out << std::endl; } out << "------------------------------------------------------"; out << std::dec << std::endl; return 1; }
sehraf/RetroShare
libretroshare/src/tcponudp/tcpstream.cc
C++
gpl-2.0
64,510
<?php /** * Maintenance controller * * @package CSVI * @author Roland Dalmulder * @link http://www.csvimproved.com * @copyright Copyright (C) 2006 - 2013 RolandD Cyber Produksi. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html * @version $Id: maintenance.php 2275 2013-01-03 21:08:43Z RolandD $ */ defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' ); jimport('joomla.application.component.controllerform'); /** * Maintenance Controller * * @package CSVIVirtueMart */ class CsviControllerMaintenance extends JControllerForm { /** * Show the maintenance screen * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.0 */ public function Maintenance() { // Create the view object $view = $this->getView('maintenance', 'html'); // Standard model $view->setModel( $this->getModel( 'maintenance', 'CsviModel' ), true ); // Extra models $view->setModel( $this->getModel( 'log', 'CsviModel' )); $view->setModel( $this->getModel( 'availablefields', 'CsviModel' )); // View if (!JRequest::getBool('cron', false)) { if (JRequest::getInt('run_id') > 0) $view->setLayout('log'); } else $view->setLayout('cron'); // Now display the view $view->display(); } /** * Redirect to the log screen * * @copyright * @author RolandD * @todo * @see * @access private * @param * @return * @since 3.3 */ private function _outputHtml() { $this->setRedirect('index.php?option=com_csvi&task=maintenance.maintenance&run_id='.JRequest::getInt('import_id')); } /** * Handle the cron output * * @copyright * @author RolandD * @todo * @see * @access private * @param * @return * @since 3.3 */ private function _outputCron() { // Create the view object $view = $this->getView('maintenance', 'html'); // Standard model $view->setModel( $this->getModel( 'maintenance', 'CsviModel' ), true ); // Extra models $view->setModel( $this->getModel( 'log', 'CsviModel' )); // View $view->setLayout('cron'); // Now display the view $view->display(); } /** * Update available fields * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function updateAvailableFields() { // Prepare $jinput = JFactory::getApplication()->input; $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Check if we are running a cron job if ($jinput->get('cron', false, 'bool')) { // Pre-configuration $available_fields = $this->getModel('availablefields', 'CsviModel'); $available_fields->prepareAvailableFields(); // Update the available fields $available_fields->getFillAvailableFields(); // Finish $model->getFinishProcess(); // Redirect $this->_outputCron(); } else { // Create the view object $view = $this->getView('maintenance', 'json'); // Pre-configuration $available_fields = $this->getModel('availablefields', 'CsviModel'); $available_fields->prepareAvailableFields(); // View $view->setLayout('availablefields'); // Now display the view $view->display(); } } /** * Update available fields in steps * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function updateAvailableFieldsSingle() { // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('availablefields'); // Load the model $view->setModel($this->getModel('maintenance', 'CsviModel'), true); $view->setModel($this->getModel('availablefields', 'CsviModel')); // Now display the view $view->display(); } /** * Install sample templates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function installDefaultTemplates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getInstallDefaultTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Sort categories * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function sortCategories() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getSortCategories(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Remove empty categories * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function removeEmptyCategories() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getRemoveEmptyCategories(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Load the exchange rates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function exchangeRates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getExchangeRates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Clean the cache folder * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function cleanTemp() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getCleanTemp(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Backup the CSVI VirtueMart templates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function backupTemplates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getBackupTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Restore the CSVI VirtueMart templates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function restoreTemplates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getRestoreTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Load the ICEcat index files * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function icecatIndex() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Check if we are running a cron job if (JRequest::getBool('cron', false)) { JRequest::setVar('loadtype', false); } // Perform the task $result = $model->getIcecatIndex(); // See if we need to do the staggered import of the index file switch ($result) { case 'full': // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); break; case 'single': // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('icecat'); // Now display the view $view->display(); break; case 'cancel': // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); break; } } /** * Empty the VirtueMart tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function icecatSingle() { // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('icecat'); // Load the model $view->setModel($this->getModel('maintenance', 'CsviModel'), true); $view->setModel($this->getModel( 'log', 'CsviModel' )); // Now display the view $view->display(); } /** * Optimize the database tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function optimizeTables() { // Prepare $jinput = JFactory::getApplication()->input; $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getOptimizeTables(); // Finish $model->getFinishProcess(); // Redirect if (!$jinput->get('cron', false, 'bool')) $this->_outputHtml(); else $this->_outputCron(); } /** * Backup the VirtueMart tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function backupVm() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getBackupVirtueMart(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Empty the VirtueMart tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function emptyDatabase() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getEmptyDatabase(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Unpublish products in unpublished categories * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.5 */ public function unpublishProductByCategory() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getUnpublishProductByCategory(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Cancel the loading of the ICEcat index * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function cancelImport() { // Clean the session $session = JFactory::getSession(); $option = JRequest::getVar('option'); $session->set($option.'.icecat_index_file', serialize('0')); $session->set($option.'.icecat_rows', serialize('0')); $session->set($option.'.icecat_position', serialize('0')); $session->set($option.'.icecat_records', serialize('0')); $session->set($option.'.icecat_wait', serialize('0')); // Redirect back to the maintenance page $this->setRedirect('index.php?option='.JRequest::getCmd('option').'&view=maintenance'); } /** * Delete all CSVI VirtueMart backup tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.5 */ public function removeCsviTables() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->removeCsviTables(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } } ?>
adrian2020my/vichi
administrator/components/com_csvi/controllers/maintenance.php
PHP
gpl-2.0
12,960
source ./templates/support.sh populate var_password_pam_unix_remember if grep -q "remember=" /etc/pam.d/system-auth; then sed -i --follow-symlink "s/\(remember *= *\).*/\1$var_password_pam_unix_remember/" /etc/pam.d/system-auth else sed -i --follow-symlink "/^password[[:space:]]\+sufficient[[:space:]]\+pam_unix.so/ s/$/ remember=$var_password_pam_unix_remember/" /etc/pam.d/system-auth fi
mpreisler/scap-security-guide-debian
scap-security-guide-0.1.21/shared/fixes/bash/accounts_password_pam_unix_remember.sh
Shell
gpl-2.0
397
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.Borders; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import net.pms.Messages; import net.pms.PMS; import net.pms.configuration.DeviceConfiguration; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.*; import net.pms.formats.Format; import net.pms.io.*; import net.pms.newgui.GuiUtil; import net.pms.util.CodecUtil; import net.pms.util.FormLayoutUtil; import net.pms.util.PlayerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TsMuxeRVideo extends Player { private static final Logger LOGGER = LoggerFactory.getLogger(TsMuxeRVideo.class); private static final String COL_SPEC = "left:pref, 0:grow"; private static final String ROW_SPEC = "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, 0:grow"; public static final String ID = "tsmuxer"; @Deprecated public TsMuxeRVideo(PmsConfiguration configuration) { this(); } public TsMuxeRVideo() { } @Override public boolean excludeFormat(Format format) { String extension = format.getMatchedExtension(); return extension != null && !extension.equals("mp4") && !extension.equals("mkv") && !extension.equals("ts") && !extension.equals("tp") && !extension.equals("m2ts") && !extension.equals("m2t") && !extension.equals("mpg") && !extension.equals("evo") && !extension.equals("mpeg") && !extension.equals("vob") && !extension.equals("m2v") && !extension.equals("mts") && !extension.equals("mov"); } @Override public int purpose() { return VIDEO_SIMPLEFILE_PLAYER; } @Override public String id() { return ID; } @Override public boolean isTimeSeekable() { return true; } @Override public String[] args() { return null; } @Override public String executable() { return configuration.getTsmuxerPath(); } @Override public ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { // Use device-specific pms conf PmsConfiguration prev = configuration; configuration = (DeviceConfiguration) params.mediaRenderer; final String filename = dlna.getSystemName(); setAudioAndSubs(filename, media, params); PipeIPCProcess ffVideoPipe; ProcessWrapperImpl ffVideo; PipeIPCProcess ffAudioPipe[] = null; ProcessWrapperImpl ffAudio[] = null; String fps = media.getValidFps(false); int width = media.getWidth(); int height = media.getHeight(); if (width < 320 || height < 240) { width = -1; height = -1; } String videoType = "V_MPEG4/ISO/AVC"; if (media.getCodecV() != null && media.getCodecV().startsWith("mpeg2")) { videoType = "V_MPEG-2"; } boolean aacTranscode = false; String[] ffmpegCommands; if (this instanceof TsMuxeRAudio && media.getFirstAudioTrack() != null) { ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "fakevideo", System.currentTimeMillis() + "videoout", false, true); String timeEndValue1 = "-t"; String timeEndValue2 = "" + params.timeend; if (params.timeend < 1) { timeEndValue1 = "-y"; timeEndValue2 = "-y"; } ffmpegCommands = new String[] { configuration.getFfmpegPath(), timeEndValue1, timeEndValue2, "-loop", "1", "-i", "DummyInput.jpg", "-f", "h264", "-c:v", "libx264", "-level", "31", "-tune", "zerolatency", "-pix_fmt", "yuv420p", "-an", "-y", ffVideoPipe.getInputPipe() }; videoType = "V_MPEG4/ISO/AVC"; OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffVideo = new ProcessWrapperImpl(ffmpegCommands, ffparams); if ( filename.toLowerCase().endsWith(".flac") && media.getFirstAudioTrack().getBitsperSample() >= 24 && media.getFirstAudioTrack().getSampleRate() % 48000 == 0 ) { ffAudioPipe = new PipeIPCProcess[1]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "flacaudio", System.currentTimeMillis() + "audioout", false, true); String[] flacCmd = new String[] { configuration.getFlacPath(), "--output-name=" + ffAudioPipe[0].getInputPipe(), "-d", "-f", "-F", filename }; ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffAudio = new ProcessWrapperImpl[1]; ffAudio[0] = new ProcessWrapperImpl(flacCmd, ffparams); } else { ffAudioPipe = new PipeIPCProcess[1]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "mlpaudio", System.currentTimeMillis() + "audioout", false, true); String depth = "pcm_s16le"; String rate = "48000"; if (media.getFirstAudioTrack().getBitsperSample() >= 24) { depth = "pcm_s24le"; } if (media.getFirstAudioTrack().getSampleRate() > 48000) { rate = "" + media.getFirstAudioTrack().getSampleRate(); } String[] flacCmd = new String[] { configuration.getFfmpegPath(), "-i", filename, "-ar", rate, "-f", "wav", "-acodec", depth, "-y", ffAudioPipe[0].getInputPipe() }; ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffAudio = new ProcessWrapperImpl[1]; ffAudio[0] = new ProcessWrapperImpl(flacCmd, ffparams); } } else { params.waitbeforestart = 5000; params.manageFastStart(); ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true); ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-c", "copy", "-f", "rawvideo", "-y", ffVideoPipe.getInputPipe() }; InputFile newInput = new InputFile(); newInput.setFilename(filename); newInput.setPush(params.stdin); /** * Note: This logic is weird; on one hand we check if the renderer requires videos to be Level 4.1 or below, but then * the other function allows the video to exceed those limits. * In reality this won't cause problems since renderers typically don't support above 4.1 anyway - nor are many * videos encoded higher than that either - but it's worth acknowledging the logic discrepancy. */ if (!media.isVideoWithinH264LevelLimits(newInput, params.mediaRenderer) && params.mediaRenderer.isH264Level41Limited()) { LOGGER.info("The video will not play or will show a black screen"); } if (media.getH264AnnexB() != null && media.getH264AnnexB().length > 0) { StreamModifier sm = new StreamModifier(); sm.setHeader(media.getH264AnnexB()); sm.setH264AnnexB(true); ffVideoPipe.setModifier(sm); } OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffVideo = new ProcessWrapperImpl(ffmpegCommands, ffparams); int numAudioTracks = 1; if (media.getAudioTracksList() != null && media.getAudioTracksList().size() > 1 && configuration.isMuxAllAudioTracks()) { numAudioTracks = media.getAudioTracksList().size(); } boolean singleMediaAudio = media.getAudioTracksList().size() <= 1; if (params.aid != null) { boolean ac3Remux; boolean dtsRemux; boolean encodedAudioPassthrough; boolean pcm; if (numAudioTracks <= 1) { ffAudioPipe = new PipeIPCProcess[numAudioTracks]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true); encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = params.aid.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.isAudioEmbedDtsInPcm() && params.aid.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( params.aid.isLossless() || (params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || params.aid.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); int channels; if (ac3Remux) { channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux || encodedAudioPassthrough) { channels = 2; } else if (pcm) { channels = params.aid.getAudioProperties().getNumberOfChannels(); } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } if (!ac3Remux && (dtsRemux || pcm || encodedAudioPassthrough)) { // DTS remux or LPCM StreamModifier sm = new StreamModifier(); sm.setPcm(pcm); sm.setDtsEmbed(dtsRemux); sm.setEncodedAudioPassthrough(encodedAudioPassthrough); sm.setNbChannels(channels); sm.setSampleFrequency(params.aid.getSampleRate() < 48000 ? 48000 : params.aid.getSampleRate()); sm.setBitsPerSample(16); ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + sm.getNbChannels(), "-f", "ac3", "-c:a", sm.isDtsEmbed() || sm.isEncodedAudioPassthrough() ? "copy" : "pcm", "-y", ffAudioPipe[0].getInputPipe() }; // Use PCM trick when media renderer does not support DTS in MPEG if (!params.mediaRenderer.isMuxDTSToMpeg()) { ffAudioPipe[0].setModifier(sm); } } else if (!ac3Remux && params.mediaRenderer.isTranscodeToAAC()) { // AAC audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "adts", "-c:a", "aac", "-strict", "experimental", "-ab", Math.min(configuration.getAudioBitrate(), 320) + "k", "-y", ffAudioPipe[0].getInputPipe() }; aacTranscode = true; } else { // AC-3 audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "ac3", "-c:a", (ac3Remux) ? "copy" : "ac3", "-ab", String.valueOf(CodecUtil.getAC3Bitrate(configuration, params.aid)) + "k", "-y", ffAudioPipe[0].getInputPipe() }; } ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffAudio = new ProcessWrapperImpl[numAudioTracks]; ffAudio[0] = new ProcessWrapperImpl(ffmpegCommands, ffparams); } else { ffAudioPipe = new PipeIPCProcess[numAudioTracks]; ffAudio = new ProcessWrapperImpl[numAudioTracks]; for (int i = 0; i < media.getAudioTracksList().size(); i++) { DLNAMediaAudio audio = media.getAudioTracksList().get(i); ffAudioPipe[i] = new PipeIPCProcess(System.currentTimeMillis() + "ffmpeg" + i, System.currentTimeMillis() + "audioout" + i, false, true); encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = audio.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.isAudioEmbedDtsInPcm() && audio.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( audio.isLossless() || (audio.isDTS() && audio.getAudioProperties().getNumberOfChannels() <= 6) || audio.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( audio.isAC3() || audio.isMP3() || audio.isAAC() || audio.isVorbis() || // audio.isWMA() || audio.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); int channels; if (ac3Remux) { channels = audio.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux || encodedAudioPassthrough) { channels = 2; } else if (pcm) { channels = audio.getAudioProperties().getNumberOfChannels(); } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } if (!ac3Remux && (dtsRemux || pcm || encodedAudioPassthrough)) { // DTS remux or LPCM StreamModifier sm = new StreamModifier(); sm.setPcm(pcm); sm.setDtsEmbed(dtsRemux); sm.setEncodedAudioPassthrough(encodedAudioPassthrough); sm.setNbChannels(channels); sm.setSampleFrequency(audio.getSampleRate() < 48000 ? 48000 : audio.getSampleRate()); sm.setBitsPerSample(16); if (!params.mediaRenderer.isMuxDTSToMpeg()) { ffAudioPipe[i].setModifier(sm); } ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + sm.getNbChannels(), "-f", "ac3", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", sm.isDtsEmbed() || sm.isEncodedAudioPassthrough() ? "copy" : "pcm", "-y", ffAudioPipe[i].getInputPipe() }; } else if (!ac3Remux && params.mediaRenderer.isTranscodeToAAC()) { // AAC audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "adts", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", "aac", "-strict", "experimental", "-ab", Math.min(configuration.getAudioBitrate(), 320) + "k", "-y", ffAudioPipe[i].getInputPipe() }; aacTranscode = true; } else { // AC-3 remux or encoding ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "ac3", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", (ac3Remux) ? "copy" : "ac3", "-ab", String.valueOf(CodecUtil.getAC3Bitrate(configuration, audio)) + "k", "-y", ffAudioPipe[i].getInputPipe() }; } ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffAudio[i] = new ProcessWrapperImpl(ffmpegCommands, ffparams); } } } } File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta"); params.log = false; try (PrintWriter pw = new PrintWriter(f)) { pw.print("MUXOPT --no-pcr-on-video-pid"); pw.print(" --new-audio-pes"); pw.print(" --no-asyncio"); pw.print(" --vbr"); pw.println(" --vbv-len=500"); String sei = "insertSEI"; if ( params.mediaRenderer.isPS3() && media.isWebDl(filename, params) ) { sei = "forceSEI"; } String videoparams = "level=4.1, " + sei + ", contSPS, track=1"; if (this instanceof TsMuxeRAudio) { videoparams = "track=224"; } if (configuration.isFix25FPSAvMismatch()) { fps = "25"; } pw.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + (fps != null ? ("fps=" + fps + ", ") : "") + (width != -1 ? ("video-width=" + width + ", ") : "") + (height != -1 ? ("video-height=" + height + ", ") : "") + videoparams); if (ffAudioPipe != null && ffAudioPipe.length == 1) { String timeshift = ""; boolean ac3Remux; boolean dtsRemux; boolean encodedAudioPassthrough; boolean pcm; encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = params.aid.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.isAudioEmbedDtsInPcm() && params.aid.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( params.aid.isLossless() || (params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || params.aid.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); String type = "A_AC3"; if (ac3Remux) { // AC-3 remux takes priority type = "A_AC3"; } else if (aacTranscode) { type = "A_AAC"; } else { if (pcm || this instanceof TsMuxeRAudio) { type = "A_LPCM"; } if (encodedAudioPassthrough || this instanceof TsMuxeRAudio) { type = "A_LPCM"; } if (dtsRemux || this instanceof TsMuxeRAudio) { type = "A_LPCM"; if (params.mediaRenderer.isMuxDTSToMpeg()) { type = "A_DTS"; } } } if (params.aid != null && params.aid.getAudioProperties().getAudioDelay() != 0 && params.timeseek == 0) { timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, "; } pw.println(type + ", \"" + ffAudioPipe[0].getOutputPipe() + "\", " + timeshift + "track=2"); } else if (ffAudioPipe != null) { for (int i = 0; i < media.getAudioTracksList().size(); i++) { DLNAMediaAudio lang = media.getAudioTracksList().get(i); String timeshift = ""; boolean ac3Remux; boolean dtsRemux; boolean encodedAudioPassthrough; boolean pcm; encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = lang.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough; dtsRemux = configuration.isAudioEmbedDtsInPcm() && lang.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( lang.isLossless() || (lang.isDTS() && lang.getAudioProperties().getNumberOfChannels() <= 6) || lang.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); String type = "A_AC3"; if (ac3Remux) { // AC-3 remux takes priority type = "A_AC3"; } else { if (pcm) { type = "A_LPCM"; } if (encodedAudioPassthrough) { type = "A_LPCM"; } if (dtsRemux) { type = "A_LPCM"; if (params.mediaRenderer.isMuxDTSToMpeg()) { type = "A_DTS"; } } } if (lang.getAudioProperties().getAudioDelay() != 0 && params.timeseek == 0) { timeshift = "timeshift=" + lang.getAudioProperties().getAudioDelay() + "ms, "; } pw.println(type + ", \"" + ffAudioPipe[i].getOutputPipe() + "\", " + timeshift + "track=" + (2 + i)); } } } PipeProcess tsPipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts"); /** * Use the newer version of tsMuxeR on PS3 since other renderers * like Panasonic TVs don't always recognize the new output */ String executable = executable(); if (params.mediaRenderer.isPS3()) { executable = configuration.getTsmuxerNewPath(); } String[] cmdArray = new String[]{ executable, f.getAbsolutePath(), tsPipe.getInputPipe() }; cmdArray = finalizeTranscoderArgs( filename, dlna, media, params, cmdArray ); ProcessWrapperImpl p = new ProcessWrapperImpl(cmdArray, params); params.maxBufferSize = 100; params.input_pipes[0] = tsPipe; params.stdin = null; ProcessWrapper pipe_process = tsPipe.getPipeProcess(); p.attachProcess(pipe_process); pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } tsPipe.deleteLater(); ProcessWrapper ff_pipe_process = ffVideoPipe.getPipeProcess(); p.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffVideoPipe.deleteLater(); p.attachProcess(ffVideo); ffVideo.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } if (ffAudioPipe != null && params.aid != null) { for (int i = 0; i < ffAudioPipe.length; i++) { ff_pipe_process = ffAudioPipe[i].getPipeProcess(); p.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffAudioPipe[i].deleteLater(); p.attachProcess(ffAudio[i]); ffAudio[i].runInNewThread(); } } try { Thread.sleep(100); } catch (InterruptedException e) { } p.runInNewThread(); configuration = prev; return p; } @Override public String mimeType() { return "video/mpeg"; } @Override public String name() { return "tsMuxeR"; } @Override public int type() { return Format.VIDEO; } private JCheckBox tsmuxerforcefps; private JCheckBox muxallaudiotracks; @Override public JComponent config() { // Apply the orientation for the locale ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale()); String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation); FormLayout layout = new FormLayout(colSpec, ROW_SPEC); PanelBuilder builder = new PanelBuilder(layout); builder.border(Borders.EMPTY); builder.opaque(false); CellConstraints cc = new CellConstraints(); JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(2, 1, 1), colSpec, orientation)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); tsmuxerforcefps = new JCheckBox(Messages.getString("TsMuxeRVideo.2"), configuration.isTsmuxerForceFps()); tsmuxerforcefps.setContentAreaFilled(false); tsmuxerforcefps.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setTsmuxerForceFps(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(GuiUtil.getPreferredSizeComponent(tsmuxerforcefps), FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation)); muxallaudiotracks = new JCheckBox(Messages.getString("TsMuxeRVideo.19"), configuration.isMuxAllAudioTracks()); muxallaudiotracks.setContentAreaFilled(false); muxallaudiotracks.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setMuxAllAudioTracks(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(GuiUtil.getPreferredSizeComponent(muxallaudiotracks), FormLayoutUtil.flip(cc.xy(2, 5), colSpec, orientation)); JPanel panel = builder.getPanel(); // Apply the orientation to the panel and all components in it panel.applyComponentOrientation(orientation); return panel; } @Override public boolean isInternalSubtitlesSupported() { return false; } @Override public boolean isExternalSubtitlesSupported() { return false; } @Override public boolean isPlayerCompatible(RendererConfiguration mediaRenderer) { return mediaRenderer != null && mediaRenderer.isMuxH264MpegTS(); } /** * {@inheritDoc} */ @Override public boolean isCompatible(DLNAResource resource) { DLNAMediaSubtitle subtitle = resource.getMediaSubtitle(); // Check whether the subtitle actually has a language defined, // uninitialized DLNAMediaSubtitle objects have a null language. if (subtitle != null && subtitle.getLang() != null) { // The resource needs a subtitle, but PMS does not support subtitles for tsMuxeR. return false; } try { String audioTrackName = resource.getMediaAudio().toString(); String defaultAudioTrackName = resource.getMedia().getAudioTracksList().get(0).toString(); if (!audioTrackName.equals(defaultAudioTrackName)) { // PMS only supports playback of the default audio track for tsMuxeR return false; } } catch (NullPointerException e) { LOGGER.trace("tsMuxeR cannot determine compatibility based on audio track for " + resource.getSystemName()); } catch (IndexOutOfBoundsException e) { LOGGER.trace("tsMuxeR cannot determine compatibility based on default audio track for " + resource.getSystemName()); } if ( PlayerUtil.isVideo(resource, Format.Identifier.MKV) || PlayerUtil.isVideo(resource, Format.Identifier.MPG) ) { return true; } return false; } }
bigretromike/UniversalMediaServer
src/main/java/net/pms/encoders/TsMuxeRVideo.java
Java
gpl-2.0
27,024
#include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/pm.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/workqueue.h> #include <linux/wakelock.h> /* wake_lock, unlock */ #include <mach/board_lge.h> #include "../../broadcast_tdmb_drv_ifdef.h" #include "../inc/broadcast_t3900.h" struct broadcast_t3900_ctrl_data { int pwr_state; struct wake_lock wakelock; struct i2c_client* pclient; struct broadcast_device_platform_data* pctrl_fun; /* defined in board_lge.h */ }; static struct broadcast_t3900_ctrl_data TdmbCtrlInfo; static uint32 user_stop_flg = 0; static uint32 mdelay_in_flg = 0; struct i2c_client* INC_GET_I2C_DRIVER(void) { return TdmbCtrlInfo.pclient; } void tdmb_t3900_set_userstop(void) { user_stop_flg = ((mdelay_in_flg == 1)? 1: 0 ); } int tdmb_t3900_mdelay(int32 ms) { int rc = 1; /* 0 : false, 1 : ture */ #if 1 int32 wait_loop =0; int32 wait_ms = ms; if(ms > 100) { wait_loop = (ms /100); /* 100, 200, 300 more only , Otherwise this must be modified e.g (ms + 40)/50 */ wait_ms = 100; } mdelay_in_flg = 1; do { msleep(wait_ms); if(user_stop_flg == 1) { printk("~~~~~~~~ Ustop flag is set so return false ~~~~~~~~\n"); rc = 0; break; } }while((--wait_loop) > 0); mdelay_in_flg = 0; user_stop_flg = 0; #else msleep(ms); #endif if(rc == 0) { printk("tdmb_t3900_delay return abnormal\n"); } return rc; } void tdmb_t3900_must_mdelay(int32 ms) { msleep(ms); } int tdmb_t3900_power_on(void) { /* if(TdmbCtrlInfo.pwr_state == 1) { printk("tdmb_t3900_power is immediately on\n"); return TRUE; } */ if((TdmbCtrlInfo.pctrl_fun == NULL) ||(TdmbCtrlInfo.pctrl_fun->dmb_power_on == NULL)) { printk("tdmb_t3900_power_on function NULL\n"); return FALSE; } wake_lock(&TdmbCtrlInfo.wakelock); TdmbCtrlInfo.pctrl_fun->dmb_power_on( ); TdmbCtrlInfo.pwr_state = 1; return TRUE; } int tdmb_t3900_power_off(void) { if(TdmbCtrlInfo.pwr_state == 0) { printk("tdmb_t3900_power is immediately off\n"); return TRUE; } if((TdmbCtrlInfo.pctrl_fun == NULL) ||(TdmbCtrlInfo.pctrl_fun->dmb_power_off == NULL)) { printk("tdmb_t3900_power_off function NULL\n"); return FALSE; } TdmbCtrlInfo.pwr_state = 0; TdmbCtrlInfo.pctrl_fun->dmb_power_off( ); wake_unlock(&TdmbCtrlInfo.wakelock); return TRUE; } int tdmb_t3900_select_antenna(unsigned int sel) { return FALSE; } static int tdmb_t3900_i2c_write(uint8* txdata, int length) { int rc; struct i2c_msg msg = { TdmbCtrlInfo.pclient->addr, 0, length, txdata }; //if(i2c_transfer(TdmbCtrlInfo.pclient->adapter, &msg, 1) < 0) rc = i2c_transfer(TdmbCtrlInfo.pclient->adapter, &msg, 1); if(rc < 0) { printk("tdmb_t3900_i2c_write fail rc = (%d) addr =(0x%X)\n", rc, TdmbCtrlInfo.pclient->addr); return FALSE; } return TRUE; } int tdmb_t3900_i2c_write_burst(uint16 waddr, uint8* wdata, int length) { uint8* buf; int wlen; int rc; /* success : 1 , fail : 0 */ wlen = length + 2; buf = (uint8*)kmalloc(wlen, GFP_KERNEL); if((buf == NULL) || (length <= 0)) { printk("tdmb_t3900_i2c_write_burst buf alloc fail\n"); return FALSE; } buf[0] = (waddr>>8)&0xFF; buf[1] = (waddr&0xFF); memcpy(&buf[2], wdata, length); rc = tdmb_t3900_i2c_write(buf, wlen); kfree(buf); return rc; } static int tdmb_t3900_i2c_read( uint16 raddr, uint8 *rxdata, int length) { int rc; uint8 r_addr[2] = {raddr>>8, raddr&0xFF}; struct i2c_msg msgs[2] = { { .addr = TdmbCtrlInfo.pclient->addr, .flags = 0, .len = 2, .buf = &r_addr[0], }, { .addr = TdmbCtrlInfo.pclient->addr, .flags = I2C_M_RD, .len = length, .buf = rxdata, }, }; //if (i2c_transfer(TdmbCtrlInfo.pclient->adapter, msgs, 2) < 0) rc = i2c_transfer(TdmbCtrlInfo.pclient->adapter, msgs, 2); if(rc < 0) { printk("tdmb_t3900_i2c_read failed! rc =(%d),%x \n", rc, TdmbCtrlInfo.pclient->addr); return FALSE; } return TRUE; }; int tdmb_t3900_i2c_read_burst(uint16 raddr, uint8* rdata, int length) { int rc; rc = tdmb_t3900_i2c_read(raddr, rdata, length); return rc; } int tdmb_t3900_i2c_write16(unsigned short reg, unsigned short val) { int err; unsigned char buf[4] = { reg>>8, reg&0xff, val>>8, val&0xff }; struct i2c_msg msg = { TdmbCtrlInfo.pclient->addr, 0, 4, buf }; if ((err = i2c_transfer( TdmbCtrlInfo.pclient->adapter, &msg, 1)) < 0) { dev_err(&TdmbCtrlInfo.pclient->dev, "i2c write error\n"); err = FALSE; } else { //printk(KERN_INFO "tdmb : i2c write ok:addr = %x data = %x\n", reg, val); err = TRUE; } return err; } int tdmb_t3900_i2c_read16(uint16 reg, uint16 *ret) { int err; uint8 w_buf[2] = {reg>>8, reg&0xff}; uint8 r_buf[2] = {0,0}; struct i2c_msg msgs[2] = { { .addr = TdmbCtrlInfo.pclient->addr, .flags = 0, .len = 2, .buf = &w_buf[0], }, { .addr = TdmbCtrlInfo.pclient->addr, .flags = I2C_M_RD, .len = 2, .buf = &r_buf[0], }, }; if ((err = i2c_transfer(TdmbCtrlInfo.pclient->adapter, msgs, 2)) < 0) { dev_err(&TdmbCtrlInfo.pclient->dev, "i2c read error\n"); err = FALSE; } else { //printk( "tdmb addr = %x : i2c read ok: data[0] = %x data[1] = %x \n", TdmbCtrlInfo.pClient->addr, r_buf[0], r_buf[1]); *ret = r_buf[0]<<8 | r_buf[1]; //printk( "tdmb : i2c read ok: data = %x\n", *ret); err = TRUE; } return err; } void tdmb_rw_test(void) { unsigned short i = 0; unsigned short w_val = 0; unsigned short r_val = 0; unsigned short err_cnt = 0; err_cnt = 0; for(i=1;i<11;i++) { w_val = (i%0xFF); tdmb_t3900_i2c_write16( 0x0a00+ 0x05, w_val); tdmb_t3900_i2c_read16(0x0a00+ 0x05, &r_val ); if(r_val != w_val) { err_cnt++; printk("w_val:%x, r_val:%x\n", w_val,r_val); } } } static int broadcast_t3900_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { int rc; struct broadcast_device_platform_data *pdata; memset((void*)&TdmbCtrlInfo, 0x00, sizeof(struct broadcast_t3900_ctrl_data)); printk("broadcast_t3900_i2c_probe( )\n"); if(!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { printk(KERN_ERR "tdmb_lg2102_i2c_probe: need I2C_FUNC_I2C\n"); rc = -ENODEV; return rc; } TdmbCtrlInfo.pclient = client; i2c_set_clientdata(client, (void*)&TdmbCtrlInfo); /* Register power control function */ TdmbCtrlInfo.pwr_state = 0; pdata = (struct broadcast_device_platform_data*)client->dev.platform_data; TdmbCtrlInfo.pctrl_fun = pdata; if(TdmbCtrlInfo.pctrl_fun && TdmbCtrlInfo.pctrl_fun->dmb_gpio_init) { TdmbCtrlInfo.pctrl_fun->dmb_gpio_init( ); } else { printk("broadcast_t3900_i2c_probe dmb_gpio_init is not called\n"); } wake_lock_init(&TdmbCtrlInfo.wakelock, WAKE_LOCK_SUSPEND, dev_name(&client->dev)); return OK; } static int broadcast_t3900_i2c_remove(struct i2c_client* client) { printk("broadcast_t3900_i2c_remove is called\n"); wake_lock_destroy(&TdmbCtrlInfo.wakelock); return OK; } static const struct i2c_device_id tdmb_t3900_id[] = { {"tdmb_t3900", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, tdmb_t3900_id); static struct i2c_driver t3900_i2c_driver = { .probe = broadcast_t3900_i2c_probe, .remove = broadcast_t3900_i2c_remove, .id_table = tdmb_t3900_id, .driver = { .name = "tdmb_t3900", .owner = THIS_MODULE, }, }; int __devinit broadcast_tdmb_drv_init(void) { int rc; printk("broadcast_tdmb_drv_init\n"); rc = broadcast_tdmb_drv_start(); if (rc) { printk("broadcast_tdmb_drv_start %s failed to load\n", __func__); return rc; } rc = i2c_add_driver(&t3900_i2c_driver); printk("broadcast_i2c_add_driver rc = (%d)\n", rc); return rc; } static void __exit broadcast_tdmb_drv_exit(void) { i2c_del_driver(&t3900_i2c_driver); } /* EXPORT_SYMBOL() : when we use external symbol which is not included in current module - over kernel 2.6 */ //EXPORT_SYMBOL(broadcast_tdmb_is_on); module_init(broadcast_tdmb_drv_init); module_exit(broadcast_tdmb_drv_exit); MODULE_DESCRIPTION("broadcast_tdmb_drv_init"); MODULE_LICENSE("INC");
JellyBeanNitro/kernel-iproj-3.4
drivers/broadcast/tdmb/t3900/src/broadcast_t3900.c
C
gpl-2.0
8,113
<html> <head> <title>XPP - 3D PARAMETERS</title> </head> <body bgcolor="#ffffff" link="#330099" alink="#FF3300" vlink="#330099"> <a href="xpprestore.html">Back</a> | <a href="xppbdry.html">Next</a> | <a href="xpphelp.html">Contents</a> <hr> <h1>3d params</h1>Brings up a dialog box allowing you to rotate the axes in three-dimensional plots and make animations. The items are: <br><ul> <li><b>theta</b>, the angle about the <font color=#77aa00> z-axis </font> to use this. <li><b>phi</b>, the angle about the <font color=#77aa00> y-axis </font> <li><b>Movie</b> set this to 1 if you want to create a little movie in which the box rotates about one of the two principle axes. <li> Choose which angle you want to rotate about: <font color=#77aa00>theta or phi</font> <li> Choose the starting angle <li> Choose the increment <li> Choose the number of frames </ul><p>If you select <b> Movie </b> then a series of frames will be drawn. You can use the <a href="xppkine.html"> Kinescope </a> command to play these back or save them in an animated gif file.<p>
sanjayankur31/xppaut
help/xpp3d.html
HTML
gpl-2.0
1,056
<?php /** * Template Name: Template Content Sidebar Sidebar * * Page template for * * @package Openstrap * @since Openstrap 0.1 */ get_header(); ?> <!-- Main Content --> <div class="col-md-6" role="main"> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; ?> <?php else : ?> <h2><?php _e('No posts.', 'openstrap' ); ?></h2> <p class="lead"><?php _e('Sorry about this, I couldn\'t seem to find what you were looking for.', 'openstrap' ); ?></p> <?php endif; ?> <?php openstrap_custom_pagination(); ?> </div> <!-- End Main Content --> <?php get_sidebar('left'); ?> <?php get_sidebar(); ?> <?php get_footer(); ?>
IdeasFactoryPL/stef-pol
wp-content/themes/openstrap/page-templates/content-sidebar-sidebar.php
PHP
gpl-2.0
791
chmod 644 /etc/group
mpreisler/scap-security-guide-debian
scap-security-guide-0.1.21/shared/fixes/bash/file_permissions_etc_group.sh
Shell
gpl-2.0
21
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace STSdb4.Data { public class DataComparer : IComparer<IData> { public readonly Func<IData, IData, int> compare; public readonly Type Type; public readonly Type DataType; public readonly CompareOption[] CompareOptions; public readonly Func<Type, MemberInfo, int> MembersOrder; public DataComparer(Type type, CompareOption[] compareOptions, Func<Type, MemberInfo, int> membersOrder = null) { Type = type; DataType = typeof(Data<>).MakeGenericType(type); CompareOption.CheckCompareOptions(type, compareOptions, membersOrder); CompareOptions = compareOptions; MembersOrder = membersOrder; compare = CreateCompareMethod().Compile(); } public DataComparer(Type type, Func<Type, MemberInfo, int> membersOrder = null) : this(type, CompareOption.GetDefaultCompareOptions(type, membersOrder), membersOrder) { } public Expression<Func<IData, IData, int>> CreateCompareMethod() { var x = Expression.Parameter(typeof(IData)); var y = Expression.Parameter(typeof(IData)); List<Expression> list = new List<Expression>(); List<ParameterExpression> parameters = new List<ParameterExpression>(); var value1 = Expression.Variable(Type, "value1"); parameters.Add(value1); list.Add(Expression.Assign(value1, Expression.Convert(x, DataType).Value())); var value2 = Expression.Variable(Type, "value2"); parameters.Add(value2); list.Add(Expression.Assign(value2, Expression.Convert(y, DataType).Value())); return Expression.Lambda<Func<IData, IData, int>>(ComparerHelper.CreateComparerBody(list, parameters, value1, value2, CompareOptions, MembersOrder), x, y); } public int Compare(IData x, IData y) { return compare(x, y); } } }
Injac/STSdb4
STSdb4/Data/DataComparer.cs
C#
gpl-2.0
2,148
/* $Id: macucs.c 5322 2005-02-16 23:30:10Z owen $ */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include "putty.h" #include "charset.h" #include "terminal.h" #include "misc.h" #include "mac.h" /* * Mac Unicode-handling routines. * * BJH: * What we _should_ do is to use the Text Encoding Conversion Manager * when it's available, and have our own routines for converting to * standard Mac OS scripts when it's not. Support for ATSUI might be * nice, too. * * I (OSD) am unsure any of the above is necessary if we just use * libcharset */ /* * Determine whether a byte is the first byte of a double-byte * character in a system character set. Only MI use is by clipme() * when copying direct-to-font text to the clipboard. */ int is_dbcs_leadbyte(int codepage, char byte) { return 0; /* we don't do DBCS */ } /* * Convert from Unicode to a system character set. MI uses are: * (1) by lpage_send(), whose only MI use is to convert the answerback * string to Unicode, and * (2) by clipme() when copying direct-to-font text to the clipboard. */ int mb_to_wc(int codepage, int flags, char *mbstr, int mblen, wchar_t *wcstr, int wclen) { int ret = 0; while (mblen > 0 && wclen > 0) { *wcstr++ = (unsigned char) *mbstr++; mblen--, wclen--, ret++; } return ret; /* FIXME: check error codes! */ } /* * Convert from a system character set to Unicode. Used by luni_send * to convert Unicode into the line character set. */ int wc_to_mb(int codepage, int flags, wchar_t *wcstr, int wclen, char *mbstr, int mblen, char *defchr, int *defused, struct unicode_data *ucsdata) { int ret = 0; if (defused) *defused = 0; while (mblen > 0 && wclen > 0) { if (*wcstr >= 0x100) { if (defchr) *mbstr++ = *defchr; else *mbstr++ = '.'; if (defused) *defused = 1; } else *mbstr++ = (unsigned char) *wcstr; wcstr++; mblen--, wclen--, ret++; } return ret; /* FIXME: check error codes! */ } /* Character conversion array, * the xterm one has the four scanlines that have no unicode 2.0 * equivalents mapped to their unicode 3.0 locations. */ static const wchar_t unitab_xterm_std[32] = { 0x2666, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, 0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7, 0x0020 }; void init_ucs(Session *s) { int i; s->ucsdata.line_codepage = decode_codepage(s->cfg.line_codepage); /* Find the line control characters. FIXME: this is not right. */ for (i = 0; i < 256; i++) if (i < ' ' || (i >= 0x7F && i < 0xA0)) s->ucsdata.unitab_ctrl[i] = i; else s->ucsdata.unitab_ctrl[i] = 0xFF; for (i = 0; i < 256; i++) s->ucsdata.unitab_line[i] = s->ucsdata.unitab_scoacs[i] = i; /* VT100 graphics - NB: Broken for non-ascii CP's */ memcpy(s->ucsdata.unitab_xterm, s->ucsdata.unitab_line, sizeof(s->ucsdata.unitab_xterm)); memcpy(s->ucsdata.unitab_xterm + '`', unitab_xterm_std, sizeof(unitab_xterm_std)); s->ucsdata.unitab_xterm['_'] = ' '; } int decode_codepage(char *cp_name) { if (!*cp_name) return CS_NONE; /* use font encoding */ return charset_from_localenc(cp_name); } char const *cp_enumerate (int index) { int charset; if (index == 0) return "Use font encoding"; charset = charset_localenc_nth(index-1); if (charset == CS_NONE) return NULL; return charset_to_localenc(charset); } char const *cp_name(int codepage) { if (codepage == CS_NONE) return "Use font encoding"; return charset_to_localenc(codepage); }
supertanglang/line-is-not-emulator
src/puttyline/putty-0.60/mac/macucs.c
C
gpl-2.0
3,763
<?php /** * This script is included by the barcode_img_wristband.php script for arabic languages */ # Version History: # version 0.1 : First release. created on ( 22/01/2004) By Walid Fathalla # # Bug Report and Suggestion to: # Walid Fathalla # fathalla_w@hotmail.com # # Modifications by Elpidio 2004-02-07 include_once($root_path.'include/inc_ttf_ar2uni.php'); /* Load the barcode image*/ $bc = ImageCreateFrompng($root_path.'cache/barcodes/en_'.$full_en.'.png'); /* Load the wristband images */ $wb_lrg = ImageCreateFrompng('wristband_large.png'); $wb_med = ImageCreateFrompng('wristband_medium.png'); $wb_sml = ImageCreateFrompng('wristband_small.png'); $wb_bby = ImageCreateFrompng('wristband_baby.png'); /* Get the image sizes*/ $size_lrg = GetImageSize('wristband_large.png'); $size_med = GetImageSize('wristband_medium.png'); $size_sml = GetImageSize('wristband_small.png'); $size_bby = GetImageSize('wristband_baby.png'); $w=1085; // The width of the image = equal to the DIN-A4 paper $h=700; // The height of the image = egual to the DIN-A4 paper /* Create the main image */ $im=ImageCreate($w,$h); $white = ImageColorAllocate ($im, 255,255,255); //white bkgrnd /* $background= ImageColorAllocate ($im, 205, 225, 236); $blue=ImageColorAllocate($im, 0, 127, 255); */ $black = ImageColorAllocate ($im, 0, 0, 0); # Check if ttf is ok include_once($root_path.'include/inc_ttf_check.php'); # Write the print instructions $lmargin=10; # Left margin $tmargin=2; # Top margin if($ttf_ok){ ImageTTFText($im,12,0,$lmargin,$tmargin+10,$black,$arial,ar2uni($LDPrintPortraitFormat)); ImageTTFText($im,12,0,$lmargin,$tmargin+25,$black,$arial,ar2uni($LDClickImgToPrint)); }else{ ImageString($im,2,10,2,$LDPrintPortraitFormat,$black); ImageString($im,2,10,15,$LDClickImgToPrint,$black); } # Create the name label $namelabel=ImageCreate(145,40); $nm_white = ImageColorAllocate ($namelabel, 255,255,255); //white bkgrnd $nm_black= ImageColorAllocate ($namelabel, 0, 0, 0); $lmargin=1; # Left margin $tmargin=11; # Top margin $dataline1=ar2uni($result['name_last']).', '.ar2uni($result['name_first']); $dataline2=$result['date_birth']; $dataline3=$result['current_ward'].' '.$result['current_dept'].' '.ar2uni($result['insurance_co_id']).' '.ar2uni($result['insurance_2_co_id']); //$ttf_ok=0; if($ttf_ok){ ImageTTFText($namelabel,11,0,$lmargin,$tmargin,$nm_black,$arial,$dataline1); ImageTTFText($namelabel,10,0,$lmargin,$tmargin+13,$nm_black,$arial,$dataline2); ImageTTFText($namelabel,10,0,$lmargin,$tmargin+26,$nm_black,$arial,$dataline3); }else{ ImageString($namelabel,2,1,2,$dataline1,$nm_black); ImageString($namelabel,2,1,15,$dataline2,$nm_black); ImageString($namelabel,2,1,28,$dataline3,$nm_black); } //-------------- place the wristbands $topm=$topmargin; ImageCopy($im,$wb_lrg,$leftmargin,$topm,0,0,$size_lrg[0],$size_lrg[1]); $topm+=$yoffset; ImageCopy($im,$wb_med,$leftmargin,$topm,0,0,$size_med[0],$size_med[1]); $topm+=$yoffset; ImageCopy($im,$wb_sml,$leftmargin,$topm,0,0,$size_sml[0],$size_sml[1]); $topm+=$yoffset; ImageCopy($im,$wb_bby,$leftmargin,$topm,0,0,$size_bby[0],$size_bby[1]); //* Place the barcodes */ $topm=$topmargin+15; $topm2=$topmargin+60; ImageCopy($im,$bc,$leftmargin+220,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+480,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+230,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+490,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+435,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+225,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+485,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+420,$topm+78,$full_en,$black); } $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$bc,$leftmargin+200,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+430,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+210,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+440,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+395,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+205,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+435,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+380,$topm+78,$full_en,$black); } $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$bc,$leftmargin+160,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+340,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+180,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+360,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+340,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+175,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+355,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+325,$topm+78,$full_en,$black); } $topm+=$yoffset; ImageCopy($im,$bc,$leftmargin+200,$topm,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+210,$topm-1,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+385,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+215,$topm-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+370,$topm+78,$full_en,$black); } //* Place the name labels*/ $topm=$topmargin+53; $topm2=$topmargin+5; ImageCopy($im,$namelabel,$leftmargin+225,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+485,$topm2,0,0,144,39); $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+205,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+435,$topm2,0,0,144,39); $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+175,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+355,$topm2,0,0,144,39); $topm+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+210,$topm,0,0,144,39); /* Create the final image */ Imagepng ($im); // Do not edit the following lines ImageDestroy ($wb_lrg); ImageDestroy ($wb_med); ImageDestroy ($wb_sml); ImageDestroy ($wb_bby); ImageDestroy ($im); ?>
blesko/ELCT
main/imgcreator/inc_wristband_ar.php
PHP
gpl-2.0
6,592
<?php /** * Webservices component for Joomla! CMS * * @copyright Copyright (C) 2004 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later */ namespace Webservices\Controller; use Webservices\Helper; use Webservices\Model\WebserviceModel; /** * Apply Webservice Controller * * @package Joomla! * @subpackage Webservices * @since 1.0 */ class ApplyController extends DisplayController { /** * Execute the controller. * * @return void Redirects the application * * @since 2.0 */ public function execute() { try { $model = new WebserviceModel; // Initialize the state for the model $model->setState($this->initializeState($model)); $id = $this->getInput()->getUint('id'); $data = $this->getInput()->getArray()['jform']; if ($model->save($data)) { $msg = \JText::_('COM_WEBSERVICES_APPLY_OK'); } else { $msg = \JText::_('COM_WEBSERVICES_APPLY_ERROR'); } $type = 'message'; $url = 'index.php?option=com_webservices&task=edit&id=' . $id; } catch (\Exception $e) { $msg = $e->getMessage(); $type = 'error'; } $url = isset($this->returnurl) ? $this->returnurl : $url; $this->getApplication()->enqueueMessage($msg, $type); $this->getApplication()->redirect(\JRoute::_($url, false)); } }
joomla-projects/webservices
component/admin/Webservices/Controller/ApplyController.php
PHP
gpl-2.0
1,362
/* * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4997799 * @summary Basic test of ThreadMXBean.getThreadUserTime and * getCurrentThreadUserTime. * @author Mandy Chung * @modules java.management */ import java.lang.management.*; public class ThreadUserTime { private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); private static boolean testFailed = false; private static boolean done = false; private static Object obj = new Object(); private static final int NUM_THREADS = 10; private static Thread[] threads = new Thread[NUM_THREADS]; private static long[] times = new long[NUM_THREADS]; // careful about this value private static final int DELTA = 100; public static void main(String[] argv) throws Exception { if (!mbean.isCurrentThreadCpuTimeSupported()) { return; } // disable user time if (mbean.isThreadCpuTimeEnabled()) { mbean.setThreadCpuTimeEnabled(false); } Thread curThread = Thread.currentThread(); long t = mbean.getCurrentThreadUserTime(); if (t != -1) { throw new RuntimeException("Invalid CurrenThreadUserTime returned = " + t + " expected = -1"); } if (mbean.isThreadCpuTimeSupported()) { long t1 = mbean.getThreadUserTime(curThread.getId()); if (t1 != -1) { throw new RuntimeException("Invalid ThreadUserTime returned = " + t1 + " expected = -1"); } } // Enable CPU Time measurement if (!mbean.isThreadCpuTimeEnabled()) { mbean.setThreadCpuTimeEnabled(true); } if (!mbean.isThreadCpuTimeEnabled()) { throw new RuntimeException("ThreadUserTime is expected to be enabled"); } long time = mbean.getCurrentThreadUserTime(); if (time < 0) { throw new RuntimeException("Invalid user time returned = " + time); } if (!mbean.isThreadCpuTimeSupported()) { return; } // Expected to be time1 >= time long time1 = mbean.getThreadUserTime(curThread.getId()); if (time1 < time) { throw new RuntimeException("User time " + time1 + " expected >= " + time); } System.out.println(curThread.getName() + " Current Thread User Time = " + time + " user time = " + time1); for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new MyThread("MyThread-" + i); threads[i].start(); } waitUntilThreadBlocked(); for (int i = 0; i < NUM_THREADS; i++) { times[i] = mbean.getThreadUserTime(threads[i].getId()); } goSleep(200); for (int i = 0; i < NUM_THREADS; i++) { long newTime = mbean.getThreadUserTime(threads[i].getId()); if (times[i] > newTime) { throw new RuntimeException("TEST FAILED: " + threads[i].getName() + " previous user user time = " + times[i] + " > current user user time = " + newTime); } if ((times[i] + DELTA) < newTime) { throw new RuntimeException("TEST FAILED: " + threads[i].getName() + " user time = " + newTime + " previous user time " + times[i] + " out of expected range"); } System.out.println(threads[i].getName() + " Previous User Time = " + times[i] + " Current User time = " + newTime); } synchronized (obj) { done = true; obj.notifyAll(); } for (int i = 0; i < NUM_THREADS; i++) { try { threads[i].join(); } catch (InterruptedException e) { System.out.println("Unexpected exception is thrown."); e.printStackTrace(System.out); testFailed = true; break; } } if (testFailed) { throw new RuntimeException("TEST FAILED"); } System.out.println("Test passed"); } private static void goSleep(long ms) throws Exception { try { Thread.sleep(ms); } catch (InterruptedException e) { System.out.println("Unexpected exception is thrown."); throw e; } } private static void waitUntilThreadBlocked() throws Exception { int count = 0; while (count != NUM_THREADS) { goSleep(100); count = 0; for (int i = 0; i < NUM_THREADS; i++) { ThreadInfo info = mbean.getThreadInfo(threads[i].getId()); if (info.getThreadState() == Thread.State.WAITING) { count++; } } } } static class MyThread extends Thread { public MyThread(String name) { super(name); } public void run() { double sum = 0; for (int i = 0; i < 5000; i++) { double r = Math.random(); double x = Math.pow(3, r); sum += x - r; } synchronized (obj) { while (!done) { try { obj.wait(); } catch (InterruptedException e) { System.out.println("Unexpected exception is thrown."); e.printStackTrace(System.out); testFailed = true; break; } } } sum = 0; for (int i = 0; i < 5000; i++) { double r = Math.random(); double x = Math.pow(3, r); sum += x - r; } long time1 = mbean.getCurrentThreadCpuTime(); long utime1 = mbean.getCurrentThreadUserTime(); long time2 = mbean.getThreadCpuTime(getId()); long utime2 = mbean.getThreadUserTime(getId()); System.out.println(getName() + ":"); System.out.println("CurrentThreadUserTime = " + utime1 + " ThreadUserTime = " + utime2); System.out.println("CurrentThreadCpuTime = " + time1 + " ThreadCpuTime = " + time2); if (time1 > time2) { throw new RuntimeException("TEST FAILED: " + getName() + " CurrentThreadCpuTime = " + time1 + " > ThreadCpuTime = " + time2); } if (utime1 > utime2) { throw new RuntimeException("TEST FAILED: " + getName() + " CurrentThreadUserTime = " + utime1 + " > ThreadUserTime = " + utime2); } } } }
FauxFaux/jdk9-jdk
test/java/lang/management/ThreadMXBean/ThreadUserTime.java
Java
gpl-2.0
8,036
<?php /* * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> * * PERL Spreadsheet::WriteExcel module. * * The author of the Spreadsheet::WriteExcel module is John McNamara * <jmcnamara@cpan.org> * * I _DO_ maintain this code, and John McNamara has nothing to do with the * porting of this code to PHP. Any questions directly related to this * class library should be directed to me. * * License Information: * * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ require_once 'PEAR.php'; require_once dirname(__FILE__) . '/Writer/Workbook.php'; /** * Class for writing Excel Spreadsheets. This class should change COMPLETELY. * * @author Xavier Noguer <xnoguer@rezebra.com> * @category FileFormats * @package Spreadsheet_Excel_Writer */ class Spreadsheet_Excel_Writer extends Spreadsheet_Excel_Writer_Workbook { /** * The constructor. It just creates a Workbook * * @param string $filename The optional filename for the Workbook. * @return Spreadsheet_Excel_Writer_Workbook The Workbook created */ function Spreadsheet_Excel_Writer($filename = '') { $this->_filename = $filename; $this->Spreadsheet_Excel_Writer_Workbook($filename); } /** * Send HTTP headers for the Excel file. * * @param string $filename The filename to use for HTTP headers * @access public */ function send($filename) { header("Content-type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0,pre-check=0"); header("Pragma: public"); } /** * Utility function for writing formulas * Converts a cell's coordinates to the A1 format. * * @access public * @static * @param integer $row Row for the cell to convert (0-indexed). * @param integer $col Column for the cell to convert (0-indexed). * @return string The cell identifier in A1 format */ function rowcolToCell($row, $col) { if ($col > 255) { //maximum column value exceeded return new PEAR_Error("Maximum column value exceeded: $col"); } $int = (int)($col / 26); $frac = $col % 26; $chr1 = ''; if ($int > 0) { $chr1 = chr(ord('A') + $int - 1); } $chr2 = chr(ord('A') + $frac); $row++; return $chr1 . $chr2 . $row; } }
GeorgeStreetCoop/CORE-POS
fannie/src/Excel/xls_write/Spreadsheet_Excel_Writer/Writer.php
PHP
gpl-2.0
3,325
/*****************************************************************************/ /* */ /* Copyright 1999 - 2003, Huawei Tech. Co., Ltd. */ /* ALL RIGHTS RESERVED */ /* */ /* FileName: v_int.c */ /* */ /* Author: Yang Xiangqian */ /* */ /* Version: 1.0 */ /* */ /* Date: 2006-10 */ /* */ /* Description: implement int function */ /* */ /* Others: */ /* */ /* History: */ /* 1. Date: */ /* Author: */ /* Modification: Create this file */ /* */ /* 2. Date: 2006-10 */ /* Author: Xu Cheng */ /* Modification: Standardize code */ /* */ /* */ /*****************************************************************************/ #ifdef __cplusplus #if __cplusplus extern "C" { #endif /* __cpluscplus */ #endif /* __cpluscplus */ #include "vos_config.h" #include "v_typdef.h" #include "v_lib.h" #if (VOS_WIN32 == VOS_OS_VER) CRITICAL_SECTION VOS_CriticalSection; /***************************************************************************** Function : VOS_SplInit() Description: Initialize the interrupt Input : None Return : Nnoe *****************************************************************************/ VOS_VOID VOS_SplInit() { InitializeCriticalSection( &VOS_CriticalSection ); } /***************************************************************************** Function : VOS_SplIMP() Description: Turn off the interrupt Input : None Return : VOS_OK; Other : none *****************************************************************************/ VOS_CPU_SR VOS_SplIMP(VOS_VOID) { EnterCriticalSection( &VOS_CriticalSection ); return VOS_OK; } /***************************************************************************** Function : VOS_Splx() Description: Turn on the interrupt Input : s -- value returned by VOS_SplIMP() Return : None *****************************************************************************/ VOS_VOID VOS_Splx( VOS_CPU_SR s ) { LeaveCriticalSection ( &VOS_CriticalSection ); } #endif #ifdef __cplusplus #if __cplusplus } #endif /* __cpluscplus */ #endif /* __cpluscplus */
gabry3795/android_kernel_huawei_mt7_l09
drivers/vendor/hisi/modem/med/hi6930/osa/src/v_int.c
C
gpl-2.0
3,786
/***************************************************************************** * SearchFragment.java ***************************************************************************** * Copyright © 2014-2015 VLC authors, VideoLAN and VideoLabs * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.gui.tv; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.ObjectAdapter; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.text.TextUtils; import org.videolan.vlc.R; import org.videolan.vlc.VLCApplication; import org.videolan.vlc.media.MediaLibrary; import org.videolan.vlc.media.MediaWrapper; import java.util.ArrayList; public class SearchFragment extends android.support.v17.leanback.app.SearchFragment implements android.support.v17.leanback.app.SearchFragment.SearchResultProvider { private static final String TAG = "SearchFragment"; private ArrayObjectAdapter mRowsAdapter; private Handler mHandler = new Handler(); private SearchRunnable mDelayedLoad; protected Activity mActivity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); setSearchResultProvider(this); setOnItemViewClickedListener(getDefaultItemClickedListener()); mDelayedLoad = new SearchRunnable(); mActivity = getActivity(); } @Override public ObjectAdapter getResultsAdapter() { return mRowsAdapter; } private void queryByWords(String words) { mRowsAdapter.clear(); if (!TextUtils.isEmpty(words) && words.length() > 2) { mDelayedLoad.setSearchQuery(words); mDelayedLoad.setSearchType(MediaWrapper.TYPE_ALL); VLCApplication.runBackground(mDelayedLoad); } } @Override public boolean onQueryTextChange(String newQuery) { queryByWords(newQuery); return true; } @Override public boolean onQueryTextSubmit(String query) { queryByWords(query); return true; } private void loadRows(String query, int type) { ArrayList<MediaWrapper> mediaList = MediaLibrary.getInstance().searchMedia(query); final ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter(mActivity)); listRowAdapter.addAll(0, mediaList); mHandler.post(new Runnable() { @Override public void run() { HeaderItem header = new HeaderItem(0, getResources().getString(R.string.search_results)); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } }); } protected OnItemViewClickedListener getDefaultItemClickedListener() { return new OnItemViewClickedListener() { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { if (item instanceof MediaWrapper) { TvUtil.openMedia(mActivity, (MediaWrapper) item, row); } } }; } private class SearchRunnable implements Runnable { private volatile String searchQuery; private volatile int searchType; public SearchRunnable() {} public void run() { loadRows(searchQuery, searchType); } public void setSearchQuery(String value) { this.searchQuery = value; } public void setSearchType(int value) { this.searchType = value; } } }
hanhailong/VCL-Official
vlc-android/src/org/videolan/vlc/gui/tv/SearchFragment.java
Java
gpl-2.0
4,897
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_processing/transient/transient_detector.h" #include <sstream> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/audio_processing/transient/common.h" #include "webrtc/modules/audio_processing/transient/file_utils.h" #include "webrtc/system_wrappers/include/file_wrapper.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/typedefs.h" namespace webrtc { static const int kSampleRatesHz[] = {ts::kSampleRate8kHz, ts::kSampleRate16kHz, ts::kSampleRate32kHz, ts::kSampleRate48kHz}; static const size_t kNumberOfSampleRates = sizeof(kSampleRatesHz) / sizeof(*kSampleRatesHz); // This test is for the correctness of the transient detector. // Checks the results comparing them with the ones stored in the detect files in // the directory: resources/audio_processing/transient/ // The files contain all the results in double precision (Little endian). // The audio files used with different sample rates are stored in the same // directory. TEST(TransientDetectorTest, DISABLED_ON_IOS(CorrectnessBasedOnFiles)) { for (size_t i = 0; i < kNumberOfSampleRates; ++i) { int sample_rate_hz = kSampleRatesHz[i]; // Prepare detect file. std::stringstream detect_file_name; detect_file_name << "audio_processing/transient/detect" << (sample_rate_hz / 1000) << "kHz"; rtc::scoped_ptr<FileWrapper> detect_file(FileWrapper::Create()); detect_file->OpenFile( test::ResourcePath(detect_file_name.str(), "dat").c_str(), true, // Read only. false, // No loop. false); // No text. bool file_opened = detect_file->Open(); ASSERT_TRUE(file_opened) << "File could not be opened.\n" << detect_file_name.str().c_str(); // Prepare audio file. std::stringstream audio_file_name; audio_file_name << "audio_processing/transient/audio" << (sample_rate_hz / 1000) << "kHz"; rtc::scoped_ptr<FileWrapper> audio_file(FileWrapper::Create()); audio_file->OpenFile( test::ResourcePath(audio_file_name.str(), "pcm").c_str(), true, // Read only. false, // No loop. false); // No text. // Create detector. TransientDetector detector(sample_rate_hz); const size_t buffer_length = sample_rate_hz * ts::kChunkSizeMs / 1000; rtc::scoped_ptr<float[]> buffer(new float[buffer_length]); const float kTolerance = 0.02f; size_t frames_read = 0; while (ReadInt16FromFileToFloatBuffer(audio_file.get(), buffer_length, buffer.get()) == buffer_length) { ++frames_read; float detector_value = detector.Detect(buffer.get(), buffer_length, NULL, 0); double file_value; ASSERT_EQ(1u, ReadDoubleBufferFromFile(detect_file.get(), 1, &file_value)) << "Detect test file is malformed.\n"; // Compare results with data from the matlab test file. EXPECT_NEAR(file_value, detector_value, kTolerance) << "Frame: " << frames_read; } detect_file->CloseFile(); audio_file->CloseFile(); } } } // namespace webrtc
raj-bhatia/grooveip-ios-public
submodules/mswebrtc/webrtc/webrtc/modules/audio_processing/transient/transient_detector_unittest.cc
C++
gpl-2.0
3,836
<HTML> <HEAD> <TITLE>Contact Information</TITLE> </HEAD> <BODY BGCOLOR=#FFFFFF> <H1>Contact Information and Copyright</H1> SheepShaver was brought to you by <UL> <LI><A HREF="mailto:Christian.Bauer@uni-mainz.de">Christian Bauer</A> (kernel, disk I/O) <LI><A HREF="mailto:Marc.Hellwig@uni-mainz.de">Marc Hellwig</A> (graphics, sound, networking) </UL> <H3><IMG SRC="iconsmall.gif" ALIGN=MIDDLE>SheepShaver WWW Site:</H3> <BLOCKQUOTE> <A HREF="http://www.sheepshaver.com/">www.sheepshaver.com</A><BR> </BLOCKQUOTE> <H3>EMail:</H3> <BLOCKQUOTE> <A HREF="mailto:Christian.Bauer@uni-mainz.de">Christian.Bauer@uni-mainz.de</A><BR> </BLOCKQUOTE> <H3>License</H3> <P>SheepShaver is available under the terms of the GNU General Public License. See the file "COPYING" that is included in the distribution for details. <P>&copy; Copyright 1997-2004 Christian Bauer and Marc Hellwig <P>Names of hardware and software items mentioned in this manual and in program texts are in most cases registered trade marks of the respective companies and not marked as such. So the lack of such a note may not be used as an indication that these names are free. <P>SheepShaver is not designed, intended, or authorized for use as a component in systems intended for surgical implant within the body, or other applications intended to support or sustain life, or for any other application in which the failure of SheepShaver could create a situation where personal injury or death may occur (so-called "killer application"). <HR> <ADDRESS> SheepShaver User's Guide </ADDRESS> </BODY> </HTML>
kallisti5/sheepshear
doc/Haiku/contact.html
HTML
gpl-2.0
1,575
#undef CONFIG_BUNZIP2
Voskrese/mipsonqemu
user/busybox/include/config/bunzip2.h
C
gpl-2.0
22
<?php /** * @file * This template outputs the description field. * * Variables: * - $title * - $artist * - $album * - $year * - $track * - $genre * - $id3 (Full ID3 Array) */ ?> <?php print $title .' '. t('by') .' '. $artist; ?>
benmirkhah/jadu
sites/all/modules/mp3player/filefieldmp3player/theme/description.tpl.php
PHP
gpl-2.0
241
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Fail2Ban is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Author: Cyril Jaquier # __author__ = "Cyril Jaquier" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" import logging.handlers # Custom debug levels logging.MSG = logging.INFO - 2 logging.TRACEDEBUG = 7 logging.HEAVYDEBUG = 5 logging.addLevelName(logging.MSG, 'MSG') logging.addLevelName(logging.TRACEDEBUG, 'TRACE') logging.addLevelName(logging.HEAVYDEBUG, 'HEAVY') """ Below derived from: https://mail.python.org/pipermail/tutor/2007-August/056243.html """ logging.NOTICE = logging.INFO + 5 logging.addLevelName(logging.NOTICE, 'NOTICE') # define a new logger function for notice # this is exactly like existing info, critical, debug...etc def _Logger_notice(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'NOTICE'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.notice("Houston, we have a %s", "major disaster", exc_info=1) """ if self.isEnabledFor(logging.NOTICE): self._log(logging.NOTICE, msg, args, **kwargs) logging.Logger.notice = _Logger_notice # define a new root level notice function # this is exactly like existing info, critical, debug...etc def _root_notice(msg, *args, **kwargs): """ Log a message with severity 'NOTICE' on the root logger. """ if len(logging.root.handlers) == 0: logging.basicConfig() logging.root.notice(msg, *args, **kwargs) # make the notice root level function known logging.notice = _root_notice # add NOTICE to the priority map of all the levels logging.handlers.SysLogHandler.priority_map['NOTICE'] = 'notice' from time import strptime # strptime thread safety hack-around - http://bugs.python.org/issue7980 strptime("2012", "%Y") # short names for pure numeric log-level ("Level 25" could be truncated by short formats): def _init(): for i in range(50): if logging.getLevelName(i).startswith('Level'): logging.addLevelName(i, '#%02d-Lev.' % i) _init()
nawawi/fail2ban
fail2ban/__init__.py
Python
gpl-2.0
2,770
// Locale support -*- C++ -*- // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, // 2006, 2007 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. /** @file ctype_noninline.h * This is an internal header file, included by other library headers. * You should not attempt to use it directly. */ // // ISO C++ 14882: 22.1 Locales // // Information as gleaned from /usr/include/ctype.h #if _GLIBCXX_C_LOCALE_GNU const ctype_base::mask* ctype<char>::classic_table() throw() { return _S_get_c_locale()->__ctype_b; } #else const ctype_base::mask* ctype<char>::classic_table() throw() { const ctype_base::mask* __ret; char* __old = setlocale(LC_CTYPE, NULL); char* __sav = NULL; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); setlocale(LC_CTYPE, "C"); } #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) __ret = *__ctype_b_loc(); #else __ret = __ctype_b; #endif if (__sav) { setlocale(LC_CTYPE, __sav); delete [] __sav; } return __ret; } #endif #if _GLIBCXX_C_LOCALE_GNU ctype<char>::ctype(__c_locale __cloc, const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_clone_c_locale(__cloc)), _M_del(__table != 0 && __del), _M_toupper(_M_c_locale_ctype->__ctype_toupper), _M_tolower(_M_c_locale_ctype->__ctype_tolower), _M_table(__table ? __table : _M_c_locale_ctype->__ctype_b), _M_widen_ok(0), _M_narrow_ok(0) { __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #else ctype<char>::ctype(__c_locale, const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_get_c_locale()), _M_del(__table != 0 && __del), _M_widen_ok(0), _M_narrow_ok(0) { char* __old = setlocale(LC_CTYPE, NULL); char* __sav = NULL; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); setlocale(LC_CTYPE, "C"); } #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) _M_toupper = *__ctype_toupper_loc(); _M_tolower = *__ctype_tolower_loc(); _M_table = __table ? __table : *__ctype_b_loc(); #else _M_toupper = __ctype_toupper; _M_tolower = __ctype_tolower; _M_table = __table ? __table : __ctype_b; #endif if (__sav) { setlocale(LC_CTYPE, __sav); delete [] __sav; } __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #endif #if _GLIBCXX_C_LOCALE_GNU ctype<char>::ctype(const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_get_c_locale()), _M_del(__table != 0 && __del), _M_toupper(_M_c_locale_ctype->__ctype_toupper), _M_tolower(_M_c_locale_ctype->__ctype_tolower), _M_table(__table ? __table : _M_c_locale_ctype->__ctype_b), _M_widen_ok(0), _M_narrow_ok(0) { __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #else ctype<char>::ctype(const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_get_c_locale()), _M_del(__table != 0 && __del), _M_widen_ok(0), _M_narrow_ok(0) { char* __old = setlocale(LC_CTYPE, NULL); char* __sav = NULL; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); setlocale(LC_CTYPE, "C"); } #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) _M_toupper = *__ctype_toupper_loc(); _M_tolower = *__ctype_tolower_loc(); _M_table = __table ? __table : *__ctype_b_loc(); #else _M_toupper = __ctype_toupper; _M_tolower = __ctype_tolower; _M_table = __table ? __table : __ctype_b; #endif if (__sav) { setlocale(LC_CTYPE, __sav); delete [] __sav; } __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #endif char ctype<char>::do_toupper(char __c) const { return _M_toupper[static_cast<unsigned char>(__c)]; } const char* ctype<char>::do_toupper(char* __low, const char* __high) const { while (__low < __high) { *__low = _M_toupper[static_cast<unsigned char>(*__low)]; ++__low; } return __high; } char ctype<char>::do_tolower(char __c) const { return _M_tolower[static_cast<unsigned char>(__c)]; } const char* ctype<char>::do_tolower(char* __low, const char* __high) const { while (__low < __high) { *__low = _M_tolower[static_cast<unsigned char>(*__low)]; ++__low; } return __high; }
epicsdeb/rtems-gcc-newlib
libstdc++-v3/config/os/gnu-linux/ctype_noninline.h
C
gpl-2.0
6,176
/* { dg-do compile } */ /* { dg-options "-O2 -fdump-tree-ccp1" } */ typedef char char16[16] __attribute__ ((aligned (16))); char16 c16[4] __attribute__ ((aligned (4))); int f5 (int i) { __SIZE_TYPE__ s = (__SIZE_TYPE__)&c16[i]; /* 0 */ return 3 & s; } /* { dg-final { scan-tree-dump "return 0;" "ccp1" } } */ /* { dg-final { cleanup-tree-dump "ccp1" } } */
totalspectrum/gcc-propeller
gcc/testsuite/gcc.dg/tree-ssa/ssa-ccp-35.c
C
gpl-2.0
366
// Copyright (C) 2019-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-options "-std=gnu++11" } // { dg-do compile { target c++11 } } // This macro should have no effect now #define _GLIBCXX_PROFILE 1 #include <vector>
Gurgel100/gcc
libstdc++-v3/testsuite/17_intro/headers/c++2011/profile_mode.cc
C++
gpl-2.0
921
/* * Copyright (c) 2014, The Linux Foundation. All rights reserved. * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all copies. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "sw.h" #include "sw_ioctl.h" #include "fal_cosmap.h" #include "fal_uk_if.h" sw_error_t fal_cosmap_dscp_to_pri_set(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t pri) { sw_error_t rv; rv= sw_uk_exec(SW_API_COSMAP_DSCP_TO_PRI_SET, dev_id, dscp, pri); return rv; } sw_error_t fal_cosmap_dscp_to_pri_get(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_DSCP_TO_PRI_GET, dev_id, dscp, (a_uint32_t)pri); return rv; } sw_error_t fal_cosmap_dscp_to_dp_set(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t dp) { sw_error_t rv; rv= sw_uk_exec(SW_API_COSMAP_DSCP_TO_DP_SET, dev_id, dscp, dp); return rv; } sw_error_t fal_cosmap_dscp_to_dp_get(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_DSCP_TO_DP_GET, dev_id, dscp, (a_uint32_t)dp); return rv; } sw_error_t fal_cosmap_up_to_pri_set(a_uint32_t dev_id, a_uint32_t up, a_uint32_t pri) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_PRI_SET, dev_id, up, pri); return rv; } sw_error_t fal_cosmap_up_to_pri_get(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_PRI_GET, dev_id, up, (a_uint32_t)pri); return rv; } sw_error_t fal_cosmap_up_to_dp_set(a_uint32_t dev_id, a_uint32_t up, a_uint32_t dp) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_DP_SET, dev_id, up, dp); return rv; } sw_error_t fal_cosmap_up_to_dp_get(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_DP_GET, dev_id, up, (a_uint32_t)dp); return rv; } sw_error_t fal_cosmap_pri_to_queue_set(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t queue) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_PRI_TO_QU_SET, dev_id, pri, queue); return rv; } sw_error_t fal_cosmap_pri_to_queue_get(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t * queue) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_PRI_TO_QU_GET, dev_id, pri, (a_uint32_t)queue); return rv; } sw_error_t fal_cosmap_pri_to_ehqueue_set(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t queue) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_PRI_TO_EHQU_SET, dev_id, pri, queue); return rv; } sw_error_t fal_cosmap_pri_to_ehqueue_get(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t * queue) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_PRI_TO_EHQU_GET, dev_id, pri, (a_uint32_t)queue); return rv; } sw_error_t fal_cosmap_egress_remark_set(a_uint32_t dev_id, a_uint32_t tbl_id, fal_egress_remark_table_t * tbl) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_EG_REMARK_SET, dev_id, tbl_id, tbl); return rv; } sw_error_t fal_cosmap_egress_remark_get(a_uint32_t dev_id, a_uint32_t tbl_id, fal_egress_remark_table_t * tbl) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_EG_REMARK_GET, dev_id, tbl_id, tbl); return rv; } sw_error_t fal_cosmap_dscp_to_ehpri_set(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t pri) { sw_error_t rv; rv= sw_uk_exec(SW_API_COSMAP_DSCP_TO_EHPRI_SET, dev_id, dscp, pri); return rv; } sw_error_t fal_cosmap_dscp_to_ehpri_get(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_DSCP_TO_EHPRI_GET, dev_id, dscp, (a_uint32_t)pri); return rv; } sw_error_t fal_cosmap_dscp_to_ehdp_set(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t dp) { sw_error_t rv; rv= sw_uk_exec(SW_API_COSMAP_DSCP_TO_EHDP_SET, dev_id, dscp, dp); return rv; } sw_error_t fal_cosmap_dscp_to_ehdp_get(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_DSCP_TO_EHDP_GET, dev_id, dscp, (a_uint32_t)dp); return rv; } sw_error_t fal_cosmap_up_to_ehpri_set(a_uint32_t dev_id, a_uint32_t up, a_uint32_t pri) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_EHPRI_SET, dev_id, up, pri); return rv; } sw_error_t fal_cosmap_up_to_ehpri_get(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_EHPRI_GET, dev_id, up, (a_uint32_t)pri); return rv; } sw_error_t fal_cosmap_up_to_ehdp_set(a_uint32_t dev_id, a_uint32_t up, a_uint32_t dp) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_EHDP_SET, dev_id, up, dp); return rv; } sw_error_t fal_cosmap_up_to_ehdp_get(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(SW_API_COSMAP_UP_TO_EHDP_GET, dev_id, up, (a_uint32_t)dp); return rv; }
paul-chambers/netgear-r7800
package/qca-ssdk-shell/src/src/fal_uk/fal_cosmap.c
C
gpl-2.0
5,610
<?php /** * @version: $Id: dbobject.php 4387 2015-02-19 12:24:35Z Radek Suski $ * @package: SobiPro Library * @author * Name: Sigrid Suski & Radek Suski, Sigsiu.NET GmbH * Email: sobi[at]sigsiu.net * Url: http://www.Sigsiu.NET * @copyright Copyright (C) 2006 - 2015 Sigsiu.NET GmbH (http://www.sigsiu.net). All rights reserved. * @license GNU/LGPL Version 3 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation, and under the additional terms according section 7 of GPL v3. * See http://www.gnu.org/licenses/lgpl.html and http://sobipro.sigsiu.net/licenses. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * $Date: 2015-02-19 13:24:35 +0100 (Thu, 19 Feb 2015) $ * $Revision: 4387 $ * $Author: Radek Suski $ * $HeadURL: file:///opt/svn/SobiPro/Component/branches/SobiPro-1.1/Site/lib/models/dbobject.php $ */ defined( 'SOBIPRO' ) || exit( 'Restricted access' ); /** * @author Radek Suski * @version 1.0 * @created 10-Jan-2009 5:24:28 PM */ abstract class SPDBObject extends SPObject { /** * @var bool */ protected $approved = false; /** * @var bool */ protected $confirmed = false; /** * @var int */ protected $counter = 0; /** * @var int */ protected $section = 0; /** * @var bool */ protected $cout = false; /** * @var string */ protected $coutTime = null; /** * @var string */ protected $createdTime = null; /** * @var string */ protected $defURL = null; /** * @var int database object id */ protected $id = 0; /** * @var string */ protected $nid = null; /** * @var string */ protected $metaDesc = null; /** * @var string */ protected $metaKeys = null; /** * @var string */ protected $metaAuthor = null; /** * @var string */ protected $metaRobots = null; /** * @var string */ protected $name = null; /** * @var array */ protected $options = array(); /** * @var string */ protected $oType = null; /** * @var int */ protected $owner = 0; /** * @var string */ protected $ownerIP = null; /** * @var array */ protected $params = array(); /** * @var int */ protected $parent = 0; /** * @var string */ protected $query = null; /** * @var int */ protected $state = 0; /** * @var string */ protected $stateExpl = null; /** * @var string */ protected $template = null; /** * @var string */ protected $updatedTime = null; /** * @var int */ protected $updater = 0; /** * @var string */ protected $updaterIP = null; /** * @var string */ protected $validSince = null; /** * @var string */ protected $validUntil = null; /** * @var int */ protected $version = 0; /** * @var array */ protected $properties = array(); /** * @param string $name * @param array $data */ public function setProperty( $name, $data ) { $this->properties[ $name ] = $data; } /** * list of adjustable properties and the corresponding request method for each property. * If a property isn't declared here, it will be ignored in the getRequest method * @var array */ private static $types = array( 'approved' => 'bool', 'state' => 'int', 'confirmed' => 'bool', 'counter' => 'int', 'createdTime' => 'timestamp', 'defURL' => 'string', 'metaAuthor' => 'string', 'metaDesc' => 'string', 'metaKeys' => 'string', 'metaRobots' => 'string', 'name' => 'string', 'nid' => 'cmd', /** * the id is not needed (and it's dangerous) because if we updating an object it's being created through the id anyway * so at that point we have to already have it. If not, we don't need it because then we are creating a new object */ // 'id' => 'int', 'owner' => 'int', 'ownerIP' => 'ip', 'parent' => 'int', 'stateExpl' => 'string', 'validSince' => 'timestamp', 'validUntil' => 'timestamp', ); /** * @var array */ private static $translatable = array( 'nid', 'metaDesc', 'metaKeys' ); /** * @return \SPDBObject */ public function __construct() { $this->validUntil = SPFactory::config()->date( SPFactory::db()->getNullDate(), 'date.db_format' ); $this->createdTime = SPFactory::config()->date( gmdate( 'U' ), 'date.db_format', null, true ); $this->validSince = SPFactory::config()->date( gmdate( 'U' ), 'date.db_format', null, true ); $this->ownerIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updaterIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updater = Sobi::My( 'id' ); $this->owner = Sobi::My( 'id' ); $this->updatedTime = SPFactory::config()->date( time(), 'date.db_format' ); Sobi::Trigger( 'CreateModel', $this->name(), array( &$this ) ); } public function formatDatesToEdit() { if ( $this->validUntil ) { $this->validUntil = SPFactory::config()->date( $this->validUntil, 'date.publishing_format' ); } $this->createdTime = SPFactory::config()->date( $this->createdTime, 'date.publishing_format' ); $this->validSince = SPFactory::config()->date( $this->validSince, 'date.publishing_format' ); } /** * @param int $state * @param string $reason */ public function changeState( $state, $reason = null ) { try { SPFactory::db()->update( 'spdb_object', array( 'state' => ( int )$state, 'stateExpl' => $reason ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } SPFactory::cache() ->purgeSectionVars() ->deleteObj( $this->type(), $this->id ) ->deleteObj( 'category', $this->parent ); } /** * Checking in current object */ public function checkIn() { if ( $this->id ) { $this->cout = 0; $this->coutTime = null; try { SPFactory::db()->update( 'spdb_object', array( 'coutTime' => $this->coutTime, 'cout' => $this->cout ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } } /** * checking out current object */ public function checkOut() { if ( $this->id ) { /* @var SPdb $db */ $config =& SPFactory::config(); $this->cout = Sobi::My( 'id' ); $this->coutTime = $config->date( ( time() + $config->key( 'editing.def_cout_time', 3600 ) ), 'date.db_format' ); try { SPFactory::db()->update( 'spdb_object', array( 'coutTime' => $this->coutTime, 'cout' => $this->cout ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } } /** */ public function delete() { Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( $this->id ) ); try { SPFactory::db()->delete( 'spdb_object', array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } try { SPFactory::db()->delete( 'spdb_relations', array( 'id' => $this->id, 'oType' => $this->type() ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } try { SPFactory::db()->delete( 'spdb_language', array( 'id' => $this->id, 'oType' => $this->type() ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } /** * @param string $type * @param bool $recursive * @param int $state * @param bool $name * @return array */ public function getChilds( $type = 'entry', $recursive = false, $state = 0, $name = false ) { static $lang = null; if ( !( $lang ) ) { $lang = Sobi::Lang( false ); } $childs = SPFactory::cache()->getVar( 'childs_' . $lang . $type . ( $recursive ? '_recursive' : '' ) . ( $name ? '_full' : '' ) . $state, $this->id ); if ( $childs ) { return $childs == SPC::NO_VALUE ? array() : $childs; } $db = SPFactory::db(); $childs = array(); try { $cond = array( 'pid' => $this->id ); if ( $state ) { $cond[ 'so.state' ] = $state; $cond[ 'so.approved' ] = $state; $tables = $db->join( array( array( 'table' => 'spdb_object', 'as' => 'so', 'key' => 'id' ), array( 'table' => 'spdb_relations', 'as' => 'sr', 'key' => 'id' ) ) ); $db->select( array( 'sr.id', 'sr.oType' ), $tables, $cond ); } else { $db->select( array( 'id', 'oType' ), 'spdb_relations', $cond ); } $results = $db->loadAssocList( 'id' ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_GET_CHILDS_DB_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( $recursive && count( $results ) ) { foreach ( $results as $cid ) { $this->rGetChilds( $results, $cid, $type ); } } if ( count( $results ) ) { if ( $type == 'all' ) { foreach ( $results as $id => $r ) { $childs[ $id ] = $r[ 'id' ]; } } else { foreach ( $results as $id => $r ) { if ( $r[ 'oType' ] == $type ) { $childs[ $id ] = $id; } } } } if ( $name && count( $childs ) ) { $names = SPLang::translateObject( $childs, array( 'name', 'alias' ), $type ); if ( is_array( $names ) && !empty( $names ) ) { foreach ( $childs as $i => $id ) { $childs[ $i ] = array( 'name' => $names[ $id ][ 'value' ], 'alias' => $names[ $id ][ 'alias' ] ); } } } if ( !$state ) { SPFactory::cache()->addVar( $childs, 'childs_' . $lang . $type . ( $recursive ? '_recursive' : '' ) . ( $name ? '_full' : '' ) . $state, $this->id ); } return $childs; } /** * @param array $results * @param string $type * @param int $id */ private function rGetChilds( &$results, $id, $type = 'entry' ) { if ( is_array( $id ) ) { $id = $id[ 'id' ]; } /* @var SPdb $db */ $db =& SPFactory::db(); try { $cond = array( 'pid' => $id ); /** Tue, Mar 25, 2014 12:46:08 - it's a recursive function so we need entries and categories * See Issue #1211 * Thanks Marcel * */ // if ( $type ) { // $cond[ 'oType' ] = $type; // } $r = $db->select( array( 'id', 'oType' ), 'spdb_relations', $cond ) ->loadAssocList( 'id' ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_GET_CHILDS_DB_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( count( $r ) ) { foreach ( $r as $id => $rs ) { if ( $rs[ 'oType' ] == 'entry' ) { continue; } $results[ $id ] = $rs; $this->rGetChilds( $results, $id, $type ); } } } /** */ protected function createAlias() { /* check nid */ $c = 1; static $add = 0; $suffix = null; if ( !( strlen( $this->nid ) ) ) { $this->nid = SPLang::nid( $this->name, true ); } while ( $c ) { try { $condition = array( 'oType' => $this->oType, 'nid' => $this->nid . $suffix ); if ( $this->id ) { $condition[ '!id' ] = $this->id; } $c = SPFactory::db() ->select( 'COUNT( nid )', 'spdb_object', $condition ) ->loadResult(); if ( $c > 0 ) { $suffix = '_' . ++$add; } } catch ( SPException $x ) { } } return $this->nid . $suffix; } /** * Gettin data from request for this object * @param string $prefix * @param string $request */ public function getRequest( $prefix = null, $request = 'POST' ) { $prefix = $prefix ? $prefix . '_' : null; /* get data types of my properties */ $properties = get_object_vars( $this ); Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$properties ) ); /* and of the parent properties */ $types = array_merge( $this->types(), self::$types ); foreach ( $properties as $property => $values ) { /* if this is an internal variable */ if ( substr( $property, 0, 1 ) == '_' ) { continue; } /* if no data type has been declared */ if ( !isset( $types[ $property ] ) ) { continue; } /* if there was no data for this property ( not if it was just empty ) */ if ( !( SPRequest::exists( $prefix . $property, $request ) ) ) { continue; } /* if the declared data type has not handler in request class */ if ( !method_exists( 'SPRequest', $types[ $property ] ) ) { Sobi::Error( $this->name(), SPLang::e( 'Method %s does not exist!', $types[ $property ] ), SPC::WARNING, 0, __LINE__, __FILE__ ); continue; } /* now we get it ;) */ $this->$property = SPRequest::$types[ $property ]( $prefix . $property, null, $request ); } /* trigger plugins */ Sobi::Trigger( 'getRequest', $this->name(), array( &$this ) ); } public function countChilds( $type = null, $state = 0 ) { return count( $this->getChilds( $type, true, $state ) ); } /** * @return string */ public function type() { return $this->oType; } public function countVisit( $reset = false ) { $count = true; Sobi::Trigger( 'CountVisit', ucfirst( $this->type() ), array( &$count, $this->id ) ); if ( $this->id && $count ) { try { SPFactory::db()->insertUpdate( 'spdb_counter', array( 'sid' => $this->id, 'counter' => ( $reset ? '0' : ++$this->counter ), 'lastUpdate' => 'FUNCTION:NOW()' ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_INC_COUNTER_DB', $x->getMessage() ), SPC::ERROR, 0, __LINE__, __FILE__ ); } } } /** */ public function save( $request = 'post' ) { $this->version++; /* get current data */ $this->updatedTime = SPRequest::now(); $this->updaterIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updater = Sobi::My( 'id' ); $this->nid = SPLang::nid( $this->nid, true ); if ( !( $this->nid ) ) { $this->nid = SPLang::nid( $this->name, true ); } /* get THIS class properties */ $properties = get_class_vars( __CLASS__ ); /* if new object */ if ( !$this->id ) { /** @var the notification App is using it to recognise if it is a new entry or an update */ $this->createdTime = $this->updatedTime; $this->owner = $this->owner ? $this->owner : $this->updater; $this->ownerIP = $this->updaterIP; } /* just a security check to avoid mistakes */ else { /** Fri, Dec 19, 2014 19:33:52 * When storing it we should actually get already UTC unix time stamp * so there is not need to remove it again */ // $this->createdTime = $this->createdTime && is_numeric( $this->createdTime ) ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->createdTime - SPFactory::config()->getTimeOffset() ) : $this->createdTime; $this->createdTime = $this->createdTime && is_numeric( $this->createdTime ) ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->createdTime ) : $this->createdTime; $obj = SPFactory::object( $this->id ); if ( $obj->oType != $this->oType ) { Sobi::Error( 'Object Save', sprintf( 'Serious security violation. Trying to save an object which claims to be an %s but it is a %s. Task was %s', $this->oType, $obj->oType, SPRequest::task() ), SPC::ERROR, 403, __LINE__, __FILE__ ); exit; } } if ( is_numeric( $this->validUntil ) ) { // $this->validUntil = $this->validUntil ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validUntil - SPFactory::config()->getTimeOffset() ) : null; $this->validUntil = $this->validUntil ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validUntil ) : null; } if ( is_numeric( $this->validSince ) ) { $this->validSince = $this->validSince ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validSince ) : null; } /* @var SPdb $db */ $db = SPFactory::db(); $db->transaction(); /* get database columns and their ordering */ $cols = $db->getColumns( 'spdb_object' ); $values = array(); /* * @todo: manage own is not implemented yet */ //$this->approved = Sobi::Can( $this->type(), 'manage', 'own' ); /* if not published, check if user can manage own and if yes, publish it */ if ( !( $this->state ) && !( defined( 'SOBIPRO_ADM' ) ) ) { $this->state = Sobi::Can( $this->type(), 'publish', 'own' ); } if ( !( defined( 'SOBIPRO_ADM' ) ) ) { $this->approved = Sobi::Can( $this->type(), 'publish', 'own' ); } // elseif ( defined( 'SOBIPRO_ADM' ) ) { // $this->approved = Sobi::Can( $this->type(), 'publish', 'own' ); // } /* and sort the properties in the same order */ foreach ( $cols as $col ) { $values[ $col ] = array_key_exists( $col, $properties ) ? $this->$col : ''; } /* trigger plugins */ Sobi::Trigger( 'save', $this->name(), array( &$this ) ); /* try to save */ try { /* if new object */ if ( !$this->id ) { $db->insert( 'spdb_object', $values ); $this->id = $db->insertid(); } /* if update */ else { $db->update( 'spdb_object', $values, array( 'id' => $this->id ) ); } } catch ( SPException $x ) { $db->rollback(); Sobi::Error( $this->name(), SPLang::e( 'CANNOT_SAVE_OBJECT_DB_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } /* get translatable properties */ $attributes = array_merge( $this->translatable(), self::$translatable ); $labels = array(); $defLabels = array(); foreach ( $attributes as $attr ) { if ( $this->has( $attr ) ) { $labels[ ] = array( 'sKey' => $attr, 'sValue' => $this->$attr, 'language' => Sobi::Lang(), 'id' => $this->id, 'oType' => $this->type(), 'fid' => 0 ); if ( Sobi::Lang() != Sobi::DefLang() ) { $defLabels[ ] = array( 'sKey' => $attr, 'sValue' => $this->$attr, 'language' => Sobi::DefLang(), 'id' => $this->id, 'oType' => $this->type(), 'fid' => 0 ); } } } /* save translatable properties */ if ( count( $labels ) ) { try { if ( Sobi::Lang() != Sobi::DefLang() ) { $db->insertArray( 'spdb_language', $defLabels, false, true ); } $db->insertArray( 'spdb_language', $labels, true ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_SAVE_OBJECT_DB_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } } $db->commit(); $this->checkIn(); } /** * Dummy function */ public function update() { return $this->save(); } /** * @param stdClass $obj */ public function extend( $obj, $cache = false ) { if ( !empty( $obj ) ) { foreach ( $obj as $k => $v ) { $this->_set( $k, $v ); } } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$obj ) ); $this->loadTable( $cache ); $this->validUntil = SPFactory::config()->date( $this->validUntil, 'Y-m-d H:i:s' ); } /** * @param int $id * @return \SPDBObject * @internal param \stdClass $obj */ public function & init( $id = 0 ) { Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$id ) ); $this->id = $id ? $id : $this->id; if ( $this->id ) { try { $obj = SPFactory::object( $this->id ); if ( !empty( $obj ) ) { /* ensure that the id was right */ if ( $obj->oType == $this->oType ) { $this->extend( $obj ); } else { $this->id = 0; } } $this->createdTime = SPFactory::config()->date( $this->createdTime ); $this->validSince = SPFactory::config()->date( $this->validSince ); if ( $this->validUntil ) { $this->validUntil = SPFactory::config()->date( $this->validUntil ); } } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_GET_OBJECT_DB_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } $this->loadTable(); } return $this; } /** */ public function load( $id ) { return $this->init( $id ); } /** */ public function loadTable() { if ( $this->has( '_dbTable' ) && $this->_dbTable ) { try { $db = SPFactory::db(); $obj = $db->select( '*', $this->_dbTable, array( 'id' => $this->id ) ) ->loadObject(); $counter = $db->select( 'counter', 'spdb_counter', array( 'sid' => $this->id ) ) ->loadResult(); if ( $counter !== null ) { $this->counter = $counter; } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$obj ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( !empty( $obj ) ) { foreach ( $obj as $k => $v ) { $this->_set( $k, $v ); } } else { Sobi::Error( $this->name(), SPLang::e( 'NO_ENTRIES' ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } $this->translate(); } /** */ protected function translate() { $attributes = array_merge( $this->translatable(), self::$translatable ); Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$attributes ) ); $db =& SPFactory::db(); try { $labels = $db ->select( 'sValue, sKey', 'spdb_language', array( 'id' => $this->id, 'sKey' => $attributes, 'language' => Sobi::Lang(), 'oType' => $this->type() ) ) ->loadAssocList( 'sKey' ); /* get labels in the default lang first */ if ( Sobi::Lang( false ) != Sobi::DefLang() ) { $dlabels = $db ->select( 'sValue, sKey', 'spdb_language', array( 'id' => $this->id, 'sKey' => $attributes, 'language' => Sobi::DefLang(), 'oType' => $this->type() ) ) ->loadAssocList( 'sKey' ); if ( count( $dlabels ) ) { foreach ( $dlabels as $k => $v ) { if ( !( isset( $labels[ $k ] ) ) || !( $labels[ $k ] ) ) { $labels[ $k ] = $v; } } } } } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( count( $labels ) ) { foreach ( $labels as $k => $v ) { $this->_set( $k, $v[ 'sValue' ] ); } } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$labels ) ); } /** * @param string $var * @param mixed $val */ protected function _set( $var, $val ) { if ( $this->has( $var ) ) { if ( is_array( $this->$var ) && is_string( $val ) && strlen( $val ) > 2 ) { try { $val = SPConfig::unserialize( $val, $var ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '%s.', $x->getMessage() ), SPC::NOTICE, 0, __LINE__, __FILE__ ); } } $this->$var = $val; } } /** * @return bool */ public function isCheckedOut() { if ( $this->cout && $this->cout != Sobi::My( 'id' ) && strtotime( $this->coutTime ) > time() ) { return true; } else { return false; } } /** * @param string $var * @param mixed $val * @return \SPObject|void */ public function set( $var, $val ) { static $types = array(); if ( !count( $types ) ) { $types = array_merge( $this->types(), self::$types ); } if ( $this->has( $var ) && isset( $types[ $var ] ) ) { if ( is_array( $this->$var ) && is_string( $val ) && strlen( $val ) > 2 ) { try { $val = SPConfig::unserialize( $val, $var ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '%s.', $x->getMessage() ), SPC::NOTICE, 0, __LINE__, __FILE__ ); } } $this->$var = $val; } } /** * @return array */ protected function translatable() { return array(); } }
vstorm83/propertease
components/com_sobipro/lib/models/dbobject.php
PHP
gpl-2.0
23,563
# -*- coding: utf-8 -*- # # python-problem documentation build configuration file, created by # sphinx-quickstart on Tue Dec 4 12:03:58 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('../problem/.libs')) # _pyabrt # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'abrt-python' copyright = u'2012, Richard Marko' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'abrt-pythondoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'abrt-python.tex', u'abrt-python Documentation', u'Richard Marko', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'abrt-python', u'abrt-python Documentation', [u'Richard Marko'], 5) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'abrt-python', u'abrt-python Documentation', u'Richard Marko', 'abrt-python', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' def setup(app): app.connect('autodoc-process-signature', process_signature) def process_signature(app, what, name, obj, options, signature, return_annotation): if what not in ('function'): return new_params = list() for param in (x.strip() for x in signature[1:-1].split(',')): if '__' not in param: new_params.append(param) return ('(%s)' % ', '.join(new_params), return_annotation)
mhabrnal/abrt
src/python-problem/doc/conf.py
Python
gpl-2.0
8,344
/* emul-target.h. Default values for struct emulation defined in emul.h Copyright 1995, 2007 Free Software Foundation, Inc. This file is part of GAS, the GNU Assembler. GAS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GAS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GAS; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef emul_init #define emul_init common_emul_init #endif #ifndef emul_bfd_name #define emul_bfd_name default_emul_bfd_name #endif #ifndef emul_local_labels_fb #define emul_local_labels_fb 0 #endif #ifndef emul_local_labels_dollar #define emul_local_labels_dollar 0 #endif #ifndef emul_leading_underscore #define emul_leading_underscore 2 #endif #ifndef emul_strip_underscore #define emul_strip_underscore 0 #endif #ifndef emul_default_endian #define emul_default_endian 2 #endif #ifndef emul_fake_label_name #define emul_fake_label_name 0 #endif struct emulation emul_struct_name = { 0, emul_name, emul_init, emul_bfd_name, emul_local_labels_fb, emul_local_labels_dollar, emul_leading_underscore, emul_strip_underscore, emul_default_endian, emul_fake_label_name, emul_format, };
wanghao-xznu/vte
openlibs/binutils-2.19.51.0.12/gas/emul-target.h
C
gpl-2.0
1,715
/* * Copyright (c) 2016-2019 Projekt Substratum * This file is part of Substratum. * * SPDX-License-Identifier: GPL-3.0-Or-Later */ package projekt.substratum.common; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import projekt.substratum.Substratum; import projekt.substratum.services.crash.AppCrashReceiver; import projekt.substratum.services.packages.OverlayFound; import projekt.substratum.services.packages.OverlayUpdater; import projekt.substratum.services.packages.PackageModificationDetector; import projekt.substratum.services.profiles.ScheduledProfileReceiver; import projekt.substratum.services.system.InterfacerAuthorizationReceiver; import static projekt.substratum.common.Internal.ENCRYPTION_KEY_EXTRA; import static projekt.substratum.common.Internal.IV_ENCRYPTION_KEY_EXTRA; import static projekt.substratum.common.Internal.MAIN_ACTIVITY_RECEIVER; import static projekt.substratum.common.Internal.OVERLAY_REFRESH; import static projekt.substratum.common.Internal.THEME_FRAGMENT_REFRESH; import static projekt.substratum.common.References.ACTIVITY_FINISHER; import static projekt.substratum.common.References.APP_CRASHED; import static projekt.substratum.common.References.INTERFACER_PACKAGE; import static projekt.substratum.common.References.KEY_RETRIEVAL; import static projekt.substratum.common.References.MANAGER_REFRESH; import static projekt.substratum.common.References.PACKAGE_ADDED; import static projekt.substratum.common.References.PACKAGE_FULLY_REMOVED; import static projekt.substratum.common.References.SUBSTRATUM_LOG; import static projekt.substratum.common.References.TEMPLATE_RECEIVE_KEYS; import static projekt.substratum.common.References.scheduledProfileReceiver; public class Broadcasts { /** * Send a localized key message for encryption to take place * * @param context Context * @param encryptionKey Encryption key * @param ivEncryptKey IV encryption key */ private static void sendLocalizedKeyMessage(Context context, byte[] encryptionKey, byte[] ivEncryptKey) { Substratum.log("KeyRetrieval", "The system has completed the handshake for keys retrieval " + "and is now passing it to the activity..."); Intent intent = new Intent(KEY_RETRIEVAL); intent.putExtra(ENCRYPTION_KEY_EXTRA, encryptionKey); intent.putExtra(IV_ENCRYPTION_KEY_EXTRA, ivEncryptKey); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * Close Substratum as a whole * * @param context Context */ public static void sendKillMessage(Context context) { Substratum.log("SubstratumKiller", "A crucial action has been conducted by the user and " + "Substratum is now shutting down!"); Intent intent = new Intent(MAIN_ACTIVITY_RECEIVER); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the ThemeFragment * * @param context Context */ public static void sendRefreshMessage(Context context) { Substratum.log("ThemeFragmentRefresher", "A theme has been modified, sending update signal to refresh the list!"); Intent intent = new Intent(THEME_FRAGMENT_REFRESH); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the Overlays tab * * @param context Context */ public static void sendOverlayRefreshMessage(Context context) { Substratum.log("OverlayRefresher", "A theme has been modified, sending update signal to refresh the list!"); Intent intent = new Intent(OVERLAY_REFRESH); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * Activity finisher when a theme was updated * * @param context Context * @param packageName Package of theme to close */ public static void sendActivityFinisherMessage(Context context, String packageName) { Substratum.log("ThemeInstaller", "A theme has been installed, sending update signal to app for further processing!"); Intent intent = new Intent(ACTIVITY_FINISHER); intent.putExtra(Internal.THEME_PID, packageName); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the ManagerFragment * * @param context Context */ public static void sendRefreshManagerMessage(Context context) { Intent intent = new Intent(MANAGER_REFRESH); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * Register the implicit intent broadcast receivers * * @param context Context */ public static void registerBroadcastReceivers(Context context) { try { IntentFilter intentPackageAdded = new IntentFilter(PACKAGE_ADDED); intentPackageAdded.addDataScheme("package"); IntentFilter intentPackageFullyRemoved = new IntentFilter(PACKAGE_FULLY_REMOVED); intentPackageFullyRemoved.addDataScheme("package"); if (Systems.checkOMS(context)) { IntentFilter intentAppCrashed = new IntentFilter(APP_CRASHED); context.getApplicationContext().registerReceiver( new AppCrashReceiver(), intentAppCrashed); context.getApplicationContext().registerReceiver( new OverlayUpdater(), intentPackageAdded); } if (Systems.checkThemeInterfacer(context)) { IntentFilter interfacerAuthorize = new IntentFilter( INTERFACER_PACKAGE + ".CALLER_AUTHORIZED"); context.getApplicationContext().registerReceiver( new InterfacerAuthorizationReceiver(), interfacerAuthorize); } context.getApplicationContext().registerReceiver( new OverlayFound(), intentPackageAdded); context.getApplicationContext().registerReceiver( new PackageModificationDetector(), intentPackageAdded); context.getApplicationContext().registerReceiver( new PackageModificationDetector(), intentPackageFullyRemoved); Substratum.log(SUBSTRATUM_LOG, "Successfully registered broadcast receivers for Substratum functionality!"); } catch (Exception e) { Log.e(SUBSTRATUM_LOG, "Failed to register broadcast receivers for Substratum functionality..."); } } /** * Register the profile screen off receiver * * @param context Context */ public static void registerProfileScreenOffReceiver(Context context) { scheduledProfileReceiver = new ScheduledProfileReceiver(); context.registerReceiver(scheduledProfileReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); } /** * Unload the profile screen off receiver * * @param context Context */ public static void unregisterProfileScreenOffReceiver(Context context) { try { context.unregisterReceiver(scheduledProfileReceiver); } catch (Exception ignored) { } } /** * Start the key retrieval receiver to obtain the key from the theme * * @param context Context */ public static void startKeyRetrievalReceiver(Context context) { try { IntentFilter intentGetKeys = new IntentFilter(TEMPLATE_RECEIVE_KEYS); context.getApplicationContext().registerReceiver( new KeyRetriever(), intentGetKeys); Substratum.log(SUBSTRATUM_LOG, "Successfully registered key retrieval receiver!"); } catch (Exception e) { Log.e(SUBSTRATUM_LOG, "Failed to register key retrieval receiver..."); } } /** * Key Retriever Receiver */ public static class KeyRetriever extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { sendLocalizedKeyMessage( context, intent.getByteArrayExtra(ENCRYPTION_KEY_EXTRA), intent.getByteArrayExtra(IV_ENCRYPTION_KEY_EXTRA)); } } }
nicholaschum/substratum
app/src/main/java/projekt/substratum/common/Broadcasts.java
Java
gpl-3.0
8,846
<?php function tous_les_fonds($dir,$pattern){ $liste = find_all_in_path($dir,$pattern); foreach($liste as $k=>$v) $liste[$k] = $dir . basename($v,'.html'); return $liste; } ?>
genova/ugb
plugins/spip-bonux/style_prive_plugins_fonctions.php
PHP
gpl-3.0
182
/* xoreos - A reimplementation of BioWare's Aurora engine * * xoreos is the legal property of its developers, whose names * can be found in the AUTHORS file distributed with this source * distribution. * * xoreos is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * xoreos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xoreos. If not, see <http://www.gnu.org/licenses/>. */ /** @file * Tables defining the engine functions in The Witcher. */ /* The functions are defined by three tables: * - kFunctionPointers * - kFunctionSignatures * - kFunctionDefaults * * kFunctionPointers provides the ID and name of the engine function, and a * pointer to Functions method doing the actual work. If the function pointer * is 0, a default unimplementedFunction method is used that just prints * the name of the function when it's called. * * kFunctionSignatures defines the signature of the function, i.e. the types * of the return value and its parameters. * * kFunctionDefaults pins default values to parameters. I.e. if a function * Foobar(int mode, int doEverything=FALSE) is called with only one parameters, * the default value FALSE is applied to the doEverything parameters. The * kFunctionDefaults entry for the function then contains a reference to a * false value. Because of ambiguities otherwise, the default values have to be * "aligned" to the right; only the last-most n parameters are allowed to have * default values, with no gaps. * * Please note that all three tables have to be of the same length, and that * the order of the functions have to be the same in all three tables. */ #ifndef ENGINES_WITCHER_NWSCRIPT_FUNCTION_TABLES_H #define ENGINES_WITCHER_NWSCRIPT_FUNCTION_TABLES_H #include "src/engines/witcher/types.h" #include "src/engines/witcher/object.h" namespace Engines { namespace Witcher { using Aurora::NWScript::kTypeVoid; using Aurora::NWScript::kTypeInt; using Aurora::NWScript::kTypeFloat; using Aurora::NWScript::kTypeString; using Aurora::NWScript::kTypeObject; using Aurora::NWScript::kTypeVector; using Aurora::NWScript::kTypeEngineType; using Aurora::NWScript::kTypeScriptState; using Aurora::NWScript::kTypeAny; /* Default values as used by the function parameters, if no explicit value * is given at the time of the calling. */ static Witcher::Object kDefaultValueObjectInvalid(kObjectTypeInvalid); static Witcher::Object kDefaultValueObjectSelf (kObjectTypeSelf); static const Aurora::NWScript::Variable kDefaultIntMinus1((int32) - 1); static const Aurora::NWScript::Variable kDefaultInt0 ((int32) 0); static const Aurora::NWScript::Variable kDefaultInt1 ((int32) 1); static const Aurora::NWScript::Variable kDefaultInt9 ((int32) 9); static const Aurora::NWScript::Variable kDefaultInt18 ((int32) 18); static const Aurora::NWScript::Variable kDefaultFloatMinus1_0(- 1.0f); static const Aurora::NWScript::Variable kDefaultFloat0_0 ( 0.0f); static const Aurora::NWScript::Variable kDefaultFloat0_5 ( 0.5f); static const Aurora::NWScript::Variable kDefaultFloat1_0 ( 1.0f); static const Aurora::NWScript::Variable kDefaultFloat30_0 ( 30.0f); static const Aurora::NWScript::Variable kDefaultFloat40_0 ( 40.0f); static const Aurora::NWScript::Variable kDefaultVector0(0.0f, 0.0f, 0.0f); static const Aurora::NWScript::Variable kDefaultStringEmpty(Common::UString("")); static const Aurora::NWScript::Variable kDefaultObjectInvalid(&kDefaultValueObjectInvalid); static const Aurora::NWScript::Variable kDefaultObjectSelf (&kDefaultValueObjectSelf); // TODO: Add the relevant enums to types.h, and use these values. static const Aurora::NWScript::Variable kDefaultCameraTransitionTypeSnap ((int32) 0); static const Aurora::NWScript::Variable kDefaultFalse ((int32) 0); static const Aurora::NWScript::Variable kDefaultGenderMale ((int32) 0); static const Aurora::NWScript::Variable kDefaultObjectTypeAll ((int32) 32767); static const Aurora::NWScript::Variable kDefaultObjectTypeCreature ((int32) 1); static const Aurora::NWScript::Variable kDefaultPersistentZoneActive ((int32) 0); static const Aurora::NWScript::Variable kDefaultProjectilePathTypeDefault((int32) 0); static const Aurora::NWScript::Variable kDefaultTalkVolumeTalk ((int32) 0); static const Aurora::NWScript::Variable kDefaultTrue ((int32) 1); static const Aurora::NWScript::Variable kDefaultFadeSpeedMedium (2.0f); /** The table defining the name and function pointer of each engine function. */ const Functions::FunctionPointer Functions::kFunctionPointers[] = { { 0, "Random" , &Functions::random }, { 1, "PrintString" , &Functions::printString }, { 2, "PrintFloat" , &Functions::printFloat }, { 3, "FloatToString" , &Functions::floatToString }, { 4, "PrintInteger" , &Functions::printInteger }, { 5, "PrintObject" , &Functions::printObject }, { 6, "AssignCommand" , &Functions::assignCommand }, { 7, "DelayCommand" , &Functions::delayCommand }, { 8, "ExecuteScript" , &Functions::executeScript }, { 9, "ClearAllActions" , 0 }, { 10, "SetFacing" , 0 }, { 11, "SetCalendar" , 0 }, { 12, "SetTime" , 0 }, { 13, "GetCalendarYear" , 0 }, { 14, "GetCalendarMonth" , 0 }, { 15, "GetCalendarDay" , 0 }, { 16, "GetTimeHour" , 0 }, { 17, "GetTimeMinute" , 0 }, { 18, "GetTimeSecond" , 0 }, { 19, "GetTimeMillisecond" , 0 }, { 20, "ActionRandomWalk" , 0 }, { 21, "ActionMoveToLocation" , &Functions::actionMoveToLocation }, { 22, "ActionMoveToObject" , &Functions::actionMoveToObject }, { 23, "ActionMoveAwayFromObject" , 0 }, { 24, "GetArea" , &Functions::getArea }, { 25, "GetEnteringObject" , &Functions::getEnteringObject }, { 26, "GetExitingObject" , &Functions::getExitingObject }, { 27, "GetPosition" , &Functions::getPosition }, { 28, "GetFacing" , 0 }, { 29, "GetItemPossessor" , 0 }, { 30, "GetItemPossessedBy" , 0 }, { 31, "CreateItemOnObject" , 0 }, { 32, "ActionEquipItem" , 0 }, { 33, "ActionUnequipItem" , 0 }, { 34, "ActionPickUpItem" , 0 }, { 35, "ActionPutDownItem" , 0 }, { 36, "GetLastAttacker" , 0 }, { 37, "ActionAttack" , 0 }, { 38, "GetNearestCreature" , &Functions::getNearestCreature }, { 39, "ActionSpeakString" , &Functions::actionSpeakString }, { 40, "ActionPlayAnimation" , 0 }, { 41, "GetDistanceToObject" , &Functions::getDistanceToObject }, { 42, "GetIsObjectValid" , &Functions::getIsObjectValid }, { 43, "ActionOpenDoor" , &Functions::actionOpenDoor }, { 44, "ActionCloseDoor" , &Functions::actionCloseDoor }, { 45, "SetCameraFacing" , 0 }, { 46, "PlaySound" , &Functions::playSound }, { 47, "GetSpellTargetObject" , 0 }, { 48, "ActionCastSpellAtObject" , 0 }, { 49, "GetCurrentVitalityPoints" , 0 }, { 50, "GetMaxVitalityPoints" , 0 }, { 51, "GetLocalInt" , &Functions::getLocalInt }, { 52, "GetLocalFloat" , &Functions::getLocalFloat }, { 53, "GetLocalString" , &Functions::getLocalString }, { 54, "GetLocalObject" , &Functions::getLocalObject }, { 55, "SetLocalInt" , &Functions::setLocalInt }, { 56, "SetLocalFloat" , &Functions::setLocalFloat }, { 57, "SetLocalString" , &Functions::setLocalString }, { 58, "SetLocalObject" , &Functions::setLocalObject }, { 59, "GetStringLength" , &Functions::getStringLength }, { 60, "GetStringUpperCase" , &Functions::getStringUpperCase }, { 61, "GetStringLowerCase" , &Functions::getStringLowerCase }, { 62, "GetStringRight" , &Functions::getStringRight }, { 63, "GetStringLeft" , &Functions::getStringLeft }, { 64, "InsertString" , &Functions::insertString }, { 65, "GetSubString" , &Functions::getSubString }, { 66, "FindSubString" , &Functions::findSubString }, { 67, "fabs" , &Functions::fabs }, { 68, "cos" , &Functions::cos }, { 69, "sin" , &Functions::sin }, { 70, "tan" , &Functions::tan }, { 71, "acos" , &Functions::acos }, { 72, "asin" , &Functions::asin }, { 73, "atan" , &Functions::atan }, { 74, "log" , &Functions::log }, { 75, "pow" , &Functions::pow }, { 76, "sqrt" , &Functions::sqrt }, { 77, "abs" , &Functions::abs }, { 78, "EffectHeal" , 0 }, { 79, "EffectDamage" , 0 }, { 80, "GetCurrentScriptSpellID" , 0 }, { 81, "GetNumRunningEffectsApplied" , 0 }, { 82, "EffectResurrection" , 0 }, { 83, "EffectSummonCreature" , 0 }, { 84, "AddAbility" , 0 }, { 85, "GetFirstEffect" , 0 }, { 86, "GetNextEffect" , 0 }, { 87, "RemoveEffect" , 0 }, { 88, "GetIsEffectValid" , 0 }, { 89, "GetEffectDurationType" , 0 }, { 90, "GetEffectSubType" , 0 }, { 91, "GetEffectCreator" , 0 }, { 92, "IntToString" , &Functions::intToString }, { 93, "GetFirstObjectInArea" , 0 }, { 94, "GetNextObjectInArea" , 0 }, { 95, "d2" , &Functions::d2 }, { 96, "d3" , &Functions::d3 }, { 97, "d4" , &Functions::d4 }, { 98, "d6" , &Functions::d6 }, { 99, "d8" , &Functions::d8 }, { 100, "d10" , &Functions::d10 }, { 101, "d12" , &Functions::d12 }, { 102, "d20" , &Functions::d20 }, { 103, "d100" , &Functions::d100 }, { 104, "VectorMagnitude" , &Functions::vectorMagnitude }, { 105, "GetPerceptionRange" , 0 }, { 106, "GetObjectType" , &Functions::getObjectType }, { 107, "GetRacialType" , 0 }, { 108, "AddRunningEffect" , 0 }, { 109, "TalentItem" , 0 }, { 110, "SetDoorUsable" , 0 }, { 111, "RemoveRunningEffect" , 0 }, { 112, "MagicalEffect" , 0 }, { 113, "SupernaturalEffect" , 0 }, { 114, "ExtraordinaryEffect" , 0 }, { 115, "RemoveAbility" , 0 }, { 116, "HasAbility" , 0 }, { 117, "GetCurrentAttribute" , 0 }, { 118, "AddSequenceAttack" , 0 }, { 119, "AddAttackSequence" , 0 }, { 120, "RemoveAttackSequence" , 0 }, { 121, "RoundsToSeconds" , 0 }, { 122, "HoursToSeconds" , 0 }, { 123, "TurnsToSeconds" , 0 }, { 124, "ApplyForce" , 0 }, { 125, "TestDirectLine" , 0 }, { 126, "GetIsAggressive" , 0 }, { 127, "SetAllowAggressiveAttitude" , 0 }, { 128, "GetFirstObjectInShape" , 0 }, { 129, "GetNextObjectInShape" , 0 }, { 130, "GetLastActionResult" , 0 }, { 131, "SignalEvent" , 0 }, { 132, "EventUserDefined" , 0 }, { 133, "EffectDeath" , 0 }, { 134, "EffectKnockdown" , 0 }, { 135, "ActionGiveItem" , 0 }, { 136, "ActionTakeItem" , 0 }, { 137, "VectorNormalize" , &Functions::vectorNormalize }, { 138, "ReplaceSequenceAttack" , 0 }, { 139, "GetAbilityScore" , 0 }, { 140, "GetIsDead" , 0 }, { 141, "PrintVector" , &Functions::printVector }, { 142, "Vector" , &Functions::vector }, { 143, "SetFacingPoint" , 0 }, { 144, "AngleToVector" , 0 }, { 145, "VectorToAngle" , 0 }, { 146, "GetCurrentEndurancePoints" , 0 }, { 147, "GetMaxEndurancePoints" , 0 }, { 148, "EffectParalyze" , 0 }, { 149, "FindSpellByTypeAndLevel" , 0 }, { 150, "EffectDeaf" , 0 }, { 151, "GetDistanceBetween" , 0 }, { 152, "SetLocalLocation" , 0 }, { 153, "GetLocalLocation" , 0 }, { 154, "EffectSleep" , 0 }, { 155, "GetItemInSlot" , 0 }, { 156, "EffectCharmed" , 0 }, { 157, "EffectConfused" , 0 }, { 158, "EffectFrightened" , 0 }, { 159, "EffectDominated" , 0 }, { 160, "EffectDazed" , 0 }, { 161, "EffectStunned" , 0 }, { 162, "SetCommandable" , 0 }, { 163, "GetCommandable" , 0 }, { 164, "EffectRegenerate" , 0 }, { 165, "EffectMovementSpeedIncrease" , 0 }, { 166, "GetHitDice" , 0 }, { 167, "ActionForceFollowObject" , 0 }, { 168, "GetTag" , &Functions::getTag }, { 169, "AddKnownSpell" , 0 }, { 170, "GetEffectType" , 0 }, { 171, "EffectAreaOfEffect" , 0 }, { 172, "GetFactionEqual" , 0 }, { 173, "ChangeFaction" , 0 }, { 174, "GetIsListening" , 0 }, { 175, "SetListening" , 0 }, { 176, "SetListenPattern" , 0 }, { 177, "TestStringAgainstPattern" , 0 }, { 178, "GetMatchedSubstring" , 0 }, { 179, "GetMatchedSubstringsCount" , 0 }, { 180, "EffectVisualEffect" , 0 }, { 181, "GetFactionWeakestMember" , 0 }, { 182, "GetFactionStrongestMember" , 0 }, { 183, "GetFactionMostDamagedMember" , 0 }, { 184, "GetFactionLeastDamagedMember" , 0 }, { 185, "GetFactionGold" , 0 }, { 186, "GetStoryPhaseByNPC" , 0 }, { 187, "SetPerceptionRangeType" , 0 }, { 188, "GetCurrentNonLethalDamagePoints" , 0 }, { 189, "GetFactionAverageLevel" , 0 }, { 190, "GetFactionAverageXP" , 0 }, { 191, "HasProfile" , 0 }, { 192, "GetFactionWorstAC" , 0 }, { 193, "GetFactionBestAC" , 0 }, { 194, "ActionSit" , 0 }, { 195, "GetListenPatternNumber" , 0 }, { 196, "ActionJumpToObject" , &Functions::actionJumpToObject }, { 197, "GetWaypointByTag" , &Functions::getWaypointByTag }, { 198, "GetTransitionTarget" , 0 }, { 199, "EffectLinkEffects" , 0 }, { 200, "GetObjectByTag" , &Functions::getObjectByTag }, { 201, "ItemIsUnarmedCombatWeapon" , 0 }, { 202, "ActionWait" , 0 }, { 203, "SetAreaTransitionBMP" , 0 }, { 204, "ActionStartConversation" , 0 }, { 205, "ActionPauseConversation" , 0 }, { 206, "ActionResumeConversation" , 0 }, { 207, "SetHostileToEnemiesOf" , 0 }, { 208, "GetStoryNPCObject" , 0 }, { 209, "GetStoryNPC" , 0 }, { 210, "GetSittingCreature" , 0 }, { 211, "GetGoingToBeAttackedBy" , 0 }, { 212, "RemoveKnownSpell" , 0 }, { 213, "GetLocation" , &Functions::getLocation }, { 214, "ActionJumpToLocation" , &Functions::actionJumpToLocation }, { 215, "Location" , &Functions::location }, { 216, "ApplyEffectAtLocation" , 0 }, { 217, "GetIsPC" , &Functions::getIsPC }, { 218, "FeetToMeters" , 0 }, { 219, "YardsToMeters" , 0 }, { 220, "ApplyEffectToObject" , 0 }, { 221, "SpeakString" , &Functions::speakString }, { 222, "GetSpellTargetLocation" , 0 }, { 223, "GetPositionFromLocation" , &Functions::getPositionFromLocation }, { 224, "GetAreaFromLocation" , 0 }, { 225, "GetFacingFromLocation" , 0 }, { 226, "GetNearestCreatureToLocation" , 0 }, { 227, "GetNearestObject" , &Functions::getNearestObject }, { 228, "GetNearestObjectToLocation" , 0 }, { 229, "GetNearestObjectByTag" , &Functions::getNearestObjectByTag }, { 230, "IntToFloat" , &Functions::intToFloat }, { 231, "FloatToInt" , &Functions::floatToInt }, { 232, "StringToInt" , &Functions::stringToInt }, { 233, "StringToFloat" , &Functions::stringToFloat }, { 234, "ActionCastSpellAtLocation" , 0 }, { 235, "GetStoryPhase" , 0 }, { 236, "GetSpawnSetSpawnPhase" , 0 }, { 237, "GetStoryNPCSpawnPhase" , 0 }, { 238, "GetPCSpeaker" , 0 }, { 239, "GetStringByStrRef" , &Functions::getStringByStrRef }, { 240, "ActionSpeakStringByStrRef" , 0 }, { 241, "DestroyObject" , 0 }, { 242, "GetModule" , &Functions::getModule }, { 243, "CreateObject" , 0 }, { 244, "EventSpellCastAt" , 0 }, { 245, "GetLastSpellCaster" , 0 }, { 246, "GetLastSpell" , 0 }, { 247, "GetUserDefinedEventNumber" , 0 }, { 248, "GetSpellId" , 0 }, { 249, "RandomName" , 0 }, { 250, "GetSpellIntensity" , 0 }, { 251, "RemoveEffectByType" , 0 }, { 252, "EffectSilence" , 0 }, { 253, "GetName" , &Functions::getName }, { 254, "GetLastSpeaker" , 0 }, { 255, "BeginConversation" , 0 }, { 256, "GetLastPerceived" , 0 }, { 257, "GetLastPerceptionHeard" , 0 }, { 258, "GetLastPerceptionInaudible" , 0 }, { 259, "GetLastPerceptionSeen" , 0 }, { 260, "GetLastClosedBy" , &Functions::getLastClosedBy }, { 261, "GetLastPerceptionVanished" , 0 }, { 262, "GetFirstInPersistentObject" , 0 }, { 263, "GetNextInPersistentObject" , 0 }, { 264, "GetAreaOfEffectCreator" , 0 }, { 265, "DeleteLocalInt" , 0 }, { 266, "DeleteLocalFloat" , 0 }, { 267, "DeleteLocalString" , 0 }, { 268, "DeleteLocalObject" , 0 }, { 269, "DeleteLocalLocation" , 0 }, { 270, "EffectHaste" , 0 }, { 271, "EffectSlow" , 0 }, { 272, "ObjectToString" , &Functions::objectToString }, { 273, "FindKnownSpellByTypeAndLevel" , 0 }, { 274, "SetCurrentScriptSpellID" , 0 }, { 275, "PrintError" , 0 }, { 276, "GetEncounterActive" , 0 }, { 277, "SetEncounterActive" , 0 }, { 278, "GetEncounterSpawnsMax" , 0 }, { 279, "SetEncounterSpawnsMax" , 0 }, { 280, "GetEncounterSpawnsCurrent" , 0 }, { 281, "SetEncounterSpawnsCurrent" , 0 }, { 282, "GetModuleItemAcquired" , 0 }, { 283, "GetModuleItemAcquiredFrom" , 0 }, { 284, "SetCustomToken" , 0 }, { 285, "GetHasFeat" , 0 }, { 286, "Mod" , 0 }, { 287, "ActionUseFeat" , 0 }, { 288, "ModAdd" , 0 }, { 289, "GetObjectSeen" , 0 }, { 290, "GetObjectHeard" , 0 }, { 291, "GetLastPlayerDied" , 0 }, { 292, "GetModuleItemLost" , 0 }, { 293, "GetModuleItemLostBy" , 0 }, { 294, "ActionDoCommand" , &Functions::actionDoCommand }, { 295, "EventConversation" , 0 }, { 296, "SetEncounterDifficulty" , 0 }, { 297, "GetEncounterDifficulty" , 0 }, { 298, "GetDistanceBetweenLocations" , 0 }, { 299, "EffectTemporaryEndurancePoints" , 0 }, { 300, "PlayAnimation" , 0 }, { 301, "TalentSpell" , 0 }, { 302, "TalentFeat" , 0 }, { 303, "ModToFloat" , 0 }, { 304, "GetHasSpellEffect" , 0 }, { 305, "GetEffectSpellId" , 0 }, { 306, "GetCreatureHasTalent" , 0 }, { 307, "GetCreatureTalentRandom" , 0 }, { 308, "GetCreatureTalentBest" , 0 }, { 309, "ActionUseTalentOnObject" , 0 }, { 310, "ActionUseTalentAtLocation" , 0 }, { 311, "GetGoldPieceValue" , 0 }, { 312, "GetIsPlayableRacialType" , 0 }, { 313, "JumpToLocation" , &Functions::jumpToLocation }, { 314, "EffectTemporaryVitalityPoints" , 0 }, { 315, "SetCurrentVitalityPoints" , 0 }, { 316, "GetAttackTarget" , 0 }, { 317, "IsCurrentActionSitting" , 0 }, { 318, "_TriggerOnWitness" , 0 }, { 319, "GetMaster" , 0 }, { 320, "GetIsInCombat" , 0 }, { 321, "GetLastAssociateCommand" , 0 }, { 322, "GiveGoldToCreature" , 0 }, { 323, "SetIsDestroyable" , 0 }, { 324, "SetLocked" , &Functions::setLocked }, { 325, "GetLocked" , &Functions::getLocked }, { 326, "GetClickingObject" , &Functions::getClickingObject }, { 327, "SetAssociateListenPatterns" , 0 }, { 328, "GetLastWeaponUsed" , 0 }, { 329, "ActionInteractObject" , 0 }, { 330, "GetLastUsedBy" , &Functions::getLastUsedBy }, { 331, "GetLevel" , 0 }, { 332, "GetIdentified" , 0 }, { 333, "SetIdentified" , 0 }, { 334, "SummonAnimalCompanion" , 0 }, { 335, "SummonFamiliar" , 0 }, { 336, "GetBlockingDoor" , 0 }, { 337, "GetIsDoorActionPossible" , 0 }, { 338, "DoDoorAction" , 0 }, { 339, "GetFirstItemInInventory" , 0 }, { 340, "GetNextItemInInventory" , 0 }, { 341, "SetCurrentEndurancePoints" , 0 }, { 342, "GetCurrentDrunkState" , 0 }, { 343, "SetCurrentDrunkState" , 0 }, { 344, "GetDamageDealtByMedium" , 0 }, { 345, "GetTotalDamageDealt" , 0 }, { 346, "GetLastDamager" , 0 }, { 347, "GetLastDisarmed" , 0 }, { 348, "GetLastDisturbed" , 0 }, { 349, "GetLastLocked" , 0 }, { 350, "GetLastUnlocked" , 0 }, { 351, "BroadcastUserDefinedEvent" , 0 }, { 352, "GetInventoryDisturbType" , 0 }, { 353, "GetInventoryDisturbItem" , 0 }, { 354, "GetHenchman" , 0 }, { 355, "GetCurrentToxicity" , 0 }, { 356, "VersusRacialTypeEffect" , 0 }, { 357, "VersusTrapEffect" , 0 }, { 358, "GetGender" , 0 }, { 359, "GetIsTalentValid" , 0 }, { 360, "ActionMoveAwayFromLocation" , 0 }, { 361, "GetAttemptedAttackTarget" , 0 }, { 362, "GetTypeFromTalent" , 0 }, { 363, "GetIdFromTalent" , 0 }, { 364, "GetAssociate" , 0 }, { 365, "AddHenchman" , 0 }, { 366, "RemoveHenchman" , 0 }, { 367, "AddJournalEntry" , 0 }, { 368, "HasJournalEntry" , 0 }, { 369, "GetPCPublicCDKey" , 0 }, { 370, "GetPCIPAddress" , 0 }, { 371, "GetPCPlayerName" , 0 }, { 372, "SetPCLike" , 0 }, { 373, "SetPCDislike" , 0 }, { 374, "SendMessageToPC" , &Functions::sendMessageToPC }, { 375, "GetAttemptedSpellTarget" , 0 }, { 376, "GetLastOpenedBy" , &Functions::getLastOpenedBy }, { 377, "GetHasSpell" , 0 }, { 378, "OpenStore" , 0 }, { 379, "EffectTurned" , 0 }, { 380, "GetFirstFactionMember" , 0 }, { 381, "GetNextFactionMember" , 0 }, { 382, "ActionForceMoveToLocation" , 0 }, { 383, "ActionForceMoveToObject" , 0 }, { 384, "GetEnemyProfile" , 0 }, { 385, "JumpToObject" , &Functions::jumpToObject }, { 386, "SetMapPinEnabled" , 0 }, { 387, "EffectHitPointChangeWhenDying" , 0 }, { 388, "PopUpGUIPanel" , 0 }, { 389, "GetIsUsingActionPoint" , 0 }, { 390, "GetCurrentActionName" , 0 }, { 391, "GetMonsterNPCObject" , 0 }, { 392, "GetMonsterNPC" , 0 }, { 393, "GiveXPToCreature" , 0 }, { 394, "SetXP" , 0 }, { 395, "GetXP" , 0 }, { 396, "IntToHexString" , &Functions::intToHexString }, { 397, "GetBaseItemType" , 0 }, { 398, "GetItemHasItemProperty" , 0 }, { 399, "ActionEquipMostDamagingMelee" , 0 }, { 400, "ActionEquipMostDamagingRanged" , 0 }, { 401, "GetAnimation" , 0 }, { 402, "ActionRest" , 0 }, { 403, "ExploreAreaForPlayer" , 0 }, { 404, "ActionEquipMostEffectiveArmor" , 0 }, { 405, "GetIsDay" , 0 }, { 406, "GetIsNight" , 0 }, { 407, "GetIsDawn" , 0 }, { 408, "GetIsDusk" , 0 }, { 409, "GetIsEncounterCreature" , 0 }, { 410, "GetLastPlayerDying" , 0 }, { 411, "GetStartingLocation" , 0 }, { 412, "ChangeToStandardFaction" , 0 }, { 413, "SoundObjectPlay" , 0 }, { 414, "SoundObjectStop" , 0 }, { 415, "SoundObjectSetVolume" , 0 }, { 416, "SoundObjectSetPosition" , 0 }, { 417, "SpeakOneLinerConversation" , &Functions::speakOneLinerConversation }, { 418, "GetGold" , 0 }, { 419, "GetLastRespawnButtonPresser" , 0 }, { 420, "GetIsDM" , 0 }, { 421, "PlayVoiceChat" , 0 }, { 422, "GetIsWeaponEffective" , 0 }, { 423, "GetLastSpellHarmful" , 0 }, { 424, "EventActivateItem" , 0 }, { 425, "MusicBackgroundPlay" , &Functions::musicBackgroundPlay }, { 426, "MusicBackgroundStop" , &Functions::musicBackgroundStop }, { 427, "MusicBackgroundSetDelay" , 0 }, { 428, "MusicBackgroundChangeDay" , &Functions::musicBackgroundChangeDay }, { 429, "MusicBackgroundChangeNight" , &Functions::musicBackgroundChangeNight }, { 430, "MusicBattlePlay" , 0 }, { 431, "MusicBattleStop" , 0 }, { 432, "MusicBattleChange" , 0 }, { 433, "AmbientSoundPlay" , 0 }, { 434, "AmbientSoundStop" , 0 }, { 435, "AmbientSoundChangeDay" , 0 }, { 436, "AmbientSoundChangeNight" , 0 }, { 437, "GetLastKiller" , 0 }, { 438, "GetSpellCastItem" , 0 }, { 439, "GetItemActivated" , 0 }, { 440, "GetItemActivator" , 0 }, { 441, "GetItemActivatedTargetLocation" , 0 }, { 442, "GetItemActivatedTarget" , 0 }, { 443, "GetIsOpen" , &Functions::getIsOpen }, { 444, "TakeGoldFromCreature" , 0 }, { 445, "IsInConversation" , 0 }, { 446, "EnableSequenceJumps" , 0 }, { 447, "SetupSpellTrigger" , 0 }, { 448, "GetLastTriggerSpellEnergy" , 0 }, { 449, "GetLastTriggerSpellID" , 0 }, { 450, "GetCurrentGamePhase" , 0 }, { 451, "EffectMovementSpeedDecrease" , 0 }, { 452, "SetCurrentGamePhase" , 0 }, { 453, "IsQuestCompleted" , 0 }, { 454, "GetQuestCurrentPhaseIndex" , 0 }, { 455, "GetPlotFlag" , 0 }, { 456, "SetPlotFlag" , 0 }, { 457, "EffectInvisibility" , 0 }, { 458, "GetQuestPhaseIndex" , 0 }, { 459, "EffectDarkness" , 0 }, { 460, "CompareGamePhases" , 0 }, { 461, "SetStoryNPCStoryPhase" , 0 }, { 462, "SetCurrentToxicity" , 0 }, { 463, "EffectPolymorph" , 0 }, { 464, "SetItemModelPart" , 0 }, { 465, "EffectTrueSeeing" , 0 }, { 466, "EffectSeeInvisible" , 0 }, { 467, "EffectTimeStop" , 0 }, { 468, "EffectBlindness" , 0 }, { 469, "_ClearPersonalAttitude" , 0 }, { 470, "GetIsObjectVisible" , 0 }, { 471, "CompareTags" , 0 }, { 472, "ActionReady" , 0 }, { 473, "EnableSpawnPhase" , 0 }, { 474, "ActivatePortal" , 0 }, { 475, "GetNumStackedItems" , 0 }, { 476, "GetValueFromSettings_Float" , 0 }, { 477, "SetConversationResponse" , 0 }, { 478, "GetLastJoiningItem" , 0 }, { 479, "GetCreatureSize" , 0 }, { 480, "EffectDisappearAppear" , 0 }, { 481, "EffectDisappear" , 0 }, { 482, "EffectAppear" , 0 }, { 483, "GetCurrentToxinCapacity" , 0 }, { 484, "SetCurrentToxinCapacity" , 0 }, { 485, "GetTimeFromLastHeartbeat" , 0 }, { 486, "GetLastTrapDetected" , 0 }, { 487, "GetConversationResponse" , 0 }, { 488, "GetNearestTrapToObject" , 0 }, { 489, "SetTag" , 0 }, { 490, "SetName" , 0 }, { 491, "HasSequenceForWeapon" , 0 }, { 492, "PlayCutscene" , 0 }, { 493, "SetAttackSequence" , 0 }, { 494, "GetCurrentWeather" , 0 }, { 495, "GetAge" , 0 }, { 496, "GetMovementRate" , 0 }, { 497, "GetAnimalCompanionCreatureType" , 0 }, { 498, "GetFamiliarCreatureType" , 0 }, { 499, "GetAnimalCompanionName" , 0 }, { 500, "GetFamiliarName" , 0 }, { 501, "ActionCastFakeSpellAtObject" , 0 }, { 502, "ActionCastFakeSpellAtLocation" , 0 }, { 503, "RemoveSummonedAssociate" , 0 }, { 504, "GetPlaceableState" , 0 }, { 505, "GetIsResting" , 0 }, { 506, "GetLastPCRested" , 0 }, { 507, "SetWeather" , 0 }, { 508, "GetLastRestEventType" , 0 }, { 509, "StartNewModule" , &Functions::startNewModule }, { 510, "HasOppositeProfileTo" , 0 }, { 511, "GetWeaponRanged" , 0 }, { 512, "DoSinglePlayerAutoSave" , 0 }, { 513, "GetGameDifficulty" , 0 }, { 514, "GetDialogActionParam" , 0 }, { 515, "PlayVoiceSetVoiceOfTag" , 0 }, { 516, "SoundObjectPlayWithFade" , 0 }, { 517, "SoundObjectStopWithFade" , 0 }, { 518, "IsSphereVisibleOnClient" , 0 }, { 519, "GetLastGiftItem" , 0 }, { 520, "OpenPlayerGoldPanel" , 0 }, { 521, "SetPanelButtonFlash" , 0 }, { 522, "GetCurrentAction" , 0 }, { 523, "SetStandardFactionReputation" , 0 }, { 524, "GetStandardFactionReputation" , 0 }, { 525, "FloatingTextStrRefOnCreature" , 0 }, { 526, "FloatingTextStringOnCreature" , 0 }, { 527, "GetTrapDisarmable" , 0 }, { 528, "GetTrapDetectable" , 0 }, { 529, "GetTrapDetectedBy" , 0 }, { 530, "GetTrapFlagged" , 0 }, { 531, "GetTrapBaseType" , 0 }, { 532, "GetTrapOneShot" , 0 }, { 533, "GetTrapCreator" , 0 }, { 534, "GetTrapKeyTag" , 0 }, { 535, "GetTrapDisarmDC" , 0 }, { 536, "GetTrapDetectDC" , 0 }, { 537, "GetLockKeyRequired" , 0 }, { 538, "GetLockKeyTag" , 0 }, { 539, "GetLockLockable" , 0 }, { 540, "GetLockUnlockDC" , 0 }, { 541, "GetLockLockDC" , 0 }, { 542, "GetPCLevellingUp" , 0 }, { 543, "GetHasFeatEffect" , 0 }, { 544, "SetPlaceableIllumination" , 0 }, { 545, "GetPlaceableIllumination" , 0 }, { 546, "GetIsPlaceableObjectActionPossible", 0 }, { 547, "DoPlaceableObjectAction" , 0 }, { 548, "GetFirstPC" , &Functions::getFirstPC }, { 549, "GetNextPC" , &Functions::getNextPC }, { 550, "SetTrapDetectedBy" , 0 }, { 551, "GetIsTrapped" , 0 }, { 552, "PreloadCreature" , 0 }, { 553, "_SetProfile" , 0 }, { 554, "PopUpDeathGUIPanel" , 0 }, { 555, "SetTrapDisabled" , 0 }, { 556, "GetLastHostileActor" , 0 }, { 557, "ExportAllCharacters" , 0 }, { 558, "MusicBackgroundGetDayTrack" , &Functions::musicBackgroundGetDayTrack }, { 559, "MusicBackgroundGetNightTrack" , &Functions::musicBackgroundGetNightTrack }, { 560, "WriteTimestampedLogEntry" , &Functions::writeTimestampedLogEntry }, { 561, "GetModuleName" , 0 }, { 562, "GetFactionLeader" , 0 }, { 563, "SendMessageToAllDMs" , 0 }, { 564, "EndGame" , 0 }, { 565, "BootPC" , 0 }, { 566, "RestartModule" , 0 }, { 567, "AmbientSoundSetDayVolume" , 0 }, { 568, "AmbientSoundSetNightVolume" , 0 }, { 569, "MusicBackgroundGetBattleTrack" , 0 }, { 570, "GetHasInventory" , 0 }, { 571, "GetStrRefSoundDuration" , 0 }, { 572, "GetAttitude" , 0 }, { 573, "CreateVisualEffectAtLocation" , 0 }, { 574, "MusicIncidentalPlay" , 0 }, { 575, "MusicIncidentalStop" , 0 }, { 576, "SetPerceptionUpdateInterval" , 0 }, { 577, "GetAppearanceType" , 0 }, { 578, "SpawnScriptDebugger" , 0 }, { 579, "GetModuleItemAcquiredStackSize" , 0 }, { 580, "BackupPersonalAttitudes" , 0 }, { 581, "RestorePersonalAttitudes" , 0 }, { 582, "GetResRef" , 0 }, { 583, "EffectPetrify" , 0 }, { 584, "CopyItem" , 0 }, { 585, "EffectCutsceneParalyze" , 0 }, { 586, "GetDroppableFlag" , 0 }, { 587, "GetUseableFlag" , 0 }, { 588, "GetStolenFlag" , 0 }, { 589, "SetCampaignFloat" , 0 }, { 590, "SetCampaignInt" , 0 }, { 591, "SetCampaignVector" , 0 }, { 592, "SetCampaignLocation" , 0 }, { 593, "SetCampaignString" , 0 }, { 594, "DestroyCampaignDatabase" , 0 }, { 595, "GetCampaignFloat" , 0 }, { 596, "GetCampaignInt" , 0 }, { 597, "GetCampaignVector" , 0 }, { 598, "GetCampaignLocation" , 0 }, { 599, "GetCampaignString" , 0 }, { 600, "CopyObject" , 0 }, { 601, "DeleteCampaignVariable" , 0 }, { 602, "StoreCampaignObject" , 0 }, { 603, "RetrieveCampaignObject" , 0 }, { 604, "EffectCutsceneDominated" , 0 }, { 605, "GetItemStackSize" , 0 }, { 606, "SetItemStackSize" , 0 }, { 607, "GetItemCharges" , 0 }, { 608, "SetItemCharges" , 0 }, { 609, "AddItemProperty" , 0 }, { 610, "RemoveItemProperty" , 0 }, { 611, "GetIsItemPropertyValid" , 0 }, { 612, "GetFirstItemProperty" , 0 }, { 613, "GetNextItemProperty" , 0 }, { 614, "GetItemPropertyType" , 0 }, { 615, "GetItemPropertyDuration" , 0 }, { 616, "GetLastBribeAmount" , 0 }, { 617, "EnableStoryNPCActions" , 0 }, { 618, "EffectPush" , 0 }, { 619, "AddWeaponEffect" , 0 }, { 620, "RemoveWeaponEffect" , 0 }, { 621, "SetProtectionPoints" , 0 }, { 622, "SetSpecialDistance" , 0 }, { 623, "GetProtectionPoints" , 0 }, { 624, "UnlockPlayerStoryBasedAbility" , 0 }, { 625, "TerminateProtection" , 0 }, { 626, "GetLastPerceptionEventType" , 0 }, { 627, "GetLastPerceptionZone" , 0 }, { 628, "GetIsItemOfType" , 0 }, { 629, "GetIsAmmoForWeapon" , 0 }, { 630, "ImmediateRest" , 0 }, { 631, "DPrint" , 0 }, { 632, "CreateVisualEffectAtCreature" , 0 }, { 633, "GetIsAISystemEnabled" , 0 }, { 634, "GetProfileName" , 0 }, { 635, "GetNumPeacefulProfiles" , 0 }, { 636, "SetPlaceableUsable" , 0 }, { 637, "AddToCallstack" , 0 }, { 638, "GetCallstackLine" , 0 }, { 639, "GetCallstack" , 0 }, { 640, "ChangePlaceableEffectPhase" , 0 }, { 641, "_SetCallstackIdent" , 0 }, { 642, "_AdjustCallstackIdent" , 0 }, { 643, "HasSequence" , 0 }, { 644, "GetCurrentSequenceId" , 0 }, { 645, "SetCurrentSequenceId" , 0 }, { 646, "GetIsWeaponRanged" , 0 }, { 647, "NoOp" , 0 }, { 648, "GetBattleMusicIdByCreature" , 0 }, { 649, "GetSpecialDistance" , 0 }, { 650, "CreateVisualEffectAtObject" , 0 }, { 651, "DeleteVisualEffectFromObject" , 0 }, { 652, "SetGiftMessages" , 0 }, { 653, "HasTheSameAffiliations" , 0 }, { 654, "IsAfraidOf" , 0 }, { 655, "GetLastItemSold" , 0 }, { 656, "CloseStoreAndInventory" , 0 }, { 657, "GetNPCDialogByTags" , 0 }, { 658, "GetDialogInterlocutorByTag" , 0 }, { 659, "IsCutscenePlaying" , 0 }, { 660, "SetPositionNearObject" , 0 }, { 661, "StartMaterialEffect" , 0 }, { 662, "StopMaterialEffect" , 0 }, { 663, "BindEffectParamToObjectPosition" , 0 }, { 664, "GetDialogFile" , 0 }, { 665, "_UpdateIsInTrigger" , 0 }, { 666, "HasJournalEntryConcerningObject" , 0 }, { 667, "Meditate" , 0 }, { 668, "GetCurrentWeatherIntensity" , 0 }, { 669, "BackupAfraidOf" , 0 }, { 670, "RestoreAfraidOf" , 0 }, { 671, "SetAfraidOfAffiliations" , 0 }, { 672, "GetProfileType" , 0 }, { 673, "GetIsExcited" , 0 }, { 674, "BindEffectParamToPartPosition" , 0 }, { 675, "ForceUpdateMeleePositions" , 0 }, { 676, "IsMeleePositionFree" , 0 }, { 677, "CanPlotNPCRaiseFromDead" , 0 }, { 678, "ProlongPlotNPCDeathEffect" , 0 }, { 679, "AddTalents" , 0 }, { 680, "CacheSequenceDistances" , 0 }, { 681, "RevealWorldMapRegion" , 0 }, { 682, "GetNearestAreaTransitionTarget" , 0 }, { 683, "AlchemyLearnMixture" , 0 }, { 684, "AlchemyLearnItem" , 0 }, { 685, "AlchemyGetItemKnown" , 0 }, { 686, "SetLockedAttackTarget" , 0 }, { 687, "ScriptDecisionsTempOff" , 0 }, { 688, "CanScriptDecideOfActions" , 0 }, { 689, "IsTriggerEnabled" , 0 }, { 690, "EnableTrigger" , 0 }, { 691, "SpeakStringByStrRef" , &Functions::speakStringByStrRef }, { 692, "SetCutsceneMode" , 0 }, { 693, "GetLastPCToCancelCutscene" , 0 }, { 694, "GetDialogSoundLength" , 0 }, { 695, "FadeFromBlack" , 0 }, { 696, "FadeToBlack" , 0 }, { 697, "StopFade" , 0 }, { 698, "BlackScreen" , 0 }, { 699, "GetBaseAttackBonus" , 0 }, { 700, "SetImmortal" , 0 }, { 701, "OpenPlayerInventory" , 0 }, { 702, "StoreCameraFacing" , 0 }, { 703, "RestoreCameraFacing" , 0 }, { 704, "LevelUpHenchman" , 0 }, { 705, "SetDroppableFlag" , 0 }, { 706, "SetNeutralBumpable" , 0 }, { 707, "GetModuleItemAcquiredBy" , 0 }, { 708, "GetImmortal" , 0 }, { 709, "_SetEmotionalSubstate" , 0 }, { 710, "Get2DAString" , &Functions::get2DAString }, { 711, "GetMainProfile" , 0 }, { 712, "GetAILevel" , 0 }, { 713, "SetAILevel" , 0 }, { 714, "GetIsPossessedFamiliar" , 0 }, { 715, "UnpossessFamiliar" , 0 }, { 716, "GetIsInside" , 0 }, { 717, "SendMessageToPCByStrRef" , 0 }, { 718, "IncrementRemainingFeatUses" , 0 }, { 719, "ExportSingleCharacter" , 0 }, { 720, "PlaySoundByStrRef" , &Functions::playSoundByStrRef }, { 721, "RunClientMacro" , 0 }, { 722, "RunClientLua" , &Functions::runClientLua }, { 723, "EffectRunScript" , 0 }, { 724, "SetEmotionalState" , 0 }, { 725, "GetEffectScriptID" , 0 }, { 726, "ForceEmotionalAnim" , 0 }, { 727, "GetObjectById" , 0 }, { 728, "TestDialogFlag" , 0 }, { 729, "SetDialogFlagValue" , 0 }, { 730, "GetDialogFlagValue" , 0 }, { 731, "FindDialogFlagIndex" , 0 }, { 732, "SetStartingStyleForWeaponType" , 0 }, { 733, "GetBestSlotForWeapon" , 0 }, { 734, "SetWaypointDesc" , 0 }, { 735, "ActionJumpToModule" , 0 }, { 736, "AddImpulse" , 0 }, { 737, "_SetPersonalAttitude" , 0 }, { 738, "GetPersonalAttitude" , 0 }, { 739, "HasPersonalAttitude" , 0 }, { 740, "_ClearPersonalAttitudeList" , 0 }, { 741, "GetFirstNeighbourCreature" , 0 }, { 742, "GetNextNeighbourCreature" , 0 }, { 743, "SetSurroundingFlag" , 0 }, { 744, "HasProfileByName" , 0 }, { 745, "AddDialogActor" , 0 }, { 746, "DespawnCreature" , 0 }, { 747, "PreloadAreaModel" , 0 }, { 748, "PostDialogCommand" , 0 }, { 749, "GetCombatState" , 0 }, { 750, "SetCombatState" , 0 }, { 751, "GetCrowdActionParticipant" , 0 }, { 752, "GetNPCDialog" , 0 }, { 753, "ErrorExit" , 0 }, { 754, "SetQueuedActionsInterruptable" , 0 }, { 755, "_SetPauseState" , 0 }, { 756, "See" , 0 }, { 757, "_StackPopObject" , 0 }, { 758, "FindNearestCreatures" , 0 }, { 759, "_GetLastInternalEventId" , 0 }, { 760, "_StackPopInteger" , 0 }, { 761, "_StackPopFloat" , 0 }, { 762, "HasEquipedMelee" , 0 }, { 763, "HasEquipedRanged" , 0 }, { 764, "GetIsFistfighter" , 0 }, { 765, "SetMapPinActive" , 0 }, { 766, "_FastSetInt" , 0 }, { 767, "_FastGetInt" , 0 }, { 768, "_FastSetObject" , 0 }, { 769, "_FastGetObject" , 0 }, { 770, "Assert" , 0 }, { 771, "_FastSetFloat" , 0 }, { 772, "_FastGetFloat" , 0 }, { 773, "TriggerInternalEvent" , 0 }, { 774, "GetNumGuardianTriggers" , 0 }, { 775, "GetNumGuardianWaypoints" , 0 }, { 776, "GetGuardianTrigger" , 0 }, { 777, "GetGuardianWaypoint" , 0 }, { 778, "SetIsInTrigger" , 0 }, { 779, "GetIsInMyTriggers" , 0 }, { 780, "SetPerceptionMultiplier" , 0 }, { 781, "GetPerceptionMultiplier" , 0 }, { 782, "SlotDlaTomka01" , 0 }, { 783, "SlotDlaTomka02" , 0 }, { 784, "SlotDlaTomka03" , 0 }, { 785, "SlotDlaTomka04" , 0 }, { 786, "HasAction" , 0 }, { 787, "ForceMapOfAnotherArea" , 0 }, { 788, "IsMapFullyLoaded" , 0 }, { 789, "GetCreatureAppearance" , 0 }, { 790, "SetCreatureAppearance" , 0 }, { 791, "DontEnableNPCActionsAfterDialog" , 0 }, { 792, "HasPhysics" , 0 }, { 793, "WillBeOneLiner" , 0 }, { 794, "SetCombatModeBaseDist" , 0 }, { 795, "ActionTeleportAndTalk" , 0 }, { 796, "PreDialogShot" , 0 }, { 797, "EnterFistfightMode" , 0 }, { 798, "LeaveFistfightMode" , 0 }, { 799, "LoadAreaMap" , 0 }, { 800, "SetDontEquipAnythingAfterDialog" , 0 }, { 801, "EndFistfightKnockOutEffect" , 0 }, { 802, "OpenPlayerBribePanel" , 0 }, { 803, "GetBribeVariationValue" , 0 }, { 804, "ResetXP" , 0 }, { 805, "AddGreaseAbility" , 0 }, { 806, "ClearGrease" , 0 }, { 807, "Get2DARow" , 0 }, { 808, "Get2DAInt" , 0 }, { 809, "SlotDlaMichala5" , 0 }, { 810, "SlotDlaMichala6" , 0 }, { 811, "SlotDlaMichala7" , 0 }, { 812, "SlotDlaMichala8" , 0 }, { 813, "SlotDlaMichala9" , 0 }, { 814, "Find5NearestCreatures" , 0 }, { 815, "IsInInteractiveMode" , 0 }, { 816, "SetMovementRate" , 0 }, { 817, "EquipMelee" , 0 }, { 818, "EquipRanged" , 0 }, { 819, "CanImmobileAttackMelee" , 0 }, { 820, "HasDialog" , 0 }, { 821, "GetNumNearbyCreatures" , 0 }, { 822, "_UpdatePassiveState" , 0 }, { 823, "_SetIsPassiveAttacker" , 0 }, { 824, "RandomFL" , 0 }, { 825, "GetBestRainHideout" , 0 }, { 826, "_DespawnBecouseOfRain" , 0 }, { 827, "_IsDespawningBecouseOfRain" , 0 }, { 828, "_GetLastExecutedScript" , 0 }, { 829, "ResetQuestUpdateFlag" , 0 }, { 830, "GetQuestUpdateFlag" , 0 }, { 831, "IsActorInDialog" , 0 }, { 832, "GetRandomLocationNearObject" , 0 }, { 833, "CanPlayVoiceSetOfType" , 0 }, { 834, "OpenPlayerBetPanel" , 0 }, { 835, "IsAreaFullyLoadedOnClient" , 0 }, { 836, "IsInInterior" , 0 }, { 837, "_CanFindPath" , 0 }, { 838, "_IsActionQueueEmpty" , 0 }, { 839, "IsModuleSaveGame" , 0 }, { 840, "GetRealMaxActiveAttackers" , 0 }, { 841, "GetRealActiveAttackers" , 0 }, { 842, "_UpdatePassiveAttackersList" , 0 }, { 843, "HasVoiceOfTag" , 0 }, { 844, "SetDialogOwner" , 0 }, { 845, "ForceCharacterDevelopment" , 0 }, { 846, "DisableCutsceneModeAfterDialog" , 0 }, { 847, "EnableMusician" , 0 } }; /** The table defining the signature (return type and type of parameters) of each engine function. */ const Functions::FunctionSignature Functions::kFunctionSignatures[] = { { 0, kTypeInt , { kTypeInt } }, { 1, kTypeVoid , { kTypeString } }, { 2, kTypeVoid , { kTypeFloat, kTypeInt, kTypeInt } }, { 3, kTypeString , { kTypeFloat, kTypeInt, kTypeInt } }, { 4, kTypeVoid , { kTypeInt } }, { 5, kTypeString , { kTypeObject } }, { 6, kTypeVoid , { kTypeObject, kTypeScriptState } }, { 7, kTypeVoid , { kTypeFloat, kTypeScriptState } }, { 8, kTypeVoid , { kTypeString, kTypeObject } }, { 9, kTypeVoid , { kTypeInt, kTypeObject } }, { 10, kTypeVoid , { kTypeFloat } }, { 11, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt } }, { 12, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt, kTypeInt } }, { 13, kTypeInt , { } }, { 14, kTypeInt , { } }, { 15, kTypeInt , { } }, { 16, kTypeInt , { } }, { 17, kTypeInt , { } }, { 18, kTypeInt , { } }, { 19, kTypeInt , { } }, { 20, kTypeVoid , { } }, { 21, kTypeVoid , { kTypeEngineType, kTypeInt } }, { 22, kTypeVoid , { kTypeObject, kTypeInt, kTypeFloat } }, { 23, kTypeVoid , { kTypeObject, kTypeInt, kTypeFloat } }, { 24, kTypeObject , { kTypeObject } }, { 25, kTypeObject , { } }, { 26, kTypeObject , { } }, { 27, kTypeVector , { kTypeObject } }, { 28, kTypeFloat , { kTypeObject } }, { 29, kTypeObject , { kTypeObject } }, { 30, kTypeObject , { kTypeObject, kTypeString } }, { 31, kTypeObject , { kTypeString, kTypeObject, kTypeInt } }, { 32, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 33, kTypeVoid , { kTypeObject, kTypeInt } }, { 34, kTypeVoid , { kTypeObject } }, { 35, kTypeVoid , { kTypeObject, kTypeInt } }, { 36, kTypeObject , { kTypeObject } }, { 37, kTypeVoid , { kTypeObject, kTypeInt } }, { 38, kTypeObject , { kTypeInt, kTypeInt, kTypeObject, kTypeInt, kTypeInt, kTypeInt, kTypeInt, kTypeInt } }, { 39, kTypeVoid , { kTypeString, kTypeInt } }, { 40, kTypeVoid , { kTypeInt, kTypeFloat, kTypeFloat } }, { 41, kTypeFloat , { kTypeObject } }, { 42, kTypeInt , { kTypeObject } }, { 43, kTypeVoid , { kTypeObject } }, { 44, kTypeVoid , { kTypeObject } }, { 45, kTypeVoid , { kTypeFloat, kTypeFloat, kTypeFloat, kTypeInt, kTypeInt } }, { 46, kTypeVoid , { kTypeString, kTypeInt, kTypeFloat } }, { 47, kTypeObject , { } }, { 48, kTypeVoid , { kTypeInt, kTypeObject, kTypeInt, kTypeInt, kTypeInt } }, { 49, kTypeInt , { kTypeObject } }, { 50, kTypeInt , { kTypeObject } }, { 51, kTypeInt , { kTypeObject, kTypeString } }, { 52, kTypeFloat , { kTypeObject, kTypeString } }, { 53, kTypeString , { kTypeObject, kTypeString } }, { 54, kTypeObject , { kTypeObject, kTypeString } }, { 55, kTypeVoid , { kTypeObject, kTypeString, kTypeInt } }, { 56, kTypeVoid , { kTypeObject, kTypeString, kTypeFloat } }, { 57, kTypeVoid , { kTypeObject, kTypeString, kTypeString } }, { 58, kTypeVoid , { kTypeObject, kTypeString, kTypeObject } }, { 59, kTypeInt , { kTypeString } }, { 60, kTypeString , { kTypeString } }, { 61, kTypeString , { kTypeString } }, { 62, kTypeString , { kTypeString, kTypeInt } }, { 63, kTypeString , { kTypeString, kTypeInt } }, { 64, kTypeString , { kTypeString, kTypeString, kTypeInt } }, { 65, kTypeString , { kTypeString, kTypeInt, kTypeInt } }, { 66, kTypeInt , { kTypeString, kTypeString } }, { 67, kTypeFloat , { kTypeFloat } }, { 68, kTypeFloat , { kTypeFloat } }, { 69, kTypeFloat , { kTypeFloat } }, { 70, kTypeFloat , { kTypeFloat } }, { 71, kTypeFloat , { kTypeFloat } }, { 72, kTypeFloat , { kTypeFloat } }, { 73, kTypeFloat , { kTypeFloat } }, { 74, kTypeFloat , { kTypeFloat } }, { 75, kTypeFloat , { kTypeFloat, kTypeFloat } }, { 76, kTypeFloat , { kTypeFloat } }, { 77, kTypeInt , { kTypeInt } }, { 78, kTypeEngineType, { kTypeInt } }, { 79, kTypeEngineType, { kTypeFloat, kTypeFloat, kTypeFloat, kTypeString, kTypeInt, kTypeString } }, { 80, kTypeInt , { kTypeObject } }, { 81, kTypeInt , { kTypeObject, kTypeString, kTypeInt } }, { 82, kTypeEngineType, { } }, { 83, kTypeEngineType, { kTypeString, kTypeInt, kTypeFloat } }, { 84, kTypeInt , { kTypeString, kTypeObject, kTypeInt, kTypeInt } }, { 85, kTypeEngineType, { kTypeObject } }, { 86, kTypeEngineType, { kTypeObject } }, { 87, kTypeVoid , { kTypeObject, kTypeEngineType } }, { 88, kTypeInt , { kTypeEngineType } }, { 89, kTypeInt , { kTypeEngineType } }, { 90, kTypeInt , { kTypeEngineType } }, { 91, kTypeObject , { kTypeEngineType } }, { 92, kTypeString , { kTypeInt } }, { 93, kTypeObject , { kTypeObject } }, { 94, kTypeObject , { kTypeObject } }, { 95, kTypeInt , { kTypeInt } }, { 96, kTypeInt , { kTypeInt } }, { 97, kTypeInt , { kTypeInt } }, { 98, kTypeInt , { kTypeInt } }, { 99, kTypeInt , { kTypeInt } }, { 100, kTypeInt , { kTypeInt } }, { 101, kTypeInt , { kTypeInt } }, { 102, kTypeInt , { kTypeInt } }, { 103, kTypeInt , { kTypeInt } }, { 104, kTypeFloat , { kTypeVector } }, { 105, kTypeFloat , { kTypeInt, kTypeObject } }, { 106, kTypeInt , { kTypeObject } }, { 107, kTypeInt , { kTypeObject } }, { 108, kTypeInt , { kTypeObject, kTypeString, kTypeInt, kTypeString, kTypeFloat, kTypeFloat, kTypeObject, kTypeString } }, { 109, kTypeEngineType, { kTypeObject } }, { 110, kTypeVoid , { kTypeObject, kTypeInt } }, { 111, kTypeInt , { kTypeObject, kTypeString, kTypeInt } }, { 112, kTypeEngineType, { kTypeEngineType } }, { 113, kTypeEngineType, { kTypeEngineType } }, { 114, kTypeEngineType, { kTypeEngineType } }, { 115, kTypeInt , { kTypeString, kTypeObject } }, { 116, kTypeInt , { kTypeString, kTypeObject } }, { 117, kTypeEngineType, { kTypeString, kTypeString, kTypeObject, kTypeObject } }, { 118, kTypeInt , { kTypeString, kTypeInt, kTypeInt, kTypeString, kTypeObject } }, { 119, kTypeInt , { kTypeString, kTypeString, kTypeString, kTypeObject } }, { 120, kTypeInt , { kTypeString, kTypeObject } }, { 121, kTypeFloat , { kTypeInt } }, { 122, kTypeFloat , { kTypeInt } }, { 123, kTypeFloat , { kTypeInt } }, { 124, kTypeVoid , { kTypeObject, kTypeEngineType, kTypeFloat, kTypeFloat, kTypeFloat } }, { 125, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 126, kTypeInt , { kTypeObject, kTypeObject } }, { 127, kTypeVoid , { kTypeInt, kTypeObject } }, { 128, kTypeObject , { kTypeInt, kTypeFloat, kTypeEngineType, kTypeInt, kTypeInt, kTypeVector, kTypeFloat } }, { 129, kTypeObject , { kTypeInt, kTypeFloat, kTypeEngineType, kTypeInt, kTypeInt, kTypeVector, kTypeFloat } }, { 130, kTypeInt , { kTypeObject } }, { 131, kTypeVoid , { kTypeObject, kTypeEngineType } }, { 132, kTypeEngineType, { kTypeInt } }, { 133, kTypeEngineType, { kTypeInt, kTypeInt } }, { 134, kTypeEngineType, { kTypeObject } }, { 135, kTypeVoid , { kTypeObject, kTypeObject } }, { 136, kTypeVoid , { kTypeObject, kTypeObject } }, { 137, kTypeVector , { kTypeVector } }, { 138, kTypeInt , { kTypeString, kTypeString, kTypeString, kTypeObject } }, { 139, kTypeInt , { kTypeObject, kTypeInt } }, { 140, kTypeInt , { kTypeObject } }, { 141, kTypeString , { kTypeVector, kTypeInt } }, { 142, kTypeVector , { kTypeFloat, kTypeFloat, kTypeFloat } }, { 143, kTypeVoid , { kTypeVector } }, { 144, kTypeVector , { kTypeFloat } }, { 145, kTypeFloat , { kTypeVector } }, { 146, kTypeInt , { kTypeObject } }, { 147, kTypeInt , { kTypeObject } }, { 148, kTypeEngineType, { } }, { 149, kTypeInt , { kTypeString, kTypeInt, kTypeInt } }, { 150, kTypeEngineType, { } }, { 151, kTypeFloat , { kTypeObject, kTypeObject } }, { 152, kTypeVoid , { kTypeObject, kTypeString, kTypeEngineType } }, { 153, kTypeEngineType, { kTypeObject, kTypeString } }, { 154, kTypeEngineType, { } }, { 155, kTypeObject , { kTypeInt, kTypeObject } }, { 156, kTypeEngineType, { } }, { 157, kTypeEngineType, { } }, { 158, kTypeEngineType, { } }, { 159, kTypeEngineType, { } }, { 160, kTypeEngineType, { } }, { 161, kTypeEngineType, { } }, { 162, kTypeVoid , { kTypeInt, kTypeObject } }, { 163, kTypeInt , { kTypeObject } }, { 164, kTypeEngineType, { kTypeInt, kTypeFloat } }, { 165, kTypeEngineType, { kTypeInt } }, { 166, kTypeInt , { kTypeObject } }, { 167, kTypeVoid , { kTypeObject, kTypeFloat, kTypeInt } }, { 168, kTypeString , { kTypeObject } }, { 169, kTypeVoid , { kTypeInt, kTypeObject } }, { 170, kTypeInt , { kTypeEngineType } }, { 171, kTypeEngineType, { kTypeInt, kTypeString, kTypeString, kTypeString } }, { 172, kTypeInt , { kTypeObject, kTypeObject } }, { 173, kTypeVoid , { kTypeObject, kTypeObject } }, { 174, kTypeInt , { kTypeObject } }, { 175, kTypeVoid , { kTypeObject, kTypeInt } }, { 176, kTypeVoid , { kTypeObject, kTypeString, kTypeInt } }, { 177, kTypeInt , { kTypeString, kTypeString } }, { 178, kTypeString , { kTypeInt } }, { 179, kTypeInt , { } }, { 180, kTypeEngineType, { kTypeInt, kTypeInt } }, { 181, kTypeObject , { kTypeObject, kTypeInt } }, { 182, kTypeObject , { kTypeObject, kTypeInt } }, { 183, kTypeObject , { kTypeObject, kTypeInt } }, { 184, kTypeObject , { kTypeObject, kTypeInt } }, { 185, kTypeInt , { kTypeObject } }, { 186, kTypeString , { kTypeString } }, { 187, kTypeVoid , { kTypeInt, kTypeObject } }, { 188, kTypeInt , { kTypeObject } }, { 189, kTypeInt , { kTypeObject } }, { 190, kTypeInt , { kTypeObject } }, { 191, kTypeInt , { kTypeObject, kTypeInt } }, { 192, kTypeObject , { kTypeObject, kTypeInt } }, { 193, kTypeObject , { kTypeObject, kTypeInt } }, { 194, kTypeVoid , { kTypeObject } }, { 195, kTypeInt , { } }, { 196, kTypeVoid , { kTypeObject, kTypeInt } }, { 197, kTypeObject , { kTypeString } }, { 198, kTypeObject , { kTypeObject } }, { 199, kTypeEngineType, { kTypeEngineType, kTypeEngineType } }, { 200, kTypeObject , { kTypeString, kTypeInt } }, { 201, kTypeInt , { kTypeObject } }, { 202, kTypeVoid , { kTypeFloat } }, { 203, kTypeVoid , { kTypeInt, kTypeString } }, { 204, kTypeVoid , { kTypeObject, kTypeString, kTypeInt, kTypeInt, kTypeInt } }, { 205, kTypeVoid , { } }, { 206, kTypeVoid , { } }, { 207, kTypeVoid , { kTypeObject, kTypeObject } }, { 208, kTypeObject , { kTypeString } }, { 209, kTypeString , { kTypeObject } }, { 210, kTypeObject , { kTypeObject } }, { 211, kTypeObject , { kTypeObject } }, { 212, kTypeVoid , { kTypeInt, kTypeObject } }, { 213, kTypeEngineType, { kTypeObject } }, { 214, kTypeVoid , { kTypeEngineType } }, { 215, kTypeEngineType, { kTypeObject, kTypeVector, kTypeFloat } }, { 216, kTypeVoid , { kTypeInt, kTypeEngineType, kTypeEngineType, kTypeFloat } }, { 217, kTypeInt , { kTypeObject } }, { 218, kTypeFloat , { kTypeFloat } }, { 219, kTypeFloat , { kTypeFloat } }, { 220, kTypeVoid , { kTypeInt, kTypeEngineType, kTypeObject, kTypeFloat, kTypeString, kTypeInt } }, { 221, kTypeVoid , { kTypeString, kTypeInt } }, { 222, kTypeEngineType, { } }, { 223, kTypeVector , { kTypeEngineType } }, { 224, kTypeObject , { kTypeEngineType } }, { 225, kTypeFloat , { kTypeEngineType } }, { 226, kTypeObject , { kTypeInt, kTypeInt, kTypeEngineType, kTypeInt, kTypeInt, kTypeInt, kTypeInt, kTypeInt } }, { 227, kTypeObject , { kTypeInt, kTypeObject, kTypeInt } }, { 228, kTypeObject , { kTypeInt, kTypeEngineType, kTypeInt } }, { 229, kTypeObject , { kTypeString, kTypeObject, kTypeInt, kTypeInt } }, { 230, kTypeFloat , { kTypeInt } }, { 231, kTypeInt , { kTypeFloat } }, { 232, kTypeInt , { kTypeString } }, { 233, kTypeFloat , { kTypeString } }, { 234, kTypeVoid , { kTypeInt, kTypeEngineType, kTypeInt, kTypeInt, kTypeInt } }, { 235, kTypeString , { kTypeObject } }, { 236, kTypeString , { kTypeString } }, { 237, kTypeString , { kTypeString } }, { 238, kTypeObject , { } }, { 239, kTypeString , { kTypeInt, kTypeInt } }, { 240, kTypeVoid , { kTypeInt, kTypeInt } }, { 241, kTypeVoid , { kTypeObject, kTypeFloat } }, { 242, kTypeObject , { } }, { 243, kTypeObject , { kTypeInt, kTypeString, kTypeEngineType, kTypeInt, kTypeString } }, { 244, kTypeEngineType, { kTypeObject, kTypeInt, kTypeInt } }, { 245, kTypeObject , { } }, { 246, kTypeInt , { } }, { 247, kTypeInt , { } }, { 248, kTypeInt , { } }, { 249, kTypeString , { } }, { 250, kTypeFloat , { kTypeString, kTypeInt, kTypeInt, kTypeObject, kTypeObject } }, { 251, kTypeVoid , { kTypeInt, kTypeObject } }, { 252, kTypeEngineType, { } }, { 253, kTypeString , { kTypeObject } }, { 254, kTypeObject , { } }, { 255, kTypeInt , { kTypeString, kTypeObject, kTypeObject } }, { 256, kTypeObject , { } }, { 257, kTypeInt , { } }, { 258, kTypeInt , { } }, { 259, kTypeInt , { } }, { 260, kTypeObject , { } }, { 261, kTypeInt , { } }, { 262, kTypeObject , { kTypeObject, kTypeInt, kTypeInt } }, { 263, kTypeObject , { kTypeObject, kTypeInt, kTypeInt } }, { 264, kTypeObject , { kTypeObject } }, { 265, kTypeVoid , { kTypeObject, kTypeString } }, { 266, kTypeVoid , { kTypeObject, kTypeString } }, { 267, kTypeVoid , { kTypeObject, kTypeString } }, { 268, kTypeVoid , { kTypeObject, kTypeString } }, { 269, kTypeVoid , { kTypeObject, kTypeString } }, { 270, kTypeEngineType, { } }, { 271, kTypeEngineType, { } }, { 272, kTypeString , { kTypeObject } }, { 273, kTypeInt , { kTypeString, kTypeInt, kTypeInt, kTypeObject } }, { 274, kTypeVoid , { kTypeInt, kTypeObject } }, { 275, kTypeVoid , { kTypeString } }, { 276, kTypeInt , { kTypeObject } }, { 277, kTypeVoid , { kTypeInt, kTypeObject } }, { 278, kTypeInt , { kTypeObject } }, { 279, kTypeVoid , { kTypeInt, kTypeObject } }, { 280, kTypeInt , { kTypeObject } }, { 281, kTypeVoid , { kTypeInt, kTypeObject } }, { 282, kTypeObject , { } }, { 283, kTypeObject , { } }, { 284, kTypeVoid , { kTypeInt, kTypeString } }, { 285, kTypeInt , { kTypeInt, kTypeObject } }, { 286, kTypeEngineType, { kTypeFloat, kTypeFloat } }, { 287, kTypeVoid , { kTypeInt, kTypeObject } }, { 288, kTypeEngineType, { kTypeEngineType, kTypeEngineType } }, { 289, kTypeInt , { kTypeObject, kTypeObject } }, { 290, kTypeInt , { kTypeObject, kTypeObject } }, { 291, kTypeObject , { } }, { 292, kTypeObject , { } }, { 293, kTypeObject , { } }, { 294, kTypeVoid , { kTypeScriptState } }, { 295, kTypeEngineType, { } }, { 296, kTypeVoid , { kTypeInt, kTypeObject } }, { 297, kTypeInt , { kTypeObject } }, { 298, kTypeFloat , { kTypeEngineType, kTypeEngineType } }, { 299, kTypeEngineType, { kTypeInt } }, { 300, kTypeVoid , { kTypeInt, kTypeFloat, kTypeFloat } }, { 301, kTypeEngineType, { kTypeInt } }, { 302, kTypeEngineType, { kTypeInt } }, { 303, kTypeFloat , { kTypeEngineType } }, { 304, kTypeInt , { kTypeInt, kTypeObject } }, { 305, kTypeInt , { kTypeEngineType } }, { 306, kTypeInt , { kTypeEngineType, kTypeObject } }, { 307, kTypeEngineType, { kTypeInt, kTypeObject } }, { 308, kTypeEngineType, { kTypeInt, kTypeInt, kTypeObject } }, { 309, kTypeVoid , { kTypeEngineType, kTypeObject } }, { 310, kTypeVoid , { kTypeEngineType, kTypeEngineType } }, { 311, kTypeInt , { kTypeObject } }, { 312, kTypeInt , { kTypeObject } }, { 313, kTypeVoid , { kTypeEngineType } }, { 314, kTypeEngineType, { kTypeInt } }, { 315, kTypeVoid , { kTypeInt, kTypeObject } }, { 316, kTypeObject , { kTypeObject } }, { 317, kTypeInt , { kTypeObject } }, { 318, kTypeInt , { kTypeInt, kTypeObject } }, { 319, kTypeObject , { kTypeObject } }, { 320, kTypeInt , { kTypeObject } }, { 321, kTypeInt , { kTypeObject } }, { 322, kTypeVoid , { kTypeObject, kTypeInt } }, { 323, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt } }, { 324, kTypeVoid , { kTypeObject, kTypeInt } }, { 325, kTypeInt , { kTypeObject } }, { 326, kTypeObject , { } }, { 327, kTypeVoid , { kTypeObject } }, { 328, kTypeObject , { kTypeObject } }, { 329, kTypeVoid , { kTypeObject } }, { 330, kTypeObject , { } }, { 331, kTypeInt , { kTypeObject } }, { 332, kTypeInt , { kTypeObject } }, { 333, kTypeVoid , { kTypeObject, kTypeInt } }, { 334, kTypeVoid , { kTypeObject } }, { 335, kTypeVoid , { kTypeObject } }, { 336, kTypeObject , { } }, { 337, kTypeInt , { kTypeObject, kTypeInt } }, { 338, kTypeVoid , { kTypeObject, kTypeInt } }, { 339, kTypeObject , { kTypeObject } }, { 340, kTypeObject , { kTypeObject } }, { 341, kTypeVoid , { kTypeInt, kTypeObject } }, { 342, kTypeInt , { kTypeObject } }, { 343, kTypeVoid , { kTypeInt, kTypeObject } }, { 344, kTypeInt , { kTypeString } }, { 345, kTypeInt , { } }, { 346, kTypeObject , { } }, { 347, kTypeObject , { } }, { 348, kTypeObject , { } }, { 349, kTypeObject , { } }, { 350, kTypeObject , { } }, { 351, kTypeVoid , { kTypeEngineType, kTypeFloat } }, { 352, kTypeInt , { } }, { 353, kTypeObject , { } }, { 354, kTypeObject , { kTypeObject } }, { 355, kTypeInt , { kTypeObject } }, { 356, kTypeEngineType, { kTypeEngineType, kTypeInt } }, { 357, kTypeEngineType, { kTypeEngineType } }, { 358, kTypeInt , { kTypeObject } }, { 359, kTypeInt , { kTypeEngineType } }, { 360, kTypeVoid , { kTypeEngineType, kTypeInt, kTypeFloat } }, { 361, kTypeObject , { } }, { 362, kTypeInt , { kTypeEngineType } }, { 363, kTypeInt , { kTypeEngineType } }, { 364, kTypeObject , { kTypeInt, kTypeObject } }, { 365, kTypeVoid , { kTypeObject, kTypeObject } }, { 366, kTypeVoid , { kTypeObject, kTypeObject } }, { 367, kTypeVoid , { kTypeString, kTypeString } }, { 368, kTypeInt , { kTypeString, kTypeString } }, { 369, kTypeString , { kTypeObject } }, { 370, kTypeString , { kTypeObject } }, { 371, kTypeString , { kTypeObject } }, { 372, kTypeVoid , { kTypeObject, kTypeObject } }, { 373, kTypeVoid , { kTypeObject, kTypeObject } }, { 374, kTypeVoid , { kTypeObject, kTypeString } }, { 375, kTypeObject , { } }, { 376, kTypeObject , { } }, { 377, kTypeInt , { kTypeInt, kTypeObject } }, { 378, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 379, kTypeEngineType, { } }, { 380, kTypeObject , { kTypeObject, kTypeInt } }, { 381, kTypeObject , { kTypeObject, kTypeInt } }, { 382, kTypeVoid , { kTypeEngineType, kTypeInt, kTypeFloat } }, { 383, kTypeVoid , { kTypeObject, kTypeInt, kTypeFloat, kTypeFloat } }, { 384, kTypeInt , { kTypeInt } }, { 385, kTypeVoid , { kTypeObject, kTypeInt } }, { 386, kTypeVoid , { kTypeObject, kTypeInt } }, { 387, kTypeEngineType, { kTypeFloat } }, { 388, kTypeVoid , { kTypeObject, kTypeInt } }, { 389, kTypeInt , { kTypeObject } }, { 390, kTypeString , { kTypeObject } }, { 391, kTypeObject , { kTypeString } }, { 392, kTypeString , { kTypeObject } }, { 393, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 394, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 395, kTypeInt , { kTypeObject } }, { 396, kTypeString , { kTypeInt } }, { 397, kTypeInt , { kTypeObject } }, { 398, kTypeInt , { kTypeObject, kTypeInt } }, { 399, kTypeVoid , { kTypeObject, kTypeInt } }, { 400, kTypeVoid , { kTypeObject } }, { 401, kTypeInt , { kTypeObject } }, { 402, kTypeVoid , { } }, { 403, kTypeVoid , { kTypeObject, kTypeObject } }, { 404, kTypeVoid , { } }, { 405, kTypeInt , { } }, { 406, kTypeInt , { } }, { 407, kTypeInt , { } }, { 408, kTypeInt , { } }, { 409, kTypeInt , { kTypeObject } }, { 410, kTypeObject , { } }, { 411, kTypeEngineType, { } }, { 412, kTypeVoid , { kTypeObject, kTypeInt } }, { 413, kTypeVoid , { kTypeObject } }, { 414, kTypeVoid , { kTypeObject } }, { 415, kTypeVoid , { kTypeObject, kTypeInt } }, { 416, kTypeVoid , { kTypeObject, kTypeVector } }, { 417, kTypeVoid , { kTypeString, kTypeObject } }, { 418, kTypeInt , { kTypeObject } }, { 419, kTypeObject , { } }, { 420, kTypeInt , { kTypeObject } }, { 421, kTypeVoid , { kTypeInt, kTypeObject } }, { 422, kTypeInt , { kTypeObject, kTypeInt } }, { 423, kTypeInt , { } }, { 424, kTypeEngineType, { kTypeObject, kTypeEngineType, kTypeObject } }, { 425, kTypeVoid , { kTypeObject } }, { 426, kTypeVoid , { kTypeObject } }, { 427, kTypeVoid , { kTypeObject, kTypeInt } }, { 428, kTypeVoid , { kTypeObject, kTypeInt } }, { 429, kTypeVoid , { kTypeObject, kTypeInt } }, { 430, kTypeVoid , { kTypeObject } }, { 431, kTypeVoid , { kTypeObject } }, { 432, kTypeVoid , { kTypeObject, kTypeInt } }, { 433, kTypeVoid , { kTypeObject } }, { 434, kTypeVoid , { kTypeObject } }, { 435, kTypeVoid , { kTypeObject, kTypeInt } }, { 436, kTypeVoid , { kTypeObject, kTypeInt } }, { 437, kTypeObject , { } }, { 438, kTypeObject , { } }, { 439, kTypeObject , { } }, { 440, kTypeObject , { } }, { 441, kTypeEngineType, { } }, { 442, kTypeObject , { } }, { 443, kTypeInt , { kTypeObject } }, { 444, kTypeVoid , { kTypeInt, kTypeObject, kTypeInt } }, { 445, kTypeInt , { kTypeObject } }, { 446, kTypeInt , { kTypeString, kTypeInt, kTypeObject } }, { 447, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt, kTypeFloat, kTypeFloat, kTypeInt, kTypeString } }, { 448, kTypeFloat , { } }, { 449, kTypeInt , { } }, { 450, kTypeString , { } }, { 451, kTypeEngineType, { kTypeInt } }, { 452, kTypeVoid , { kTypeString } }, { 453, kTypeInt , { kTypeString } }, { 454, kTypeInt , { kTypeString } }, { 455, kTypeInt , { kTypeObject } }, { 456, kTypeVoid , { kTypeObject, kTypeInt } }, { 457, kTypeEngineType, { kTypeInt } }, { 458, kTypeInt , { kTypeString, kTypeString, kTypeString } }, { 459, kTypeEngineType, { } }, { 460, kTypeInt , { kTypeString, kTypeString } }, { 461, kTypeVoid , { kTypeString, kTypeString } }, { 462, kTypeVoid , { kTypeInt, kTypeObject } }, { 463, kTypeEngineType, { kTypeInt } }, { 464, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt, kTypeObject } }, { 465, kTypeEngineType, { } }, { 466, kTypeEngineType, { } }, { 467, kTypeEngineType, { } }, { 468, kTypeEngineType, { } }, { 469, kTypeVoid , { kTypeObject, kTypeObject } }, { 470, kTypeInt , { kTypeFloat, kTypeObject } }, { 471, kTypeInt , { kTypeString, kTypeString, kTypeInt } }, { 472, kTypeVoid , { } }, { 473, kTypeVoid , { kTypeString, kTypeInt } }, { 474, kTypeVoid , { kTypeObject, kTypeString, kTypeString, kTypeString, kTypeInt } }, { 475, kTypeInt , { kTypeObject } }, { 476, kTypeFloat , { kTypeString } }, { 477, kTypeVoid , { kTypeInt, kTypeInt, kTypeObject } }, { 478, kTypeObject , { kTypeObject } }, { 479, kTypeInt , { kTypeObject } }, { 480, kTypeEngineType, { kTypeEngineType } }, { 481, kTypeEngineType, { } }, { 482, kTypeEngineType, { } }, { 483, kTypeInt , { kTypeObject } }, { 484, kTypeVoid , { kTypeInt, kTypeObject } }, { 485, kTypeFloat , { kTypeObject } }, { 486, kTypeObject , { kTypeObject } }, { 487, kTypeInt , { kTypeInt, kTypeObject } }, { 488, kTypeObject , { kTypeObject, kTypeInt } }, { 489, kTypeVoid , { kTypeString, kTypeObject } }, { 490, kTypeVoid , { kTypeString, kTypeObject } }, { 491, kTypeInt , { kTypeObject, kTypeObject } }, { 492, kTypeVoid , { kTypeString, kTypeString, kTypeInt, kTypeInt, kTypeInt, kTypeInt, kTypeInt } }, { 493, kTypeInt , { kTypeInt, kTypeObject } }, { 494, kTypeInt , { kTypeObject } }, { 495, kTypeInt , { kTypeObject } }, { 496, kTypeInt , { kTypeObject } }, { 497, kTypeInt , { kTypeObject } }, { 498, kTypeInt , { kTypeObject } }, { 499, kTypeString , { kTypeObject } }, { 500, kTypeString , { kTypeObject } }, { 501, kTypeVoid , { kTypeInt, kTypeObject, kTypeInt } }, { 502, kTypeVoid , { kTypeInt, kTypeEngineType, kTypeInt } }, { 503, kTypeVoid , { kTypeObject, kTypeObject } }, { 504, kTypeInt , { kTypeObject } }, { 505, kTypeInt , { kTypeObject } }, { 506, kTypeObject , { } }, { 507, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 508, kTypeInt , { } }, { 509, kTypeVoid , { kTypeString } }, { 510, kTypeInt , { kTypeObject, kTypeObject } }, { 511, kTypeInt , { kTypeObject } }, { 512, kTypeVoid , { } }, { 513, kTypeInt , { } }, { 514, kTypeString , { kTypeInt, kTypeObject } }, { 515, kTypeFloat , { kTypeObject, kTypeInt } }, { 516, kTypeVoid , { kTypeObject } }, { 517, kTypeVoid , { kTypeObject } }, { 518, kTypeInt , { kTypeVector, kTypeFloat } }, { 519, kTypeObject , { kTypeObject } }, { 520, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 521, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 522, kTypeInt , { kTypeObject } }, { 523, kTypeVoid , { kTypeInt, kTypeInt, kTypeObject } }, { 524, kTypeInt , { kTypeInt, kTypeObject } }, { 525, kTypeVoid , { kTypeInt, kTypeObject, kTypeInt } }, { 526, kTypeVoid , { kTypeString, kTypeObject, kTypeInt } }, { 527, kTypeInt , { kTypeObject } }, { 528, kTypeInt , { kTypeObject } }, { 529, kTypeInt , { kTypeObject, kTypeObject } }, { 530, kTypeInt , { kTypeObject } }, { 531, kTypeInt , { kTypeObject } }, { 532, kTypeInt , { kTypeObject } }, { 533, kTypeObject , { kTypeObject } }, { 534, kTypeString , { kTypeObject } }, { 535, kTypeInt , { kTypeObject } }, { 536, kTypeInt , { kTypeObject } }, { 537, kTypeInt , { kTypeObject } }, { 538, kTypeString , { kTypeObject } }, { 539, kTypeInt , { kTypeObject } }, { 540, kTypeInt , { kTypeObject } }, { 541, kTypeInt , { kTypeObject } }, { 542, kTypeObject , { } }, { 543, kTypeInt , { kTypeInt, kTypeObject } }, { 544, kTypeVoid , { kTypeObject, kTypeInt } }, { 545, kTypeInt , { kTypeObject } }, { 546, kTypeInt , { kTypeObject, kTypeInt } }, { 547, kTypeVoid , { kTypeObject, kTypeInt } }, { 548, kTypeObject , { } }, { 549, kTypeObject , { } }, { 550, kTypeInt , { kTypeObject, kTypeObject } }, { 551, kTypeInt , { kTypeObject } }, { 552, kTypeInt , { kTypeString, kTypeObject } }, { 553, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 554, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt, kTypeInt, kTypeString } }, { 555, kTypeVoid , { kTypeObject } }, { 556, kTypeObject , { kTypeObject } }, { 557, kTypeVoid , { } }, { 558, kTypeInt , { kTypeObject } }, { 559, kTypeInt , { kTypeObject } }, { 560, kTypeVoid , { kTypeString } }, { 561, kTypeString , { } }, { 562, kTypeObject , { kTypeObject } }, { 563, kTypeVoid , { kTypeString } }, { 564, kTypeVoid , { kTypeString } }, { 565, kTypeVoid , { kTypeObject } }, { 566, kTypeVoid , { } }, { 567, kTypeVoid , { kTypeObject, kTypeInt } }, { 568, kTypeVoid , { kTypeObject, kTypeInt } }, { 569, kTypeInt , { kTypeObject } }, { 570, kTypeInt , { kTypeObject } }, { 571, kTypeFloat , { kTypeInt } }, { 572, kTypeInt , { kTypeObject, kTypeObject } }, { 573, kTypeVoid , { kTypeString, kTypeEngineType } }, { 574, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt, kTypeInt, kTypeInt } }, { 575, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt, kTypeInt } }, { 576, kTypeVoid , { kTypeInt } }, { 577, kTypeInt , { kTypeObject } }, { 578, kTypeVoid , { } }, { 579, kTypeInt , { } }, { 580, kTypeVoid , { kTypeObject } }, { 581, kTypeVoid , { kTypeObject } }, { 582, kTypeString , { kTypeObject } }, { 583, kTypeEngineType, { } }, { 584, kTypeObject , { kTypeObject, kTypeObject } }, { 585, kTypeEngineType, { } }, { 586, kTypeInt , { kTypeObject } }, { 587, kTypeInt , { kTypeObject } }, { 588, kTypeInt , { kTypeObject } }, { 589, kTypeVoid , { kTypeString, kTypeString, kTypeFloat, kTypeObject } }, { 590, kTypeVoid , { kTypeString, kTypeString, kTypeInt, kTypeObject } }, { 591, kTypeVoid , { kTypeString, kTypeString, kTypeVector, kTypeObject } }, { 592, kTypeVoid , { kTypeString, kTypeString, kTypeEngineType, kTypeObject } }, { 593, kTypeVoid , { kTypeString, kTypeString, kTypeString, kTypeObject } }, { 594, kTypeVoid , { kTypeString } }, { 595, kTypeFloat , { kTypeString, kTypeString, kTypeObject } }, { 596, kTypeInt , { kTypeString, kTypeString, kTypeObject } }, { 597, kTypeVector , { kTypeString, kTypeString, kTypeObject } }, { 598, kTypeEngineType, { kTypeString, kTypeString, kTypeObject } }, { 599, kTypeString , { kTypeString, kTypeString, kTypeObject } }, { 600, kTypeObject , { kTypeObject, kTypeEngineType, kTypeObject, kTypeString } }, { 601, kTypeVoid , { kTypeString, kTypeString, kTypeObject } }, { 602, kTypeInt , { kTypeString, kTypeString, kTypeObject, kTypeObject } }, { 603, kTypeObject , { kTypeString, kTypeString, kTypeEngineType, kTypeObject, kTypeObject } }, { 604, kTypeEngineType, { } }, { 605, kTypeInt , { kTypeObject } }, { 606, kTypeVoid , { kTypeObject, kTypeInt } }, { 607, kTypeInt , { kTypeObject } }, { 608, kTypeVoid , { kTypeObject, kTypeInt } }, { 609, kTypeVoid , { } }, { 610, kTypeVoid , { } }, { 611, kTypeVoid , { } }, { 612, kTypeVoid , { } }, { 613, kTypeVoid , { } }, { 614, kTypeVoid , { } }, { 615, kTypeVoid , { } }, { 616, kTypeInt , { kTypeObject } }, { 617, kTypeVoid , { kTypeInt, kTypeObject } }, { 618, kTypeEngineType, { kTypeFloat } }, { 619, kTypeInt , { kTypeString, kTypeInt, kTypeString, kTypeFloat, kTypeObject } }, { 620, kTypeVoid , { kTypeInt, kTypeObject } }, { 621, kTypeVoid , { kTypeObject, kTypeFloat, kTypeFloat, kTypeInt, kTypeString, kTypeInt } }, { 622, kTypeVoid , { kTypeInt, kTypeFloat, kTypeObject } }, { 623, kTypeFloat , { kTypeObject } }, { 624, kTypeVoid , { kTypeString } }, { 625, kTypeVoid , { kTypeObject } }, { 626, kTypeInt , { kTypeObject } }, { 627, kTypeInt , { kTypeObject } }, { 628, kTypeInt , { kTypeString, kTypeObject } }, { 629, kTypeInt , { kTypeObject, kTypeObject } }, { 630, kTypeVoid , { kTypeInt } }, { 631, kTypeVoid , { kTypeString, kTypeInt } }, { 632, kTypeVoid , { kTypeString, kTypeString, kTypeObject, kTypeInt } }, { 633, kTypeInt , { kTypeObject } }, { 634, kTypeString , { kTypeInt } }, { 635, kTypeInt , { kTypeObject, kTypeObject } }, { 636, kTypeVoid , { kTypeObject, kTypeInt } }, { 637, kTypeVoid , { kTypeString, kTypeObject, kTypeInt } }, { 638, kTypeString , { kTypeInt, kTypeObject } }, { 639, kTypeString , { kTypeObject } }, { 640, kTypeVoid , { kTypeObject, kTypeString } }, { 641, kTypeVoid , { kTypeInt, kTypeObject } }, { 642, kTypeVoid , { kTypeInt, kTypeObject } }, { 643, kTypeInt , { kTypeString, kTypeObject } }, { 644, kTypeString , { kTypeObject } }, { 645, kTypeInt , { kTypeString, kTypeObject } }, { 646, kTypeInt , { kTypeObject } }, { 647, kTypeVoid , { } }, { 648, kTypeInt , { kTypeObject } }, { 649, kTypeFloat , { kTypeInt, kTypeObject } }, { 650, kTypeVoid , { kTypeString, kTypeString, kTypeObject } }, { 651, kTypeVoid , { kTypeString, kTypeObject, kTypeInt } }, { 652, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt, kTypeObject } }, { 653, kTypeInt , { kTypeObject, kTypeObject } }, { 654, kTypeInt , { kTypeObject, kTypeObject } }, { 655, kTypeObject , { kTypeObject } }, { 656, kTypeVoid , { kTypeInt } }, { 657, kTypeString , { kTypeString, kTypeString, kTypeString } }, { 658, kTypeString , { kTypeString, kTypeString } }, { 659, kTypeInt , { } }, { 660, kTypeVoid , { kTypeObject, kTypeObject } }, { 661, kTypeVoid , { kTypeObject, kTypeString } }, { 662, kTypeVoid , { kTypeObject, kTypeString } }, { 663, kTypeVoid , { kTypeObject, kTypeString, kTypeString, kTypeObject, kTypeVector } }, { 664, kTypeString , { kTypeObject } }, { 665, kTypeVoid , { kTypeObject } }, { 666, kTypeInt , { kTypeString, kTypeString } }, { 667, kTypeVoid , { kTypeObject } }, { 668, kTypeInt , { kTypeObject } }, { 669, kTypeVoid , { kTypeObject } }, { 670, kTypeVoid , { kTypeObject } }, { 671, kTypeVoid , { kTypeObject, kTypeObject } }, { 672, kTypeInt , { kTypeInt } }, { 673, kTypeInt , { kTypeObject } }, { 674, kTypeVoid , { kTypeObject, kTypeString, kTypeString, kTypeObject, kTypeString } }, { 675, kTypeVoid , { kTypeObject } }, { 676, kTypeInt , { kTypeObject, kTypeObject } }, { 677, kTypeInt , { kTypeObject } }, { 678, kTypeVoid , { kTypeObject, kTypeFloat } }, { 679, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt } }, { 680, kTypeVoid , { kTypeObject } }, { 681, kTypeVoid , { kTypeInt } }, { 682, kTypeObject , { kTypeObject } }, { 683, kTypeVoid , { kTypeString } }, { 684, kTypeVoid , { kTypeString } }, { 685, kTypeInt , { kTypeObject } }, { 686, kTypeVoid , { kTypeObject, kTypeObject } }, { 687, kTypeVoid , { kTypeObject, kTypeInt } }, { 688, kTypeInt , { kTypeObject } }, { 689, kTypeInt , { kTypeObject } }, { 690, kTypeVoid , { kTypeObject, kTypeInt } }, { 691, kTypeVoid , { kTypeInt, kTypeInt } }, { 692, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 693, kTypeObject , { } }, { 694, kTypeFloat , { kTypeInt } }, { 695, kTypeVoid , { kTypeObject, kTypeFloat } }, { 696, kTypeVoid , { kTypeObject, kTypeFloat } }, { 697, kTypeVoid , { kTypeObject } }, { 698, kTypeVoid , { kTypeObject } }, { 699, kTypeInt , { kTypeObject } }, { 700, kTypeVoid , { kTypeObject, kTypeInt } }, { 701, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 702, kTypeVoid , { } }, { 703, kTypeVoid , { } }, { 704, kTypeInt , { kTypeObject, kTypeInt, kTypeInt } }, { 705, kTypeVoid , { kTypeObject, kTypeInt } }, { 706, kTypeVoid , { kTypeObject, kTypeInt } }, { 707, kTypeObject , { } }, { 708, kTypeInt , { kTypeObject } }, { 709, kTypeVoid , { kTypeString, kTypeInt, kTypeObject } }, { 710, kTypeString , { kTypeString, kTypeString, kTypeInt } }, { 711, kTypeInt , { kTypeObject } }, { 712, kTypeInt , { kTypeObject } }, { 713, kTypeVoid , { kTypeObject, kTypeInt } }, { 714, kTypeInt , { kTypeObject } }, { 715, kTypeVoid , { kTypeObject } }, { 716, kTypeVoid , { } }, { 717, kTypeVoid , { } }, { 718, kTypeVoid , { } }, { 719, kTypeVoid , { kTypeObject } }, { 720, kTypeVoid , { kTypeInt, kTypeInt } }, { 721, kTypeVoid , { kTypeString } }, { 722, kTypeVoid , { kTypeString } }, { 723, kTypeEngineType, { kTypeString, kTypeString, kTypeInt } }, { 724, kTypeVoid , { kTypeObject, kTypeString } }, { 725, kTypeInt , { kTypeEngineType } }, { 726, kTypeVoid , { kTypeObject, kTypeString, kTypeInt } }, { 727, kTypeObject , { kTypeInt } }, { 728, kTypeInt , { kTypeString, kTypeInt } }, { 729, kTypeVoid , { kTypeString, kTypeInt } }, { 730, kTypeInt , { kTypeString } }, { 731, kTypeInt , { kTypeString } }, { 732, kTypeInt , { kTypeObject, kTypeInt, kTypeInt } }, { 733, kTypeInt , { kTypeObject, kTypeObject } }, { 734, kTypeVoid , { kTypeObject, kTypeString } }, { 735, kTypeVoid , { kTypeObject, kTypeString, kTypeString, kTypeString } }, { 736, kTypeVoid , { kTypeObject, kTypeVector } }, { 737, kTypeVoid , { kTypeInt, kTypeObject, kTypeObject } }, { 738, kTypeInt , { kTypeObject, kTypeObject } }, { 739, kTypeInt , { kTypeObject, kTypeObject } }, { 740, kTypeVoid , { kTypeObject } }, { 741, kTypeObject , { kTypeObject } }, { 742, kTypeObject , { kTypeObject } }, { 743, kTypeVoid , { kTypeObject, kTypeInt } }, { 744, kTypeInt , { kTypeObject, kTypeString } }, { 745, kTypeVoid , { kTypeObject, kTypeObject } }, { 746, kTypeVoid , { kTypeObject, kTypeInt } }, { 747, kTypeInt , { kTypeString } }, { 748, kTypeInt , { kTypeScriptState, kTypeObject, kTypeInt } }, { 749, kTypeInt , { kTypeObject } }, { 750, kTypeVoid , { kTypeObject, kTypeInt } }, { 751, kTypeObject , { kTypeObject, kTypeInt } }, { 752, kTypeString , { kTypeObject, kTypeString } }, { 753, kTypeVoid , { kTypeString, kTypeInt } }, { 754, kTypeVoid , { kTypeInt, kTypeObject } }, { 755, kTypeVoid , { kTypeInt, kTypeInt, kTypeInt } }, { 756, kTypeInt , { kTypeObject, kTypeObject } }, { 757, kTypeObject , { } }, { 758, kTypeObject , { kTypeObject, kTypeInt, kTypeInt } }, { 759, kTypeInt , { kTypeObject } }, { 760, kTypeInt , { } }, { 761, kTypeFloat , { } }, { 762, kTypeInt , { kTypeObject } }, { 763, kTypeInt , { kTypeObject } }, { 764, kTypeInt , { kTypeObject, kTypeInt } }, { 765, kTypeVoid , { kTypeObject, kTypeInt } }, { 766, kTypeVoid , { kTypeObject, kTypeInt, kTypeInt } }, { 767, kTypeInt , { kTypeObject, kTypeInt } }, { 768, kTypeVoid , { kTypeObject, kTypeInt, kTypeObject } }, { 769, kTypeObject , { kTypeObject, kTypeInt } }, { 770, kTypeVoid , { kTypeString, kTypeInt, kTypeInt } }, { 771, kTypeVoid , { kTypeObject, kTypeInt, kTypeFloat } }, { 772, kTypeFloat , { kTypeObject, kTypeInt } }, { 773, kTypeVoid , { kTypeObject, kTypeFloat, kTypeInt, kTypeObject, kTypeInt } }, { 774, kTypeInt , { kTypeObject } }, { 775, kTypeInt , { kTypeObject } }, { 776, kTypeObject , { kTypeInt, kTypeObject, kTypeInt, kTypeObject } }, { 777, kTypeObject , { kTypeInt, kTypeObject, kTypeInt, kTypeInt, kTypeObject } }, { 778, kTypeVoid , { kTypeObject, kTypeInt, kTypeObject } }, { 779, kTypeInt , { kTypeObject, kTypeObject } }, { 780, kTypeVoid , { kTypeFloat, kTypeObject } }, { 781, kTypeFloat , { kTypeObject } }, { 782, kTypeVoid , { } }, { 783, kTypeVoid , { } }, { 784, kTypeVoid , { } }, { 785, kTypeVoid , { } }, { 786, kTypeInt , { kTypeObject, kTypeInt } }, { 787, kTypeVoid , { kTypeObject, kTypeFloat, kTypeString, kTypeString, kTypeString, kTypeString, kTypeString } }, { 788, kTypeInt , { } }, { 789, kTypeInt , { kTypeObject } }, { 790, kTypeVoid , { kTypeObject, kTypeInt } }, { 791, kTypeVoid , { kTypeObject } }, { 792, kTypeInt , { kTypeObject } }, { 793, kTypeInt , { kTypeObject, kTypeString } }, { 794, kTypeVoid , { kTypeObject, kTypeFloat } }, { 795, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt, kTypeString, kTypeString, kTypeString, kTypeObject, kTypeInt } }, { 796, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 797, kTypeVoid , { kTypeObject } }, { 798, kTypeVoid , { kTypeObject } }, { 799, kTypeVoid , { kTypeString, kTypeString, kTypeString } }, { 800, kTypeVoid , { kTypeObject } }, { 801, kTypeVoid , { kTypeObject } }, { 802, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 803, kTypeInt , { kTypeObject } }, { 804, kTypeVoid , { kTypeObject } }, { 805, kTypeInt , { kTypeString, kTypeObject, kTypeInt } }, { 806, kTypeVoid , { kTypeObject } }, { 807, kTypeInt , { kTypeString, kTypeString, kTypeInt } }, { 808, kTypeInt , { kTypeString, kTypeString, kTypeInt } }, { 809, kTypeVoid , { } }, { 810, kTypeVoid , { } }, { 811, kTypeVoid , { } }, { 812, kTypeVoid , { } }, { 813, kTypeVoid , { } }, { 814, kTypeVoid , { kTypeObject, kTypeInt } }, { 815, kTypeInt , { kTypeObject } }, { 816, kTypeVoid , { kTypeInt, kTypeObject } }, { 817, kTypeInt , { kTypeObject, kTypeInt } }, { 818, kTypeInt , { kTypeObject, kTypeInt } }, { 819, kTypeInt , { kTypeObject, kTypeObject } }, { 820, kTypeInt , { kTypeObject } }, { 821, kTypeInt , { kTypeFloat, kTypeInt, kTypeInt, kTypeObject } }, { 822, kTypeVoid , { kTypeObject } }, { 823, kTypeVoid , { kTypeInt, kTypeObject } }, { 824, kTypeFloat , { kTypeFloat, kTypeFloat } }, { 825, kTypeObject , { kTypeObject } }, { 826, kTypeVoid , { kTypeObject } }, { 827, kTypeInt , { kTypeObject } }, { 828, kTypeString , { } }, { 829, kTypeVoid , { } }, { 830, kTypeInt , { } }, { 831, kTypeInt , { kTypeObject, kTypeObject } }, { 832, kTypeEngineType, { kTypeFloat, kTypeObject, kTypeObject } }, { 833, kTypeInt , { kTypeInt, kTypeObject } }, { 834, kTypeVoid , { kTypeObject, kTypeObject, kTypeInt } }, { 835, kTypeInt , { kTypeObject } }, { 836, kTypeInt , { kTypeObject } }, { 837, kTypeInt , { kTypeObject, kTypeObject } }, { 838, kTypeInt , { kTypeObject } }, { 839, kTypeInt , { } }, { 840, kTypeInt , { kTypeObject, kTypeObject } }, { 841, kTypeInt , { kTypeObject } }, { 842, kTypeVoid , { kTypeObject } }, { 843, kTypeVoid , { kTypeObject, kTypeInt } }, { 844, kTypeVoid , { kTypeObject, kTypeObject } }, { 845, kTypeVoid , { } }, { 846, kTypeVoid , { kTypeInt } }, { 847, kTypeVoid , { kTypeInt, kTypeInt, kTypeObject, kTypeInt } } }; /** The table defining the default values for the parameters of each engine function. */ const Functions::FunctionDefaults Functions::kFunctionDefaults[] = { { 0, { } }, { 1, { } }, { 2, { &kDefaultInt18, &kDefaultInt9 } }, { 3, { &kDefaultInt18, &kDefaultInt9 } }, { 4, { } }, { 5, { } }, { 6, { } }, { 7, { } }, { 8, { &kDefaultObjectSelf } }, { 9, { &kDefaultFalse, &kDefaultObjectInvalid } }, { 10, { } }, { 11, { } }, { 12, { &kDefaultInt0, &kDefaultInt0, &kDefaultInt0 } }, { 13, { } }, { 14, { } }, { 15, { } }, { 16, { } }, { 17, { } }, { 18, { } }, { 19, { } }, { 20, { } }, { 21, { &kDefaultFalse } }, { 22, { &kDefaultFalse, &kDefaultFloat1_0 } }, { 23, { &kDefaultFalse, &kDefaultFloat40_0 } }, { 24, { } }, { 25, { } }, { 26, { } }, { 27, { } }, { 28, { } }, { 29, { } }, { 30, { } }, { 31, { &kDefaultObjectSelf, &kDefaultInt1 } }, { 32, { &kDefaultFalse } }, { 33, { &kDefaultFalse } }, { 34, { } }, { 35, { &kDefaultTrue } }, { 36, { &kDefaultObjectSelf } }, { 37, { &kDefaultFalse } }, { 38, { &kDefaultObjectSelf, &kDefaultInt1, &kDefaultIntMinus1, &kDefaultIntMinus1, &kDefaultIntMinus1, &kDefaultIntMinus1 } }, { 39, { &kDefaultTalkVolumeTalk } }, { 40, { &kDefaultFloat1_0, &kDefaultFloat0_0 } }, { 41, { } }, { 42, { } }, { 43, { } }, { 44, { } }, { 45, { &kDefaultFloatMinus1_0, &kDefaultFloatMinus1_0, &kDefaultCameraTransitionTypeSnap, &kDefaultInt0 } }, { 46, { &kDefaultInt0, &kDefaultFloat0_0 } }, { 47, { } }, { 48, { &kDefaultFalse, &kDefaultProjectilePathTypeDefault, &kDefaultFalse } }, { 49, { &kDefaultObjectSelf } }, { 50, { &kDefaultObjectSelf } }, { 51, { } }, { 52, { } }, { 53, { } }, { 54, { } }, { 55, { } }, { 56, { } }, { 57, { } }, { 58, { } }, { 59, { } }, { 60, { } }, { 61, { } }, { 62, { } }, { 63, { } }, { 64, { } }, { 65, { } }, { 66, { } }, { 67, { } }, { 68, { } }, { 69, { } }, { 70, { } }, { 71, { } }, { 72, { } }, { 73, { } }, { 74, { } }, { 75, { } }, { 76, { } }, { 77, { } }, { 78, { } }, { 79, { &kDefaultInt0, &kDefaultStringEmpty } }, { 80, { &kDefaultObjectSelf } }, { 81, { &kDefaultIntMinus1 } }, { 82, { } }, { 83, { &kDefaultInt0, &kDefaultFloat0_0 } }, { 84, { &kDefaultObjectSelf, &kDefaultInt0, &kDefaultFalse } }, { 85, { } }, { 86, { } }, { 87, { } }, { 88, { } }, { 89, { } }, { 90, { } }, { 91, { } }, { 92, { } }, { 93, { &kDefaultObjectInvalid } }, { 94, { &kDefaultObjectInvalid } }, { 95, { &kDefaultInt1 } }, { 96, { &kDefaultInt1 } }, { 97, { &kDefaultInt1 } }, { 98, { &kDefaultInt1 } }, { 99, { &kDefaultInt1 } }, { 100, { &kDefaultInt1 } }, { 101, { &kDefaultInt1 } }, { 102, { &kDefaultInt1 } }, { 103, { &kDefaultInt1 } }, { 104, { } }, { 105, { &kDefaultObjectSelf } }, { 106, { } }, { 107, { } }, { 108, { &kDefaultFloatMinus1_0, &kDefaultFloat0_0, &kDefaultObjectInvalid, &kDefaultStringEmpty } }, { 109, { } }, { 110, { } }, { 111, { &kDefaultIntMinus1 } }, { 112, { } }, { 113, { } }, { 114, { } }, { 115, { &kDefaultObjectSelf } }, { 116, { &kDefaultObjectSelf } }, { 117, { &kDefaultStringEmpty, &kDefaultObjectSelf, &kDefaultObjectInvalid } }, { 118, { &kDefaultObjectSelf } }, { 119, { &kDefaultObjectSelf } }, { 120, { &kDefaultObjectSelf } }, { 121, { } }, { 122, { } }, { 123, { } }, { 124, { } }, { 125, { &kDefaultTrue } }, { 126, { &kDefaultObjectSelf } }, { 127, { &kDefaultTrue, &kDefaultObjectSelf } }, { 128, { &kDefaultFalse, &kDefaultObjectTypeCreature, &kDefaultVector0, &kDefaultFloat0_5 } }, { 129, { &kDefaultFalse, &kDefaultObjectTypeCreature, &kDefaultVector0, &kDefaultFloat0_5 } }, { 130, { &kDefaultObjectSelf } }, { 131, { } }, { 132, { } }, { 133, { &kDefaultFalse, &kDefaultTrue } }, { 134, { &kDefaultObjectInvalid } }, { 135, { } }, { 136, { } }, { 137, { } }, { 138, { &kDefaultObjectSelf } }, { 139, { } }, { 140, { } }, { 141, { } }, { 142, { &kDefaultFloat0_0, &kDefaultFloat0_0, &kDefaultFloat0_0 } }, { 143, { } }, { 144, { } }, { 145, { } }, { 146, { &kDefaultObjectSelf } }, { 147, { &kDefaultObjectSelf } }, { 148, { } }, { 149, { } }, { 150, { } }, { 151, { } }, { 152, { } }, { 153, { } }, { 154, { } }, { 155, { &kDefaultObjectSelf } }, { 156, { } }, { 157, { } }, { 158, { } }, { 159, { } }, { 160, { } }, { 161, { } }, { 162, { &kDefaultObjectSelf } }, { 163, { &kDefaultObjectSelf } }, { 164, { } }, { 165, { } }, { 166, { } }, { 167, { &kDefaultFloat0_0, &kDefaultInt0 } }, { 168, { } }, { 169, { &kDefaultObjectSelf } }, { 170, { } }, { 171, { &kDefaultStringEmpty, &kDefaultStringEmpty, &kDefaultStringEmpty } }, { 172, { &kDefaultObjectSelf } }, { 173, { } }, { 174, { } }, { 175, { } }, { 176, { &kDefaultInt0 } }, { 177, { } }, { 178, { } }, { 179, { } }, { 180, { &kDefaultFalse } }, { 181, { &kDefaultObjectSelf, &kDefaultTrue } }, { 182, { &kDefaultObjectSelf, &kDefaultTrue } }, { 183, { &kDefaultObjectSelf, &kDefaultTrue } }, { 184, { &kDefaultObjectSelf, &kDefaultTrue } }, { 185, { } }, { 186, { } }, { 187, { &kDefaultObjectSelf } }, { 188, { &kDefaultObjectSelf } }, { 189, { } }, { 190, { } }, { 191, { } }, { 192, { &kDefaultObjectSelf, &kDefaultTrue } }, { 193, { &kDefaultObjectSelf, &kDefaultTrue } }, { 194, { } }, { 195, { } }, { 196, { &kDefaultTrue } }, { 197, { } }, { 198, { } }, { 199, { } }, { 200, { &kDefaultInt0 } }, { 201, { } }, { 202, { } }, { 203, { &kDefaultStringEmpty } }, { 204, { &kDefaultStringEmpty, &kDefaultFalse, &kDefaultTrue, &kDefaultFalse } }, { 205, { } }, { 206, { } }, { 207, { } }, { 208, { } }, { 209, { &kDefaultObjectSelf } }, { 210, { } }, { 211, { } }, { 212, { &kDefaultObjectSelf } }, { 213, { } }, { 214, { } }, { 215, { } }, { 216, { &kDefaultFloat0_0 } }, { 217, { } }, { 218, { } }, { 219, { } }, { 220, { &kDefaultFloat0_0, &kDefaultStringEmpty, &kDefaultIntMinus1 } }, { 221, { &kDefaultTalkVolumeTalk } }, { 222, { } }, { 223, { } }, { 224, { } }, { 225, { } }, { 226, { &kDefaultInt1, &kDefaultIntMinus1, &kDefaultIntMinus1, &kDefaultIntMinus1, &kDefaultIntMinus1 } }, { 227, { &kDefaultObjectTypeAll, &kDefaultObjectSelf, &kDefaultInt1 } }, { 228, { &kDefaultInt1 } }, { 229, { &kDefaultObjectSelf, &kDefaultInt1, &kDefaultObjectTypeAll } }, { 230, { } }, { 231, { } }, { 232, { } }, { 233, { } }, { 234, { &kDefaultFalse, &kDefaultProjectilePathTypeDefault, &kDefaultFalse } }, { 235, { &kDefaultObjectSelf } }, { 236, { } }, { 237, { } }, { 238, { } }, { 239, { &kDefaultGenderMale } }, { 240, { &kDefaultTalkVolumeTalk } }, { 241, { &kDefaultFloat0_0 } }, { 242, { } }, { 243, { &kDefaultFalse, &kDefaultStringEmpty } }, { 244, { &kDefaultTrue } }, { 245, { } }, { 246, { } }, { 247, { } }, { 248, { } }, { 249, { } }, { 250, { } }, { 251, { &kDefaultObjectSelf } }, { 252, { } }, { 253, { } }, { 254, { } }, { 255, { &kDefaultStringEmpty, &kDefaultObjectInvalid, &kDefaultObjectInvalid } }, { 256, { } }, { 257, { } }, { 258, { } }, { 259, { } }, { 260, { } }, { 261, { } }, { 262, { &kDefaultObjectSelf, &kDefaultObjectTypeCreature, &kDefaultPersistentZoneActive } }, { 263, { &kDefaultObjectSelf, &kDefaultObjectTypeCreature, &kDefaultPersistentZoneActive } }, { 264, { &kDefaultObjectSelf } }, { 265, { } }, { 266, { } }, { 267, { } }, { 268, { } }, { 269, { } }, { 270, { } }, { 271, { } }, { 272, { } }, { 273, { &kDefaultIntMinus1, &kDefaultObjectSelf } }, { 274, { &kDefaultObjectSelf } }, { 275, { } }, { 276, { &kDefaultObjectSelf } }, { 277, { &kDefaultObjectSelf } }, { 278, { &kDefaultObjectSelf } }, { 279, { &kDefaultObjectSelf } }, { 280, { &kDefaultObjectSelf } }, { 281, { &kDefaultObjectSelf } }, { 282, { } }, { 283, { } }, { 284, { } }, { 285, { &kDefaultObjectSelf } }, { 286, { &kDefaultFloat1_0 } }, { 287, { } }, { 288, { } }, { 289, { &kDefaultObjectSelf } }, { 290, { &kDefaultObjectSelf } }, { 291, { } }, { 292, { } }, { 293, { } }, { 294, { } }, { 295, { } }, { 296, { &kDefaultObjectSelf } }, { 297, { &kDefaultObjectSelf } }, { 298, { } }, { 299, { } }, { 300, { &kDefaultFloat1_0, &kDefaultFloat0_0 } }, { 301, { } }, { 302, { } }, { 303, { } }, { 304, { &kDefaultObjectSelf } }, { 305, { } }, { 306, { &kDefaultObjectSelf } }, { 307, { &kDefaultObjectSelf } }, { 308, { &kDefaultObjectSelf } }, { 309, { } }, { 310, { } }, { 311, { } }, { 312, { } }, { 313, { } }, { 314, { } }, { 315, { &kDefaultObjectSelf } }, { 316, { &kDefaultObjectSelf } }, { 317, { &kDefaultObjectSelf } }, { 318, { } }, { 319, { &kDefaultObjectSelf } }, { 320, { &kDefaultObjectSelf } }, { 321, { &kDefaultObjectSelf } }, { 322, { } }, { 323, { &kDefaultTrue, &kDefaultFalse } }, { 324, { } }, { 325, { } }, { 326, { } }, { 327, { &kDefaultObjectSelf } }, { 328, { } }, { 329, { } }, { 330, { } }, { 331, { &kDefaultObjectSelf } }, { 332, { } }, { 333, { } }, { 334, { &kDefaultObjectSelf } }, { 335, { &kDefaultObjectSelf } }, { 336, { } }, { 337, { } }, { 338, { } }, { 339, { &kDefaultObjectSelf } }, { 340, { &kDefaultObjectSelf } }, { 341, { &kDefaultObjectSelf } }, { 342, { &kDefaultObjectSelf } }, { 343, { &kDefaultObjectSelf } }, { 344, { } }, { 345, { } }, { 346, { } }, { 347, { } }, { 348, { } }, { 349, { } }, { 350, { } }, { 351, { } }, { 352, { } }, { 353, { } }, { 354, { &kDefaultObjectSelf } }, { 355, { &kDefaultObjectSelf } }, { 356, { } }, { 357, { } }, { 358, { } }, { 359, { } }, { 360, { &kDefaultFalse, &kDefaultFloat40_0 } }, { 361, { } }, { 362, { } }, { 363, { } }, { 364, { &kDefaultObjectSelf } }, { 365, { &kDefaultObjectSelf } }, { 366, { &kDefaultObjectSelf } }, { 367, { } }, { 368, { } }, { 369, { } }, { 370, { } }, { 371, { } }, { 372, { } }, { 373, { } }, { 374, { } }, { 375, { } }, { 376, { } }, { 377, { &kDefaultObjectSelf } }, { 378, { &kDefaultIntMinus1 } }, { 379, { } }, { 380, { &kDefaultTrue } }, { 381, { &kDefaultTrue } }, { 382, { &kDefaultFalse, &kDefaultFloat30_0 } }, { 383, { &kDefaultFalse, &kDefaultFloat1_0, &kDefaultFloat30_0 } }, { 384, { } }, { 385, { &kDefaultInt1 } }, { 386, { } }, { 387, { } }, { 388, { } }, { 389, { &kDefaultObjectSelf } }, { 390, { &kDefaultObjectSelf } }, { 391, { } }, { 392, { &kDefaultObjectSelf } }, { 393, { &kDefaultTrue } }, { 394, { &kDefaultTrue } }, { 395, { } }, { 396, { } }, { 397, { } }, { 398, { } }, { 399, { &kDefaultObjectInvalid, &kDefaultFalse } }, { 400, { &kDefaultObjectInvalid } }, { 401, { &kDefaultObjectSelf } }, { 402, { } }, { 403, { } }, { 404, { } }, { 405, { } }, { 406, { } }, { 407, { } }, { 408, { } }, { 409, { &kDefaultObjectSelf } }, { 410, { } }, { 411, { } }, { 412, { } }, { 413, { } }, { 414, { } }, { 415, { } }, { 416, { } }, { 417, { &kDefaultStringEmpty, &kDefaultObjectInvalid } }, { 418, { &kDefaultObjectSelf } }, { 419, { } }, { 420, { } }, { 421, { &kDefaultObjectSelf } }, { 422, { &kDefaultObjectInvalid, &kDefaultFalse } }, { 423, { } }, { 424, { &kDefaultObjectInvalid } }, { 425, { } }, { 426, { } }, { 427, { } }, { 428, { } }, { 429, { } }, { 430, { } }, { 431, { } }, { 432, { } }, { 433, { } }, { 434, { } }, { 435, { } }, { 436, { } }, { 437, { } }, { 438, { } }, { 439, { } }, { 440, { } }, { 441, { } }, { 442, { } }, { 443, { } }, { 444, { &kDefaultFalse } }, { 445, { } }, { 446, { &kDefaultInt1, &kDefaultObjectSelf } }, { 447, { } }, { 448, { } }, { 449, { } }, { 450, { } }, { 451, { } }, { 452, { } }, { 453, { } }, { 454, { } }, { 455, { &kDefaultObjectSelf } }, { 456, { } }, { 457, { } }, { 458, { &kDefaultStringEmpty, &kDefaultStringEmpty } }, { 459, { } }, { 460, { } }, { 461, { } }, { 462, { &kDefaultObjectSelf } }, { 463, { } }, { 464, { &kDefaultInt0, &kDefaultObjectSelf } }, { 465, { } }, { 466, { } }, { 467, { } }, { 468, { } }, { 469, { } }, { 470, { &kDefaultObjectSelf } }, { 471, { &kDefaultFalse } }, { 472, { } }, { 473, { &kDefaultTrue } }, { 474, { &kDefaultStringEmpty, &kDefaultStringEmpty, &kDefaultStringEmpty, &kDefaultFalse } }, { 475, { } }, { 476, { } }, { 477, { &kDefaultObjectSelf } }, { 478, { &kDefaultObjectSelf } }, { 479, { } }, { 480, { } }, { 481, { } }, { 482, { } }, { 483, { &kDefaultObjectSelf } }, { 484, { &kDefaultObjectSelf } }, { 485, { &kDefaultObjectSelf } }, { 486, { &kDefaultObjectSelf } }, { 487, { &kDefaultObjectSelf } }, { 488, { &kDefaultObjectSelf, &kDefaultTrue } }, { 489, { &kDefaultObjectSelf } }, { 490, { &kDefaultObjectSelf } }, { 491, { } }, { 492, { &kDefaultStringEmpty, &kDefaultInt1, &kDefaultInt1, &kDefaultInt1, &kDefaultInt0, &kDefaultInt0 } }, { 493, { &kDefaultObjectSelf } }, { 494, { } }, { 495, { } }, { 496, { } }, { 497, { } }, { 498, { } }, { 499, { } }, { 500, { } }, { 501, { &kDefaultProjectilePathTypeDefault } }, { 502, { &kDefaultProjectilePathTypeDefault } }, { 503, { &kDefaultObjectSelf } }, { 504, { &kDefaultObjectSelf } }, { 505, { &kDefaultObjectSelf } }, { 506, { } }, { 507, { } }, { 508, { } }, { 509, { } }, { 510, { &kDefaultObjectSelf } }, { 511, { } }, { 512, { } }, { 513, { } }, { 514, { &kDefaultObjectSelf } }, { 515, { } }, { 516, { } }, { 517, { } }, { 518, { } }, { 519, { } }, { 520, { } }, { 521, { } }, { 522, { &kDefaultObjectSelf } }, { 523, { &kDefaultObjectSelf } }, { 524, { &kDefaultObjectSelf } }, { 525, { &kDefaultTrue } }, { 526, { &kDefaultTrue } }, { 527, { } }, { 528, { } }, { 529, { } }, { 530, { } }, { 531, { } }, { 532, { } }, { 533, { } }, { 534, { } }, { 535, { } }, { 536, { } }, { 537, { } }, { 538, { } }, { 539, { } }, { 540, { } }, { 541, { } }, { 542, { } }, { 543, { &kDefaultObjectSelf } }, { 544, { &kDefaultObjectSelf, &kDefaultTrue } }, { 545, { &kDefaultObjectSelf } }, { 546, { } }, { 547, { } }, { 548, { } }, { 549, { } }, { 550, { } }, { 551, { } }, { 552, { } }, { 553, { } }, { 554, { &kDefaultTrue, &kDefaultTrue, &kDefaultInt0, &kDefaultStringEmpty } }, { 555, { } }, { 556, { &kDefaultObjectSelf } }, { 557, { } }, { 558, { } }, { 559, { } }, { 560, { } }, { 561, { } }, { 562, { } }, { 563, { } }, { 564, { } }, { 565, { } }, { 566, { } }, { 567, { } }, { 568, { } }, { 569, { } }, { 570, { } }, { 571, { } }, { 572, { &kDefaultObjectSelf } }, { 573, { } }, { 574, { &kDefaultInt0, &kDefaultIntMinus1, &kDefaultFalse } }, { 575, { &kDefaultInt0, &kDefaultIntMinus1, &kDefaultFalse } }, { 576, { } }, { 577, { } }, { 578, { } }, { 579, { } }, { 580, { } }, { 581, { } }, { 582, { } }, { 583, { } }, { 584, { &kDefaultObjectInvalid } }, { 585, { } }, { 586, { } }, { 587, { &kDefaultObjectSelf } }, { 588, { } }, { 589, { &kDefaultObjectInvalid } }, { 590, { &kDefaultObjectInvalid } }, { 591, { &kDefaultObjectInvalid } }, { 592, { &kDefaultObjectInvalid } }, { 593, { &kDefaultObjectInvalid } }, { 594, { } }, { 595, { &kDefaultObjectInvalid } }, { 596, { &kDefaultObjectInvalid } }, { 597, { &kDefaultObjectInvalid } }, { 598, { &kDefaultObjectInvalid } }, { 599, { &kDefaultObjectInvalid } }, { 600, { &kDefaultObjectInvalid, &kDefaultStringEmpty } }, { 601, { &kDefaultObjectInvalid } }, { 602, { &kDefaultObjectInvalid } }, { 603, { &kDefaultObjectInvalid, &kDefaultObjectInvalid } }, { 604, { } }, { 605, { } }, { 606, { } }, { 607, { } }, { 608, { } }, { 609, { } }, { 610, { } }, { 611, { } }, { 612, { } }, { 613, { } }, { 614, { } }, { 615, { } }, { 616, { } }, { 617, { &kDefaultObjectSelf } }, { 618, { } }, { 619, { &kDefaultObjectSelf } }, { 620, { &kDefaultObjectSelf } }, { 621, { } }, { 622, { &kDefaultFloat0_0, &kDefaultObjectSelf } }, { 623, { &kDefaultObjectSelf } }, { 624, { } }, { 625, { &kDefaultObjectSelf } }, { 626, { &kDefaultObjectSelf } }, { 627, { &kDefaultObjectSelf } }, { 628, { &kDefaultObjectSelf } }, { 629, { &kDefaultObjectSelf } }, { 630, { } }, { 631, { &kDefaultInt0 } }, { 632, { &kDefaultFalse } }, { 633, { } }, { 634, { } }, { 635, { } }, { 636, { } }, { 637, { &kDefaultInt0 } }, { 638, { } }, { 639, { } }, { 640, { } }, { 641, { } }, { 642, { } }, { 643, { } }, { 644, { } }, { 645, { } }, { 646, { } }, { 647, { } }, { 648, { } }, { 649, { } }, { 650, { } }, { 651, { } }, { 652, { } }, { 653, { } }, { 654, { } }, { 655, { &kDefaultObjectSelf } }, { 656, { &kDefaultTrue } }, { 657, { } }, { 658, { } }, { 659, { } }, { 660, { } }, { 661, { } }, { 662, { } }, { 663, { &kDefaultVector0 } }, { 664, { } }, { 665, { } }, { 666, { } }, { 667, { } }, { 668, { } }, { 669, { } }, { 670, { } }, { 671, { } }, { 672, { } }, { 673, { } }, { 674, { } }, { 675, { } }, { 676, { } }, { 677, { } }, { 678, { } }, { 679, { } }, { 680, { } }, { 681, { } }, { 682, { } }, { 683, { } }, { 684, { } }, { 685, { } }, { 686, { } }, { 687, { } }, { 688, { } }, { 689, { } }, { 690, { } }, { 691, { &kDefaultTalkVolumeTalk } }, { 692, { &kDefaultTrue, &kDefaultFalse } }, { 693, { } }, { 694, { } }, { 695, { &kDefaultFadeSpeedMedium } }, { 696, { &kDefaultFadeSpeedMedium } }, { 697, { } }, { 698, { } }, { 699, { } }, { 700, { } }, { 701, { &kDefaultIntMinus1 } }, { 702, { } }, { 703, { } }, { 704, { &kDefaultFalse } }, { 705, { } }, { 706, { } }, { 707, { } }, { 708, { &kDefaultObjectSelf } }, { 709, { } }, { 710, { } }, { 711, { &kDefaultObjectSelf } }, { 712, { &kDefaultObjectSelf } }, { 713, { } }, { 714, { } }, { 715, { } }, { 716, { } }, { 717, { } }, { 718, { } }, { 719, { } }, { 720, { &kDefaultTrue } }, { 721, { } }, { 722, { } }, { 723, { } }, { 724, { } }, { 725, { } }, { 726, { &kDefaultIntMinus1 } }, { 727, { } }, { 728, { } }, { 729, { } }, { 730, { } }, { 731, { } }, { 732, { } }, { 733, { } }, { 734, { } }, { 735, { } }, { 736, { } }, { 737, { } }, { 738, { } }, { 739, { } }, { 740, { } }, { 741, { } }, { 742, { } }, { 743, { } }, { 744, { } }, { 745, { } }, { 746, { &kDefaultTrue } }, { 747, { } }, { 748, { &kDefaultObjectSelf, &kDefaultFalse } }, { 749, { } }, { 750, { } }, { 751, { } }, { 752, { } }, { 753, { } }, { 754, { &kDefaultObjectSelf } }, { 755, { } }, { 756, { } }, { 757, { } }, { 758, { &kDefaultInt1 } }, { 759, { } }, { 760, { } }, { 761, { } }, { 762, { } }, { 763, { } }, { 764, { &kDefaultFalse } }, { 765, { } }, { 766, { } }, { 767, { } }, { 768, { } }, { 769, { } }, { 770, { &kDefaultFalse } }, { 771, { } }, { 772, { } }, { 773, { &kDefaultObjectInvalid, &kDefaultInt0 } }, { 774, { } }, { 775, { } }, { 776, { &kDefaultFalse, &kDefaultObjectInvalid } }, { 777, { &kDefaultFalse, &kDefaultFalse, &kDefaultObjectInvalid } }, { 778, { } }, { 779, { } }, { 780, { } }, { 781, { } }, { 782, { } }, { 783, { } }, { 784, { } }, { 785, { } }, { 786, { } }, { 787, { &kDefaultStringEmpty, &kDefaultStringEmpty, &kDefaultStringEmpty } }, { 788, { } }, { 789, { } }, { 790, { } }, { 791, { } }, { 792, { } }, { 793, { &kDefaultStringEmpty } }, { 794, { } }, { 795, { &kDefaultInt0, &kDefaultStringEmpty, &kDefaultStringEmpty, &kDefaultStringEmpty, &kDefaultObjectSelf, &kDefaultInt0 } }, { 796, { &kDefaultInt0 } }, { 797, { } }, { 798, { } }, { 799, { &kDefaultStringEmpty, &kDefaultStringEmpty } }, { 800, { } }, { 801, { } }, { 802, { } }, { 803, { } }, { 804, { } }, { 805, { &kDefaultObjectSelf, &kDefaultInt0 } }, { 806, { } }, { 807, { } }, { 808, { } }, { 809, { } }, { 810, { } }, { 811, { } }, { 812, { } }, { 813, { } }, { 814, { } }, { 815, { } }, { 816, { } }, { 817, { &kDefaultFalse } }, { 818, { &kDefaultFalse } }, { 819, { } }, { 820, { } }, { 821, { } }, { 822, { } }, { 823, { } }, { 824, { } }, { 825, { } }, { 826, { } }, { 827, { } }, { 828, { } }, { 829, { } }, { 830, { } }, { 831, { } }, { 832, { } }, { 833, { } }, { 834, { } }, { 835, { } }, { 836, { } }, { 837, { } }, { 838, { } }, { 839, { } }, { 840, { } }, { 841, { } }, { 842, { } }, { 843, { } }, { 844, { } }, { 845, { } }, { 846, { &kDefaultTrue } }, { 847, { &kDefaultFalse } } }; } // End of namespace Witcher } // End of namespace Engines #endif // ENGINES_WITCHER_NWSCRIPT_FUNCTION_TABLES_H
Supermanu/xoreos
src/engines/witcher/nwscript/function_tables.h
C
gpl-3.0
149,962
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.client.hook; import java.util.Map; import com.alibaba.rocketmq.client.impl.CommunicationMode; import com.alibaba.rocketmq.client.producer.SendResult; import com.alibaba.rocketmq.common.message.Message; import com.alibaba.rocketmq.common.message.MessageQueue; public class SendMessageContext { private String producerGroup; private Message message; private MessageQueue mq; private String brokerAddr; private String bornHost; private CommunicationMode communicationMode; private SendResult sendResult; private Exception exception; private Object mqTraceContext; private Map<String, String> props; public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } public MessageQueue getMq() { return mq; } public void setMq(MessageQueue mq) { this.mq = mq; } public String getBrokerAddr() { return brokerAddr; } public void setBrokerAddr(String brokerAddr) { this.brokerAddr = brokerAddr; } public CommunicationMode getCommunicationMode() { return communicationMode; } public void setCommunicationMode(CommunicationMode communicationMode) { this.communicationMode = communicationMode; } public SendResult getSendResult() { return sendResult; } public void setSendResult(SendResult sendResult) { this.sendResult = sendResult; } public Exception getException() { return exception; } public void setException(Exception exception) { this.exception = exception; } public Object getMqTraceContext() { return mqTraceContext; } public void setMqTraceContext(Object mqTraceContext) { this.mqTraceContext = mqTraceContext; } public Map<String, String> getProps() { return props; } public void setProps(Map<String, String> props) { this.props = props; } public String getBornHost() { return bornHost; } public void setBornHost(String bornHost) { this.bornHost = bornHost; } }
y123456yz/reading-and-annotate-rocketmq-3.4.6
rocketmq-src/RocketMQ-3.4.6/rocketmq-client/src/main/java/com/alibaba/rocketmq/client/hook/SendMessageContext.java
Java
gpl-3.0
3,205
<?php /** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link git://git.assembla.com/nooku-framework.git for the canonical source repository */ namespace Nooku\Library; /** * Object Set * * ObjectSet implements an associative container that stores objects, and in which the object themselves are the keys. * Objects are stored in the set in FIFO order. * * @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens> * @package Nooku\Library\Object * @see http://www.php.net/manual/en/class.splobjectstorage.php */ class ObjectSet extends Object implements \IteratorAggregate, \ArrayAccess, \Countable, \Serializable { /** * Object set * * @var array */ protected $_object_set = null; /** * Constructor * * @param ObjectConfig $config A ObjectConfig object with configuration options * @return ObjectSet */ public function __construct(ObjectConfig $config) { parent::__construct($config); $this->_object_set = new \ArrayObject(); } /** * Inserts an object in the set * * @param ObjectHandlable $object * @return boolean TRUE on success FALSE on failure */ public function insert(ObjectHandlable $object) { $result = false; if ($handle = $object->getHandle()) { $this->_object_set->offsetSet($handle, $object); $result = true; } return $result; } /** * Removes an object from the set * * All numerical array keys will be modified to start counting from zero while literal keys won't be touched. * * @param ObjectHandlable $object * @return ObjectSet */ public function extract(ObjectHandlable $object) { $handle = $object->getHandle(); if ($this->_object_set->offsetExists($handle)) { $this->_object_set->offsetUnset($handle); } return $this; } /** * Checks if the set contains a specific object * * @param ObjectHandlable $object * @return bool Returns TRUE if the object is in the set, FALSE otherwise */ public function contains(ObjectHandlable $object) { return $this->_object_set->offsetExists($object->getHandle()); } /** * Merge-in another object set * * @param ObjectSet $set * @return ObjectSet */ public function merge(ObjectSet $set) { foreach ($set as $object) { $this->insert($object); } return $this; } /** * Check if the object exists in the queue * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return bool Returns TRUE if the object exists in the storage, and FALSE otherwise * @throws \InvalidArgumentException if the object doesn't implement ObjectHandlable */ public function offsetExists($object) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } return $this->contains($object); } /** * Returns the object from the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return ObjectHandlable * @throws \InvalidArgumentException if the object doesn't implement ObjectHandlable */ public function offsetGet($object) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } return $this->_object_set->offsetGet($object->getHandle()); } /** * Store an object in the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @param mixed $data The data to associate with the object [UNUSED] * @return ObjectSet * @throws \InvalidArgumentException if the object doesn't implement ObjectHandlable */ public function offsetSet($object, $data) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } $this->insert($object); return $this; } /** * Removes an object from the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return ObjectSet * @throws InvalidArgumentException if the object doesn't implement the ObjectHandlable interface */ public function offsetUnset($object) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } $this->extract($object); return $this; } /** * Return a string representation of the set * * Required by interface \Serializable * * @return string A serialized object */ public function serialize() { return serialize($this->_object_set); } /** * Unserializes a set from its string representation * * Required by interface \Serializable * * @param string $serialized The serialized data */ public function unserialize($serialized) { $this->_object_set = unserialize($serialized); } /** * Returns the number of elements in the collection. * * Required by the Countable interface * * @return int */ public function count() { return $this->_object_set->count(); } /** * Return the first object in the set * * @return ObjectHandlable or NULL is queue is empty */ public function top() { $objects = array_values($this->_object_set->getArrayCopy()); $object = null; if (isset($objects[0])) { $object = $objects[0]; } return $object; } /** * Defined by IteratorAggregate * * @return \ArrayIterator */ public function getIterator() { return $this->_object_set->getIterator(); } /** * Return an associative array of the data. * * @return array */ public function toArray() { return $this->_object_set->getArrayCopy(); } /** * Preform a deep clone of the object * * @retun void */ public function __clone() { parent::__clone(); $this->_object_set = clone $this->_object_set; } }
jowillems/internet-platform
library/object/set.php
PHP
gpl-3.0
6,776
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Standard library of functions and constants for lesson * * @package mod_lesson * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later **/ defined('MOODLE_INTERNAL') || die(); /* Do not include any libraries here! */ /** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will create a new instance and return the id number * of the new instance. * * @global object * @global object * @param object $lesson Lesson post data from the form * @return int **/ function lesson_add_instance($data, $mform) { global $DB; $cmid = $data->coursemodule; $draftitemid = $data->mediafile; $context = context_module::instance($cmid); lesson_process_pre_save($data); unset($data->mediafile); $lessonid = $DB->insert_record("lesson", $data); $data->id = $lessonid; lesson_update_media_file($lessonid, $context, $draftitemid); lesson_process_post_save($data); lesson_grade_item_update($data); return $lessonid; } /** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will update an existing instance with new data. * * @global object * @param object $lesson Lesson post data from the form * @return boolean **/ function lesson_update_instance($data, $mform) { global $DB; $data->id = $data->instance; $cmid = $data->coursemodule; $draftitemid = $data->mediafile; $context = context_module::instance($cmid); lesson_process_pre_save($data); unset($data->mediafile); $DB->update_record("lesson", $data); lesson_update_media_file($data->id, $context, $draftitemid); lesson_process_post_save($data); // update grade item definition lesson_grade_item_update($data); // update grades - TODO: do it only when grading style changes lesson_update_grades($data, 0, false); return true; } /** * This function updates the events associated to the lesson. * If $override is non-zero, then it updates only the events * associated with the specified override. * * @uses LESSON_MAX_EVENT_LENGTH * @param object $lesson the lesson object. * @param object $override (optional) limit to a specific override */ function lesson_update_events($lesson, $override = null) { global $CFG, $DB; require_once($CFG->dirroot . '/mod/lesson/locallib.php'); require_once($CFG->dirroot . '/calendar/lib.php'); // Load the old events relating to this lesson. $conds = array('modulename' => 'lesson', 'instance' => $lesson->id); if (!empty($override)) { // Only load events for this override. if (isset($override->userid)) { $conds['userid'] = $override->userid; } else { $conds['groupid'] = $override->groupid; } } $oldevents = $DB->get_records('event', $conds); // Now make a to-do list of all that needs to be updated. if (empty($override)) { // We are updating the primary settings for the lesson, so we need to add all the overrides. $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id)); // As well as the original lesson (empty override). $overrides[] = new stdClass(); } else { // Just do the one override. $overrides = array($override); } // Get group override priorities. $grouppriorities = lesson_get_group_override_priorities($lesson->id); foreach ($overrides as $current) { $groupid = isset($current->groupid) ? $current->groupid : 0; $userid = isset($current->userid) ? $current->userid : 0; $available = isset($current->available) ? $current->available : $lesson->available; $deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline; // Only add open/close events for an override if they differ from the lesson default. $addopen = empty($current->id) || !empty($current->available); $addclose = empty($current->id) || !empty($current->deadline); if (!empty($lesson->coursemodule)) { $cmid = $lesson->coursemodule; } else { $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id; } $event = new stdClass(); $event->description = format_module_intro('lesson', $lesson, $cmid); // Events module won't show user events when the courseid is nonzero. $event->courseid = ($userid) ? 0 : $lesson->course; $event->groupid = $groupid; $event->userid = $userid; $event->modulename = 'lesson'; $event->instance = $lesson->id; $event->timestart = $available; $event->timeduration = max($deadline - $available, 0); $event->visible = instance_is_visible('lesson', $lesson); $event->eventtype = 'open'; // Determine the event name and priority. if ($groupid) { // Group override event. $params = new stdClass(); $params->lesson = $lesson->name; $params->group = groups_get_group_name($groupid); if ($params->group === false) { // Group doesn't exist, just skip it. continue; } $eventname = get_string('overridegroupeventname', 'lesson', $params); // Set group override priority. if ($grouppriorities !== null) { $openpriorities = $grouppriorities['open']; if (isset($openpriorities[$available])) { $event->priority = $openpriorities[$available]; } } } else if ($userid) { // User override event. $params = new stdClass(); $params->lesson = $lesson->name; $eventname = get_string('overrideusereventname', 'lesson', $params); // Set user override priority. $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY; } else { // The parent event. $eventname = $lesson->name; } if ($addopen or $addclose) { // Separate start and end events. $event->timeduration = 0; if ($available && $addopen) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('lessonopens', 'lesson').')'; // The method calendar_event::create will reuse a db record if the id field is set. calendar_event::create($event); } if ($deadline && $addclose) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('lessoncloses', 'lesson').')'; $event->timestart = $deadline; $event->eventtype = 'close'; if ($groupid && $grouppriorities !== null) { $closepriorities = $grouppriorities['close']; if (isset($closepriorities[$deadline])) { $event->priority = $closepriorities[$deadline]; } } calendar_event::create($event); } } } // Delete any leftover events. foreach ($oldevents as $badevent) { $badevent = calendar_event::load($badevent); $badevent->delete(); } } /** * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson. * * @param int $lessonid The quiz ID. * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides. */ function lesson_get_group_override_priorities($lessonid) { global $DB; // Fetch group overrides. $where = 'lessonid = :lessonid AND groupid IS NOT NULL'; $params = ['lessonid' => $lessonid]; $overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline'); if (!$overrides) { return null; } $grouptimeopen = []; $grouptimeclose = []; foreach ($overrides as $override) { if ($override->available !== null && !in_array($override->available, $grouptimeopen)) { $grouptimeopen[] = $override->available; } if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) { $grouptimeclose[] = $override->deadline; } } // Sort open times in descending manner. The earlier open time gets higher priority. rsort($grouptimeopen); // Set priorities. $opengrouppriorities = []; $openpriority = 1; foreach ($grouptimeopen as $timeopen) { $opengrouppriorities[$timeopen] = $openpriority++; } // Sort close times in ascending manner. The later close time gets higher priority. sort($grouptimeclose); // Set priorities. $closegrouppriorities = []; $closepriority = 1; foreach ($grouptimeclose as $timeclose) { $closegrouppriorities[$timeclose] = $closepriority++; } return [ 'open' => $opengrouppriorities, 'close' => $closegrouppriorities ]; } /** * This standard function will check all instances of this module * and make sure there are up-to-date events created for each of them. * If courseid = 0, then every lesson event in the site is checked, else * only lesson events belonging to the course specified are checked. * This function is used, in its new format, by restore_refresh_events() * * @param int $courseid * @return bool */ function lesson_refresh_events($courseid = 0) { global $DB; if ($courseid == 0) { if (!$lessons = $DB->get_records('lesson')) { return true; } } else { if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) { return true; } } foreach ($lessons as $lesson) { lesson_update_events($lesson); } return true; } /** * Given an ID of an instance of this module, * this function will permanently delete the instance * and any data that depends on it. * * @global object * @param int $id * @return bool */ function lesson_delete_instance($id) { global $DB, $CFG; require_once($CFG->dirroot . '/mod/lesson/locallib.php'); $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST); $lesson = new lesson($lesson); return $lesson->delete(); } /** * Return a small object with summary information about what a * user has done with a given particular instance of this module * Used for user activity reports. * $return->time = the time they did it * $return->info = a short text description * * @global object * @param object $course * @param object $user * @param object $mod * @param object $lesson * @return object */ function lesson_user_outline($course, $user, $mod, $lesson) { global $CFG, $DB; require_once("$CFG->libdir/gradelib.php"); $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id); $return = new stdClass(); if (empty($grades->items[0]->grades)) { $return->info = get_string("nolessonattempts", "lesson"); } else { $grade = reset($grades->items[0]->grades); if (empty($grade->grade)) { // Check to see if it an ungraded / incomplete attempt. $sql = "SELECT * FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid ORDER BY starttime DESC"; $params = array('lessonid' => $lesson->id, 'userid' => $user->id); if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) { $attempt = reset($attempts); if ($attempt->completed) { $return->info = get_string("completed", "lesson"); } else { $return->info = get_string("notyetcompleted", "lesson"); } $return->time = $attempt->lessontime; } else { $return->info = get_string("nolessonattempts", "lesson"); } } else { $return->info = get_string("grade") . ': ' . $grade->str_long_grade; // Datesubmitted == time created. dategraded == time modified or time overridden. // If grade was last modified by the user themselves use date graded. Otherwise use date submitted. // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704. if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) { $return->time = $grade->dategraded; } else { $return->time = $grade->datesubmitted; } } } return $return; } /** * Print a detailed representation of what a user has done with * a given particular instance of this module, for user activity reports. * * @global object * @param object $course * @param object $user * @param object $mod * @param object $lesson * @return bool */ function lesson_user_complete($course, $user, $mod, $lesson) { global $DB, $OUTPUT, $CFG; require_once("$CFG->libdir/gradelib.php"); $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id); // Display the grade and feedback. if (empty($grades->items[0]->grades)) { echo $OUTPUT->container(get_string("nolessonattempts", "lesson")); } else { $grade = reset($grades->items[0]->grades); if (empty($grade->grade)) { // Check to see if it an ungraded / incomplete attempt. $sql = "SELECT * FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid ORDER by starttime desc"; $params = array('lessonid' => $lesson->id, 'userid' => $user->id); if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) { if ($attempt->completed) { $status = get_string("completed", "lesson"); } else { $status = get_string("notyetcompleted", "lesson"); } } else { $status = get_string("nolessonattempts", "lesson"); } } else { $status = get_string("grade") . ': ' . $grade->str_long_grade; } // Display the grade or lesson status if there isn't one. echo $OUTPUT->container($status); if ($grade->str_feedback) { echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback); } } // Display the lesson progress. // Attempt, pages viewed, questions answered, correct answers, time. $params = array ("lessonid" => $lesson->id, "userid" => $user->id); $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen"); $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen"); if (!empty($attempts) or !empty($branches)) { echo $OUTPUT->box_start(); $table = new html_table(); // Table Headings. $table->head = array (get_string("attemptheader", "lesson"), get_string("totalpagesviewedheader", "lesson"), get_string("numberofpagesviewedheader", "lesson"), get_string("numberofcorrectanswersheader", "lesson"), get_string("time")); $table->width = "100%"; $table->align = array ("center", "center", "center", "center", "center"); $table->size = array ("*", "*", "*", "*", "*"); $table->cellpadding = 2; $table->cellspacing = 0; $retry = 0; $nquestions = 0; $npages = 0; $ncorrect = 0; // Filter question pages (from lesson_attempts). foreach ($attempts as $attempt) { if ($attempt->retry == $retry) { $npages++; $nquestions++; if ($attempt->correct) { $ncorrect++; } $timeseen = $attempt->timeseen; } else { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); $retry++; $nquestions = 1; $npages = 1; if ($attempt->correct) { $ncorrect = 1; } else { $ncorrect = 0; } } } // Filter content pages (from lesson_branch). foreach ($branches as $branch) { if ($branch->retry == $retry) { $npages++; $timeseen = $branch->timeseen; } else { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); $retry++; $npages = 1; } } if ($npages > 0) { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); } echo html_writer::table($table); echo $OUTPUT->box_end(); } return true; } /** * Prints lesson summaries on MyMoodle Page * * Prints lesson name, due date and attempt information on * lessons that have a deadline that has not already passed * and it is available for taking. * * @global object * @global stdClass * @global object * @uses CONTEXT_MODULE * @param array $courses An array of course objects to get lesson instances from * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output ) * @return void */ function lesson_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB, $OUTPUT; if (!$lessons = get_all_instances_in_courses('lesson', $courses)) { return; } // Get all of the current users attempts on all lessons. $params = array($USER->id); $sql = 'SELECT lessonid, userid, count(userid) as attempts FROM {lesson_grades} WHERE userid = ? GROUP BY lessonid, userid'; $allattempts = $DB->get_records_sql($sql, $params); $completedattempts = array(); foreach ($allattempts as $myattempt) { $completedattempts[$myattempt->lessonid] = $myattempt->attempts; } // Get the current course ID. $listoflessons = array(); foreach ($lessons as $lesson) { $listoflessons[] = $lesson->id; } // Get the last page viewed by the current user for every lesson in this course. list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED); $dbparams = array_merge($inparams, array('userid' => $USER->id)); // Get the lesson attempts for the user that have the maximum 'timeseen' value. $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype "; $from = "FROM {lesson_attempts} l JOIN ( SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id FROM {lesson_attempts} idselect JOIN ( SELECT lessonid, userid, MAX(timeseen) AS timeseen FROM {lesson_attempts} WHERE userid = :userid AND lessonid $insql GROUP BY userid, lessonid ) timeselect ON timeselect.timeseen = idselect.timeseen AND timeselect.userid = idselect.userid AND timeselect.lessonid = idselect.lessonid GROUP BY idselect.userid, idselect.lessonid ) aid ON l.id = aid.id JOIN {lesson_pages} p ON l.pageid = p.id "; $lastattempts = $DB->get_records_sql($select . $from, $dbparams); // Now, get the lesson branches for the user that have the maximum 'timeseen' value. $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype "; $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from); $lastbranches = $DB->get_records_sql($select . $from, $dbparams); $lastviewed = array(); foreach ($lastattempts as $lastattempt) { $lastviewed[$lastattempt->lessonid] = $lastattempt; } // Go through the branch times and record the 'timeseen' value if it doesn't exist // for the lesson, or replace it if it exceeds the current recorded time. foreach ($lastbranches as $lastbranch) { if (!isset($lastviewed[$lastbranch->lessonid])) { $lastviewed[$lastbranch->lessonid] = $lastbranch; } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) { $lastviewed[$lastbranch->lessonid] = $lastbranch; } } // Since we have lessons in this course, now include the constants we need. require_once($CFG->dirroot . '/mod/lesson/locallib.php'); $now = time(); foreach ($lessons as $lesson) { if ($lesson->deadline != 0 // The lesson has a deadline and $lesson->deadline >= $now // And it is before the deadline has been met and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available // Visibility. $class = (!$lesson->visible) ? 'dimmed' : ''; // Context. $context = context_module::instance($lesson->coursemodule); // Link to activity. $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule)); $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class)); $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name'); // Deadline. $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info'); // Attempt information. if (has_capability('mod/lesson:manage', $context)) { // This is a teacher, Get the Number of user attempts. $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id)); $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // This is a student, See if the user has at least started the lesson. if (isset($lastviewed[$lesson->id]->timeseen)) { // See if the user has finished this attempt. if (isset($completedattempts[$lesson->id]) && ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) { // Are additional attempts allowed? if ($lesson->retake) { // User can retake the lesson. $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // User has completed the lesson and no retakes are allowed. $str = ''; } } else { // The last attempt was not finished or the lesson does not contain questions. // See if the last page viewed was a branchtable. require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php'); if ($lastviewed[$lesson->id]->qtype == LESSON_PAGE_BRANCHTABLE) { // See if the next pageid is the end of lesson. if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) { // The last page viewed was the End of Lesson. if ($lesson->retake) { // User can retake the lesson. $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // User has completed the lesson and no retakes are allowed. $str = ''; } } else { // The last page viewed was NOT the end of lesson. $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } else { // Last page was a question page, so the attempt is not completed yet. $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } } else { // User has not yet started this lesson. $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } if (!empty($str)) { if (empty($htmlarray[$lesson->course]['lesson'])) { $htmlarray[$lesson->course]['lesson'] = $str; } else { $htmlarray[$lesson->course]['lesson'] .= $str; } } } } } /** * Function to be run periodically according to the moodle cron * This function searches for things that need to be done, such * as sending out mail, toggling flags etc ... * @global stdClass * @return bool true */ function lesson_cron () { global $CFG; return true; } /** * Return grade for given user or all users. * * @global stdClass * @global object * @param int $lessonid id of lesson * @param int $userid optional user id, 0 means all users * @return array array of grades */ function lesson_get_user_grades($lesson, $userid=0) { global $CFG, $DB; $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id); if (!empty($userid)) { $params["userid"] = $userid; $params["userid2"] = $userid; $user = "AND u.id = :userid"; $fuser = "AND uu.id = :userid2"; } else { $user=""; $fuser=""; } if ($lesson->retake) { if ($lesson->usemaxgrade) { $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade FROM {user} u, {lesson_grades} g WHERE u.id = g.userid AND g.lessonid = :lessonid $user GROUP BY u.id"; } else { $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade FROM {user} u, {lesson_grades} g WHERE u.id = g.userid AND g.lessonid = :lessonid $user GROUP BY u.id"; } unset($params['lessonid2']); unset($params['userid2']); } else { // use only first attempts (with lowest id in lesson_grades table) $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted FROM {user} uu, {lesson_grades} gg WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2 $fuser GROUP BY uu.id"; $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade FROM {user} u, {lesson_grades} g, ($firstonly) f WHERE u.id = g.userid AND g.lessonid = :lessonid AND g.id = f.firstcompleted AND g.userid=f.userid $user"; } return $DB->get_records_sql($sql, $params); } /** * Update grades in central gradebook * * @category grade * @param object $lesson * @param int $userid specific user only, 0 means all * @param bool $nullifnone */ function lesson_update_grades($lesson, $userid=0, $nullifnone=true) { global $CFG, $DB; require_once($CFG->libdir.'/gradelib.php'); if ($lesson->grade == 0 || $lesson->practice) { lesson_grade_item_update($lesson); } else if ($grades = lesson_get_user_grades($lesson, $userid)) { lesson_grade_item_update($lesson, $grades); } else if ($userid and $nullifnone) { $grade = new stdClass(); $grade->userid = $userid; $grade->rawgrade = null; lesson_grade_item_update($lesson, $grade); } else { lesson_grade_item_update($lesson); } } /** * Create grade item for given lesson * * @category grade * @uses GRADE_TYPE_VALUE * @uses GRADE_TYPE_NONE * @param object $lesson object with extra cmidnumber * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook * @return int 0 if ok, error code otherwise */ function lesson_grade_item_update($lesson, $grades=null) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once($CFG->libdir.'/gradelib.php'); } if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber); } else { $params = array('itemname'=>$lesson->name); } if (!$lesson->practice and $lesson->grade > 0) { $params['gradetype'] = GRADE_TYPE_VALUE; $params['grademax'] = $lesson->grade; $params['grademin'] = 0; } else if (!$lesson->practice and $lesson->grade < 0) { $params['gradetype'] = GRADE_TYPE_SCALE; $params['scaleid'] = -$lesson->grade; // Make sure current grade fetched correctly from $grades $currentgrade = null; if (!empty($grades)) { if (is_array($grades)) { $currentgrade = reset($grades); } else { $currentgrade = $grades; } } // When converting a score to a scale, use scale's grade maximum to calculate it. if (!empty($currentgrade) && $currentgrade->rawgrade !== null) { $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid); $params['grademax'] = reset($grade->items)->grademax; } } else { $params['gradetype'] = GRADE_TYPE_NONE; } if ($grades === 'reset') { $params['reset'] = true; $grades = null; } else if (!empty($grades)) { // Need to calculate raw grade (Note: $grades has many forms) if (is_object($grades)) { $grades = array($grades->userid => $grades); } else if (array_key_exists('userid', $grades)) { $grades = array($grades['userid'] => $grades); } foreach ($grades as $key => $grade) { if (!is_array($grade)) { $grades[$key] = $grade = (array) $grade; } //check raw grade isnt null otherwise we erroneously insert a grade of 0 if ($grade['rawgrade'] !== null) { $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100); } else { //setting rawgrade to null just in case user is deleting a grade $grades[$key]['rawgrade'] = null; } } } return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params); } /** * List the actions that correspond to a view of this module. * This is used by the participation report. * * Note: This is not used by new logging system. Event with * crud = 'r' and edulevel = LEVEL_PARTICIPATING will * be considered as view action. * * @return array */ function lesson_get_view_actions() { return array('view','view all'); } /** * List the actions that correspond to a post of this module. * This is used by the participation report. * * Note: This is not used by new logging system. Event with * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING * will be considered as post action. * * @return array */ function lesson_get_post_actions() { return array('end','start'); } /** * Runs any processes that must run before * a lesson insert/update * * @global object * @param object $lesson Lesson form data * @return void **/ function lesson_process_pre_save(&$lesson) { global $DB; $lesson->timemodified = time(); if (empty($lesson->timelimit)) { $lesson->timelimit = 0; } if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) { $lesson->timespent = 0; } if (!isset($lesson->completed)) { $lesson->completed = 0; } if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) { $lesson->gradebetterthan = 0; } else if ($lesson->gradebetterthan > 100) { $lesson->gradebetterthan = 100; } if (empty($lesson->width)) { $lesson->width = 640; } if (empty($lesson->height)) { $lesson->height = 480; } if (empty($lesson->bgcolor)) { $lesson->bgcolor = '#FFFFFF'; } // Conditions for dependency $conditions = new stdClass; $conditions->timespent = $lesson->timespent; $conditions->completed = $lesson->completed; $conditions->gradebetterthan = $lesson->gradebetterthan; $lesson->conditions = serialize($conditions); unset($lesson->timespent); unset($lesson->completed); unset($lesson->gradebetterthan); if (empty($lesson->password)) { unset($lesson->password); } } /** * Runs any processes that must be run * after a lesson insert/update * * @global object * @param object $lesson Lesson form data * @return void **/ function lesson_process_post_save(&$lesson) { // Update the events relating to this lesson. lesson_update_events($lesson); } /** * Implementation of the function for printing the form elements that control * whether the course reset functionality affects the lesson. * * @param $mform form passed by reference */ function lesson_reset_course_form_definition(&$mform) { $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson')); $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson')); $mform->addElement('advcheckbox', 'reset_lesson_user_overrides', get_string('removealluseroverrides', 'lesson')); $mform->addElement('advcheckbox', 'reset_lesson_group_overrides', get_string('removeallgroupoverrides', 'lesson')); } /** * Course reset form defaults. * @param object $course * @return array */ function lesson_reset_course_form_defaults($course) { return array('reset_lesson' => 1, 'reset_lesson_group_overrides' => 1, 'reset_lesson_user_overrides' => 1); } /** * Removes all grades from gradebook * * @global stdClass * @global object * @param int $courseid * @param string optional type */ function lesson_reset_gradebook($courseid, $type='') { global $CFG, $DB; $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid FROM {lesson} l, {course_modules} cm, {modules} m WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course"; $params = array ("course" => $courseid); if ($lessons = $DB->get_records_sql($sql,$params)) { foreach ($lessons as $lesson) { lesson_grade_item_update($lesson, 'reset'); } } } /** * Actual implementation of the reset course functionality, delete all the * lesson attempts for course $data->courseid. * * @global stdClass * @global object * @param object $data the data submitted from the reset course. * @return array status array */ function lesson_reset_userdata($data) { global $CFG, $DB; $componentstr = get_string('modulenameplural', 'lesson'); $status = array(); if (!empty($data->reset_lesson)) { $lessonssql = "SELECT l.id FROM {lesson} l WHERE l.course=:course"; $params = array ("course" => $data->courseid); $lessons = $DB->get_records_sql($lessonssql, $params); // Get rid of attempts files. $fs = get_file_storage(); if ($lessons) { foreach ($lessons as $lessonid => $unused) { if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) { continue; } $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses'); } } $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params); $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params); $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params); $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params); // remove all grades from gradebook if (empty($data->reset_gradebook_grades)) { lesson_reset_gradebook($data->courseid); } $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false); } // Remove user overrides. if (!empty($data->reset_lesson_user_overrides)) { $DB->delete_records_select('lesson_overrides', 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid)); $status[] = array( 'component' => $componentstr, 'item' => get_string('useroverridesdeleted', 'lesson'), 'error' => false); } // Remove group overrides. if (!empty($data->reset_lesson_group_overrides)) { $DB->delete_records_select('lesson_overrides', 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid)); $status[] = array( 'component' => $componentstr, 'item' => get_string('groupoverridesdeleted', 'lesson'), 'error' => false); } /// updating dates - shift may be negative too if ($data->timeshift) { $DB->execute("UPDATE {lesson_overrides} SET available = available + ? WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND available <> 0", array($data->timeshift, $data->courseid)); $DB->execute("UPDATE {lesson_overrides} SET deadline = deadline + ? WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND deadline <> 0", array($data->timeshift, $data->courseid)); shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid); $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false); } return $status; } /** * Returns all other caps used in module * @return array */ function lesson_get_extra_capabilities() { return array('moodle/site:accessallgroups'); } /** * @uses FEATURE_GROUPS * @uses FEATURE_GROUPINGS * @uses FEATURE_MOD_INTRO * @uses FEATURE_COMPLETION_TRACKS_VIEWS * @uses FEATURE_GRADE_HAS_GRADE * @uses FEATURE_GRADE_OUTCOMES * @param string $feature FEATURE_xx constant for requested feature * @return mixed True if module supports feature, false if not, null if doesn't know */ function lesson_supports($feature) { switch($feature) { case FEATURE_GROUPS: return true; case FEATURE_GROUPINGS: return true; case FEATURE_MOD_INTRO: return true; case FEATURE_COMPLETION_TRACKS_VIEWS: return true; case FEATURE_GRADE_HAS_GRADE: return true; case FEATURE_COMPLETION_HAS_RULES: return true; case FEATURE_GRADE_OUTCOMES: return true; case FEATURE_BACKUP_MOODLE2: return true; case FEATURE_SHOW_DESCRIPTION: return true; default: return null; } } /** * Obtains the automatic completion state for this lesson based on any conditions * in lesson settings. * * @param object $course Course * @param object $cm course-module * @param int $userid User ID * @param bool $type Type of comparison (or/and; can be used as return value if no conditions) * @return bool True if completed, false if not, $type if conditions not set. */ function lesson_get_completion_state($course, $cm, $userid, $type) { global $CFG, $DB; // Get lesson details. $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST); $result = $type; // Default return value. // If completion option is enabled, evaluate it and return true/false. if ($lesson->completionendreached) { $value = $DB->record_exists('lesson_timer', array( 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1)); if ($type == COMPLETION_AND) { $result = $result && $value; } else { $result = $result || $value; } } if ($lesson->completiontimespent != 0) { $duration = $DB->get_field_sql( "SELECT SUM(lessontime - starttime) FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid", array('userid' => $userid, 'lessonid' => $lesson->id)); if (!$duration) { $duration = 0; } if ($type == COMPLETION_AND) { $result = $result && ($lesson->completiontimespent < $duration); } else { $result = $result || ($lesson->completiontimespent < $duration); } } return $result; } /** * This function extends the settings navigation block for the site. * * It is safe to rely on PAGE here as we will only ever be within the module * context when this is called * * @param settings_navigation $settings * @param navigation_node $lessonnode */ function lesson_extend_settings_navigation($settings, $lessonnode) { global $PAGE, $DB; // We want to add these new nodes after the Edit settings node, and before the // Locally assigned roles node. Of course, both of those are controlled by capabilities. $keys = $lessonnode->get_children_key_list(); $beforekey = null; $i = array_search('modedit', $keys); if ($i === false and array_key_exists(0, $keys)) { $beforekey = $keys[0]; } else if (array_key_exists($i + 1, $keys)) { $beforekey = $keys[$i + 1]; } if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id)); $node = navigation_node::create(get_string('groupoverrides', 'lesson'), new moodle_url($url, array('mode' => 'group')), navigation_node::TYPE_SETTING, null, 'mod_lesson_groupoverrides'); $lessonnode->add_node($node, $beforekey); $node = navigation_node::create(get_string('useroverrides', 'lesson'), new moodle_url($url, array('mode' => 'user')), navigation_node::TYPE_SETTING, null, 'mod_lesson_useroverrides'); $lessonnode->add_node($node, $beforekey); } if (has_capability('mod/lesson:edit', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id)); $lessonnode->add(get_string('preview', 'lesson'), $url); $editnode = $lessonnode->add(get_string('edit', 'lesson')); $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed')); $editnode->add(get_string('collapsed', 'lesson'), $url); $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full')); $editnode->add(get_string('full', 'lesson'), $url); } if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) { $reportsnode = $lessonnode->add(get_string('reports', 'lesson')); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview')); $reportsnode->add(get_string('overview', 'lesson'), $url); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail')); $reportsnode->add(get_string('detailedstats', 'lesson'), $url); } if (has_capability('mod/lesson:grade', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id)); $lessonnode->add(get_string('manualgrading', 'lesson'), $url); } } /** * Get list of available import or export formats * * Copied and modified from lib/questionlib.php * * @param string $type 'import' if import list, otherwise export list assumed * @return array sorted list of import/export formats available */ function lesson_get_import_export_formats($type) { global $CFG; $fileformats = core_component::get_plugin_list("qformat"); $fileformatname=array(); foreach ($fileformats as $fileformat=>$fdir) { $format_file = "$fdir/format.php"; if (file_exists($format_file) ) { require_once($format_file); } else { continue; } $classname = "qformat_$fileformat"; $format_class = new $classname(); if ($type=='import') { $provided = $format_class->provide_import(); } else { $provided = $format_class->provide_export(); } if ($provided) { $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat); } } natcasesort($fileformatnames); return $fileformatnames; } /** * Serves the lesson attachments. Implements needed access control ;-) * * @package mod_lesson * @category files * @param stdClass $course course object * @param stdClass $cm course module object * @param stdClass $context context object * @param string $filearea file area * @param array $args extra arguments * @param bool $forcedownload whether or not force download * @param array $options additional options affecting the file serving * @return bool false if file not found, does not return if found - justsend the file */ function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) { global $CFG, $DB; if ($context->contextlevel != CONTEXT_MODULE) { return false; } $fileareas = lesson_get_file_areas(); if (!array_key_exists($filearea, $fileareas)) { return false; } if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) { return false; } require_course_login($course, true, $cm); if ($filearea === 'page_contents') { $pageid = (int)array_shift($args); if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args); } else if ($filearea === 'page_answers' || $filearea === 'page_responses') { $itemid = (int)array_shift($args); if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args); } else if ($filearea === 'essay_responses') { $itemid = (int)array_shift($args); if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args); } else if ($filearea === 'mediafile') { if (count($args) > 1) { // Remove the itemid when it appears to be part of the arguments. If there is only one argument // then it is surely the file name. The itemid is sometimes used to prevent browser caching. array_shift($args); } $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args); } else { return false; } $fs = get_file_storage(); if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { return false; } // finally send the file send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security! } /** * Returns an array of file areas * * @package mod_lesson * @category files * @return array a list of available file areas */ function lesson_get_file_areas() { $areas = array(); $areas['page_contents'] = get_string('pagecontents', 'mod_lesson'); $areas['mediafile'] = get_string('mediafile', 'mod_lesson'); $areas['page_answers'] = get_string('pageanswers', 'mod_lesson'); $areas['page_responses'] = get_string('pageresponses', 'mod_lesson'); $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson'); return $areas; } /** * Returns a file_info_stored object for the file being requested here * * @package mod_lesson * @category files * @global stdClass $CFG * @param file_browse $browser file browser instance * @param array $areas file areas * @param stdClass $course course object * @param stdClass $cm course module object * @param stdClass $context context object * @param string $filearea file area * @param int $itemid item ID * @param string $filepath file path * @param string $filename file name * @return file_info_stored */ function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { global $CFG, $DB; if (!has_capability('moodle/course:managefiles', $context)) { // No peaking here for students! return null; } // Mediafile area does not have sub directories, so let's select the default itemid to prevent // the user from selecting a directory to access the mediafile content. if ($filearea == 'mediafile' && is_null($itemid)) { $itemid = 0; } if (is_null($itemid)) { return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea); } $fs = get_file_storage(); $filepath = is_null($filepath) ? '/' : $filepath; $filename = is_null($filename) ? '.' : $filename; if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) { return null; } $itemname = $filearea; if ($filearea == 'page_contents') { $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid)); $itemname = format_string($itemname, true, array('context' => $context)); } else { $areas = lesson_get_file_areas(); if (isset($areas[$filearea])) { $itemname = $areas[$filearea]; } } $urlbase = $CFG->wwwroot . '/pluginfile.php'; return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false); } /** * Return a list of page types * @param string $pagetype current page type * @param stdClass $parentcontext Block's parent context * @param stdClass $currentcontext Current context of block */ function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) { $module_pagetype = array( 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'), 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'), 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson')); return $module_pagetype; } /** * Update the lesson activity to include any file * that was uploaded, or if there is none, set the * mediafile field to blank. * * @param int $lessonid the lesson id * @param stdClass $context the context * @param int $draftitemid the draft item */ function lesson_update_media_file($lessonid, $context, $draftitemid) { global $DB; // Set the filestorage object. $fs = get_file_storage(); // Save the file if it exists that is currently in the draft area. file_save_draft_area_files($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0); // Get the file if it exists. $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false); // Check that there is a file to process. if (count($files) == 1) { // Get the first (and only) file. $file = reset($files); // Set the mediafile column in the lessons table. $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid)); } else { // Set the mediafile column in the lessons table. $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid)); } } /** * Get icon mapping for font-awesome. */ function mod_lesson_get_fontawesome_icon_map() { return [ 'mod_lesson:e/copy' => 'fa-clone', ]; }
fwsl/moodle
mod/lesson/lib.php
PHP
gpl-3.0
55,138
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_7Z_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Archive/File_7z.h" //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Buffer - File header //*************************************************************************** //--------------------------------------------------------------------------- bool File_7z::FileHeader_Begin() { // Minimum buffer size if (Buffer_Size<6) return false; // Must wait for more data // Testing if (Buffer[0]!=0x37 // "7z...." || Buffer[1]!=0x7A || Buffer[2]!=0xBC || Buffer[3]!=0xAF || Buffer[4]!=0x27 || Buffer[5]!=0x1C) { Reject("7-Zip"); return false; } // All should be OK... return true; } //*************************************************************************** // Buffer - Global //*************************************************************************** //--------------------------------------------------------------------------- void File_7z::Read_Buffer_Continue() { Skip_B6( "Magic"); Skip_XX(File_Size-6, "Data"); FILLING_BEGIN(); Accept("7-Zip"); Fill(Stream_General, 0, General_Format, "7-Zip"); Finish("7-Zip"); FILLING_END(); } } //NameSpace #endif //MEDIAINFO_7Z_YES
xucp/mpc_hc
src/thirdparty/MediaInfo/library/Source/MediaInfo/Archive/File_7z.cpp
C++
gpl-3.0
2,366
/* Class: Graphic.Ellipse Shape implementation of an ellipse. Author: Sébastien Gruhier, <http://www.xilinus.com> License: MIT-style license. See Also: <Shape> */ Graphic.Ellipse = Class.create(); Object.extend(Graphic.Ellipse.prototype, Graphic.Shape.prototype); // Keep parent initialize Graphic.Ellipse.prototype._shapeInitialize = Graphic.Shape.prototype.initialize; Object.extend(Graphic.Ellipse.prototype, { initialize: function(renderer) { this._shapeInitialize(renderer, "ellipse"); Object.extend(this.attributes, {cx: 0, cy: 0, rx: 0, ry: 0}) return this; }, getSize: function() { return {w: 2 * this.attributes.rx, h: 2 * this.attributes.ry} }, setSize: function(width, height) { var location = this.getLocation(); this._setAttributes({rx: width/2, ry: height/2}); this.setLocation(location.x, location.y); return this; }, getLocation: function() { return {x: this.attributes.cx - this.attributes.rx, y: this.attributes.cy - this.attributes.ry} }, setLocation: function(x, y) { this._setAttributes({cx: x + this.attributes.rx, cy: y + this.attributes.ry}); return this; } })
j9recurses/whirld
vendor/assets/components/cartagen/lib/prototype-graphic/src/shape/ellipse.js
JavaScript
gpl-3.0
1,191
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-PDU" * found in "/home/einstein/openairinterface5g/openair-cn/S1AP/MESSAGES/ASN1/R10.5/S1AP-PDU.asn" * `asn1c -gen-PER` */ #ifndef _S1ap_HandoverPreparationFailure_H_ #define _S1ap_HandoverPreparationFailure_H_ #include <asn_application.h> /* Including external dependencies */ #include <asn_SEQUENCE_OF.h> #include <constr_SEQUENCE_OF.h> #include <constr_SEQUENCE.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct S1ap_IE; /* S1ap-HandoverPreparationFailure */ typedef struct S1ap_HandoverPreparationFailure { struct S1ap_HandoverPreparationFailure__s1ap_HandoverPreparationFailure_ies { A_SEQUENCE_OF(struct S1ap_IE) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } s1ap_HandoverPreparationFailure_ies; /* * This type is extensible, * possible extensions are below. */ /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } S1ap_HandoverPreparationFailure_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_S1ap_HandoverPreparationFailure; #ifdef __cplusplus } #endif /* Referred external types */ #include "S1ap-IE.h" #endif /* _S1ap_HandoverPreparationFailure_H_ */ #include <asn_internal.h>
massar5289/openairinterface5G
cmake_targets/oaisim_build_oai/build/CMakeFiles/R10.5/S1ap-HandoverPreparationFailure.h
C
gpl-3.0
1,318
/* ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio. This file is part of ChibiOS. ChibiOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. ChibiOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @file chschd.c * @brief Scheduler code. * * @addtogroup scheduler * @details This module provides the default portable scheduler code. * @{ */ #include "ch.h" /*===========================================================================*/ /* Module local definitions. */ /*===========================================================================*/ /*===========================================================================*/ /* Module exported variables. */ /*===========================================================================*/ /** * @brief System data structures. */ ch_system_t ch; /*===========================================================================*/ /* Module local types. */ /*===========================================================================*/ /*===========================================================================*/ /* Module local variables. */ /*===========================================================================*/ /*===========================================================================*/ /* Module local functions. */ /*===========================================================================*/ /*===========================================================================*/ /* Module exported functions. */ /*===========================================================================*/ /** * @brief Scheduler initialization. * * @notapi */ void _scheduler_init(void) { queue_init(&ch.rlist.queue); ch.rlist.prio = NOPRIO; #if CH_CFG_USE_REGISTRY == TRUE ch.rlist.newer = (thread_t *)&ch.rlist; ch.rlist.older = (thread_t *)&ch.rlist; #endif } #if (CH_CFG_OPTIMIZE_SPEED == FALSE) || defined(__DOXYGEN__) /** * @brief Inserts a thread into a priority ordered queue. * @note The insertion is done by scanning the list from the highest * priority toward the lowest. * * @param[in] tp the pointer to the thread to be inserted in the list * @param[in] tqp the pointer to the threads list header * * @notapi */ void queue_prio_insert(thread_t *tp, threads_queue_t *tqp) { thread_t *cp = (thread_t *)tqp; do { cp = cp->queue.next; } while ((cp != (thread_t *)tqp) && (cp->prio >= tp->prio)); tp->queue.next = cp; tp->queue.prev = cp->queue.prev; tp->queue.prev->queue.next = tp; cp->queue.prev = tp; } /** * @brief Inserts a thread into a queue. * * @param[in] tp the pointer to the thread to be inserted in the list * @param[in] tqp the pointer to the threads list header * * @notapi */ void queue_insert(thread_t *tp, threads_queue_t *tqp) { tp->queue.next = (thread_t *)tqp; tp->queue.prev = tqp->prev; tp->queue.prev->queue.next = tp; tqp->prev = tp; } /** * @brief Removes the first-out thread from a queue and returns it. * @note If the queue is priority ordered then this function returns the * thread with the highest priority. * * @param[in] tqp the pointer to the threads list header * @return The removed thread pointer. * * @notapi */ thread_t *queue_fifo_remove(threads_queue_t *tqp) { thread_t *tp = tqp->next; tqp->next = tp->queue.next; tqp->next->queue.prev = (thread_t *)tqp; return tp; } /** * @brief Removes the last-out thread from a queue and returns it. * @note If the queue is priority ordered then this function returns the * thread with the lowest priority. * * @param[in] tqp the pointer to the threads list header * @return The removed thread pointer. * * @notapi */ thread_t *queue_lifo_remove(threads_queue_t *tqp) { thread_t *tp = tqp->prev; tqp->prev = tp->queue.prev; tqp->prev->queue.next = (thread_t *)tqp; return tp; } /** * @brief Removes a thread from a queue and returns it. * @details The thread is removed from the queue regardless of its relative * position and regardless the used insertion method. * * @param[in] tp the pointer to the thread to be removed from the queue * @return The removed thread pointer. * * @notapi */ thread_t *queue_dequeue(thread_t *tp) { tp->queue.prev->queue.next = tp->queue.next; tp->queue.next->queue.prev = tp->queue.prev; return tp; } /** * @brief Pushes a thread_t on top of a stack list. * * @param[in] tp the pointer to the thread to be inserted in the list * @param[in] tlp the pointer to the threads list header * * @notapi */ void list_insert(thread_t *tp, threads_list_t *tlp) { tp->queue.next = tlp->next; tlp->next = tp; } /** * @brief Pops a thread from the top of a stack list and returns it. * @pre The list must be non-empty before calling this function. * * @param[in] tlp the pointer to the threads list header * @return The removed thread pointer. * * @notapi */ thread_t *list_remove(threads_list_t *tlp) { thread_t *tp = tlp->next; tlp->next = tp->queue.next; return tp; } #endif /* CH_CFG_OPTIMIZE_SPEED */ /** * @brief Inserts a thread in the Ready List placing it behind its peers. * @details The thread is positioned behind all threads with higher or equal * priority. * @pre The thread must not be already inserted in any list through its * @p next and @p prev or list corruption would occur. * @post This function does not reschedule so a call to a rescheduling * function must be performed before unlocking the kernel. Note that * interrupt handlers always reschedule on exit so an explicit * reschedule must not be performed in ISRs. * * @param[in] tp the thread to be made ready * @return The thread pointer. * * @iclass */ thread_t *chSchReadyI(thread_t *tp) { thread_t *cp; chDbgCheckClassI(); chDbgCheck(tp != NULL); chDbgAssert((tp->state != CH_STATE_READY) && (tp->state != CH_STATE_FINAL), "invalid state"); tp->state = CH_STATE_READY; cp = (thread_t *)&ch.rlist.queue; do { cp = cp->queue.next; } while (cp->prio >= tp->prio); /* Insertion on prev.*/ tp->queue.next = cp; tp->queue.prev = cp->queue.prev; tp->queue.prev->queue.next = tp; cp->queue.prev = tp; return tp; } /** * @brief Inserts a thread in the Ready List placing it ahead its peers. * @details The thread is positioned ahead all threads with higher or equal * priority. * @pre The thread must not be already inserted in any list through its * @p next and @p prev or list corruption would occur. * @post This function does not reschedule so a call to a rescheduling * function must be performed before unlocking the kernel. Note that * interrupt handlers always reschedule on exit so an explicit * reschedule must not be performed in ISRs. * * @param[in] tp the thread to be made ready * @return The thread pointer. * * @iclass */ thread_t *chSchReadyAheadI(thread_t *tp) { thread_t *cp; chDbgCheckClassI(); chDbgCheck(tp != NULL); chDbgAssert((tp->state != CH_STATE_READY) && (tp->state != CH_STATE_FINAL), "invalid state"); tp->state = CH_STATE_READY; cp = (thread_t *)&ch.rlist.queue; do { cp = cp->queue.next; } while (cp->prio > tp->prio); /* Insertion on prev.*/ tp->queue.next = cp; tp->queue.prev = cp->queue.prev; tp->queue.prev->queue.next = tp; cp->queue.prev = tp; return tp; } /** * @brief Puts the current thread to sleep into the specified state. * @details The thread goes into a sleeping state. The possible * @ref thread_states are defined into @p threads.h. * * @param[in] newstate the new thread state * * @sclass */ void chSchGoSleepS(tstate_t newstate) { thread_t *otp = currp; chDbgCheckClassS(); /* New state.*/ otp->state = newstate; #if CH_CFG_TIME_QUANTUM > 0 /* The thread is renouncing its remaining time slices so it will have a new time quantum when it will wakeup.*/ otp->ticks = (tslices_t)CH_CFG_TIME_QUANTUM; #endif /* Next thread in ready list becomes current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-enter hook.*/ if (currp->prio == IDLEPRIO) { CH_CFG_IDLE_ENTER_HOOK(); } /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } /* * Timeout wakeup callback. */ static void wakeup(void *p) { thread_t *tp = (thread_t *)p; chSysLockFromISR(); switch (tp->state) { case CH_STATE_READY: /* Handling the special case where the thread has been made ready by another thread with higher priority.*/ chSysUnlockFromISR(); return; case CH_STATE_SUSPENDED: *tp->u.wttrp = NULL; break; #if CH_CFG_USE_SEMAPHORES == TRUE case CH_STATE_WTSEM: chSemFastSignalI(tp->u.wtsemp); #endif /* Falls through.*/ case CH_STATE_QUEUED: /* Falls through.*/ #if (CH_CFG_USE_CONDVARS == TRUE) && (CH_CFG_USE_CONDVARS_TIMEOUT == TRUE) case CH_STATE_WTCOND: #endif /* States requiring dequeuing.*/ (void) queue_dequeue(tp); break; default: /* Any other state, nothing to do.*/ break; } tp->u.rdymsg = MSG_TIMEOUT; (void) chSchReadyI(tp); chSysUnlockFromISR(); } /** * @brief Puts the current thread to sleep into the specified state with * timeout specification. * @details The thread goes into a sleeping state, if it is not awakened * explicitly within the specified timeout then it is forcibly * awakened with a @p MSG_TIMEOUT low level message. The possible * @ref thread_states are defined into @p threads.h. * * @param[in] newstate the new thread state * @param[in] timeout the number of ticks before the operation timeouts, the * special values are handled as follow: * - @a TIME_INFINITE the thread enters an infinite sleep * state, this is equivalent to invoking * @p chSchGoSleepS() but, of course, less efficient. * - @a TIME_IMMEDIATE this value is not allowed. * . * @return The wakeup message. * @retval MSG_TIMEOUT if a timeout occurs. * * @sclass */ msg_t chSchGoSleepTimeoutS(tstate_t newstate, sysinterval_t timeout) { chDbgCheckClassS(); if (TIME_INFINITE != timeout) { virtual_timer_t vt; chVTDoSetI(&vt, timeout, wakeup, currp); chSchGoSleepS(newstate); if (chVTIsArmedI(&vt)) { chVTDoResetI(&vt); } } else { chSchGoSleepS(newstate); } return currp->u.rdymsg; } /** * @brief Wakes up a thread. * @details The thread is inserted into the ready list or immediately made * running depending on its relative priority compared to the current * thread. * @pre The thread must not be already inserted in any list through its * @p next and @p prev or list corruption would occur. * @note It is equivalent to a @p chSchReadyI() followed by a * @p chSchRescheduleS() but much more efficient. * @note The function assumes that the current thread has the highest * priority. * * @param[in] ntp the thread to be made ready * @param[in] msg the wakeup message * * @sclass */ void chSchWakeupS(thread_t *ntp, msg_t msg) { thread_t *otp = currp; chDbgCheckClassS(); chDbgAssert((ch.rlist.queue.next == (thread_t *)&ch.rlist.queue) || (ch.rlist.current->prio >= ch.rlist.queue.next->prio), "priority order violation"); /* Storing the message to be retrieved by the target thread when it will restart execution.*/ ntp->u.rdymsg = msg; /* If the waken thread has a not-greater priority than the current one then it is just inserted in the ready list else it made running immediately and the invoking thread goes in the ready list instead.*/ if (ntp->prio <= otp->prio) { (void) chSchReadyI(ntp); } else { otp = chSchReadyI(otp); /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { CH_CFG_IDLE_LEAVE_HOOK(); } /* The extracted thread is marked as current.*/ currp = ntp; ntp->state = CH_STATE_CURRENT; /* Swap operation as tail call.*/ chSysSwitch(ntp, otp); } } /** * @brief Performs a reschedule if a higher priority thread is runnable. * @details If a thread with a higher priority than the current thread is in * the ready list then make the higher priority thread running. * * @sclass */ void chSchRescheduleS(void) { chDbgCheckClassS(); if (chSchIsRescRequiredI()) { chSchDoRescheduleAhead(); } } #if !defined(CH_SCH_IS_PREEMPTION_REQUIRED_HOOKED) /** * @brief Evaluates if preemption is required. * @details The decision is taken by comparing the relative priorities and * depending on the state of the round robin timeout counter. * @note Not a user function, it is meant to be invoked by the scheduler * itself or from within the port layer. * * @retval true if there is a thread that must go in running state * immediately. * @retval false if preemption is not required. * * @special */ bool chSchIsPreemptionRequired(void) { tprio_t p1 = firstprio(&ch.rlist.queue); tprio_t p2 = currp->prio; #if CH_CFG_TIME_QUANTUM > 0 /* If the running thread has not reached its time quantum, reschedule only if the first thread on the ready queue has a higher priority. Otherwise, if the running thread has used up its time quantum, reschedule if the first thread on the ready queue has equal or higher priority.*/ return (currp->ticks > (tslices_t)0) ? (p1 > p2) : (p1 >= p2); #else /* If the round robin preemption feature is not enabled then performs a simpler comparison.*/ return p1 > p2; #endif } #endif /* !defined(CH_SCH_IS_PREEMPTION_REQUIRED_HOOKED) */ /** * @brief Switches to the first thread on the runnable queue. * @details The current thread is positioned in the ready list behind all * threads having the same priority. The thread regains its time * quantum. * @note Not a user function, it is meant to be invoked by the scheduler * itself. * * @special */ void chSchDoRescheduleBehind(void) { thread_t *otp = currp; /* Picks the first thread from the ready queue and makes it current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { CH_CFG_IDLE_LEAVE_HOOK(); } #if CH_CFG_TIME_QUANTUM > 0 /* It went behind peers so it gets a new time quantum.*/ otp->ticks = (tslices_t)CH_CFG_TIME_QUANTUM; #endif /* Placing in ready list behind peers.*/ otp = chSchReadyI(otp); /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } /** * @brief Switches to the first thread on the runnable queue. * @details The current thread is positioned in the ready list ahead of all * threads having the same priority. * @note Not a user function, it is meant to be invoked by the scheduler * itself. * * @special */ void chSchDoRescheduleAhead(void) { thread_t *otp = currp; /* Picks the first thread from the ready queue and makes it current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { CH_CFG_IDLE_LEAVE_HOOK(); } /* Placing in ready list ahead of peers.*/ otp = chSchReadyAheadI(otp); /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } #if !defined(CH_SCH_DO_RESCHEDULE_HOOKED) /** * @brief Switches to the first thread on the runnable queue. * @details The current thread is positioned in the ready list behind or * ahead of all threads having the same priority depending on * if it used its whole time slice. * @note Not a user function, it is meant to be invoked by the scheduler * itself or from within the port layer. * * @special */ void chSchDoReschedule(void) { thread_t *otp = currp; /* Picks the first thread from the ready queue and makes it current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { CH_CFG_IDLE_LEAVE_HOOK(); } #if CH_CFG_TIME_QUANTUM > 0 /* If CH_CFG_TIME_QUANTUM is enabled then there are two different scenarios to handle on preemption: time quantum elapsed or not.*/ if (currp->ticks == (tslices_t)0) { /* The thread consumed its time quantum so it is enqueued behind threads with same priority level, however, it acquires a new time quantum.*/ otp = chSchReadyI(otp); /* The thread being swapped out receives a new time quantum.*/ otp->ticks = (tslices_t)CH_CFG_TIME_QUANTUM; } else { /* The thread didn't consume all its time quantum so it is put ahead of threads with equal priority and does not acquire a new time quantum.*/ otp = chSchReadyAheadI(otp); } #else /* !(CH_CFG_TIME_QUANTUM > 0) */ /* If the round-robin mechanism is disabled then the thread goes always ahead of its peers.*/ otp = chSchReadyAheadI(otp); #endif /* !(CH_CFG_TIME_QUANTUM > 0) */ /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } #endif /*!defined(CH_SCH_DO_RESCHEDULE_HOOKED) */ /** @} */
serdzz/ChibiOS
os/rt/src/chschd.c
C
gpl-3.0
19,314
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Setup\Module\Di\Compiler\Config; interface ModificationInterface { /** * Modifies input config * * @param array $config * @return array */ public function modify(array $config); }
rajmahesh/magento2-master
vendor/magento/magento2-base/setup/src/Magento/Setup/Module/Di/Compiler/Config/ModificationInterface.php
PHP
gpl-3.0
338
openag\_atlas\_do ================= This repository contains an OpenAg firmware module for reading from the [Atlas Scientific EZO DO Circuit](http://www.atlas-scientific.com/product_pages/circuits/ezo_do.html). The module defines 1 output "water\_dissolved\_oxygen" on which water DO readings are sent at a rate of no more than 0.5 Hz. The module will enter an ERROR state whenever it fails to read from a sensor and will have a state of OK otherwise. Status Codes ------------ - "31": Unknown error - "32": No response - "33": Request failed
goruck/openag_brain
firmware/lib/openag_atlas_do/README.md
Markdown
gpl-3.0
545
#ifndef _SOCKS_H #define _SOCKS_H #pragma pack(push,1) struct socks5_method_request { char ver; char nmethods; char methods[255]; }; struct socks5_method_response { char ver; char method; }; struct xsocks_request { char atyp; char addr[0]; }; struct socks5_request { char ver; char cmd; char rsv; char atyp; char addr[0]; }; struct socks5_response { char ver; char rep; char rsv; char atyp; }; #pragma pack(pop) enum s5_auth_method { S5_AUTH_NONE = 0x00, S5_AUTH_GSSAPI = 0x01, S5_AUTH_PASSWD = 0x02, }; enum s5_auth_result { S5_AUTH_ALLOW = 0x00, S5_AUTH_DENY = 0x01, }; enum xsocks_atyp { ATYP_IPV4 = 0x01, ATYP_HOST = 0x03, ATYP_IPV6 = 0x04, }; enum s5_cmd { S5_CMD_CONNECT = 0x01, S5_CMD_BIND = 0x02, S5_CMD_UDP_ASSOCIATE = 0x03, }; enum s5_rep { S5_REP_SUCCESSED = 0X00, S5_REP_SOCKS_FAILURE = 0X01, S5_REP_RULESET_DENY = 0X02, S5_REP_NETWORK_UNREACHABLE = 0X03, S5_REP_HOST_UNREACHABLE = 0X04, S5_REP_CONNECTION_REFUSED = 0X05, S5_REP_TTL_EXPIRED = 0X06, S5_REP_CMD_NOT_SUPPORTED = 0X07, S5_REP_ADDRESS_TYPE_NOT_SUPPORTED = 0X08, S5_REP_UNASSIGNED = 0X09, }; enum xstage { XSTAGE_HANDSHAKE, XSTAGE_REQUEST, XSTAGE_RESOLVE, XSTAGE_CONNECT, XSTAGE_UDP_RELAY, XSTAGE_FORWARD, XSTAGE_TERMINATE, XSTAGE_DEAD, }; #endif // for #ifndef _SOCKS_H
fqtools/xsocks
src/socks.h
C
gpl-3.0
1,438
/**************************************************************/ /* ********************************************************** */ /* * * */ /* * SUBSUMPTION * */ /* * * */ /* * $Module: SUBSUMPTION * */ /* * * */ /* * Copyright (C) 1996, 1997, 1999, 2000 * */ /* * MPI fuer Informatik * */ /* * * */ /* * This program is free software; you can redistribute * */ /* * it and/or modify it under the terms of the FreeBSD * */ /* * Licence. * */ /* * * */ /* * This program is distributed in the hope that it will * */ /* * be useful, but WITHOUT ANY WARRANTY; without even * */ /* * the implied warranty of MERCHANTABILITY or FITNESS * */ /* * FOR A PARTICULAR PURPOSE. See the LICENCE file * */ /* * for more details. * */ /* * * */ /* * * */ /* $Revision: 1.3 $ * */ /* $State: Exp $ * */ /* $Date: 2010-02-22 14:09:59 $ * */ /* $Author: weidenb $ * */ /* * * */ /* * Contact: * */ /* * Christoph Weidenbach * */ /* * MPI fuer Informatik * */ /* * Stuhlsatzenhausweg 85 * */ /* * 66123 Saarbruecken * */ /* * Email: spass@mpi-inf.mpg.de * */ /* * Germany * */ /* * * */ /* ********************************************************** */ /**************************************************************/ /* $RCSfile: subsumption.h,v $ */ #ifndef _SUBSUMPTION_ #define _SUBSUMPTION_ /**************************************************************/ /* Includes */ /**************************************************************/ #include "misc.h" #include "unify.h" #include "component.h" #include "vector.h" #include "clause.h" /**************************************************************/ /* Functions */ /**************************************************************/ static __inline__ int subs_NoException(void) { return -1; } void subs_Init(void); void subs_Free(void); BOOL subs_Subsumes(CLAUSE, CLAUSE, int, int); BOOL subs_SubsumesBasic(CLAUSE, CLAUSE, int, int); BOOL subs_SubsumesWithSignature(CLAUSE, CLAUSE, BOOL, LIST*); BOOL subs_Idc(CLAUSE, CLAUSE); BOOL subs_IdcRes(CLAUSE, int, int); BOOL subs_IdcEq(CLAUSE, CLAUSE); BOOL subs_IdcEqMatch(CLAUSE, CLAUSE, SUBST); BOOL subs_IdcEqMatchExcept(CLAUSE, int, CLAUSE, int, SUBST); #endif
KULeuven-KRR/IDP
lib/SPASS-3.7/SPASS/subsumption.h
C
gpl-3.0
3,397
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Render an attempt at a HotPot quiz * Output format: hp_6 * * @package mod-hotpot * @copyright 2010 Gordon Bateson <gordon.bateson@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); // get parent class require_once($CFG->dirroot.'/mod/hotpot/attempt/hp/renderer.php'); /** * mod_hotpot_attempt_hp_6_renderer * * @copyright 2010 Gordon Bateson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 */ class mod_hotpot_attempt_hp_6_renderer extends mod_hotpot_attempt_hp_renderer { /** * init * * @param xxx $hotpot */ function init($hotpot) { parent::init($hotpot); array_unshift($this->templatesfolders, 'mod/hotpot/attempt/hp/6/templates'); } /** * fix_headcontent_DragAndDrop for JMix and JMatch */ function fix_headcontent_DragAndDrop() { // replace one line functions that get and set positions of positionable elements $search = array( '/(?<=function CardGetL).*/', '/(?<=function CardGetT).*/', '/(?<=function CardGetW).*/', '/(?<=function CardGetH).*/', '/(?<=function CardGetB).*/', '/(?<=function CardGetR).*/', '/(?<=function CardSetL).*/', '/(?<=function CardSetT).*/', '/(?<=function CardSetW).*/', '/(?<=function CardSetH).*/', ); $replace = array( "(){return getOffset(this.elm, 'Left')}", "(){return getOffset(this.elm, 'Top')}", "(){return getOffset(this.elm, 'Width')}", "(){return getOffset(this.elm, 'Height')}", "(){return getOffset(this.elm, 'Bottom')}", "(){return getOffset(this.elm, 'Right')}", "(NewL){setOffset(this.elm, 'Left', NewL)}", "(NewT){setOffset(this.elm, 'Top', NewT)}", "(NewW){setOffset(this.elm, 'Width', NewW)}", "(NewH){setOffset(this.elm, 'Height', NewH)}" ); $this->headcontent = preg_replace($search, $replace, $this->headcontent, 1); } /** * fix_headcontent_rottmeier * * @param xxx $type (optional, default='') */ function fix_headcontent_rottmeier($type='') { switch ($type) { case 'dropdown': // adding missing brackets to call to Is_ExerciseFinished() in CheckAnswers() $search = '/(Finished\s*=\s*Is_ExerciseFinished)(;)/'; $this->headcontent = preg_replace($search, '$1()$2', $this->headcontent); break; case 'findit': // get position of last </style> tag and // insert CSS to make <b> and <em> tags bold // even within GapSpans added by javascript $search = '</style>'; if ($pos = strrpos($this->headcontent, $search)) { $insert = "\n" .'<!--[if IE 6]><style type="text/css">'."\n" .'span.GapSpan{'."\n" .' font-size:24px;'."\n" .'}'."\n" .'</style><![endif]-->'."\n" .'<style type="text/css">'."\n" .'b span.GapSpan,'."\n" .'em span.GapSpan{'."\n" .' font-weight:inherit;'."\n" .'}'."\n" .'</style>'."\n" ; $this->headcontent = substr_replace($this->headcontent, $insert, $pos + strlen($search), 0); } break; case 'jintro': // add TimeOver variable, so we can use standard detection of quiz completion if ($pos = strpos($this->headcontent, 'var Score = 0;')) { $insert = "var TimeOver = false;\n"; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } break; case 'jmemori': // add TimeOver variable, so we can use standard detection of quiz completion if ($pos = strpos($this->headcontent, 'var Score = 0;')) { $insert = "var TimeOver = false;\n"; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } // override table border collapse from standard Moodle styles if ($pos = strrpos($this->headcontent, '</style>')) { $insert = '' .'#'.$this->themecontainer.' form table'."\n" .'{'."\n" .' border-collapse: separate;'."\n" .' border-spacing: 2px;'."\n" .'}'."\n" ; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } break; } } /** * fix_bodycontent_rottmeier * * @param xxx $hideclozeform (optional, default=false) */ function fix_bodycontent_rottmeier($hideclozeform=false) { // fix left aligned instructions in Rottmeier-based formats // JCloze: DropDown, FindIt(a)+(b), JGloss // JMatch: JMemori $search = '/<p id="Instructions">(.*?)<\/p>/is'; $replace = '<div id="Instructions">$1</div>'; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); if ($hideclozeform) { // initially hide the Cloze text (so gaps are not revealed) $search = '/<(form id="Cloze" [^>]*)>/is'; $replace = '<$1 style="display:none;">'; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); } } /** * get_js_functionnames * * @return xxx */ function get_js_functionnames() { // return a comma-separated list of js functions to be "fixed". // Each function name requires an corresponding function called: // fix_js_{$name} return 'Client,ShowElements,GetViewportHeight,PageDim,TrimString,RemoveBottomNavBarForIE,StartUp,GetUserName,PreloadImages,ShowMessage,HideFeedback,SendResults,Finish,WriteToInstructions,ShowSpecialReadingForQuestion'; } /** * fix_js_Client * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_Client(&$str, $start, $length) { $substr = substr($str, $start, $length); // refine detection of Chrome browser $search = 'this.geckoVer < 20020000'; if ($pos = strpos($substr, $search)) { $substr = substr_replace($substr, 'this.geckoVer > 10000000 && ', $pos, 0); } // add detection of Chrome browser $search = '/(\s*)if \(this\.min == false\)\{/s'; $replace = '$1' ."this.chrome = (this.ua.indexOf('Chrome') > 0);".'$1' ."if (this.chrome) {".'$1' ." this.geckoVer = 0;".'$1' ." this.safari = false;".'$1' ." this.min = true;".'$1' ."}$0" ; $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowElements * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_ShowElements(&$str, $start, $length) { $substr = substr($str, $start, $length); // hide <embed> tags (required for Chrome browser) if ($pos = strpos($substr, 'TagName == "object"')) { $substr = substr_replace($substr, 'TagName == "embed" || ', $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_PageDim * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_PageDim(&$str, $start, $length) { if ($this->usemoodletheme) { $obj = "document.getElementById('$this->themecontainer')"; // moodle } else { $obj = "document.getElementsByTagName('body')[0]"; // original } $replace = '' ."function getStyleValue(obj, property_name, propertyName){\n" ." var value = 0;\n" ." // Watch out for HTMLDocument which has no style property\n" ." // as this causes errors later in getComputedStyle() in FF\n" ." if (obj && obj.style){\n" ." // based on http://www.quirksmode.org/dom/getstyles.html\n" ." if (document.defaultView && document.defaultView.getComputedStyle){\n" ." // Firefox, Opera, Safari\n" ." value = document.defaultView.getComputedStyle(obj, null).getPropertyValue(property_name);\n" ." } else if (obj.currentStyle) {" ." // IE (and Opera)\n" ." value = obj.currentStyle[propertyName];\n" ." }\n" ." if (typeof(value)=='string'){\n" ." var r = new RegExp('([0-9.]*)([a-z]+)');\n" ." var m = value.match(r);\n" ." if (m){\n" ." switch (m[2]){\n" ." case 'em':\n" ." // as far as I can see, only IE needs this\n" ." // other browsers have getComputedStyle() in px\n" ." if (typeof(obj.EmInPx)=='undefined'){\n" ." var div = obj.parentNode.appendChild(document.createElement('div'));\n" ." div.style.margin = '0px';\n" ." div.style.padding = '0px';\n" ." div.style.border = 'none';\n" ." div.style.height = '1em';\n" ." obj.EmInPx = getOffset(div, 'Height');\n" ." obj.parentNode.removeChild(div);\n" ." }\n" ." value = parseFloat(m[1] * obj.EmInPx);\n" ." break;\n" ." case 'px':\n" ." value = parseFloat(m[1]);\n" ." break;\n" ." default:\n" ." value = 0;\n" ." }\n" ." } else {\n" ." value = 0 ;\n" ." }\n" ." } else {\n" ." value = 0;\n" ." }\n" ." }\n" ." return value;\n" ."}\n" ."function isStrict(){\n" ." return false;\n" ." if (typeof(window.cache_isStrict)=='undefined'){\n" ." if (document.compatMode) { // ie6+\n" ." window.cache_isStrict = (document.compatMode=='CSS1Compat');\n" ." } else if (document.doctype){\n" ." var s = document.doctype.systemId || document.doctype.name; // n6 OR ie5mac\n" ." window.cache_isStrict = (s && s.indexOf('strict.dtd') >= 0);\n" ." } else {\n" ." window.cache_isStrict = false;\n" ." }\n" ." }\n" ." return window.cache_isStrict;\n" ."}\n" ."function setOffset(obj, type, value){\n" ." if (! obj){\n" ." return false;\n" ." }\n" ."\n" ." switch (type){\n" ." case 'Right':\n" ." return setOffset(obj, 'Width', value - getOffset(obj, 'Left'));\n" ." case 'Bottom':\n" ." return setOffset(obj, 'Height', value - getOffset(obj, 'Top'));\n" ." }\n" ."\n" ." if (isStrict()){\n" ." // set arrays of p(roperties) and s(ub-properties)\n" ." var properties = new Array('margin', 'border', 'padding');\n" ." switch (type){\n" ." case 'Top':\n" ." var sides = new Array('Top');\n" ." break;\n" ." case 'Left':\n" ." var sides = new Array('Left');\n" ." break;\n" ." case 'Width':\n" ." var sides = new Array('Left', 'Right');\n" ." break;\n" ." case 'Height':\n" ." var sides = new Array('Top', 'Bottom');\n" ." break;\n" ." default:\n" ." return 0;\n" ." }\n" ." for (var p=0; p<properties.length; p++){\n" ." for (var s=0; s<sides.length; s++){\n" ." var propertyName = properties[p] + sides[s];\n" ." var property_name = properties[p] + '-' + sides[s].toLowerCase();\n" ." value -= getStyleValue(obj, property_name, propertyName);\n" ." }\n" ." }\n" ." value = Math.floor(value);\n" ." }\n" ." if (type=='Top' || type=='Left') {\n" ." value -= getOffset(obj.offsetParent, type);\n" ." }\n" ." if (obj.style) {\n" ." obj.style[type.toLowerCase()] = value + 'px';\n" ." }\n" ."}\n" ."function getOffset(obj, type){\n" ." if (! obj){\n" ." return 0;\n" ." }\n" ." switch (type){\n" ." case 'Width':\n" ." case 'Height':\n" ." return eval('(obj.offset'+type+'||0)');\n" ."\n" ." case 'Top':\n" ." case 'Left':\n" ." return eval('(obj.offset'+type+'||0) + getOffset(obj.offsetParent, type)');\n" ."\n" ." case 'Right':\n" ." return getOffset(obj, 'Left') + getOffset(obj, 'Width');\n" ."\n" ." case 'Bottom':\n" ." return getOffset(obj, 'Top') + getOffset(obj, 'Height');\n" ."\n" ." default:\n" ." return 0;\n" ." } // end switch\n" ."}\n" ."function PageDim(){\n" ." var obj = $obj;\n" ." this.W = getOffset(obj, 'Width');\n" ." this.H = getOffset(obj, 'Height');\n" ." this.Top = getOffset(obj, 'Top');\n" ." this.Left = getOffset(obj, 'Left');\n" ."}\n" ."function getClassAttribute(className, attributeName){\n" ." //based on http://www.shawnolson.net/a/503/\n" ." if (! document.styleSheets){\n" ." return null; // old browser\n" ." }\n" ." var css = document.styleSheets;\n" ." var rules = (document.all ? 'rules' : 'cssRules');\n" ." var regexp = new RegExp('\\\\.'+className+'\\\\b');\n" ." try {\n" ." var i_max = css.length;\n" ." } catch(err) {\n" ." var i_max = 0; // shouldn't happen !!\n" ." }\n" ." for (var i=0; i<i_max; i++){\n" ." try {\n" ." var ii_max = css[i][rules].length;\n" ." } catch(err) {\n" ." var ii_max = 0; // shouldn't happen !!\n" ." }\n" ." for (var ii=0; ii<ii_max; ii++){\n" ." if (! css[i][rules][ii].selectorText){\n" ." continue;\n" ." }\n" ." if (css[i][rules][ii].selectorText.match(regexp)){\n" ." if (css[i][rules][ii].style[attributeName]){\n" ." // class/attribute found\n" ." return css[i][rules][ii].style[attributeName];\n" ." }\n" ." }\n" ." }\n" ." }\n" ." // class/attribute not found\n" ." return null;\n" ."}\n" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_GetViewportHeight * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_GetViewportHeight(&$str, $start, $length) { $replace = '' ."function GetViewportSize(type){\n" ." if (eval('window.inner' + type)){\n" ." return eval('window.inner' + type);\n" ." }\n" ." if (document.documentElement){\n" ." if (eval('document.documentElement.client' + type)){\n" ." return eval('document.documentElement.client' + type);\n" ." }\n" ." }\n" ." if (document.body){\n" ." if (eval('document.body.client' + type)){\n" ." return eval('document.body.client' + type);\n" ." }\n" ." }\n" ." return 0;\n" ."}\n" ."function GetViewportHeight(){\n" ." return GetViewportSize('Height');\n" ."}\n" ."function GetViewportWidth(){\n" ." return GetViewportSize('Width');\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * remove_js_function * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @param xxx $function */ function remove_js_function(&$str, $start, $length, $function) { // remove this function $str = substr_replace($str, '', $start, $length); // remove all direct calls to this function $search = '/\s*'.$function.'\([^)]*\);/s'; $str = preg_replace($search, '', $str); } /** * fix_js_TrimString * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_TrimString(&$str, $start, $length) { $replace = '' ."function TrimString(InString){\n" ." if (typeof(InString)=='string'){\n" ." InString = InString.replace(new RegExp('^\\\\s+', 'g'), ''); // left\n" ." InString = InString.replace(new RegExp('\\\\s+$', 'g'), ''); // right\n" ." InString = InString.replace(new RegExp('\\\\s+', 'g'), ' '); // inner\n" ." }\n" ." return InString;\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_TypeChars * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_TypeChars(&$str, $start, $length) { if ($obj = $this->fix_js_TypeChars_obj()) { $substr = substr($str, $start, $length); if (strpos($substr, 'document.selection')===false) { $replace = '' ."function TypeChars(Chars){\n" .$this->fix_js_TypeChars_init() ." if ($obj==null || $obj.style.display=='none') {\n" ." return;\n" ." }\n" ." $obj.focus();\n" ." if (typeof($obj.selectionStart)=='number') {\n" ." // FF, Safari, Chrome, Opera\n" ." var startPos = $obj.selectionStart;\n" ." var endPos = $obj.selectionEnd;\n" ." $obj.value = $obj.value.substring(0, startPos) + Chars + $obj.value.substring(endPos);\n" ." var newPos = startPos + Chars.length;\n" ." $obj.setSelectionRange(newPos, newPos);\n" ." } else if (document.selection) {\n" ." // IE (tested on IE6, IE7, IE8)\n" ." var rng = document.selection.createRange();\n" ." rng.text = Chars;\n" ." rng = null; // prevent memory leak\n" ." } else {\n" ." // this browser can't insert text, so append instead\n" ." $obj.value += Chars;\n" ." }\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } } } /** * fix_js_TypeChars_init * * @return xxx */ function fix_js_TypeChars_init() { return ''; } /** * fix_js_TypeChars_obj * * @return xxx */ function fix_js_TypeChars_obj() { return ''; } /** * fix_js_SendResults * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_SendResults(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'SendResults'); } /** * fix_js_GetUserName * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_GetUserName(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'GetUserName'); } /** * fix_js_Finish * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_Finish(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'Finish'); } /** * fix_js_PreloadImages * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_PreloadImages(&$str, $start, $length) { $substr = substr($str, $start, $length); // fix issue in IE8 which sometimes doesn't have Image object in popups // http://moodle.org/mod/forum/discuss.php?d=134510 $search = "Imgs[i] = new Image();"; if ($pos = strpos($substr, $search)) { $replace = "Imgs[i] = (window.Image ? new Image() : document.createElement('img'));"; $substr = substr_replace($substr, $replace, $pos, strlen($search)); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_WriteToInstructions * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_WriteToInstructions(&$str, $start, $length) { $substr = substr($str, $start, $length); if ($pos = strpos($substr, '{')) { $insert = "\n" ." // check required HTML element exists\n" ." if (! document.getElementById('InstructionsDiv')) return false;\n" ; $substr = substr_replace($substr, $insert, $pos+1, 0); } if ($pos = strrpos($substr, '}')) { $append = "\n" ." StretchCanvasToCoverContent(true);\n" ; $substr = substr_replace($substr, $append, $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowMessage * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_ShowMessage(&$str, $start, $length) { // the ShowMessage function is used by all HP6 quizzes $substr = substr($str, $start, $length); // only show feedback if the required HTML elements exist // this prevents JavaScript errors which block the returning of the quiz results to Moodle if ($pos = strpos($substr, '{')) { $insert = "\n" ." // check required HTML elements exist\n" ." if (! document.getElementById('FeedbackDiv')) return false;\n" ." if (! document.getElementById('FeedbackContent')) return false;\n" ." if (! document.getElementById('FeedbackOKButton')) return false;\n" ; $substr = substr_replace($substr, $insert, $pos+1, 0); } // hide <embed> elements on Chrome browser $search = "/(\s*)ShowElements\(true, 'object', 'FeedbackContent'\);/s"; $replace = '' ."$0".'$1' ."if (C.chrome) {".'$1' ." ShowElements(false, 'embed');".'$1' ." ShowElements(true, 'embed', 'FeedbackContent');".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); // fix "top" setting to position FeedbackDiv if ($this->usemoodletheme) { $canvas = "document.getElementById('$this->themecontainer')"; // moodle } else { $canvas = "document.getElementsByTagName('body')[0]"; // original } $search = "/FDiv.style.top = [^;]*;(\s*)(FDiv.style.display = [^;]*;)/s"; $replace = '' .'$1$2' .'$1'."var t = getOffset($canvas, 'Top');" .'$1'."setOffset(FDiv, 'Top', Math.max(t, TopSettingWithScrollOffset(30)));" ; $substr = preg_replace($search, $replace, $substr, 1); // append link to student feedback form, if necessary if ($this->hotpot->studentfeedback) { $search = '/(\s*)var Output = [^;]*;/'; $replace = '' ."$0".'$1' ."if (window.FEEDBACK) {".'$1' ." Output += '".'<a href="javascript:hpFeedback();">'."' + FEEDBACK[6] + '</a>';".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_RemoveBottomNavBarForIE * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_RemoveBottomNavBarForIE(&$str, $start, $length) { $replace = '' ."function RemoveBottomNavBarForIE(){\n" ." if (C.ie) {\n" ." if (document.getElementById('Reading')){\n" ." var obj = document.getElementById('BottomNavBar');\n" ." if (obj){\n" ." obj.parentNode.removeChild(obj);\n" ." }\n" ." }\n" ." }\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_StartUp_DragAndDrop * * @param xxx $substr (passed by reference) */ function fix_js_StartUp_DragAndDrop(&$substr) { // fixes for Drag and Drop (JMatch and JMix) } /** * fix_js_StartUp_DragAndDrop_DragArea * * @param xxx $substr (passed by reference) */ function fix_js_StartUp_DragAndDrop_DragArea(&$substr) { // fix LeftCol (=left side of drag area) $search = '/(LeftColPos = [^;]+);/'; $replace = '$1 + pg.Left;'; $substr = preg_replace($search, $replace, $substr, 1); // fix DragTop (=top side of Drag area) $search = '/DragTop = [^;]+;/'; $replace = "DragTop = getOffset(document.getElementById('CheckButtonDiv'),'Bottom') + 10;"; $substr = preg_replace($search, $replace, $substr, 1); } /** * fix_js_StartUp * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_StartUp(&$str, $start, $length) { $substr = substr($str, $start, $length); // if necessary, fix drag area for JMatch or JMix drag-and-drop $this->fix_js_StartUp_DragAndDrop($substr); if ($pos = strrpos($substr, '}')) { if ($this->hotpot->delay3==hotpot::TIME_DISABLE) { $forceajax = 1; } else { $forceajax = 0; } if ($this->can_continue()==hotpot::CONTINUE_RESUMEQUIZ) { $onunload_status = hotpot::STATUS_INPROGRESS; } else { $onunload_status = hotpot::STATUS_ABANDONED; } $append = "\n" ."// adjust size and position of Feedback DIV\n" ." if (! window.pg){\n" ." window.pg = new PageDim();\n" ." }\n" ." var FDiv = document.getElementById('FeedbackDiv');\n" ." if (FDiv){\n" ." var w = getOffset(FDiv, 'Width') || FDiv.style.width || getClassAttribute(FDiv.className, 'width');\n" ." if (w){\n" ." if (typeof(w)=='string' && w.indexOf('%')>=0){\n" ." var percent = parseInt(w);\n" ." } else {\n" ." var percent = Math.floor(100 * parseInt(w) / pg.W);\n" ." }\n" ." } else if (window.FeedbackWidth && window.DivWidth){\n" ." var percent = Math.floor(100 * FeedbackWidth / DivWidth);\n" ." } else {\n" ." var percent = 34; // default width as percentage\n" ." }\n" ." FDiv.style.display = 'block';\n" ." setOffset(FDiv, 'Left', pg.Left + Math.floor(pg.W * (50 - percent/2) / 100));\n" ." setOffset(FDiv, 'Width', Math.floor(pg.W * percent / 100));\n" ." FDiv.style.display = 'none';\n" ." }\n" ."\n" ."// create HP object (to collect and send responses)\n" ." window.HP = new ".$this->js_object_type."('".$this->can_clickreport()."','".$forceajax."');\n" ."\n" //."// call HP.onunload to send results when this page unloads\n" //." var s = '';\n" //." if (typeof(window.onunload)=='function'){\n" //." window.onunload_StartUp = onunload;\n" //." s += 'window.onunload_StartUp();'\n" //." }\n" //." window.onunload = new Function(s + 'if(window.HP){HP.status=$onunload_status;HP.onunload();object_destroy(HP);}return true;');\n" //."\n" ." window.onunload = function() {\n" ." if (window.HP) {\n" ." HP.status=$onunload_status;\n" ." HP.onunload();\n" ." object_destroy(HP);\n" ." }\n" ." return true;\n" ." }\n" ."\n" ; $substr = substr_replace($substr, $append, $pos, 0); } // stretch the canvas vertically down, if there is a reading if ($pos = strrpos($substr, '}')) { // Reading is contained in <div class="LeftContainer"> // MainDiv is contained in <div class="RightContainer"> // when there is a reading. Otherwise, MainDiv is not contained. // ReadingDiv is used to show different reading for each question if ($this->usemoodletheme) { $canvas = "document.getElementById('$this->themecontainer')"; // moodle } else { $canvas = "document.getElementsByTagName('body')[0]"; // original } // None: $canvas = "document.getElementById('page-mod-hotpot-attempt')" $id = $this->embed_object_id; $onload = $this->embed_object_onload; $insert = "\n" ."// fix canvas height, if necessary\n" ." if (! window.hotpot_mediafilter_loader){\n" ." StretchCanvasToCoverContent();\n" ." }\n" ."}\n" ."function StretchCanvasToCoverContent(skipTimeout){\n" ." if (! skipTimeout){\n" ." if (navigator.userAgent.indexOf('Firefox/3')>=0){\n" ." var millisecs = 1000;\n" ." } else {\n" ." var millisecs = 500;\n" ." }\n" ." setTimeout('StretchCanvasToCoverContent(true)', millisecs);\n" ." return;\n" ." }\n" ." var canvas = $canvas;\n" ." if (canvas){\n" ." var ids = new Array('Reading','ReadingDiv','MainDiv');\n" ." var i_max = ids.length;\n" ." for (var i=i_max-1; i>=0; i--){\n" ." var obj = document.getElementById(ids[i]);\n" ." if (obj){\n" ." obj.style.height = ''; // reset height\n" ." } else {\n" ." ids.splice(i, 1); // remove this id\n" ." i_max--;\n" ." }\n" ." }\n" ." var b = 0;\n" ." for (var i=0; i<i_max; i++){\n" ." var obj = document.getElementById(ids[i]);\n" ." b = Math.max(b, getOffset(obj,'Bottom'));\n" ." }\n" ." if (window.Segments) {\n" // JMix special ." var obj = document.getElementById('D'+(Segments.length-1));\n" ." if (obj) {\n" ." b = Math.max(b, getOffset(obj,'Bottom'));\n" ." }\n" ." }\n" ." if (b){\n" ." setOffset(canvas, 'Bottom', b + 21);\n" ." for (var i=0; i<i_max; i++){\n" ." var obj = document.getElementById(ids[i]);\n" ." setOffset(obj, 'Bottom', b);\n" ." }\n" ." }\n" ." }\n" ; if ($this->hotpot->navigation==hotpot::NAVIGATION_EMBED) { // stretch container object/iframe $insert .= '' ." if (parent.$onload) {\n" ." parent.$onload(null, parent.document.getElementById('".$this->embed_object_id."'));\n" ." }\n" ; } $substr = substr_replace($substr, $insert, $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_HideFeedback * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_HideFeedback(&$str, $start, $length) { global $CFG; $substr = substr($str, $start, $length); // unhide <embed> elements on Chrome browser $search = "/(\s*)ShowElements\(true, 'object'\);/s"; $replace = '' .'$0$1' ."if (C.chrome) {".'$1' ." ShowElements(true, 'embed');".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); $search = '/('.'\s*if \(Finished == true\){\s*)(?:.*?)(\s*})/s'; if ($this->hotpot->delay3==hotpot::TIME_AFTEROK) { // -1 : send form only (do not set form values, as that has already been done) $replace = '$1'.'HP.onunload(HP.status,-1);'.'$2'; } else { $replace = ''; // i.e. remove this if-block } $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowSpecialReadingForQuestion * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_ShowSpecialReadingForQuestion(&$str, $start, $length) { $replace = '' ."function ShowSpecialReadingForQuestion(){\n" ." var ReadingDiv = document.getElementById('ReadingDiv');\n" ." if (ReadingDiv){\n" ." var ReadingText = null;\n" ." var divs = ReadingDiv.getElementsByTagName('div');\n" ." for (var i=0; i<divs.length; i++){\n" ." if (divs[i].className=='ReadingText' || divs[i].className=='TempReadingText'){\n" ." ReadingText = divs[i];\n" ." break;\n" ." }\n" ." }\n" ." if (ReadingText && HiddenReadingShown){\n" ." SwapReadingTexts(ReadingText, HiddenReadingShown);\n" ." ReadingText = HiddenReadingShown;\n" ." HiddenReadingShown = false;\n" ." }\n" ." var HiddenReading = null;\n" ." if (QArray[CurrQNum]){\n" ." var divs = QArray[CurrQNum].getElementsByTagName('div');\n" ." for (var i=0; i<divs.length; i++){\n" ." if (divs[i].className=='HiddenReading'){\n" ." HiddenReading = divs[i];\n" ." break;\n" ." }\n" ." }\n" ." }\n" ." if (HiddenReading){\n" ." if (! ReadingText){\n" ." ReadingText = document.createElement('div');\n" ." ReadingText.className = 'ReadingText';\n" ." ReadingDiv.appendChild(ReadingText);\n" ." }\n" ." SwapReadingTexts(ReadingText, HiddenReading);\n" ." HiddenReadingShown = ReadingText;\n" ." }\n" ." var btn = document.getElementById('ShowMethodButton');\n" ." if (btn){\n" ." if (HiddenReadingShown){\n" ." if (btn.style.display!='none'){\n" ." btn.style.display = 'none';\n" ." }\n" ." } else {\n" ." if (btn.style.display=='none'){\n" ." btn.style.display = '';\n" ." }\n" ." }\n" ." }\n" ." btn = null;\n" ." ReadingDiv = null;\n" ." ReadingText = null;\n" ." HiddenReading = null;\n" ." }\n" ."}\n" ."function SwapReadingTexts(ReadingText, HiddenReading) {\n" ." HiddenReadingParentNode = HiddenReading.parentNode;\n" ." HiddenReadingParentNode.removeChild(HiddenReading);\n" ."\n" ." // replaceChild(new_node, old_node)\n" ." ReadingText.parentNode.replaceChild(HiddenReading, ReadingText);\n" ."\n" ." if (HiddenReading.IsOriginalReadingText){\n" ." HiddenReading.className = 'ReadingText';\n" ." } else {\n" ." HiddenReading.className = 'TempReadingText';\n" ." }\n" ." HiddenReading.style.display = '';\n" ."\n" ." if (ReadingText.className=='ReadingText'){\n" ." ReadingText.IsOriginalReadingText = true;\n" ." } else {\n" ." ReadingText.IsOriginalReadingText = false;\n" ." }\n" ." ReadingText.style.display = 'none';\n" ." ReadingText.className = 'HiddenReading';\n" ."\n" ." HiddenReadingParentNode.appendChild(ReadingText);\n" ." HiddenReadingParentNode = null;\n" ."}\n" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_CheckAnswers * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_CheckAnswers(&$str, $start, $length) { // JCloze, JCross, JMatch : CheckAnswers // JMix : CheckAnswer // JQuiz : CheckFinished $substr = substr($str, $start, $length); // intercept Checks, if necessary if ($insert = $this->get_stop_function_intercept()) { if ($pos = strpos($substr, '{')) { $substr = substr_replace($substr, $insert, $pos+1, 0); } } // add extra argument to function - so it can be called from the "Give Up" button $name = $this->get_stop_function_name(); $search = '/(function '.$name.'\()(.*?)(\))/s'; $callback = array($this, 'fix_js_CheckAnswers_arguments'); $substr = preg_replace_callback($search, $callback, $substr, 1); // add call to Finish function (including QuizStatus) $search = $this->get_stop_function_search(); $replace = $this->get_stop_function_replace(); $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_CheckAnswers_arguments * * @param xxx $match * @return xxx */ function fix_js_CheckAnswers_arguments($match) { if (empty($match[2])) { return $match[1].'ForceQuizStatus'.$match[3]; } else { return $match[1].$match[2].',ForceQuizStatus'.$match[3]; } } /** * get_stop_onclick * * @return xxx */ function get_stop_onclick() { if ($name = $this->get_stop_function_name()) { return 'if('.$this->get_stop_function_confirm().')'.$name.'('.$this->get_stop_function_args().')'; } else { return 'if(window.HP)HP.onunload('.hotpot::STATUS_ABANDONED.')'; } } /** * get_stop_function_confirm * * @return xxx */ function get_stop_function_confirm() { // Note: "&&" in onclick must be encoded as html-entities for strict XHTML return '' ."confirm(" ."'".$this->hotpot->source->js_value_safe(get_string('confirmstop', 'hotpot'), true)."'" ."+'\\n\\n'+(window.onbeforeunload &amp;&amp; onbeforeunload()?(onbeforeunload()+'\\n\\n'):'')+" ."'".$this->hotpot->source->js_value_safe(get_string('pressoktocontinue', 'hotpot'), true)."'" .")" ; } /** * get_stop_function_name * * @return xxx */ function get_stop_function_name() { // the name of the javascript function into which the "give up" code should be inserted return ''; } /** * get_stop_function_args * * @return xxx */ function get_stop_function_args() { // the arguments required by the javascript function which the stop_function() code calls return hotpot::STATUS_ABANDONED; } /** * get_stop_function_intercept * * @return xxx */ function get_stop_function_intercept() { // JMix and JQuiz each have their own version of this function return "\n" ." // intercept this Check\n" ." HP.onclickCheck();\n" ; } /** * get_stop_function_search * * @return xxx */ function get_stop_function_search() { // JCloze : AllCorrect || Finished // JCross : AllCorrect || TimeOver // JMatch : AllDone || TimeOver // JMix : AllDone || TimeOver (in the CheckAnswer function) // JQuiz : AllDone (in the CheckFinished function) return '/\s*if \(\((\w+) == true\)\|\|\(\w+ == true\)\)({).*?}\s*/s'; } /** * get_stop_function_replace * * @return xxx */ function get_stop_function_replace() { // $1 : name of the "all correct/done" variable // $2 : opening curly brace of if-block plus any following text to be kept if ($this->hotpot->delay3==hotpot::TIME_AFTEROK) { $flag = 1; // set form values only } else { $flag = 0; // set form values and send form } if ($this->hotpot->delay3==hotpot::TIME_DISABLE) { $forceredirect = '(ForceQuizStatus ? 1 : 0)'; } else { $forceredirect = 1; } return "\n" ." if ($1){\n" ." var QuizStatus = 4; // completed\n" ." } else if (ForceQuizStatus){\n" ." var QuizStatus = ForceQuizStatus; // 3=abandoned\n" ." } else if (TimeOver){\n" ." var QuizStatus = 2; // timed out\n" ." } else {\n" ." var QuizStatus = 1; // in progress\n" ." }\n" ." if (QuizStatus > 1) $2\n" ." if (window.Interval) {\n" ." clearInterval(window.Interval);\n" ." }\n" ." TimeOver = true;\n" ." Locked = true;\n" ." Finished = true;\n" ." }\n" ." if (Finished || HP.sendallclicks){\n" ." var ForceRedirect = $forceredirect;\n" ." if (ForceQuizStatus || QuizStatus==1){\n" ." // send results immediately\n" ." HP.onunload(QuizStatus, 0, ForceRedirect);\n" ." } else {\n" ." // send results after delay\n" ." setTimeout('HP.onunload('+QuizStatus+',$flag,'+ForceRedirect+')', SubmissionTimeout);\n" ." }\n" ." }\n" ; } /** * postprocessing * * after headcontent and bodycontent have been setup and * before content is sent to browser, we add title edit icon, * insert submission form, adjust navigation butons (if any) * and add external javascripts (to the top of the page) */ function postprocessing() { $this->fix_title_icons(); $this->fix_submissionform(); $this->fix_navigation_buttons(); foreach ($this->javascripts as $script) { $this->page->requires->js('/'.$script, true); } } /** * fix_navigation_buttons * * @return xxx */ function fix_navigation_buttons() { if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL) { // replace relative URLs in <button class="NavButton" ... onclick="location='...'"> $search = '/'.'(?<='.'onclick="'."location='".')'."([^']*)".'(?='."'; return false;".'")'.'/is'; $callback = array($this, 'convert_url_navbutton'); $this->bodycontent = preg_replace_callback($search, $callback, $this->bodycontent); // replace history.back() in <button class="NavButton" ... onclick="history.back(); ..."> // with a link to the course page $params = array('id'=>$this->hotpot->course->id); $search = '/'.'(?<='.'onclick=")'.'history\.back\(\)'.'(?=; return false;")'.'/'; $replace = "location='".new moodle_url('/course/view.php', $params)."'"; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); } } /** * fix_TimeLimit */ function fix_TimeLimit() { if ($this->hotpot->timelimit > 0) { $search = '/(?<=var Seconds = )\d+(?=;)/'; $this->headcontent = preg_replace($search, $this->hotpot->timelimit, $this->headcontent, 1); } } /** * fix_SubmissionTimeout */ function fix_SubmissionTimeout() { if ($this->hotpot->delay3==hotpot::TIME_TEMPLATE) { // use default from source/template file (=30000 ms =30 seconds) if ($this->hasSubmissionTimeout) { $timeout = null; } else { $timeout = 30000; // = 30 secs is HP default } } else { if ($this->hotpot->delay3 >= 0) { $timeout = $this->hotpot->delay3 * 1000; // milliseconds } else { $timeout = 0; // i.e. immediately } } if (is_null($timeout)) { return; // nothing to do } if ($this->hasSubmissionTimeout) { // remove HPNStartTime $search = '/var HPNStartTime\b[^;]*?;\s*/'; $this->headcontent = preg_replace($search, '', $this->headcontent, 1); // reset the value of SubmissionTimeout $search = '/(?<=var SubmissionTimeout = )\d+(?=;)/'; $this->headcontent = preg_replace($search, $timeout, $this->headcontent, 1); } else { // Rhubarb, Sequitur and Quandary $search = '/var FinalScore = 0;/'; $replace = '$0'."\n".'var SubmissionTimeout = '.$timeout.';'; $this->headcontent = preg_replace($search, $replace, $this->headcontent, 1); } } /** * fix_navigation */ function fix_navigation() { if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL) { // do nothing - leave navigation as it is return; } // insert the stop button, if required if ($this->hotpot->stopbutton) { // replace top nav buttons with a single stop button if ($this->hotpot->stopbutton==hotpot::STOPBUTTON_LANGPACK) { if ($pos = strpos($this->hotpot->stoptext, '_')) { $mod = substr($this->hotpot->stoptext, 0, $pos); $str = substr($this->hotpot->stoptext, $pos + 1); $stoptext = get_string($str, $mod); } else if ($this->hotpot->stoptext) { $stoptext = get_string($this->hotpot->stoptext); } else { $stoptext = ''; } } else { $stoptext = $this->hotpot->stoptext; } if (trim($stoptext)=='') { $stoptext = get_string('giveup', 'hotpot'); } $confirm = get_string('confirmstop', 'hotpot'); //$search = '/<!-- BeginTopNavButtons -->'.'.*?'.'<!-- EndTopNavButtons -->/s'; $search = '/<(div class="Titles")>/s'; $replace = '<$1 style="position: relative">'."\n\t" .'<div class="hotpotstopbutton">' .'<button class="FuncButton" ' .'onclick="'.$this->get_stop_onclick().'" ' .'onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" ' .'onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" ' .'onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)">' .hotpot_textlib('utf8_to_entities', $stoptext) .'</button>' .'</div>' ; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent, 1); } // remove (remaining) navigation buttons $search = '/<!-- Begin(Top|Bottom)NavButtons -->'.'.*?'.'<!-- End'.'\\1'.'NavButtons -->/s'; $this->bodycontent = preg_replace($search, '', $this->bodycontent); } /** * fix_filters * * @return xxx */ function fix_filters() { global $CFG; if (isset($CFG->textfilters)) { $textfilters = $CFG->textfilters; } else { $textfilters = ''; } if ($this->hotpot->usefilters) { $filters = filter_get_active_in_context($this->hotpot->context); $filters = array_keys($filters); } else { $filters = array(); } if ($this->hotpot->useglossary && ! in_array('mod/glossary', $filters)) { $filters[] = 'mod/glossary'; } if ($this->hotpot->usemediafilter) { // exclude certain unnecessary or miscreant $filters // - "mediaplugins" because it duplicates work done by "usemediafilter" setting // - "asciimath" because it does not behave like a filter is supposed to behave $filters = preg_grep('/^filter\/(mediaplugin|asciimath)$/', $filters, PREG_GREP_INVERT); } $CFG->textfilters = implode(',', $filters); $this->filter_text_headcontent(); $this->filter_text_bodycontent(); $CFG->textfilters = $textfilters; // fix unwanted conversions by the Moodle's Tex filter // http://moodle.org/mod/forum/discuss.php?d=68435 // http://tracker.moodle.org/browse/MDL-7849 if (preg_match('/jcross|jmix/', get_class($this))) { $search = '/(?<=replace\(\/)'.'<a[^>]*><img[^>]*class="texrender"[^>]*title="(.*?)"[^>]*><\/a>'.'(?=\/g)/is'; $replace = '\['.'$1'.'\]'; $this->headcontent = preg_replace($search, $replace, $this->headcontent); } // make sure openpopup() function is available if needed (for glossary entries) // Note: this could also be done using filter_add_javascript($this->htmlcontent) // but that function expects entire htmlcontent, where we would prefer just the headcontent if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL && in_array('mod/glossary', $filters)) { // add openwindow() function (from lib/javascript.php) $this->headcontent .= "\n" .'<script type="text/javascript">'."\n" .'//<![CDATA['."\n" .'function openpopup(url, name, options, fullscreen) {'."\n" .' var fullurl = "'.$CFG->httpswwwroot.'" + url;'."\n" .' var windowobj = window.open(fullurl, name, options);'."\n" .' if (!windowobj) {'."\n" .' return true;'."\n" .' }'."\n" .' if (fullscreen) {'."\n" .' windowobj.moveTo(0, 0);'."\n" .' windowobj.resizeTo(screen.availWidth, screen.availHeight);'."\n" .' }'."\n" .' windowobj.focus();'."\n" .' return false;'."\n" .'}'."\n" .'//]]>'."\n" .'</script>' ; } } /** * filter_text_headcontent */ function filter_text_headcontent() { if ($names = $this->headcontent_strings) { $search = '/^'."((?:var )?(?:$names)(?:\[\d+\])*\s*=\s*')(.*)(';)".'$/m'; $callback = array($this, 'filter_text_headcontent_string'); $this->headcontent = preg_replace_callback($search, $callback, $this->headcontent); } if ($names = $this->headcontent_arrays) { $search = '/^'."((?:var )?(?:$names)(?:\[\d+\])* = new Array\()(.*)(\);)".'$/m'; $callback = array($this, 'filter_text_headcontent_array'); $this->headcontent = preg_replace_callback($search, $callback, $this->headcontent); } } /** * filter_text_headcontent_array * * @param xxx $match * @return xxx */ function filter_text_headcontent_array($match) { // I[q][0][a] = new Array('JQuiz answer text', 'feedback', 0, 0, 0) $before = $match[1]; $str = $match[count($match) - 2]; $after = $match[count($match) - 1]; $search = "/(')((?:\\\\\\\\|\\\\'|[^'])*)(')/"; $callback = array($this, 'filter_text_headcontent_string'); return $before.preg_replace_callback($search, $callback, $str).$after; } /** * filter_text_headcontent_string * * @param xxx $match * @return xxx */ function filter_text_headcontent_string($match) { // var YourScoreIs = 'Your score is'; // I[q][1][a][2] = 'JCloze clue'; global $CFG; static $replace_pairs = array( // backslashes and quotes '\\\\'=>'\\', "\\'"=>"'", '\\"'=>'"', // newlines '\\n'=>"\n", // other (closing tag is for XHTML compliance) '\\0'=>"\0", '<\\/'=>'</' ); $before = $match[1]; $str = $match[count($match) - 2]; $after = $match[count($match) - 1]; // unescape backslashes, quote and newlines $str = strtr($str, $replace_pairs); // convert javascript unicode $search = '/\\\\u([0-9a-f]{4})/i'; $str = $this->filter_text_to_utf8($str, $search); // convert html entities $search = '/&#x([0-9a-f]+);/i'; $str = $this->filter_text_to_utf8($str, $search); // fix relative urls $str = $this->fix_relativeurls($str); // filter string, // $str = filter_text($str); // return safe javascript unicode return $before.$this->hotpot->source->js_value_safe($str, true).$after; } /** * filter_text_bodycontent * * @param xxx $str * @param xxx $search * @return string $str * @return boolean $modified */ function filter_text_to_utf8($str, $search) { if (preg_match_all($search, $str, $matches, PREG_OFFSET_CAPTURE)) { $i_max = count($matches[0]) - 1; for ($i=$i_max; $i>=0; $i--) { list($match, $start) = $matches[0][$i]; $char = $matches[1][$i][0]; $char = hotpot_textlib('code2utf8', hexdec($char)); $str = substr_replace($str, $char, $start, strlen($match)); } } return $str; } /** * filter_text_bodycontent */ function filter_text_bodycontent() { // convert entities to utf8, filter text and convert back //$this->bodycontent = hotpot_textlib('entities_to_utf8', $this->bodycontent); //$this->bodycontent = filter_text($this->bodycontent); //$this->bodycontent = hotpot_textlib('utf8_to_entities', $this->bodycontent); } /** * fix_feedbackform */ function fix_feedbackform() { // we are aiming to generate the following javascript to send to the client //FEEDBACK = new Array(); //FEEDBACK[0] = ''; // url of feedback page/script //FEEDBACK[1] = ''; // array of array('teachername', 'value'); //FEEDBACK[2] = ''; // 'student name' [formmail only] //FEEDBACK[3] = ''; // 'student email' [formmail only] //FEEDBACK[4] = ''; // window width //FEEDBACK[5] = ''; // window height //FEEDBACK[6] = ''; // 'Send a message to teacher' [prompt/button text] //FEEDBACK[7] = ''; // 'Title' //FEEDBACK[8] = ''; // 'Teacher' //FEEDBACK[9] = ''; // 'Message' //FEEDBACK[10] = ''; // 'Close this window' global $CFG, $USER; $feedback = array(); switch ($this->hotpot->studentfeedback) { case hotpot::FEEDBACK_NONE: // do nothing - feedback form is not required break; case hotpot::FEEDBACK_WEBPAGE: if ($this->hotpot->studentfeedbackurl) { $feedback[0] = "'".addslashes_js($this->hotpot->studentfeedbackurl)."'"; } else { $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; case hotpot::FEEDBACK_FORMMAIL: if ($this->hotpot->studentfeedbackurl) { $teachers = $this->get_feedback_teachers(); } else { $teachers = ''; } if ($teachers) { $feedback[0] = "'".addslashes_js($this->hotpot->studentfeedbackurl)."'"; $feedback[1] = $teachers; $feedback[2] = "'".addslashes_js(fullname($USER))."'"; $feedback[3] = "'".addslashes_js($USER->email)."'"; $feedback[4] = 500; // width $feedback[5] = 300; // height } else { // no teachers (or no feedback url) $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; case hotpot::FEEDBACK_MOODLEFORUM: $cmids = array(); if ($modinfo = get_fast_modinfo($this->hotpot->course)) { foreach ($modinfo->cms as $cmid=>$mod) { if ($mod->modname=='forum' && $mod->visible) { $cmids[] = $cmid; } } } switch (count($cmids)) { case 0: $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; break; // no forums !! case 1: $feedback[0] = "'".$CFG->wwwroot.'/mod/forum/view.php?id='.$cmids[0]."'"; break; default: $feedback[0] = "'".$CFG->wwwroot.'/mod/forum/index.php?id='.$this->hotpot->course->id."'"; } break; case hotpot::FEEDBACK_MOODLEMESSAGING: if ($CFG->messaging) { $teachers = $this->get_feedback_teachers(); } else { $teachers = ''; } if ($teachers) { $feedback[0] = "'$CFG->wwwroot/message/discussion.php?id='"; $feedback[1] = $teachers; $feedback[4] = 400; // width $feedback[5] = 500; // height } else { // no teachers (or no Moodle messaging) $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; default: // unrecognized feedback setting, so reset it to something valid $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_NONE) { // do nothing - feedback form is not required } else { // complete remaining feedback fields if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_MOODLEFORUM) { $feedback[6] = "'".addslashes_js(get_string('feedbackdiscuss', 'hotpot'))."'"; } else { // FEEDBACK_WEBPAGE, FEEDBACK_FORMMAIL, FEEDBACK_MOODLEMESSAGING $feedback[6] = "'".addslashes_js(get_string('feedbacksendmessage', 'hotpot'))."'"; } $feedback[7] = "'".addslashes_js(get_string('feedback'))."'"; $feedback[8] = "'".addslashes_js(get_string('defaultcourseteacher'))."'"; $feedback[9] = "'".addslashes_js(get_string('messagebody'))."'"; $feedback[10] = "'".addslashes_js(get_string('closewindow'))."'"; $js = ''; foreach ($feedback as $i=>$str) { $js .= 'FEEDBACK['.$i."] = $str;\n"; } $js = '<script type="text/javascript">'."\n//<![CDATA[\n"."FEEDBACK = new Array();\n".$js."//]]>\n</script>\n"; if ($this->usemoodletheme) { $this->headcontent .= $js; } else { $this->bodycontent = preg_replace('/<\/head>/i', "$js</head>", $this->bodycontent, 1); } } } /** * get_feedback_teachers * * @return xxx */ function get_feedback_teachers() { $context = hotpot_get_context(CONTEXT_COURSE, $this->hotpot->source->courseid); $teachers = get_users_by_capability($context, 'mod/hotpot:reviewallattempts'); $details = array(); if (isset($teachers) && count($teachers)) { if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_MOODLEMESSAGING) { $detail = 'id'; } else { $detail = 'email'; } foreach ($teachers as $teacher) { $details[] = "new Array('".addslashes_js(fullname($teacher))."', '".addslashes_js($teacher->$detail)."')"; } } if ($details = implode(', ', $details)) { return 'new Array('.$details.')'; } else { return ''; // no teachers } } /** * fix_reviewoptions */ function fix_reviewoptions() { // enable / disable review options } /** * fix_submissionform */ function fix_submissionform() { $params = array( 'id' => $this->hotpot->create_attempt(), $this->scorefield => '0', 'detail' => '0', 'status' => '0', 'starttime' => '0', 'endtime' => '0', 'redirect' => '0', ); $attributes = array( 'id' => $this->formid, 'autocomplete' => 'off' ); $form_start = $this->form_start('submit.php', $params, $attributes); $search = '<!-- BeginSubmissionForm -->'; if (! $pos = strpos($this->bodycontent, $search)) { throw new moodle_exception('couldnotinsertsubmissionform', 'hotpot'); } $this->bodycontent = substr_replace($this->bodycontent, $form_start, $pos, strlen($search)); $search = '<!-- EndSubmissionForm -->'; if (! $pos = strpos($this->bodycontent, $search)) { throw new moodle_exception('couldnotinsertsubmissionform', 'hotpot'); } $this->bodycontent = substr_replace($this->bodycontent, $this->form_end(), $pos, strlen($search)); } /** * fix_mediafilter_onload_extra * * @return xxx */ function fix_mediafilter_onload_extra() { return '' .' if(window.StretchCanvasToCoverContent) {'."\n" .' StretchCanvasToCoverContent();'."\n" .' }'."\n" ; } // captions and messages /** * expand_AlsoCorrect * * @return xxx */ function expand_AlsoCorrect() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',also-correct'); } /** * expand_BottomNavBar * * @return xxx */ function expand_BottomNavBar() { return $this->expand_NavBar('BottomNavBar'); } /** * expand_CapitalizeFirst * * @return xxx */ function expand_CapitalizeFirst() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',capitalize-first-letter'); } /** * expand_CheckCaption * * @return xxx */ function expand_CheckCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,check-caption'); } /** * expand_ContentsURL * * @return xxx */ function expand_ContentsURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,contents-url'); } /** * expand_CorrectIndicator * * @return xxx */ function expand_CorrectIndicator() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,correct-indicator'); } /** * expand_Back * * @return xxx */ function expand_Back() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-back'); } /** * expand_BackCaption * * @return xxx */ function expand_BackCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,back-caption'); } /** * expand_CaseSensitive * * @return xxx */ function expand_CaseSensitive() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',case-sensitive'); } /** * expand_ClickToAdd * * @return xxx */ function expand_ClickToAdd() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',click-to-add'); } /** * expand_ClueCaption * * @return xxx */ function expand_ClueCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,clue-caption'); } /** * expand_Clues * * @return xxx */ function expand_Clues() { // Note: WinHotPot6 uses "include-clues", but JavaHotPotatoes6 uses "include-clue" (missing "s") return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-clues'); } /** * expand_Contents * * @return xxx */ function expand_Contents() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-contents'); } /** * expand_ContentsCaption * * @return xxx */ function expand_ContentsCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,contents-caption'); } /** * expand_Correct * * @return xxx */ function expand_Correct() { if ($this->hotpot->source->hbs_quiztype=='jcloze') { $tag = 'guesses-correct'; } else { $tag = 'guess-correct'; } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_DeleteCaption * * @return xxx */ function expand_DeleteCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',delete-caption'); } /** * expand_DublinCoreMetadata * * @return xxx */ function expand_DublinCoreMetadata() { $dc = ''; if ($value = $this->hotpot->source->xml_value('', "['rdf:RDF'][0]['@']['xmlns:dc']")) { $dc .= '<link rel="schema.DC" href="'.str_replace('"', '&quot;', $value).'" />'."\n"; } if (is_array($this->hotpot->source->xml_value('rdf:RDF,rdf:Description'))) { $names = array('DC:Creator'=>'dc:creator', 'DC:Title'=>'dc:title'); foreach ($names as $name => $tag) { $i = 0; $values = array(); while($value = $this->hotpot->source->xml_value("rdf:RDF,rdf:Description,$tag", "[$i]['#']")) { if ($value = trim(strip_tags($value))) { $values[strtoupper($value)] = htmlspecialchars($value); } $i++; } if ($value = implode(', ', $values)) { $dc .= '<meta name="'.$name.'" content="'.$value.'" />'."\n"; } } } return $dc; } /** * expand_EMail * * @return xxx */ function expand_EMail() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,email'); } /** * expand_EscapedExerciseTitle * this string only used in resultsp6sendresults.js_ which is not required in Moodle * * @return xxx */ function expand_EscapedExerciseTitle() { return $this->hotpot->source->xml_value_js('data,title'); } /** * expand_ExBGColor * * @return xxx */ function expand_ExBGColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); } /** * expand_ExerciseSubtitle * * @return xxx */ function expand_ExerciseSubtitle() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',exercise-subtitle'); } /** * expand_ExerciseTitle * * @return xxx */ function expand_ExerciseTitle() { return $this->hotpot->source->xml_value('data,title'); } /** * expand_FontFace * * @return xxx */ function expand_FontFace() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,font-face'); } /** * expand_FontSize * * @return xxx */ function expand_FontSize() { $value = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,font-size'); return (empty($value) ? 'small' : $value); } /** * expand_FormMailURL * * @return xxx */ function expand_FormMailURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,formmail-url'); } /** * expand_FullVersionInfo * * @return xxx */ function expand_FullVersionInfo() { global $CFG; return $this->hotpot->source->xml_value('version').'.x (Moodle '.$CFG->release.', HotPot '.hotpot::get_version_info('release').')'; } /** * expand_FuncLightColor * * @return xxx */ function expand_FuncLightColor() { // top-left of buttons $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); return $this->expand_halfway_color($color, '#ffffff'); } /** * expand_FuncShadeColor * * @return xxx */ function expand_FuncShadeColor() { // bottom right of buttons $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); return $this->expand_halfway_color($color, '#000000'); } /** * expand_GiveHint * * @return xxx */ function expand_GiveHint() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-correct-letter'); } /** * expand_GraphicURL * * @return xxx */ function expand_GraphicURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,graphic-url'); } /** * expand_GuessCorrect * * @return xxx */ function expand_GuessCorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',guess-correct'); } /** * expand_GuessIncorrect * * @return xxx */ function expand_GuessIncorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',guess-incorrect'); } /** * expand_HeaderCode * * @return xxx */ function expand_HeaderCode() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,header-code'); } /** * expand_Hint * * @return xxx */ function expand_Hint() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-hint'); } /** * expand_HintCaption * * @return xxx */ function expand_HintCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,hint-caption'); } /** * expand_Incorrect * * @return xxx */ function expand_Incorrect() { if ($this->hotpot->source->hbs_quiztype=='jcloze') { $tag = 'guesses-incorrect'; } else { $tag = 'guess-incorrect'; } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_IncorrectIndicator * * @return xxx */ function expand_IncorrectIndicator() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,incorrect-indicator'); } /** * expand_Instructions * * @return xxx */ function expand_Instructions() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',instructions'); } /** * expand_JSBrowserCheck * * @return xxx */ function expand_JSBrowserCheck() { return $this->expand_template('hp6browsercheck.js_'); } /** * expand_JSButtons * * @return xxx */ function expand_JSButtons() { return $this->expand_template('hp6buttons.js_'); } /** * expand_JSCard * * @return xxx */ function expand_JSCard() { return $this->expand_template('hp6card.js_'); } /** * expand_JSCheckShortAnswer * * @return xxx */ function expand_JSCheckShortAnswer() { return $this->expand_template('hp6checkshortanswer.js_'); } /** * expand_JSHotPotNet * * @return xxx */ function expand_JSHotPotNet() { return $this->expand_template('hp6hotpotnet.js_'); } /** * expand_JSSendResults * * @return xxx */ function expand_JSSendResults() { return $this->expand_template('hp6sendresults.js_'); } /** * expand_JSShowMessage * * @return xxx */ function expand_JSShowMessage() { return $this->expand_template('hp6showmessage.js_'); } /** * expand_JSTimer * * @return xxx */ function expand_JSTimer() { return $this->expand_template('hp6timer.js_'); } /** * expand_JSUtilities * * @return xxx */ function expand_JSUtilities() { return $this->expand_template('hp6utilities.js_'); } /** * expand_LastQCaption * * @return xxx */ function expand_LastQCaption() { $caption = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,last-q-caption'); return ($caption=='<=' ? '&lt;=' : $caption); } /** * expand_LinkColor * * @return xxx */ function expand_LinkColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,link-color'); } /** * expand_NamePlease * * @return xxx */ function expand_NamePlease() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,name-please'); } /** * expand_NavBar * * @param xxx $navbarid (optional, default='') * @return xxx */ function expand_NavBar($navbarid='') { $this->navbarid = $navbarid; $navbar = $this->expand_template('hp6navbar.ht_'); unset($this->navbarid); return $navbar; } /** * expand_NavBarID * * @return xxx */ function expand_NavBarID() { // $this->navbarid is set in "$this->expand_NavBar" return empty($this->navbarid) ? '' : $this->navbarid; } /** * expand_NavBarJS * * @return xxx */ function expand_NavBarJS() { return $this->expand_NavButtons(); } /** * expand_NavButtons * * @return xxx */ function expand_NavButtons() { return ($this->expand_Back() || $this->expand_NextEx() || $this->expand_Contents()); } /** * expand_NavTextColor * * @return xxx */ function expand_NavTextColor() { // might be 'title-color' ? return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,text-color'); } /** * expand_NavBarColor * * @return xxx */ function expand_NavBarColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); } /** * expand_NavLightColor * * @return xxx */ function expand_NavLightColor() { $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); return $this->expand_halfway_color($color, '#ffffff'); } /** * expand_NavShadeColor * * @return xxx */ function expand_NavShadeColor() { $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); return $this->expand_halfway_color($color, '#000000'); } /** * expand_NextCaption * * @return xxx */ function expand_NextCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-caption'); } /** * expand_NextCorrect * * @return xxx */ function expand_NextCorrect() { if ($this->hotpot->source->hbs_quiztype=='jquiz') { $tag = 'next-correct-letter'; // jquiz } else { $tag = 'next-correct-part'; // jmix } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_NextEx * * @return xxx */ function expand_NextEx() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-next-ex'); } /** * expand_NextExCaption * * @return xxx */ function expand_NextExCaption() { $caption = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,next-ex-caption'); return ($caption=='=>' ? '=&gt;' : $caption); } /** * expand_NextQCaption * * @return xxx */ function expand_NextQCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,next-q-caption'); } /** * expand_NextExURL * * @return xxx */ function expand_NextExURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-ex-url'); } /** * expand_OKCaption * * @return xxx */ function expand_OKCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ok-caption'); } /** * expand_PageBGColor * * @return xxx */ function expand_PageBGColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,page-bg-color'); } /** * expand_PlainTitle * * @return xxx */ function expand_PlainTitle() { return $this->hotpot->source->xml_value('data,title'); } /** * expand_PreloadImages * * @return xxx */ function expand_PreloadImages() { $value = $this->expand_PreloadImageList(); return empty($value) ? false : true; } /** * expand_PreloadImageList * * @return xxx */ function expand_PreloadImageList() { if (! isset($this->PreloadImageList)) { $this->PreloadImageList = ''; $images = array(); // extract all src values from <img> tags in the xml file $search = '/&amp;#x003C;img.*?src=&quot;(.*?)&quot;.*?&amp;#x003E;/is'; if (preg_match_all($search, $this->hotpot->source->filecontents, $matches)) { $images = array_merge($images, $matches[1]); } // extract all urls from HotPot's [square bracket] notation // e.g. [%sitefiles%/images/screenshot.jpg image 350 265 center] $search = '/\['."([^\?\]]*\.(?:jpg|gif|png)(?:\?[^ \t\r\n\]]*)?)".'[^\]]*'.'\]/s'; if (preg_match_all($search, $this->hotpot->source->filecontents, $matches)) { $images = array_merge($images, $matches[1]); } if (count($images)) { $images = array_unique($images); $this->PreloadImageList = "\n\t\t'".implode("',\n\t\t'", $images)."'\n\t"; } } return $this->PreloadImageList; } /** * expand_Reading * * @return xxx */ function expand_Reading() { return $this->hotpot->source->xml_value_int('data,reading,include-reading'); } /** * expand_ReadingText * * @return xxx */ function expand_ReadingText() { $title = $this->expand_ReadingTitle(); if ($value = $this->hotpot->source->xml_value('data,reading,reading-text')) { $value = '<div class="ReadingText">'.$value.'</div>'; } else { $value = ''; } return $title.$value; } /** * expand_ReadingTitle * * @return xxx */ function expand_ReadingTitle() { $value = $this->hotpot->source->xml_value('data,reading,reading-title'); return empty($value) ? '' : ('<h3 class="ExerciseSubtitle">'.$value.'</h3>'); } /** * expand_Restart * * @return xxx */ function expand_Restart() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-restart'); } /** * expand_RestartCaption * * @return xxx */ function expand_RestartCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,restart-caption'); } /** * expand_Scorm12 * * @return xxx */ function expand_Scorm12() { return false; // HP scorm functionality is always disabled in Moodle } /** * expand_Seconds * * @return xxx */ function expand_Seconds() { return $this->hotpot->source->xml_value('data,timer,seconds'); } /** * expand_SendResults * * @return xxx */ function expand_SendResults() { return false; // send results (via formmail) is always disabled in Moodle // $tags = $this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',send-email'; // return $this->hotpot->source->xml_value($tags); } /** * expand_ShowAllQuestionsCaption * * @return xxx */ function expand_ShowAllQuestionsCaption($convert_to_unicode=false) { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,show-all-questions-caption'); } /** * expand_ShowAnswer * * @return xxx */ function expand_ShowAnswer() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-show-answer'); } /** * expand_SolutionCaption * * @return xxx */ function expand_SolutionCaption() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,solution-caption'); } /** * expand_ShowOneByOneCaption * * @return xxx */ function expand_ShowOneByOneCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,show-one-by-one-caption'); } /** * expand_StyleSheet * * @return xxx */ function expand_StyleSheet() { return $this->expand_template('hp6.cs_'); } /** * expand_TextColor * * @return xxx */ function expand_TextColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,text-color'); } /** * expand_TheseAnswersToo * * @return xxx */ function expand_TheseAnswersToo() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',also-correct'); } /** * expand_ThisMuch * * @return xxx */ function expand_ThisMuch() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',this-much-correct'); } /** * expand_Timer * * @return xxx */ function expand_Timer() { if ($this->hotpot->timelimit < 0) { // use setting in source file return $this->hotpot->source->xml_value_int('data,timer,include-timer'); } else { // override setting in source file return $this->hotpot->timelimit; } } /** * expand_TimesUp * * @return xxx */ function expand_TimesUp() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,times-up'); } /** * expand_TitleColor * * @return xxx */ function expand_TitleColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,title-color'); } /** * expand_TopNavBar * * @return xxx */ function expand_TopNavBar() { return $this->expand_NavBar('TopNavBar'); } /** * expand_Undo * * @return xxx */ function expand_Undo() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-undo'); } /** * expand_UndoCaption * * @return xxx */ function expand_UndoCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,undo-caption'); } /** * expand_UserDefined1 * * @return xxx */ function expand_UserDefined1() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-1'); } /** * expand_UserDefined2 * * @return xxx */ function expand_UserDefined2() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-2'); } /** * expand_UserDefined3 * * @return xxx */ function expand_UserDefined3() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-3'); } /** * expand_VLinkColor * * @return xxx */ function expand_VLinkColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,vlink-color'); } /** * expand_YourScoreIs * * @return xxx */ function expand_YourScoreIs() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,your-score-is'); } /** * expand_Keypad * * @return xxx */ function expand_Keypad() { $str = ''; if ($this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-keypad')) { // these characters must always be in the keypad $chars = array(); $this->add_keypad_chars($chars, $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,keypad-characters')); // append other characters used in the answers switch ($this->hotpot->source->hbs_quiztype) { case 'jcloze': $tags = 'data,gap-fill,question-record'; break; case 'jquiz': $tags = 'data,questions,question-record'; break; case 'rhubarb': $tags = 'data,rhubarb-text'; break; default: $tags = ''; } if ($tags) { $q = 0; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { if ($this->hotpot->source->hbs_quiztype=='jquiz') { $answers = $question."['answers'][0]['#']"; } else { $answers = $question; } $a = 0; while (($answer=$answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $this->add_keypad_chars($chars, $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']")); $a++; } $q++; } } // remove duplicate characters and sort $chars = array_unique($chars); usort($chars, array($this, 'hotpot_keypad_chars_sort')); // create keypad buttons for each character foreach ($chars as $char) { $str .= '<button onclick="'."TypeChars('".$this->hotpot->source->js_value_safe($char, true)."');".'return false;">'.$char.'</button>'; } } return $str; } /** * add_keypad_chars * * @param xxx $chars (passed by reference) * @param xxx $text */ function add_keypad_chars(&$chars, $text) { if (preg_match_all('/&[^;]+;/', $text, $more_chars)) { $chars = array_merge($chars, $more_chars[0]); } } /** * hotpot_keypad_chars_sort * * @param xxx $a_char * @param xxx $b_char * @return xxx */ function hotpot_keypad_chars_sort($a_char, $b_char) { $a_value = $this->hotpot_keypad_char_value($a_char); $b_value = $this->hotpot_keypad_char_value($b_char); if ($a_value < $b_value) { return -1; } if ($a_value > $b_value) { return 1; } // values are equal return 0; } /** * hotpot_keypad_char_value * * @param xxx $char * @return xxx */ function hotpot_keypad_char_value($char) { $char = hotpot_textlib('entities_to_utf8', $char); $ord = ord($char); // lowercase letters (plain or accented) if (($ord>=97 && $ord<=122) || ($ord>=224 && $ord<=255)) { return ($ord-31) + ($ord/1000); } // subscripts and superscripts switch ($ord) { case 0x2070: return 48.1; // super 0 = ord('0') + 0.1 case 0x00B9: return 49.1; // super 1 case 0x00B2: return 50.1; // super 2 case 0x00B3: return 51.1; // super 3 case 0x2074: return 52.1; // super 4 case 0x2075: return 53.1; // super 5 case 0x2076: return 54.1; // super 6 case 0x2077: return 55.1; // super 7 case 0x2078: return 56.1; // super 8 case 0x2079: return 57.1; // super 9 case 0x207A: return 43.1; // super + case 0x207B: return 45.1; // super - case 0x207C: return 61.1; // super = case 0x207D: return 40.1; // super ( case 0x207E: return 41.1; // super ) case 0x207F: return 110.1; // super n case 0x2080: return 47.9; // sub 0 = ord('0') - 0.1 case 0x2081: return 48.9; // sub 1 case 0x2082: return 49.9; // sub 2 case 0x2083: return 50.9; // sub 3 case 0x2084: return 51.9; // sub 4 case 0x2085: return 52.9; // sub 5 case 0x2086: return 53.9; // sub 6 case 0x2087: return 54.9; // sub 7 case 0x2088: return 55.9; // sub 8 case 0x2089: return 56.9; // sub 9 case 0x208A: return 42.9; // sub + case 0x208B: return 44.9; // sub - case 0x208C: return 60.9; // sub = case 0x208D: return 39.9; // sub ( case 0x208E: return 40.9; // sub ) case 0x208F: return 109.9; // sub n } return $ord; } // JCloze /** * expand_JSJCloze6 * * @return xxx */ function expand_JSJCloze6() { return $this->expand_template('jcloze6.js_'); } /** * expand_ClozeBody * * @return xxx */ function expand_ClozeBody() { $str = ''; // get drop down list of words, if required $dropdownlist = ''; if ($this->use_DropDownList()) { $this->set_WordList(); foreach ($this->wordlist as $word) { $dropdownlist .= '<option value="'.$word.'">'.$word.'</option>'; } } // cache clues flag and caption $includeclues = $this->expand_Clues(); $cluecaption = $this->expand_ClueCaption(); // detect if cloze starts with gap if (strpos($this->hotpot->source->filecontents, '<gap-fill><question-record>')) { $startwithgap = true; } else { $startwithgap = false; } // initialize loop values $q = 0; $tags = 'data,gap-fill'; $question_record = "$tags,question-record"; // initialize loop values $q = 0; $tags = 'data,gap-fill'; $question_record = "$tags,question-record"; // loop through text and gaps $looping = true; while ($looping) { $text = $this->hotpot->source->xml_value($tags, "[0]['#'][$q]"); $gap = ''; if (($question="[$q]['#']") && $this->hotpot->source->xml_value($question_record, $question)) { $gap .= '<span class="GapSpan" id="GapSpan'.$q.'">'; if ($this->use_DropDownList()) { $gap .= '<select id="Gap'.$q.'"><option value=""></option>'.$dropdownlist.'</select>'; } else { // minimum gap size if (! $gapsize = $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',minimum-gap-size')) { $gapsize = 6; } // increase gap size to length of longest answer for this gap $a = 0; while (($answer=$question."['answer'][$a]['#']") && $this->hotpot->source->xml_value($question_record, $answer)) { $answertext = $this->hotpot->source->xml_value($question_record, $answer."['text'][0]['#']"); $answertext = preg_replace('/&[#a-zA-Z0-9]+;/', 'x', $answertext); $gapsize = max($gapsize, strlen($answertext)); $a++; } $gap .= '<input type="text" id="Gap'.$q.'" onfocus="TrackFocus('.$q.')" onblur="LeaveGap()" class="GapBox" size="'.$gapsize.'"></input>'; } if ($includeclues) { $clue = $this->hotpot->source->xml_value($question_record, $question."['clue'][0]['#']"); if (strlen($clue)) { $gap .= '<button style="line-height: 1.0" class="FuncButton" onfocus="FuncBtnOver(this)" onmouseover="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" onclick="ShowClue('.$q.')">'.$cluecaption.'</button>'; } } $gap .= '</span>'; } if (strlen($text) || strlen($gap)) { if ($startwithgap) { $str .= $gap.$text; } else { $str .= $text.$gap; } $q++; } else { // no text or gap, so force end of loop $looping = false; } } if ($q==0) { // oops, no gaps found! return $this->hotpot->source->xml_value($tags); } else { return $str; } } /** * expand_ItemArray * * @return xxx */ function expand_ItemArray() { // this method is overridden by JCloze and JQuiz output formats } /** * expand_WordList * * @return xxx */ function expand_WordList() { $str = ''; if ($this->include_WordList()) { $this->set_WordList(); $str = implode(' &#160;&#160; ', $this->wordlist); } return $str; } /** * include_WordList * * @return xxx */ function include_WordList() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-word-list'); } /** * use_DropDownList * * @return xxx */ function use_DropDownList() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',use-drop-down-list'); } /** * set_WordList */ function set_WordList() { if (isset($this->wordlist)) { // do nothing } else { $this->wordlist = array(); // is the wordlist required if ($this->include_WordList() || $this->use_DropDownList()) { $q = 0; $tags = 'data,gap-fill,question-record'; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { $a = 0; $aa = 0; while (($answer=$question."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']"); $correct = $this->hotpot->source->xml_value_int($tags, $answer."['correct'][0]['#']"); if (strlen($text) && $correct) { // $correct is always true $this->wordlist[] = $text; $aa++; } $a++; } $q++; } $this->wordlist = array_unique($this->wordlist); sort($this->wordlist); } } } // jcross /** * expand_JSJCross6 * * @return xxx */ function expand_JSJCross6() { return $this->expand_template('jcross6.js_'); } /** * expand_CluesAcrossLabel * * @return xxx */ function expand_CluesAcrossLabel() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',clues-across'); } /** * expand_CluesDownLabel * * @return xxx */ function expand_CluesDownLabel() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',clues-down'); } /** * expand_EnterCaption * * @return xxx */ function expand_EnterCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',enter-caption'); } /** * expand_ShowHideClueList * * @return xxx */ function expand_ShowHideClueList() { $value = $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-clue-list'); return empty($value) ? ' style="display: none;"' : ''; } /** * expand_CluesDown * * @return xxx */ function expand_CluesDown() { return $this->expand_jcross_clues('D'); } /** * expand_CluesAcross * * @return xxx */ function expand_CluesAcross() { return $this->expand_jcross_clues('A'); } /** * expand_jcross_clues * * @param xxx $direction * @return xxx */ function expand_jcross_clues($direction) { // $direction: A(cross) or D(own) $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $clue_i = 0; // clue index; $str = ''; for ($r=0; $r<=$r_max; $r++) { for ($c=0; $c<=$c_max; $c++) { $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if ($aword || $dword) { $clue_i++; // increment clue index // get the definition for this word $def = ''; $word = ($direction=='A') ? $aword : $dword; $word = hotpot_textlib('utf8_to_entities', $word); $i = 0; $clues = 'data,crossword,clues,item'; while (($clue = "[$i]['#']") && $this->hotpot->source->xml_value($clues, $clue)) { if ($word==$this->hotpot->source->xml_value($clues, $clue."['word'][0]['#']")) { $def = $this->hotpot->source->xml_value($clues, $clue."['def'][0]['#']"); break; } $i++; } if ($def) { $str .= '<tr><td class="ClueNum">'.$clue_i.'. </td><td id="Clue_'.$direction.'_'.$clue_i.'" class="Clue">'.$def.'</td></tr>'; } } } } return $str; } /** * expand_LetterArray * * @return xxx */ function expand_LetterArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "L[$r] = new Array("; for ($c=0; $c<=$c_max; $c++) { $str .= ($c>0 ? ',' : '')."'".$this->hotpot->source->js_value_safe($row[$r]['cell'][$c]['#'], true)."'"; } $str .= ");\n"; } return $str; } /** * expand_GuessArray * * @return xxx */ function expand_GuessArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "G[$r] = new Array('".str_repeat("','", $c_max)."');\n"; } return $str; } /** * expand_ClueNumArray * * @return xxx */ function expand_ClueNumArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $i = 0; // clue index $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "CL[$r] = new Array("; for ($c=0; $c<=$c_max; $c++) { if ($c>0) { $str .= ','; } $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if (empty($aword) && empty($dword)) { $str .= 0; } else { $i++; // increment the clue index $str .= $i; } } $str .= ");\n"; } return $str; } /** * expand_GridBody * * @return xxx */ function expand_GridBody() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $i = 0; // clue index; $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= '<tr id="Row_'.$r.'">'; for ($c=0; $c<=$c_max; $c++) { if (empty($row[$r]['cell'][$c]['#'])) { $str .= '<td class="BlankCell">&nbsp;</td>'; } else { $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if (empty($aword) && empty($dword)) { $str .= '<td class="LetterOnlyCell"><span id="L_'.$r.'_'.$c.'">&nbsp;</span></td>'; } else { $i++; // increment clue index $str .= '<td class="NumLetterCell"><a href="javascript:void(0);" class="GridNum" onclick="ShowClue('.$i.','.$r.','.$c.')">'.$i.'</a><span class="NumLetterCellText" id="L_'.$r.'_'.$c.'" onclick="ShowClue('.$i.','.$r.','.$c.')">&nbsp;&nbsp;&nbsp;</span></td>'; } } } $str .= '</tr>'; } return $str; } /** * get_jcross_grid * * @param xxx $rows (passed by reference) * @param xxx $r_max (passed by reference) * @param xxx $c_max (passed by reference) */ function get_jcross_grid(&$rows, &$r_max, &$c_max) { $r_max = 0; $c_max = 0; $r = 0; $tags = 'data,crossword,grid,row'; while (($moretags="[$r]['#']") && $row = $this->hotpot->source->xml_value($tags, $moretags)) { $rows[$r] = $row; for ($c=0; $c<count($row['cell']); $c++) { if (! empty($row['cell'][$c]['#'])) { $r_max = max($r, $r_max); $c_max = max($c, $c_max); } } $r++; } } /** * get_jcross_dword * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @return xxx */ function get_jcross_dword(&$row, $r, $r_max, $c, $c_max) { $str = ''; if (($r==0 || empty($row[$r-1]['cell'][$c]['#'])) && $r<$r_max && !empty($row[$r+1]['cell'][$c]['#'])) { $str = $this->get_jcross_word($row, $r, $r_max, $c, $c_max, true); } return $str; } /** * get_jcross_aword * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @return xxx */ function get_jcross_aword(&$row, $r, $r_max, $c, $c_max) { $str = ''; if (($c==0 || empty($row[$r]['cell'][$c-1]['#'])) && $c<$c_max && !empty($row[$r]['cell'][$c+1]['#'])) { $str = $this->get_jcross_word($row, $r, $r_max, $c, $c_max, false); } return $str; } /** * get_jcross_word * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @param xxx $go_down (optional, default=false) * @return xxx */ function get_jcross_word(&$row, $r, $r_max, $c, $c_max, $go_down=false) { $str = ''; while ($r<=$r_max && $c<=$c_max && !empty($row[$r]['cell'][$c]['#'])) { $str .= $row[$r]['cell'][$c]['#']; if ($go_down) { $r++; } else { $c++; } } return $str; } // jmatch /** * expand_JSJMatch6 * * @return xxx */ function expand_JSJMatch6() { return $this->expand_template('jmatch6.js_'); } /** * expand_JSDJMatch6 * * @return xxx */ function expand_JSDJMatch6() { return $this->expand_template('djmatch6.js_'); } /** * expand_JSFJMatch6 * * @return xxx */ function expand_JSFJMatch6() { return $this->expand_template('fjmatch6.js_'); } /** * expand_ShuffleQs * * @return xxx */ function expand_ShuffleQs() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',shuffle-questions'); } /** * expand_QsToShow * * @return xxx */ function expand_QsToShow() { $i = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-limited-questions'); if ($i) { $i = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',questions-to-show'); } if (empty($i)) { $i = 0; if ($this->hotpot->source->hbs_quiztype=='jmatch') { $tags = 'data,matching-exercise,pair'; } else if ($this->hotpot->source->hbs_quiztype=='jquiz') { $tags = 'data,questions,question-record'; } else { $tags = ''; } if ($tags) { while (($moretags="[$i]['#']") && $value = $this->hotpot->source->xml_value($tags, $moretags)) { $i++; } } } return $i; } /** * expand_MatchDivItems * * @return xxx */ function expand_MatchDivItems() { $this->set_jmatch_items(); $l_keys = $this->shuffle_jmatch_items($this->l_items); $r_keys = $this->shuffle_jmatch_items($this->r_items); $options = '<option value="x">'.$this->hotpot->source->xml_value('data,matching-exercise,default-right-item').'</option>'."\n"; foreach ($r_keys as $key) { // only add the first occurrence of the text (i.e. skip duplicates) if ($key==$this->r_items[$key]['key']) { $options .= '<option value="'.$key.'">'.$this->r_items[$key]['text'].'</option>'."\n"; // Note: if the 'text' contains an image, it could be added as the background image of the option // http://www.small-software-utilities.com/design/91/html-select-with-background-image-or-icon-next-to-text/ // ... or of an optgroup ... // http://ask.metafilter.com/16153/Images-in-HTML-select-form-elements } } $str = ''; foreach ($l_keys as $key) { $str .= '<tr><td class="l_item">'.$this->l_items[$key]['text'].'</td>'; $str .= '<td class="r_item">'; if ($this->r_items[$key]['fixed']) { $str .= $this->r_items[$key]['text']; } else { $str .= '<select id="s'.$this->r_items[$key]['key'].'_'.$key.'">'.$options.'</select>'; } $str .= '</td><td></td></tr>'; } return $str; } /** * expand_FixedArray * * @return xxx */ function expand_FixedArray() { $this->set_jmatch_items(); $str = ''; foreach ($this->l_items as $i=>$item) { $str .= "F[$i] = new Array();\n"; $str .= "F[$i][0] = '".$this->hotpot->source->js_value_safe($item['text'], true)."';\n"; $str .= "F[$i][1] = ".($item['key']+1).";\n"; } return $str; } /** * expand_DragArray * * @return xxx */ function expand_DragArray() { $this->set_jmatch_items(); $str = ''; foreach ($this->r_items as $i=>$item) { $str .= "D[$i] = new Array();\n"; $str .= "D[$i][0] = '".$this->hotpot->source->js_value_safe($item['text'], true)."';\n"; $str .= "D[$i][1] = ".($item['key']+1).";\n"; $str .= "D[$i][2] = ".$item['fixed'].";\n"; } return $str; } /** * expand_Slide * * @return xxx */ function expand_Slide() { // return true if any JMatch drag-and-drop RH items are fixed and therefore need to slide to the LHS $this->set_jmatch_items(); foreach ($this->r_items as $i=>$item) { if ($item['fixed']) { return true; } } return false; } /** * set_jmatch_items */ function set_jmatch_items() { if (count($this->l_items)) { return; } $tags = 'data,matching-exercise,pair'; $i = 0; while (($item = "[$i]['#']") && $this->hotpot->source->xml_value($tags, $item)) { $l_item = $item."['left-item'][0]['#']"; $l_text = $this->hotpot->source->xml_value($tags, $l_item."['text'][0]['#']"); $l_fixed = $this->hotpot->source->xml_value_int($tags, $l_item."['fixed'][0]['#']"); $r_item = $item."['right-item'][0]['#']"; $r_text = $this->hotpot->source->xml_value($tags, $r_item."['text'][0]['#']"); $r_fixed = $this->hotpot->source->xml_value_int($tags, $r_item."['fixed'][0]['#']"); // typically all right-hand items are unique, but there may be duplicates // in which case we want the key of the first item containing this text for ($key=0; $key<$i; $key++) { if (isset($this->r_items[$key]) && $this->r_items[$key]['text']==$r_text) { break; } } if (strlen($r_text)) { $addright = true; } else { $addright = false; } if (strlen($l_text)) { $this->l_items[] = array('key' => $key, 'text' => $l_text, 'fixed' => $l_fixed); $addright = true; // force right item to be added } if ($addright) { $this->r_items[] = array('key' => $key, 'text' => $r_text, 'fixed' => $r_fixed); } $i++; } } /** * shuffle_jmatch_items * * @param xxx $items (passed by reference) * @return xxx */ function shuffle_jmatch_items(&$items) { // get moveable items $moveable_keys = array(); for ($i=0; $i<count($items); $i++) { if(! $items[$i]['fixed']) { $moveable_keys[] = $i; } } // shuffle moveable items $this->seed_random_number_generator(); shuffle($moveable_keys); $keys = array(); for ($i=0, $ii=0; $i<count($items); $i++) { if($items[$i]['fixed']) { // fixed items stay where they are $keys[] = $i; } else { // moveable items are inserted in a shuffled order $keys[] = $moveable_keys[$ii++]; } } return $keys; } /** * seed_random_number_generator */ function seed_random_number_generator() { static $seeded = false; if (! $seeded) { srand((double) microtime() * 1000000); $seeded = true; } } // JMatch flash card /** * expand_TRows * * @return xxx */ function expand_TRows() { $str = ''; $this->set_jmatch_items(); $i_max = count($this->l_items); for ($i=0; $i<$i_max; $i++) { $str .= '<tr class="FlashcardRow" id="I_'.$i.'"><td id="L_'.$i.'">'.$this->l_items[$i]['text'].'</td><td id="R_'.$i.'">'.$this->r_items[$i]['text'].'</td></tr>'."\n"; } return $str; } // jmix /** * expand_JSJMix6 * * @return xxx */ function expand_JSJMix6() { return $this->expand_template('jmix6.js_'); } /** * expand_JSFJMix6 * * @return xxx */ function expand_JSFJMix6() { return $this->expand_template('fjmix6.js_'); } /** * expand_JSDJMix6 * * @return xxx */ function expand_JSDJMix6() { return $this->expand_template('djmix6.js_'); } /** * expand_Punctuation * * @return xxx */ function expand_Punctuation() { $chars = array(); // RegExp pattern to match HTML entity $pattern = '/&#x([0-9A-F]+);/i'; // entities for all punctutation except '&#;' (because they are used in html entities) $entities = $this->jmix_encode_punctuation('!"$%'."'".'()*+,-./:<=>?@[\]^_`{|}~'); // xml tags for JMix segments and alternate answers $punctuation_tags = array( 'data,jumbled-order-exercise,main-order,segment', 'data,jumbled-order-exercise,alternate' ); foreach ($punctuation_tags as $tags) { // get next segment (or alternate answer) $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { // convert low-ascii punctuation to entities $value = strtr($value, $entities); // extract all hex HTML entities if (preg_match_all($pattern, $value, $matches)) { // loop through hex entities $m_max = count($matches[0]); for ($m=0; $m<$m_max; $m++) { // convert to hex string to number //eval('$hex=0x'.$matches[1][$m].';'); $hex = hexdec($matches[1][$m]); // is this a punctuation character? if ( ($hex>=0x0020 && $hex<=0x00BF) || // ascii punctuation ($hex>=0x2000 && $hex<=0x206F) || // general punctuation ($hex>=0x3000 && $hex<=0x303F) || // CJK punctuation ($hex>=0xFE30 && $hex<=0xFE4F) || // CJK compatability ($hex>=0xFE50 && $hex<=0xFE6F) || // small form variants ($hex>=0xFF00 && $hex<=0xFF40) || // halfwidth and fullwidth forms (1) ($hex>=0xFF5B && $hex<=0xFF65) || // halfwidth and fullwidth forms (2) ($hex>=0xFFE0 && $hex<=0xFFEE) // halfwidth and fullwidth forms (3) ) { // add this character $chars[] = $matches[0][$m]; } } } // end if HTML entity $i++; } // end while next segment (or alternate answer) } // end foreach $tags $chars = implode('', array_unique($chars)); return $this->hotpot->source->js_value_safe($chars, true); } /** * expand_OpenPunctuation * * @return xxx */ function expand_OpenPunctuation() { $chars = array(); // unicode punctuation designations (pi="initial quote", ps="open") // http://www.sql-und-xml.de/unicode-database/pi.html // http://www.sql-und-xml.de/unicode-database/ps.html $pi = '0022|0027|00AB|2018|201B|201C|201F|2039'; $ps = '0028|005B|007B|0F3A|0F3C|169B|201A|201E|2045|207D|208D|2329|23B4|2768|276A|276C|276E|2770|2772|2774|27E6|27E8|27EA|2983|2985|2987|2989|298B|298D|298F|2991|2993|2995|2997|29D8|29DA|29FC|3008|300A|300C|300E|3010|3014|3016|3018|301A|301D|FD3E|FE35|FE37|FE39|FE3B|FE3D|FE3F|FE41|FE43|FE47|FE59|FE5B|FE5D|FF08|FF3B|FF5B|FF5F|FF62'; $pattern = '/(&#x('.$pi.'|'.$ps.');)/i'; // HMTL entities of opening punctuation $entities = $this->jmix_encode_punctuation('"'."'".'(<[{'); // xml tags for JMix segments and alternate answers $punctuation_tags = array( 'data,jumbled-order-exercise,main-order,segment', 'data,jumbled-order-exercise,alternate' ); foreach ($punctuation_tags as $tags) { $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { $value = strtr($value, $entities); if (preg_match_all($pattern, $value, $matches)) { $chars = array_merge($chars, $matches[0]); } $i++; } } $chars = implode('', array_unique($chars)); return $this->hotpot->source->js_value_safe($chars, true); } /** * jmix_encode_punctuation * * @param xxx $str * @return xxx */ function jmix_encode_punctuation($str) { $entities = array(); $i_max = strlen($str); for ($i=0; $i<$i_max; $i++) { $entities[$str{$i}] = '&#x'.sprintf('%04X', ord($str{$i})).';'; } return $entities; } /* * expand_ForceLowercase * * Should we force the first letter of the first word to be lowercase? * (all other letters are assumed to have the correct case) * * When generating html files with standard JMix program, the user is prompted: * Should the word Xxxxx begin with a capital letter * even when it isn't at the beginning of a sentence? * * The "force-lowercase" xml tag implements a similar functionality * This tag does not exist in standard Hot Potatoes XML files, * but it can be added manually, for example to a HP config file * * @return xxx */ function expand_ForceLowercase() { $tag = $this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',force-lowercase'; return $this->hotpot->source->xml_value_int($tag); } /** * expand_SegmentArray * * @return xxx */ function expand_SegmentArray($more_values=array()) { $segments = array(); $values = array(); // XML tags to the start of a segment $tags = 'data,jumbled-order-exercise,main-order,segment'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { if ($i==0 && $this->expand_ForceLowercase()) { $value = strtolower(substr($value, 0, 1)).substr($value, 1); } $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key; } else { $segments[] = $i; $values[$i] = $value; } $i++; } foreach ($more_values as $value) { $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key; } else { $segments[] = $i; $values[$i] = $value; } $i++; } $this->seed_random_number_generator(); $keys = array_keys($segments); shuffle($keys); $str = ''; for ($i=0; $i<count($keys); $i++) { $key = $segments[$keys[$i]]; $str .= "Segments[$i] = new Array();\n"; $str .= "Segments[$i][0] = '".$this->hotpot->source->js_value_safe($values[$key], true)."';\n"; $str .= "Segments[$i][1] = ".($key+1).";\n"; $str .= "Segments[$i][2] = 0;\n"; } return $str; } /** * expand_AnswerArray * * @return xxx */ function expand_AnswerArray() { $segments = array(); $values = array(); $escapedvalues = array(); // XML tags to the start of a segment $tags = 'data,jumbled-order-exercise,main-order,segment'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { if ($i==0 && $this->expand_ForceLowercase()) { $value = strtolower(substr($value, 0, 1)).substr($value, 1); } $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key+1; } else { $segments[] = $i+1; $values[$i] = $value; $escapedvalues[] = preg_quote($value, '/'); } $i++; } // start the answers array $a = 0; $str = 'Answers['.($a++).'] = new Array('.implode(',', $segments).");\n"; // pattern to match the next part of an alternate answer $pattern = '/^('.implode('|', $escapedvalues).')\s*/i'; // XML tags to the start of an alternate answer $tags = 'data,jumbled-order-exercise,alternate'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { $segments = array(); while (strlen($value) && preg_match($pattern, $value, $matches)) { $key = array_search($matches[1], $values); if (is_numeric($key)) { $segments[] = $key+1; $value = substr($value, strlen($matches[0])); } else { // invalid alternate sequence - shouldn't happen !! $segments = array(); break; } } if (count($segments)) { $str .= 'Answers['.($a++).'] = new Array('.implode(',', $segments).");\n"; } $i++; } return $str; } /** * expand_RemainingWords * * @return xxx */ function expand_RemainingWords() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',remaining-words'); } /** * expand_DropTotal * * @return xxx */ function expand_DropTotal() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,drop-total'); } // JQuiz /** * expand_JSJQuiz6 * * @return xxx */ function expand_JSJQuiz6() { return $this->expand_template('jquiz6.js_'); } /** * expand_QuestionOutput * * @return xxx */ function expand_QuestionOutput() { // start question list $str = '<ol class="QuizQuestions" id="Questions">'."\n"; $q = 0; $tags = 'data,questions,question-record'; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question) && ($answers = $question."['answers'][0]['#']") && $this->hotpot->source->xml_value($tags, $answers)) { // get question $question_text = $this->hotpot->source->xml_value($tags, $question."['question'][0]['#']"); $question_type = $this->hotpot->source->xml_value_int($tags, $question."['question-type'][0]['#']"); switch ($question_type) { case 1: // MULTICHOICE: $textbox = false; $liststart = '<ol class="MCAnswers">'."\n"; break; case 2: // SHORTANSWER: $textbox = true; $liststart = ''; break; case 3: // HYBRID: $textbox = true; $liststart = '<ol class="MCAnswers" id="Q_'.$q.'_Hybrid_MC" style="display: none;">'."\n"; break; case 4: // MULTISELECT: $textbox = false; $liststart = '<ol class="MSelAnswers">'."\n"; break; default: continue; // unknown question type } $first_answer_tags = $question."['answers'][0]['#']['answer'][0]['#']['text'][0]['#']"; $first_answer_text = $this->hotpot->source->xml_value($tags, $first_answer_tags, '', false); // check we have a question (or at least one answer) if (strlen($question_text) || strlen($first_answer_text)) { // start question $str .= '<li class="QuizQuestion" id="Q_'.$q.'" style="display: none;">'; $str .= '<p class="QuestionText">'.$question_text.'</p>'; if ($textbox) { // get prefix, suffix and maximum size of ShortAnswer box (default = 9) list($prefix, $suffix, $size) = $this->expand_jquiz_textbox_details($tags, $answers, $q); $str .= '<div class="ShortAnswer" id="Q_'.$q.'_SA"><form method="post" action="" onsubmit="return false;"><div>'; $str .= $prefix; if ($size<=25) { // text box $str .= '<input type="text" id="Q_'.$q.'_Guess" onfocus="TrackFocus('."'".'Q_'.$q.'_Guess'."'".')" onblur="LeaveGap()" class="ShortAnswerBox" size="'.$size.'"></input>'; } else { // textarea (29 cols wide) $str .= '<textarea id="Q_'.$q.'_Guess" onfocus="TrackFocus('."'".'Q_'.$q.'_Guess'."'".')" onblur="LeaveGap()" class="ShortAnswerBox" cols="29" rows="'.ceil($size/25).'"></textarea>'; } $str .= $suffix; $str .= '<br /><br />'; $caption = $this->expand_CheckCaption(); $str .= $this->expand_jquiz_button($caption, "CheckShortAnswer($q)"); if ($this->expand_Hint()) { $caption = $this->expand_HintCaption(); $str .= $this->expand_jquiz_button($caption, "ShowHint($q)"); } if ($this->expand_ShowAnswer()) { $caption = $this->expand_ShowAnswerCaption(); $str .= $this->expand_jquiz_button($caption, "ShowAnswers($q)"); } $str .= '</div></form></div>'; } if ($liststart) { $str .= $liststart; $a = 0; $aa = 0; while (($answer = $answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']"); if (strlen($text)) { if ($question_type==1 || $question_type==3) { // MULTICHOICE or HYBRID: button if ($this->hotpot->source->xml_value_int($tags, $answer."['include-in-mc-options'][0]['#']")) { $str .= '<li id="Q_'.$q.'_'.$aa.'"><button class="FuncButton" onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" id="Q_'.$q.'_'.$aa.'_Btn" onclick="CheckMCAnswer('.$q.','.$aa.',this)">&nbsp;&nbsp;?&nbsp;&nbsp;</button>&nbsp;&nbsp;'.$text.'</li>'."\n"; } } else if ($question_type==4) { // MULTISELECT: checkbox $str .= '<li id="Q_'.$q.'_'.$aa.'"><form method="post" action="" onsubmit="return false;"><div><input type="checkbox" id="Q_'.$q.'_'.$aa.'_Chk" class="MSelCheckbox" />'.$text.'</div></form></li>'."\n"; } $aa++; } $a++; } // finish answer list $str .= '</ol>'; if ($question_type==4) { // MULTISELECT: check button $caption = $this->expand_CheckCaption(); $str .= $this->expand_jquiz_button($caption, "CheckMultiSelAnswer($q)"); } } // finish question $str .= "</li>\n"; } $q++; } // end while $question // finish question list and finish return $str."</ol>\n"; } /** * expand_jquiz_textbox_details * * @param xxx $tags * @param xxx $answers * @param xxx $q * @param xxx $defaultsize (optional, default=9) * @return xxx */ function expand_jquiz_textbox_details($tags, $answers, $q, $defaultsize=9) { $prefix = ''; $suffix = ''; $size = $defaultsize; $a = 0; while (($answer = $answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']", '', false); $text = preg_replace('/&[#a-zA-Z0-9]+;/', 'x', $text); $size = max($size, strlen($text)); $a++; } return array($prefix, $suffix, $size); } /** * expand_jquiz_button * * @param xxx $caption * @param xxx $onclick * @return xxx */ function expand_jquiz_button($caption, $onclick) { return '<button class="FuncButton" onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" onclick="'.$onclick.'">'.$caption.'</button>'; } /** * expand_MultiChoice * * @return xxx */ function expand_MultiChoice() { return $this->jquiz_has_question_type(1); } /** * expand_ShortAnswer * * @return xxx */ function expand_ShortAnswer() { return $this->jquiz_has_question_type(2); } /** * expand_MultiSelect * * @return xxx */ function expand_MultiSelect() { return $this->jquiz_has_question_type(4); } /** * jquiz_has_question_type * * @param xxx $type * @return xxx */ function jquiz_has_question_type($type) { // does this JQuiz have any questions of the given $type? $q = 0; $tags = 'data,questions,question-record'; while (($question = "[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { $question_type = $this->hotpot->source->xml_value($tags, $question."['question-type'][0]['#']"); if ($question_type==$type || ($question_type==3 && ($type==1 || $type==2))) { // 1=MULTICHOICE 2=SHORTANSWER 3=HYBRID return true; } $q++; } return false; } /** * expand_CompletedSoFar * * @return xxx */ function expand_CompletedSoFar() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,completed-so-far'); } /** * expand_ContinuousScoring * * @return xxx */ function expand_ContinuousScoring() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',continuous-scoring'); } /** * expand_CorrectFirstTime * * @return xxx */ function expand_CorrectFirstTime() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,correct-first-time'); } /** * expand_ExerciseCompleted * * @return xxx */ function expand_ExerciseCompleted() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,exercise-completed'); } /** * expand_ShowCorrectFirstTime * * @return xxx */ function expand_ShowCorrectFirstTime() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-correct-first-time'); } /** * expand_ShuffleAs * * @return xxx */ function expand_ShuffleAs() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',shuffle-answers'); } /** * expand_DefaultRight * * @return xxx */ function expand_DefaultRight() { return $this->expand_GuessCorrect(); } /** * expand_DefaultWrong * * @return xxx */ function expand_DefaultWrong() { return $this->expand_GuessIncorrect(); } /** * expand_ShowAllQuestionsCaptionJS * * @return xxx */ function expand_ShowAllQuestionsCaptionJS() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,show-all-questions-caption'); } /** * expand_ShowOneByOneCaptionJS * * @return xxx */ function expand_ShowOneByOneCaptionJS() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,show-one-by-one-caption'); } /** * expand_CorrectList * * @return xxx */ function expand_CorrectList() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',correct-answers'); } /** * expand_HybridTries * * @return xxx */ function expand_HybridTries() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',short-answer-tries-on-hybrid-q'); } /** * expand_PleaseEnter * * @return xxx */ function expand_PleaseEnter() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',enter-a-guess'); } /** * expand_PartlyIncorrect * * @return xxx */ function expand_PartlyIncorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',partly-incorrect'); } /** * expand_ShowAnswerCaption * * @return xxx */ function expand_ShowAnswerCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-answer-caption'); } /** * expand_ShowAlsoCorrect * * @return xxx */ function expand_ShowAlsoCorrect() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,global,show-also-correct'); } // Textoys stylesheets (tt3.cs_) /** * expand_isRTL * * @return xxx */ function expand_isRTL() { // this may require some clever detection of RTL languages (e.g. Hebrew) // but for now we just check the RTL setting in Options -> Configure Output return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,process-for-rtl'); } /** * expand_isLTR * * @return xxx */ function expand_isLTR() { if ($this->expand_isRTL()) { return false; } else { return true; } } /** * expand_RTLText * * @return xxx */ function expand_RTLText() { return $this->expand_isRTL(); } }
orvsd/moodle25
mod/hotpot/attempt/hp/6/renderer.php
PHP
gpl-3.0
143,352
''' Copyright (C) 2014 Travis DeWolf This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import numpy as np class Shell(object): """ """ def __init__(self, controller, target_list, threshold=.01, pen_down=False): """ control Control instance: the controller to use pen_down boolean: True if the end-effector is drawing """ self.controller = controller self.pen_down = pen_down self.target_list = target_list self.threshold = threshold self.not_at_start = True self.target_index = 0 self.set_target() def control(self, arm): """Move to a series of targets. """ if self.controller.check_distance(arm) < self.threshold: if self.target_index < len(self.target_list)-1: self.target_index += 1 self.set_target() self.controller.apply_noise = True self.not_at_start = not self.not_at_start self.pen_down = not self.pen_down self.u = self.controller.control(arm) return self.u def set_target(self): """ Set the current target for the controller. """ if self.target_index == len(self.target_list)-1: target = [1, 2] else: target = self.target_list[self.target_index] if target[0] != target[0]: # if it's NANs self.target_index += 1 self.set_target() else: self.controller.target = target
russellgeoff/blog
Control/Controllers/target_list.py
Python
gpl-3.0
2,121
<fieldset class="previsu"> <legend><:previsualisation:></legend> <ul> <li> <ul class='forum'> <li class="forum-fil"> <div class="comment"> <div class="comment-meta"> [<strong class="comment-titre">(#ENV*{titre})</strong>] [<small><:par_auteur:> <span>(#SESSION{session_nom}|safehtml|sinon{[(#SESSION{nom}|typo)]}|sinon{<span class="erreur_message blink">?</span>})</span></small>] </div> <div class="comment-content"> [<div class="comment-texte">(#ENV*{texte}|lignes_longues)</div>] [<div class="comment-notes">(#ENV*{notes}|lignes_longues)</div>] [<p class="#EDIT{hyperlien} hyperlien"><:voir_en_ligne:> : <a href="(#ENV{url_site}|attribut_html)" class="spip_out">[(#ENV*{nom_site}|sinon{[(#ENV{url_site}|couper{80})]})]</a></p>] [<div class="comment-doc"><:medias:info_document:> : (#ENV{ajouter_document}|table_valeur{name})</div>] <B_mots><p class="comment-mots"><:forum:forum_avez_selectionne:> <BOUCLE_mots(MOTS){id_mot IN #ENV**{ajouter_mot}}{par num type}{par type}{par num titre}{par titre}{', '}>#TITRE</BOUCLE_mots></p></B_mots> </div> </div> </li> </ul> [<li class="reponse_formulaire reponse error">(#ENV*{erreur})</li>] </li> </ul> [<p class="boutons"><input type="submit" class="submit" onclick="confirmer_previsu_forum_poste=true;" name="confirmer_previsu_forum" value="(#ENV*{bouton})" /></p>] </fieldset> <br class="clear" /> <script type="text/javascript">/*<![CDATA[*/ var confirmer_previsu_forum_poste = false; if (window.jQuery){ jQuery(function(){ jQuery(window).unload(function() { if (!confirmer_previsu_forum_poste) alert('<:forum:forum_attention_message_non_poste|texte_script:>');confirmer_previsu_forum_poste=true;});});} /*]]>*/</script>
VertigeASBL/Caravelle
plugins-dist/forum/formulaires/inc-forum_previsu.html
HTML
gpl-3.0
1,775
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #ifndef PLSCALARCHANNEL_INC #define PLSCALARCHANNEL_INC ///////////////////////////////////////////////////////////////////////////////////////// // // INCLUDES // ///////////////////////////////////////////////////////////////////////////////////////// // base #include "plAGChannel.h" #include "plAGApplicator.h" ///////////////////////////////////////////////////////////////////////////////////////// // // FORWARDS // ///////////////////////////////////////////////////////////////////////////////////////// class plController; class plAnimTimeConvert; class plSimpleStateVariable; class plControllerCacheInfo; ///////////////////////////////////////////////////////////////////////////////////////// // // DEFINITIONS // ///////////////////////////////////////////////////////////////////////////////////////// ////////////////// // PLSCALARCHANNEL ////////////////// // an animation channel that outputs a scalar value class plScalarChannel : public plAGChannel { protected: float fResult; public: plScalarChannel(); virtual ~plScalarChannel(); // AG PROTOCOL virtual const float & Value(double time, bool peek = false); virtual void Value(float &result, double time, bool peek = false); // combine it (allocates combine object) virtual plAGChannel * MakeCombine(plAGChannel * channelB); // blend it (allocates blend object) virtual plAGChannel * MakeBlend(plAGChannel * channelB, plScalarChannel * channelBias, int blendPriority); // const eval at time zero virtual plAGChannel * MakeZeroState(); // make a timeScale instance virtual plAGChannel * MakeTimeScale(plScalarChannel *timeSource); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarChannel ); GETINTERFACE_ANY( plScalarChannel, plAGChannel ); }; /////////////////// // PLSCALARCONSTANT /////////////////// // A scalar source that just keeps handing out the same value class plScalarConstant : public plScalarChannel { public: plScalarConstant(); plScalarConstant(float value); virtual ~plScalarConstant(); void Set(float value) { fResult = value; } float Get() { return fResult; } // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarConstant ); GETINTERFACE_ANY( plScalarConstant, plScalarChannel ); void Read(hsStream *stream, hsResMgr *mgr); void Write(hsStream *stream, hsResMgr *mgr); }; //////////////////// // PLSCALARTIMESCALE //////////////////// // Adapts the time scale before passing it to the next channel in line. // Use to instance animations while allowing each instance to run at different speeds. class plScalarTimeScale : public plScalarChannel { protected: plScalarChannel *fTimeSource; plScalarChannel *fChannelIn; public: plScalarTimeScale(); plScalarTimeScale(plScalarChannel *channel, plScalarChannel *timeSource); virtual ~plScalarTimeScale(); virtual bool IsStoppedAt(double time); virtual const float & Value(double time, bool peek = false); virtual plAGChannel * Detach(plAGChannel * channel); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarTimeScale ); GETINTERFACE_ANY( plScalarTimeScale, plScalarChannel ); }; //////////////// // PLSCALARBLEND //////////////// // blends two scalars into one with weighting class plScalarBlend : public plScalarChannel { protected: plScalarChannel * fChannelA; plScalarChannel * fChannelB; plScalarChannel * fChannelBias; public: // xTORs plScalarBlend(); plScalarBlend(plScalarChannel * channelA, plScalarChannel * channelB, plScalarChannel * channelBias); virtual ~plScalarBlend(); // SPECIFICS const plScalarChannel * GetChannelA() const { return fChannelA; } void SetChannelA(plScalarChannel * channel) { fChannelA = channel; } const plScalarChannel * GetChannelB() const { return fChannelB; } void SetChannelB(plScalarChannel * channel) { fChannelB = channel; } const plScalarChannel * GetChannelBias() const { return fChannelBias; } void SetChannelBias(plScalarChannel * channel) { fChannelBias = channel; } virtual bool IsStoppedAt(double time); // AG PROTOCOL virtual const float & Value(double time, bool peek = false); // remove the specified channel from our graph virtual plAGChannel * Detach(plAGChannel * channel); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarBlend ); GETINTERFACE_ANY( plScalarBlend, plScalarChannel ); }; //////////////////////////// // PLSCALARCONTROLLERCHANNEL //////////////////////////// // converts a plController-style animation into a plScalarChannel class plScalarControllerChannel : public plScalarChannel { protected: plController *fController; public: // xTORs plScalarControllerChannel(); plScalarControllerChannel(plController *controller); virtual ~plScalarControllerChannel(); // AG PROTOCOL virtual const float & Value(double time, bool peek = false); virtual const float & Value(double time, bool peek, plControllerCacheInfo *cache); virtual plAGChannel *MakeCacheChannel(plAnimTimeConvert *atc); // PLASMA PROTOCOL // rtti CLASSNAME_REGISTER( plScalarControllerChannel ); GETINTERFACE_ANY( plScalarControllerChannel, plScalarChannel ); // persistence virtual void Write(hsStream *stream, hsResMgr *mgr); virtual void Read(hsStream *s, hsResMgr *mgr); }; ///////////////////////////////// // PLSCALARCONTROLLERCACHECHANNEL ///////////////////////////////// // Same as plScalarController, but with caching info class plScalarControllerCacheChannel : public plScalarChannel { protected: plControllerCacheInfo *fCache; plScalarControllerChannel *fControllerChannel; public: plScalarControllerCacheChannel(); plScalarControllerCacheChannel(plScalarControllerChannel *channel, plControllerCacheInfo *cache); virtual ~plScalarControllerCacheChannel(); virtual const float & Value(double time, bool peek = false); virtual plAGChannel * Detach(plAGChannel * channel); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarControllerCacheChannel ); GETINTERFACE_ANY( plScalarControllerCacheChannel, plScalarChannel ); // Created at runtime only, so no Read/Write }; //////////////////// // PLATCChannel //////////////////// // Channel interface for a plAnimTimeConvert object class plATCChannel : public plScalarChannel { protected: plAnimTimeConvert *fConvert; public: plATCChannel(); plATCChannel(plAnimTimeConvert *convert); virtual ~plATCChannel(); virtual bool IsStoppedAt(double time); virtual const float & Value(double time, bool peek = false); // PLASMA PROTOCOL CLASSNAME_REGISTER( plATCChannel ); GETINTERFACE_ANY( plATCChannel, plScalarChannel ); }; //////////////////// // PLSCALARSDLCHANNEL //////////////////// // Returns the value of an SDL scalar variable class plScalarSDLChannel : public plScalarChannel { protected: plSimpleStateVariable *fVar; float fLength; public: plScalarSDLChannel(); plScalarSDLChannel(float length); virtual ~plScalarSDLChannel(); virtual bool IsStoppedAt(double time); virtual const float & Value(double time, bool peek = false); void SetVar(plSimpleStateVariable *var) { fVar = var; } // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarSDLChannel ); GETINTERFACE_ANY( plScalarSDLChannel, plScalarChannel ); }; //////////////////////////// // // Channel Applicator classes class plScalarChannelApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plScalarChannelApplicator ); GETINTERFACE_ANY( plScalarChannelApplicator, plAGApplicator ); }; class plSpotInnerApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plSpotInnerApplicator ); GETINTERFACE_ANY( plSpotInnerApplicator, plAGApplicator ); }; class plSpotOuterApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plSpotOuterApplicator ); GETINTERFACE_ANY( plSpotOuterApplicator, plAGApplicator ); }; class plOmniApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plOmniApplicator ); GETINTERFACE_ANY( plOmniApplicator, plAGApplicator ); }; class plOmniSqApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plOmniSqApplicator ); GETINTERFACE_ANY( plOmniSqApplicator, plAGApplicator ); }; class plOmniCutoffApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plOmniCutoffApplicator ); GETINTERFACE_ANY( plOmniCutoffApplicator, plAGApplicator ); }; #endif
cwalther/Plasma-nobink
Sources/Plasma/PubUtilLib/plAvatar/plScalarChannel.h
C
gpl-3.0
10,792
///////////////////////////////////////////////////////////////////////////// // Name: wx/os2/frame.h // Purpose: wxFrame class // Author: David Webster // Modified by: // Created: 10/27/99 // RCS-ID: $Id$ // Copyright: (c) David Webster // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_FRAME_H_ #define _WX_FRAME_H_ // // Get the default resource ID's for frames // #include "wx/os2/wxrsc.h" class WXDLLIMPEXP_CORE wxFrame : public wxFrameBase { public: // construction wxFrame() { Init(); } wxFrame( wxWindow* pParent ,wxWindowID vId ,const wxString& rsTitle ,const wxPoint& rPos = wxDefaultPosition ,const wxSize& rSize = wxDefaultSize ,long lStyle = wxDEFAULT_FRAME_STYLE ,const wxString& rsName = wxFrameNameStr ) { Init(); Create(pParent, vId, rsTitle, rPos, rSize, lStyle, rsName); } bool Create( wxWindow* pParent ,wxWindowID vId ,const wxString& rsTitle ,const wxPoint& rPos = wxDefaultPosition ,const wxSize& rSize = wxDefaultSize ,long lStyle = wxDEFAULT_FRAME_STYLE ,const wxString& rsName = wxFrameNameStr ); virtual ~wxFrame(); // implement base class pure virtuals #if wxUSE_MENUS_NATIVE virtual void SetMenuBar(wxMenuBar* pMenubar); #endif virtual bool ShowFullScreen( bool bShow ,long lStyle = wxFULLSCREEN_ALL ); // implementation only from now on // ------------------------------- virtual void Raise(void); // event handlers void OnSysColourChanged(wxSysColourChangedEvent& rEvent); // Toolbar #if wxUSE_TOOLBAR virtual wxToolBar* CreateToolBar( long lStyle = -1 ,wxWindowID vId = -1 ,const wxString& rsName = wxToolBarNameStr ); virtual wxToolBar* OnCreateToolBar( long lStyle ,wxWindowID vId ,const wxString& rsName ); virtual void PositionToolBar(void); #endif // wxUSE_TOOLBAR // Status bar #if wxUSE_STATUSBAR virtual wxStatusBar* OnCreateStatusBar( int nNumber = 1 ,long lStyle = wxSTB_DEFAULT_STYLE ,wxWindowID vId = 0 ,const wxString& rsName = wxStatusLineNameStr ); virtual void PositionStatusBar(void); // Hint to tell framework which status bar to use: the default is to use // native one for the platforms which support it (Win32), the generic one // otherwise // TODO: should this go into a wxFrameworkSettings class perhaps? static void UseNativeStatusBar(bool bUseNative) { m_bUseNativeStatusBar = bUseNative; }; static bool UsesNativeStatusBar() { return m_bUseNativeStatusBar; }; #endif // wxUSE_STATUSBAR WXHMENU GetWinMenu() const { return m_hMenu; } // Returns the origin of client area (may be different from (0,0) if the // frame has a toolbar) virtual wxPoint GetClientAreaOrigin() const; // event handlers bool HandlePaint(void); bool HandleSize( int nX ,int nY ,WXUINT uFlag ); bool HandleCommand( WXWORD wId ,WXWORD wCmd ,WXHWND wControl ); bool HandleMenuSelect( WXWORD wItem ,WXWORD wFlags ,WXHMENU hMenu ); // tooltip management #if wxUSE_TOOLTIPS WXHWND GetToolTipCtrl(void) const { return m_hWndToolTip; } void SetToolTipCtrl(WXHWND hHwndTT) { m_hWndToolTip = hHwndTT; } #endif // tooltips void SetClient(WXHWND c_Hwnd); void SetClient(wxWindow* c_Window); wxWindow *GetClient(); friend MRESULT EXPENTRY wxFrameWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); friend MRESULT EXPENTRY wxFrameMainWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); protected: // common part of all ctors void Init(void); virtual WXHICON GetDefaultIcon(void) const; // override base class virtuals virtual void DoGetClientSize( int* pWidth ,int* pHeight ) const; virtual void DoSetClientSize( int nWidth ,int nWeight ); inline virtual bool IsMDIChild(void) const { return FALSE; } #if wxUSE_MENUS_NATIVE // helper void DetachMenuBar(void); // perform MSW-specific action when menubar is changed virtual void AttachMenuBar(wxMenuBar* pMenubar); // a plug in for MDI frame classes which need to do something special when // the menubar is set virtual void InternalSetMenuBar(void); #endif // propagate our state change to all child frames void IconizeChildFrames(bool bIconize); // we add menu bar accel processing bool OS2TranslateMessage(WXMSG* pMsg); // window proc for the frames MRESULT OS2WindowProc( WXUINT uMessage ,WXWPARAM wParam ,WXLPARAM lParam ); bool m_bIconized; WXHICON m_hDefaultIcon; #if wxUSE_STATUSBAR static bool m_bUseNativeStatusBar; #endif // wxUSE_STATUSBAR // Data to save/restore when calling ShowFullScreen long m_lFsStyle; // Passed to ShowFullScreen wxRect m_vFsOldSize; long m_lFsOldWindowStyle; int m_nFsStatusBarFields; // 0 for no status bar int m_nFsStatusBarHeight; int m_nFsToolBarHeight; bool m_bFsIsMaximized; bool m_bFsIsShowing; bool m_bWasMinimized; bool m_bIsShown; private: #if wxUSE_TOOLTIPS WXHWND m_hWndToolTip; #endif // tooltips // // Handles to child windows of the Frame, and the frame itself, // that we don't have child objects for (m_hWnd in wxWindow is the // handle of the Frame's client window! // WXHWND m_hTitleBar; WXHWND m_hHScroll; WXHWND m_hVScroll; // // Swp structures for various client data // DW: Better off in attached RefData? // SWP m_vSwpTitleBar; SWP m_vSwpMenuBar; SWP m_vSwpHScroll; SWP m_vSwpVScroll; SWP m_vSwpStatusBar; SWP m_vSwpToolBar; DECLARE_EVENT_TABLE() DECLARE_DYNAMIC_CLASS(wxFrame) }; MRESULT EXPENTRY wxFrameWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); MRESULT EXPENTRY wxFrameMainWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); #endif // _WX_FRAME_H_
p0sixspwn/p0sixspwn
include/wxWidgets-2.9.2/include/wx/os2/frame.h
C
gpl-3.0
7,760
using System; using System.Collections.Generic; using Antlr4.Runtime; using Rubberduck.Parsing.Symbols; using Rubberduck.UI; using Rubberduck.VBEditor; namespace Rubberduck.Inspections { public class IdentifierNotUsedInspectionResult : CodeInspectionResultBase { private readonly IEnumerable<CodeInspectionQuickFix> _quickFixes; public IdentifierNotUsedInspectionResult(IInspection inspection, Declaration target, ParserRuleContext context, QualifiedModuleName qualifiedName) : base(inspection, string.Format(inspection.Description, target.IdentifierName), qualifiedName, context) { _quickFixes = new[] { new RemoveUnusedDeclarationQuickFix(context, QualifiedSelection), }; } public override IEnumerable<CodeInspectionQuickFix> QuickFixes { get { return _quickFixes; } } } /// <summary> /// A code inspection quickfix that removes an unused identifier declaration. /// </summary> public class RemoveUnusedDeclarationQuickFix : CodeInspectionQuickFix { public RemoveUnusedDeclarationQuickFix(ParserRuleContext context, QualifiedSelection selection) : base(context, selection, RubberduckUI.Inspections_RemoveUnusedDeclaration) { } public override void Fix() { var module = Selection.QualifiedName.Component.CodeModule; var selection = Selection.Selection; var originalCodeLines = module.get_Lines(selection.StartLine, selection.LineCount) .Replace("\r\n", " ") .Replace("_", string.Empty); var originalInstruction = Context.GetText(); module.DeleteLines(selection.StartLine, selection.LineCount); var newInstruction = string.Empty; var newCodeLines = string.IsNullOrEmpty(newInstruction) ? string.Empty : originalCodeLines.Replace(originalInstruction, newInstruction); if (!string.IsNullOrEmpty(newCodeLines)) { module.InsertLines(selection.StartLine, newCodeLines); } } } }
r14r/fork_vba_rubberduck
RetailCoder.VBE/Inspections/IdentifierNotUsedInspectionResult.cs
C#
gpl-3.0
2,194
/* Copyright (c) 2001-2008, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hsqldb.sample; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.hsqldb.jdbc.jdbcDataSource; /** * Title: Testdb * Description: simple hello world db example of a * standalone persistent db application * * every time it runs it adds four more rows to sample_table * it does a query and prints the results to standard out * * Author: Karl Meissner karl@meissnersd.com */ public class Testdb { Connection conn; //our connnection to the db - presist for life of program // we dont want this garbage collected until we are done public Testdb(String db_file_name_prefix) throws Exception { // note more general exception // connect to the database. This will load the db files and start the // database if it is not alread running. // db_file_name_prefix is used to open or create files that hold the state // of the db. // It can contain directory names relative to the // current working directory jdbcDataSource dataSource = new jdbcDataSource(); dataSource.setDatabase("jdbc:hsqldb:" + db_file_name_prefix); Connection c = dataSource.getConnection("sa", ""); } public void shutdown() throws SQLException { Statement st = conn.createStatement(); // db writes out to files and performs clean shuts down // otherwise there will be an unclean shutdown // when program ends st.execute("SHUTDOWN"); conn.close(); // if there are no other open connection } //use for SQL command SELECT public synchronized void query(String expression) throws SQLException { Statement st = null; ResultSet rs = null; st = conn.createStatement(); // statement objects can be reused with // repeated calls to execute but we // choose to make a new one each time rs = st.executeQuery(expression); // run the query // do something with the result set. dump(rs); st.close(); // NOTE!! if you close a statement the associated ResultSet is // closed too // so you should copy the contents to some other object. // the result set is invalidated also if you recycle an Statement // and try to execute some other query before the result set has been // completely examined. } //use for SQL commands CREATE, DROP, INSERT and UPDATE public synchronized void update(String expression) throws SQLException { Statement st = null; st = conn.createStatement(); // statements int i = st.executeUpdate(expression); // run the query if (i == -1) { System.out.println("db error : " + expression); } st.close(); } // void update() public static void dump(ResultSet rs) throws SQLException { // the order of the rows in a cursor // are implementation dependent unless you use the SQL ORDER statement ResultSetMetaData meta = rs.getMetaData(); int colmax = meta.getColumnCount(); int i; Object o = null; // the result set is a cursor into the data. You can only // point to one row at a time // assume we are pointing to BEFORE the first row // rs.next() points to next row and returns true // or false if there is no next row, which breaks the loop for (; rs.next(); ) { for (i = 0; i < colmax; ++i) { o = rs.getObject(i + 1); // Is SQL the first column is indexed // with 1 not 0 System.out.print(o.toString() + " "); } System.out.println(" "); } } //void dump( ResultSet rs ) public static void main(String[] args) { Testdb db = null; try { db = new Testdb("db_file"); } catch (Exception ex1) { ex1.printStackTrace(); // could not start db return; // bye bye } try { //make an empty table // // by declaring the id column IDENTITY, the db will automatically // generate unique values for new rows- useful for row keys db.update( "CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)"); } catch (SQLException ex2) { //ignore //ex2.printStackTrace(); // second time we run program // should throw execption since table // already there // // this will have no effect on the db } try { // add some rows - will create duplicates if run more then once // the id column is automatically generated db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Toyota', 200)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Honda', 300)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('GM', 400)"); // do a query db.query("SELECT * FROM sample_table WHERE num_col < 250"); // at end of program db.shutdown(); } catch (SQLException ex3) { ex3.printStackTrace(); } } // main() } // class Testdb
ckaestne/LEADT
workspace/hsqldb/src/org/hsqldb/sample/Testdb.java
Java
gpl-3.0
7,388
/* Unix SMB/CIFS implementation. DNS server utils Copyright (C) 2010 Kai Blin <kai@samba.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "libcli/util/ntstatus.h" #include "libcli/util/werror.h" #include "librpc/ndr/libndr.h" #include "librpc/gen_ndr/ndr_dns.h" #include "librpc/gen_ndr/ndr_dnsp.h" #include <ldb.h> #include "dsdb/samdb/samdb.h" #include "dsdb/common/util.h" #include "dns_server/dns_server.h" #undef DBGC_CLASS #define DBGC_CLASS DBGC_DNS uint8_t werr_to_dns_err(WERROR werr) { if (W_ERROR_EQUAL(WERR_OK, werr)) { return DNS_RCODE_OK; } else if (W_ERROR_EQUAL(DNS_ERR(FORMAT_ERROR), werr)) { return DNS_RCODE_FORMERR; } else if (W_ERROR_EQUAL(DNS_ERR(SERVER_FAILURE), werr)) { return DNS_RCODE_SERVFAIL; } else if (W_ERROR_EQUAL(DNS_ERR(NAME_ERROR), werr)) { return DNS_RCODE_NXDOMAIN; } else if (W_ERROR_EQUAL(DNS_ERR(NOT_IMPLEMENTED), werr)) { return DNS_RCODE_NOTIMP; } else if (W_ERROR_EQUAL(DNS_ERR(REFUSED), werr)) { return DNS_RCODE_REFUSED; } else if (W_ERROR_EQUAL(DNS_ERR(YXDOMAIN), werr)) { return DNS_RCODE_YXDOMAIN; } else if (W_ERROR_EQUAL(DNS_ERR(YXRRSET), werr)) { return DNS_RCODE_YXRRSET; } else if (W_ERROR_EQUAL(DNS_ERR(NXRRSET), werr)) { return DNS_RCODE_NXRRSET; } else if (W_ERROR_EQUAL(DNS_ERR(NOTAUTH), werr)) { return DNS_RCODE_NOTAUTH; } else if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) { return DNS_RCODE_NOTZONE; } else if (W_ERROR_EQUAL(DNS_ERR(BADKEY), werr)) { return DNS_RCODE_BADKEY; } DEBUG(5, ("No mapping exists for %s\n", win_errstr(werr))); return DNS_RCODE_SERVFAIL; } bool dns_name_match(const char *zone, const char *name, size_t *host_part_len) { size_t zl = strlen(zone); size_t nl = strlen(name); ssize_t zi, ni; static const size_t fixup = 'a' - 'A'; if (zl > nl) { return false; } for (zi = zl, ni = nl; zi >= 0; zi--, ni--) { char zc = zone[zi]; char nc = name[ni]; /* convert to lower case */ if (zc >= 'A' && zc <= 'Z') { zc += fixup; } if (nc >= 'A' && nc <= 'Z') { nc += fixup; } if (zc != nc) { return false; } } if (ni >= 0) { if (name[ni] != '.') { return false; } ni--; } *host_part_len = ni+1; return true; } /* Names are equal if they match and there's nothing left over */ bool dns_name_equal(const char *name1, const char *name2) { size_t host_part_len; bool ret = dns_name_match(name1, name2, &host_part_len); return ret && (host_part_len == 0); } /* see if two dns records match */ bool dns_records_match(struct dnsp_DnssrvRpcRecord *rec1, struct dnsp_DnssrvRpcRecord *rec2) { bool status; int i; if (rec1->wType != rec2->wType) { return false; } /* see if the data matches */ switch (rec1->wType) { case DNS_TYPE_A: return strcmp(rec1->data.ipv4, rec2->data.ipv4) == 0; case DNS_TYPE_AAAA: return strcmp(rec1->data.ipv6, rec2->data.ipv6) == 0; case DNS_TYPE_CNAME: return dns_name_equal(rec1->data.cname, rec2->data.cname); case DNS_TYPE_TXT: if (rec1->data.txt.count != rec2->data.txt.count) { return false; } status = true; for (i=0; i<rec1->data.txt.count; i++) { status = status && (strcmp(rec1->data.txt.str[i], rec2->data.txt.str[i]) == 0); } return status; case DNS_TYPE_PTR: return strcmp(rec1->data.ptr, rec2->data.ptr) == 0; case DNS_TYPE_NS: return dns_name_equal(rec1->data.ns, rec2->data.ns); case DNS_TYPE_SRV: return rec1->data.srv.wPriority == rec2->data.srv.wPriority && rec1->data.srv.wWeight == rec2->data.srv.wWeight && rec1->data.srv.wPort == rec2->data.srv.wPort && dns_name_equal(rec1->data.srv.nameTarget, rec2->data.srv.nameTarget); case DNS_TYPE_MX: return rec1->data.mx.wPriority == rec2->data.mx.wPriority && dns_name_equal(rec1->data.mx.nameTarget, rec2->data.mx.nameTarget); case DNS_TYPE_HINFO: return strcmp(rec1->data.hinfo.cpu, rec2->data.hinfo.cpu) == 0 && strcmp(rec1->data.hinfo.os, rec2->data.hinfo.os) == 0; case DNS_TYPE_SOA: return dns_name_equal(rec1->data.soa.mname, rec2->data.soa.mname) && dns_name_equal(rec1->data.soa.rname, rec2->data.soa.rname) && rec1->data.soa.serial == rec2->data.soa.serial && rec1->data.soa.refresh == rec2->data.soa.refresh && rec1->data.soa.retry == rec2->data.soa.retry && rec1->data.soa.expire == rec2->data.soa.expire && rec1->data.soa.minimum == rec2->data.soa.minimum; default: break; } return false; } WERROR dns_lookup_records(struct dns_server *dns, TALLOC_CTX *mem_ctx, struct ldb_dn *dn, struct dnsp_DnssrvRpcRecord **records, uint16_t *rec_count) { static const char * const attrs[] = { "dnsRecord", NULL}; struct ldb_message_element *el; uint16_t ri; int ret; struct ldb_message *msg = NULL; struct dnsp_DnssrvRpcRecord *recs; ret = dsdb_search_one(dns->samdb, mem_ctx, &msg, dn, LDB_SCOPE_BASE, attrs, 0, "%s", "(objectClass=dnsNode)"); if (ret != LDB_SUCCESS) { /* TODO: we need to check if there's a glue record we need to * create a referral to */ return DNS_ERR(NAME_ERROR); } el = ldb_msg_find_element(msg, attrs[0]); if (el == NULL) { *records = NULL; *rec_count = 0; return DNS_ERR(NAME_ERROR); } recs = talloc_zero_array(mem_ctx, struct dnsp_DnssrvRpcRecord, el->num_values); if (recs == NULL) { return WERR_NOMEM; } for (ri = 0; ri < el->num_values; ri++) { struct ldb_val *v = &el->values[ri]; enum ndr_err_code ndr_err; ndr_err = ndr_pull_struct_blob(v, recs, &recs[ri], (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n")); return DNS_ERR(SERVER_FAILURE); } } *records = recs; *rec_count = el->num_values; return WERR_OK; } WERROR dns_replace_records(struct dns_server *dns, TALLOC_CTX *mem_ctx, struct ldb_dn *dn, bool needs_add, const struct dnsp_DnssrvRpcRecord *records, uint16_t rec_count) { struct ldb_message_element *el; uint16_t i; int ret; struct ldb_message *msg = NULL; msg = ldb_msg_new(mem_ctx); W_ERROR_HAVE_NO_MEMORY(msg); msg->dn = dn; ret = ldb_msg_add_empty(msg, "dnsRecord", LDB_FLAG_MOD_REPLACE, &el); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } el->values = talloc_zero_array(el, struct ldb_val, rec_count); if (rec_count > 0) { W_ERROR_HAVE_NO_MEMORY(el->values); } for (i = 0; i < rec_count; i++) { static const struct dnsp_DnssrvRpcRecord zero; struct ldb_val *v = &el->values[el->num_values]; enum ndr_err_code ndr_err; if (memcmp(&records[i], &zero, sizeof(zero)) == 0) { continue; } ndr_err = ndr_push_struct_blob(v, el->values, &records[i], (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n")); return DNS_ERR(SERVER_FAILURE); } el->num_values++; } if (el->num_values == 0) { if (needs_add) { return WERR_OK; } /* No entries left, delete the dnsNode object */ ret = ldb_delete(dns->samdb, msg->dn); if (ret != LDB_SUCCESS) { DEBUG(0, ("Deleting record failed; %d\n", ret)); return DNS_ERR(SERVER_FAILURE); } return WERR_OK; } if (needs_add) { ret = ldb_msg_add_string(msg, "objectClass", "dnsNode"); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } ret = ldb_add(dns->samdb, msg); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } return WERR_OK; } ret = ldb_modify(dns->samdb, msg); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } return WERR_OK; } bool dns_authorative_for_zone(struct dns_server *dns, const char *name) { const struct dns_server_zone *z; size_t host_part_len = 0; if (name == NULL) { return false; } if (strcmp(name, "") == 0) { return true; } for (z = dns->zones; z != NULL; z = z->next) { bool match; match = dns_name_match(z->name, name, &host_part_len); if (match) { break; } } if (z == NULL) { return false; } return true; } WERROR dns_name2dn(struct dns_server *dns, TALLOC_CTX *mem_ctx, const char *name, struct ldb_dn **_dn) { struct ldb_dn *base; struct ldb_dn *dn; const struct dns_server_zone *z; size_t host_part_len = 0; if (name == NULL) { return DNS_ERR(FORMAT_ERROR); } /*TODO: Check if 'name' is a valid DNS name */ if (strcmp(name, "") == 0) { base = ldb_get_default_basedn(dns->samdb); dn = ldb_dn_copy(mem_ctx, base); ldb_dn_add_child_fmt(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System"); *_dn = dn; return WERR_OK; } for (z = dns->zones; z != NULL; z = z->next) { bool match; match = dns_name_match(z->name, name, &host_part_len); if (match) { break; } } if (z == NULL) { return DNS_ERR(NAME_ERROR); } if (host_part_len == 0) { dn = ldb_dn_copy(mem_ctx, z->dn); ldb_dn_add_child_fmt(dn, "DC=@"); *_dn = dn; return WERR_OK; } dn = ldb_dn_copy(mem_ctx, z->dn); ldb_dn_add_child_fmt(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name); *_dn = dn; return WERR_OK; } WERROR dns_generate_options(struct dns_server *dns, TALLOC_CTX *mem_ctx, struct dns_res_rec **options) { struct dns_res_rec *o; o = talloc_zero(mem_ctx, struct dns_res_rec); if (o == NULL) { return WERR_NOMEM; } o->name = '\0'; o->rr_type = DNS_QTYPE_OPT; /* This is ugly, but RFC2671 wants the payload size in this field */ o->rr_class = (enum dns_qclass) dns->max_payload; o->ttl = 0; o->length = 0; *options = o; return WERR_OK; }
framon/samba
source4/dns_server/dns_utils.c
C
gpl-3.0
10,153
/* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2008 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file ngram_search_fwdflat.c Flat lexicon search. */ /* System headers. */ #include <string.h> #include <assert.h> /* SphinxBase headers. */ #include <sphinxbase/ckd_alloc.h> #include <sphinxbase/listelem_alloc.h> #include <sphinxbase/err.h> /* Local headers. */ #include "ngram_search.h" #include "ps_lattice_internal.h" /* Turn this on to dump channels for debugging */ #define __CHAN_DUMP__ 0 #if __CHAN_DUMP__ #define chan_v_eval(chan) hmm_dump_vit_eval(&(chan)->hmm, stderr) #else #define chan_v_eval(chan) hmm_vit_eval(&(chan)->hmm) #endif static void ngram_fwdflat_expand_all(ngram_search_t *ngs) { int n_words, i; /* For all "real words" (not fillers or <s>/</s>) in the dictionary, * * 1) Add the ones which are in the LM to the fwdflat wordlist * 2) And to the expansion list (since we are expanding all) */ ngs->n_expand_words = 0; n_words = ps_search_n_words(ngs); bitvec_clear_all(ngs->expand_word_flag, ps_search_n_words(ngs)); for (i = 0; i < n_words; ++i) { if (!ngram_model_set_known_wid(ngs->lmset, dict_basewid(ps_search_dict(ngs),i))) continue; ngs->fwdflat_wordlist[ngs->n_expand_words] = i; ngs->expand_word_list[ngs->n_expand_words] = i; bitvec_set(ngs->expand_word_flag, i); ngs->n_expand_words++; } E_INFO("Utterance vocabulary contains %d words\n", ngs->n_expand_words); ngs->expand_word_list[ngs->n_expand_words] = -1; ngs->fwdflat_wordlist[ngs->n_expand_words] = -1; } static void ngram_fwdflat_allocate_1ph(ngram_search_t *ngs) { dict_t *dict = ps_search_dict(ngs); int n_words = ps_search_n_words(ngs); int i, w; /* Allocate single-phone words, since they won't have * been allocated for us by fwdtree initialization. */ ngs->n_1ph_words = 0; for (w = 0; w < n_words; w++) { if (dict_is_single_phone(dict, w)) ++ngs->n_1ph_words; } ngs->single_phone_wid = ckd_calloc(ngs->n_1ph_words, sizeof(*ngs->single_phone_wid)); ngs->rhmm_1ph = ckd_calloc(ngs->n_1ph_words, sizeof(*ngs->rhmm_1ph)); i = 0; for (w = 0; w < n_words; w++) { if (!dict_is_single_phone(dict, w)) continue; /* DICT2PID location */ ngs->rhmm_1ph[i].ciphone = dict_first_phone(dict, w); ngs->rhmm_1ph[i].ci2phone = bin_mdef_silphone(ps_search_acmod(ngs)->mdef); hmm_init(ngs->hmmctx, &ngs->rhmm_1ph[i].hmm, TRUE, /* ssid */ bin_mdef_pid2ssid(ps_search_acmod(ngs)->mdef, ngs->rhmm_1ph[i].ciphone), /* tmatid */ bin_mdef_pid2tmatid(ps_search_acmod(ngs)->mdef, ngs->rhmm_1ph[i].ciphone)); ngs->rhmm_1ph[i].next = NULL; ngs->word_chan[w] = (chan_t *) &(ngs->rhmm_1ph[i]); ngs->single_phone_wid[i] = w; i++; } } static void ngram_fwdflat_free_1ph(ngram_search_t *ngs) { int i, w; int n_words = ps_search_n_words(ngs); for (i = w = 0; w < n_words; ++w) { if (!dict_is_single_phone(ps_search_dict(ngs), w)) continue; hmm_deinit(&ngs->rhmm_1ph[i].hmm); ++i; } ckd_free(ngs->rhmm_1ph); ngs->rhmm_1ph = NULL; ckd_free(ngs->single_phone_wid); } void ngram_fwdflat_init(ngram_search_t *ngs) { int n_words; n_words = ps_search_n_words(ngs); ngs->fwdflat_wordlist = ckd_calloc(n_words + 1, sizeof(*ngs->fwdflat_wordlist)); ngs->expand_word_flag = bitvec_alloc(n_words); ngs->expand_word_list = ckd_calloc(n_words + 1, sizeof(*ngs->expand_word_list)); ngs->frm_wordlist = ckd_calloc(ngs->n_frame_alloc, sizeof(*ngs->frm_wordlist)); ngs->min_ef_width = cmd_ln_int32_r(ps_search_config(ngs), "-fwdflatefwid"); ngs->max_sf_win = cmd_ln_int32_r(ps_search_config(ngs), "-fwdflatsfwin"); E_INFO("fwdflat: min_ef_width = %d, max_sf_win = %d\n", ngs->min_ef_width, ngs->max_sf_win); /* No tree-search; pre-build the expansion list, including all LM words. */ if (!ngs->fwdtree) { /* Build full expansion list from LM words. */ ngram_fwdflat_expand_all(ngs); /* Allocate single phone words. */ ngram_fwdflat_allocate_1ph(ngs); } } void ngram_fwdflat_deinit(ngram_search_t *ngs) { double n_speech = (double)ngs->n_tot_frame / cmd_ln_int32_r(ps_search_config(ngs), "-frate"); E_INFO("TOTAL fwdflat %.2f CPU %.3f xRT\n", ngs->fwdflat_perf.t_tot_cpu, ngs->fwdflat_perf.t_tot_cpu / n_speech); E_INFO("TOTAL fwdflat %.2f wall %.3f xRT\n", ngs->fwdflat_perf.t_tot_elapsed, ngs->fwdflat_perf.t_tot_elapsed / n_speech); /* Free single-phone words if we allocated them. */ if (!ngs->fwdtree) { ngram_fwdflat_free_1ph(ngs); } ckd_free(ngs->fwdflat_wordlist); bitvec_free(ngs->expand_word_flag); ckd_free(ngs->expand_word_list); ckd_free(ngs->frm_wordlist); } int ngram_fwdflat_reinit(ngram_search_t *ngs) { /* Reallocate things that depend on the number of words. */ int n_words; ckd_free(ngs->fwdflat_wordlist); ckd_free(ngs->expand_word_list); bitvec_free(ngs->expand_word_flag); n_words = ps_search_n_words(ngs); ngs->fwdflat_wordlist = ckd_calloc(n_words + 1, sizeof(*ngs->fwdflat_wordlist)); ngs->expand_word_flag = bitvec_alloc(n_words); ngs->expand_word_list = ckd_calloc(n_words + 1, sizeof(*ngs->expand_word_list)); /* No tree-search; take care of the expansion list and single phone words. */ if (!ngs->fwdtree) { /* Free single-phone words. */ ngram_fwdflat_free_1ph(ngs); /* Reallocate word_chan. */ ckd_free(ngs->word_chan); ngs->word_chan = ckd_calloc(dict_size(ps_search_dict(ngs)), sizeof(*ngs->word_chan)); /* Rebuild full expansion list from LM words. */ ngram_fwdflat_expand_all(ngs); /* Allocate single phone words. */ ngram_fwdflat_allocate_1ph(ngs); } /* Otherwise there is nothing to do since the wordlist is * generated anew every utterance. */ return 0; } /** * Find all active words in backpointer table and sort by frame. */ static void build_fwdflat_wordlist(ngram_search_t *ngs) { int32 i, f, sf, ef, wid, nwd; bptbl_t *bp; ps_latnode_t *node, *prevnode, *nextnode; /* No tree-search, use statically allocated wordlist. */ if (!ngs->fwdtree) return; memset(ngs->frm_wordlist, 0, ngs->n_frame_alloc * sizeof(*ngs->frm_wordlist)); /* Scan the backpointer table for all active words and record * their exit frames. */ for (i = 0, bp = ngs->bp_table; i < ngs->bpidx; i++, bp++) { sf = (bp->bp < 0) ? 0 : ngs->bp_table[bp->bp].frame + 1; ef = bp->frame; wid = bp->wid; /* Anything that can be transitioned to in the LM can go in * the word list. */ if (!ngram_model_set_known_wid(ngs->lmset, dict_basewid(ps_search_dict(ngs), wid))) continue; /* Look for it in the wordlist. */ for (node = ngs->frm_wordlist[sf]; node && (node->wid != wid); node = node->next); /* Update last end frame. */ if (node) node->lef = ef; else { /* New node; link to head of list */ node = listelem_malloc(ngs->latnode_alloc); node->wid = wid; node->fef = node->lef = ef; node->next = ngs->frm_wordlist[sf]; ngs->frm_wordlist[sf] = node; } } /* Eliminate "unlikely" words, for which there are too few end points */ for (f = 0; f < ngs->n_frame; f++) { prevnode = NULL; for (node = ngs->frm_wordlist[f]; node; node = nextnode) { nextnode = node->next; /* Word has too few endpoints */ if ((node->lef - node->fef < ngs->min_ef_width) || /* Word is </s> and doesn't actually end in last frame */ ((node->wid == ps_search_finish_wid(ngs)) && (node->lef < ngs->n_frame - 1))) { if (!prevnode) ngs->frm_wordlist[f] = nextnode; else prevnode->next = nextnode; listelem_free(ngs->latnode_alloc, node); } else prevnode = node; } } /* Form overall wordlist for 2nd pass */ nwd = 0; bitvec_clear_all(ngs->word_active, ps_search_n_words(ngs)); for (f = 0; f < ngs->n_frame; f++) { for (node = ngs->frm_wordlist[f]; node; node = node->next) { if (!bitvec_is_set(ngs->word_active, node->wid)) { bitvec_set(ngs->word_active, node->wid); ngs->fwdflat_wordlist[nwd++] = node->wid; } } } ngs->fwdflat_wordlist[nwd] = -1; E_INFO("Utterance vocabulary contains %d words\n", nwd); } /** * Build HMM network for one utterance of fwdflat search. */ static void build_fwdflat_chan(ngram_search_t *ngs) { int32 i, wid, p; root_chan_t *rhmm; chan_t *hmm, *prevhmm; dict_t *dict; dict2pid_t *d2p; dict = ps_search_dict(ngs); d2p = ps_search_dict2pid(ngs); /* Build word HMMs for each word in the lattice. */ for (i = 0; ngs->fwdflat_wordlist[i] >= 0; i++) { wid = ngs->fwdflat_wordlist[i]; /* Single-phone words are permanently allocated */ if (dict_is_single_phone(dict, wid)) continue; assert(ngs->word_chan[wid] == NULL); /* Multiplex root HMM for first phone (one root per word, flat * lexicon). diphone is irrelevant here, for the time being, * at least. */ rhmm = listelem_malloc(ngs->root_chan_alloc); rhmm->ci2phone = dict_second_phone(dict, wid); rhmm->ciphone = dict_first_phone(dict, wid); rhmm->next = NULL; hmm_init(ngs->hmmctx, &rhmm->hmm, TRUE, bin_mdef_pid2ssid(ps_search_acmod(ngs)->mdef, rhmm->ciphone), bin_mdef_pid2tmatid(ps_search_acmod(ngs)->mdef, rhmm->ciphone)); /* HMMs for word-internal phones */ prevhmm = NULL; for (p = 1; p < dict_pronlen(dict, wid) - 1; p++) { hmm = listelem_malloc(ngs->chan_alloc); hmm->ciphone = dict_pron(dict, wid, p); hmm->info.rc_id = (p == dict_pronlen(dict, wid) - 1) ? 0 : -1; hmm->next = NULL; hmm_init(ngs->hmmctx, &hmm->hmm, FALSE, dict2pid_internal(d2p,wid,p), bin_mdef_pid2tmatid(ps_search_acmod(ngs)->mdef, hmm->ciphone)); if (prevhmm) prevhmm->next = hmm; else rhmm->next = hmm; prevhmm = hmm; } /* Right-context phones */ ngram_search_alloc_all_rc(ngs, wid); /* Link in just allocated right-context phones */ if (prevhmm) prevhmm->next = ngs->word_chan[wid]; else rhmm->next = ngs->word_chan[wid]; ngs->word_chan[wid] = (chan_t *) rhmm; } } void ngram_fwdflat_start(ngram_search_t *ngs) { root_chan_t *rhmm; int i; ptmr_reset(&ngs->fwdflat_perf); ptmr_start(&ngs->fwdflat_perf); build_fwdflat_wordlist(ngs); build_fwdflat_chan(ngs); ngs->bpidx = 0; ngs->bss_head = 0; for (i = 0; i < ps_search_n_words(ngs); i++) ngs->word_lat_idx[i] = NO_BP; /* Reset the permanently allocated single-phone words, since they * may have junk left over in them from previous searches. */ for (i = 0; i < ngs->n_1ph_words; i++) { int32 w = ngs->single_phone_wid[i]; rhmm = (root_chan_t *) ngs->word_chan[w]; hmm_clear(&rhmm->hmm); } /* Start search with <s>; word_chan[<s>] is permanently allocated */ rhmm = (root_chan_t *) ngs->word_chan[ps_search_start_wid(ngs)]; hmm_enter(&rhmm->hmm, 0, NO_BP, 0); ngs->active_word_list[0][0] = ps_search_start_wid(ngs); ngs->n_active_word[0] = 1; ngs->best_score = 0; ngs->renormalized = FALSE; for (i = 0; i < ps_search_n_words(ngs); i++) ngs->last_ltrans[i].sf = -1; if (!ngs->fwdtree) ngs->n_frame = 0; ngs->st.n_fwdflat_chan = 0; ngs->st.n_fwdflat_words = 0; ngs->st.n_fwdflat_word_transition = 0; ngs->st.n_senone_active_utt = 0; } static void compute_fwdflat_sen_active(ngram_search_t *ngs, int frame_idx) { int32 i, nw, w; int32 *awl; root_chan_t *rhmm; chan_t *hmm; acmod_clear_active(ps_search_acmod(ngs)); nw = ngs->n_active_word[frame_idx & 0x1]; awl = ngs->active_word_list[frame_idx & 0x1]; for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *)ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == frame_idx) { acmod_activate_hmm(ps_search_acmod(ngs), &rhmm->hmm); } for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) == frame_idx) { acmod_activate_hmm(ps_search_acmod(ngs), &hmm->hmm); } } } } static void fwdflat_eval_chan(ngram_search_t *ngs, int frame_idx) { int32 i, w, nw, bestscore; int32 *awl; root_chan_t *rhmm; chan_t *hmm; nw = ngs->n_active_word[frame_idx & 0x1]; awl = ngs->active_word_list[frame_idx & 0x1]; bestscore = WORST_SCORE; ngs->st.n_fwdflat_words += nw; /* Scan all active words. */ for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == frame_idx) { int32 score = chan_v_eval(rhmm); if ((score BETTER_THAN bestscore) && (w != ps_search_finish_wid(ngs))) bestscore = score; ngs->st.n_fwdflat_chan++; } for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) == frame_idx) { int32 score = chan_v_eval(hmm); if (score BETTER_THAN bestscore) bestscore = score; ngs->st.n_fwdflat_chan++; } } } ngs->best_score = bestscore; } static void fwdflat_prune_chan(ngram_search_t *ngs, int frame_idx) { int32 i, nw, cf, nf, w, pip, newscore, thresh, wordthresh; int32 *awl; root_chan_t *rhmm; chan_t *hmm, *nexthmm; cf = frame_idx; nf = cf + 1; nw = ngs->n_active_word[cf & 0x1]; awl = ngs->active_word_list[cf & 0x1]; bitvec_clear_all(ngs->word_active, ps_search_n_words(ngs)); thresh = ngs->best_score + ngs->fwdflatbeam; wordthresh = ngs->best_score + ngs->fwdflatwbeam; pip = ngs->pip; E_DEBUG(3,("frame %d thresh %d wordthresh %d\n", frame_idx, thresh, wordthresh)); /* Scan all active words. */ for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; /* Propagate active root channels */ if (hmm_frame(&rhmm->hmm) == cf && hmm_bestscore(&rhmm->hmm) BETTER_THAN thresh) { hmm_frame(&rhmm->hmm) = nf; bitvec_set(ngs->word_active, w); /* Transitions out of root channel */ newscore = hmm_out_score(&rhmm->hmm); if (rhmm->next) { assert(!dict_is_single_phone(ps_search_dict(ngs), w)); newscore += pip; if (newscore BETTER_THAN thresh) { hmm = rhmm->next; /* Enter all right context phones */ if (hmm->info.rc_id >= 0) { for (; hmm; hmm = hmm->next) { if ((hmm_frame(&hmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&hmm->hmm))) { hmm_enter(&hmm->hmm, newscore, hmm_out_history(&rhmm->hmm), nf); } } } /* Just a normal word internal phone */ else { if ((hmm_frame(&hmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&hmm->hmm))) { hmm_enter(&hmm->hmm, newscore, hmm_out_history(&rhmm->hmm), nf); } } } } else { assert(dict_is_single_phone(ps_search_dict(ngs), w)); /* Word exit for single-phone words (where did their * whmms come from?) (either from * ngram_search_fwdtree, or from * ngram_fwdflat_allocate_1ph(), that's where) */ if (newscore BETTER_THAN wordthresh) { ngram_search_save_bp(ngs, cf, w, newscore, hmm_out_history(&rhmm->hmm), 0); } } } /* Transitions out of non-root channels. */ for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) >= cf) { /* Propagate forward HMMs inside the beam. */ if (hmm_bestscore(&hmm->hmm) BETTER_THAN thresh) { hmm_frame(&hmm->hmm) = nf; bitvec_set(ngs->word_active, w); newscore = hmm_out_score(&hmm->hmm); /* Word-internal phones */ if (hmm->info.rc_id < 0) { newscore += pip; if (newscore BETTER_THAN thresh) { nexthmm = hmm->next; /* Enter all right-context phones. */ if (nexthmm->info.rc_id >= 0) { for (; nexthmm; nexthmm = nexthmm->next) { if ((hmm_frame(&nexthmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&nexthmm->hmm))) { hmm_enter(&nexthmm->hmm, newscore, hmm_out_history(&hmm->hmm), nf); } } } /* Enter single word-internal phone. */ else { if ((hmm_frame(&nexthmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&nexthmm->hmm))) { hmm_enter(&nexthmm->hmm, newscore, hmm_out_history(&hmm->hmm), nf); } } } } /* Right-context phones - apply word beam and exit. */ else { if (newscore BETTER_THAN wordthresh) { ngram_search_save_bp(ngs, cf, w, newscore, hmm_out_history(&hmm->hmm), hmm->info.rc_id); } } } /* Zero out inactive HMMs. */ else if (hmm_frame(&hmm->hmm) != nf) { hmm_clear_scores(&hmm->hmm); } } } } } static void get_expand_wordlist(ngram_search_t *ngs, int32 frm, int32 win) { int32 f, sf, ef; ps_latnode_t *node; if (!ngs->fwdtree) { ngs->st.n_fwdflat_word_transition += ngs->n_expand_words; return; } sf = frm - win; if (sf < 0) sf = 0; ef = frm + win; if (ef > ngs->n_frame) ef = ngs->n_frame; bitvec_clear_all(ngs->expand_word_flag, ps_search_n_words(ngs)); ngs->n_expand_words = 0; for (f = sf; f < ef; f++) { for (node = ngs->frm_wordlist[f]; node; node = node->next) { if (!bitvec_is_set(ngs->expand_word_flag, node->wid)) { ngs->expand_word_list[ngs->n_expand_words++] = node->wid; bitvec_set(ngs->expand_word_flag, node->wid); } } } ngs->expand_word_list[ngs->n_expand_words] = -1; ngs->st.n_fwdflat_word_transition += ngs->n_expand_words; } static void fwdflat_word_transition(ngram_search_t *ngs, int frame_idx) { int32 cf, nf, b, thresh, pip, i, nw, w, newscore; int32 best_silrc_score = 0, best_silrc_bp = 0; /* FIXME: good defaults? */ bptbl_t *bp; int32 *rcss; root_chan_t *rhmm; int32 *awl; float32 lwf; dict_t *dict = ps_search_dict(ngs); dict2pid_t *d2p = ps_search_dict2pid(ngs); cf = frame_idx; nf = cf + 1; thresh = ngs->best_score + ngs->fwdflatbeam; pip = ngs->pip; best_silrc_score = WORST_SCORE; lwf = ngs->fwdflat_fwdtree_lw_ratio; /* Search for all words starting within a window of this frame. * These are the successors for words exiting now. */ get_expand_wordlist(ngs, cf, ngs->max_sf_win); /* Scan words exited in current frame */ for (b = ngs->bp_table_idx[cf]; b < ngs->bpidx; b++) { xwdssid_t *rssid; int32 silscore; bp = ngs->bp_table + b; ngs->word_lat_idx[bp->wid] = NO_BP; if (bp->wid == ps_search_finish_wid(ngs)) continue; /* DICT2PID location */ /* Get the mapping from right context phone ID to index in the * right context table and the bscore_stack. */ rcss = ngs->bscore_stack + bp->s_idx; if (bp->last2_phone == -1) rssid = NULL; else rssid = dict2pid_rssid(d2p, bp->last_phone, bp->last2_phone); /* Transition to all successor words. */ for (i = 0; ngs->expand_word_list[i] >= 0; i++) { int32 n_used; w = ngs->expand_word_list[i]; /* Get the exit score we recorded in save_bwd_ptr(), or * something approximating it. */ if (rssid) newscore = rcss[rssid->cimap[dict_first_phone(dict, w)]]; else newscore = bp->score; if (newscore == WORST_SCORE) continue; /* FIXME: Floating point... */ newscore += lwf * (ngram_tg_score(ngs->lmset, dict_basewid(dict, w), bp->real_wid, bp->prev_real_wid, &n_used) >> SENSCR_SHIFT); newscore += pip; /* Enter the next word */ if (newscore BETTER_THAN thresh) { rhmm = (root_chan_t *) ngs->word_chan[w]; if ((hmm_frame(&rhmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&rhmm->hmm))) { hmm_enter(&rhmm->hmm, newscore, b, nf); /* DICT2PID: This is where mpx ssids get introduced. */ /* Look up the ssid to use when entering this mpx triphone. */ hmm_mpx_ssid(&rhmm->hmm, 0) = dict2pid_ldiph_lc(d2p, rhmm->ciphone, rhmm->ci2phone, dict_last_phone(dict, bp->wid)); assert(IS_S3SSID(hmm_mpx_ssid(&rhmm->hmm, 0))); E_DEBUG(6,("ssid %d(%d,%d) = %d\n", rhmm->ciphone, dict_last_phone(dict, bp->wid), rhmm->ci2phone, hmm_mpx_ssid(&rhmm->hmm, 0))); bitvec_set(ngs->word_active, w); } } } /* Get the best exit into silence. */ if (rssid) silscore = rcss[rssid->cimap[ps_search_acmod(ngs)->mdef->sil]]; else silscore = bp->score; if (silscore BETTER_THAN best_silrc_score) { best_silrc_score = silscore; best_silrc_bp = b; } } /* Transition to <sil> */ newscore = best_silrc_score + ngs->silpen + pip; if ((newscore BETTER_THAN thresh) && (newscore BETTER_THAN WORST_SCORE)) { w = ps_search_silence_wid(ngs); rhmm = (root_chan_t *) ngs->word_chan[w]; if ((hmm_frame(&rhmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&rhmm->hmm))) { hmm_enter(&rhmm->hmm, newscore, best_silrc_bp, nf); bitvec_set(ngs->word_active, w); } } /* Transition to noise words */ newscore = best_silrc_score + ngs->fillpen + pip; if ((newscore BETTER_THAN thresh) && (newscore BETTER_THAN WORST_SCORE)) { for (w = dict_filler_start(dict); w <= dict_filler_end(dict); w++) { if (w == ps_search_silence_wid(ngs)) continue; rhmm = (root_chan_t *) ngs->word_chan[w]; /* Noise words that aren't a single phone will have NULL here. */ if (rhmm == NULL) continue; if ((hmm_frame(&rhmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&rhmm->hmm))) { hmm_enter(&rhmm->hmm, newscore, best_silrc_bp, nf); bitvec_set(ngs->word_active, w); } } } /* Reset initial channels of words that have become inactive even after word trans. */ nw = ngs->n_active_word[cf & 0x1]; awl = ngs->active_word_list[cf & 0x1]; for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == cf) { hmm_clear_scores(&rhmm->hmm); } } } static void fwdflat_renormalize_scores(ngram_search_t *ngs, int frame_idx, int32 norm) { root_chan_t *rhmm; chan_t *hmm; int32 i, nw, cf, w, *awl; cf = frame_idx; /* Renormalize individual word channels */ nw = ngs->n_active_word[cf & 0x1]; awl = ngs->active_word_list[cf & 0x1]; for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == cf) { hmm_normalize(&rhmm->hmm, norm); } for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) == cf) { hmm_normalize(&hmm->hmm, norm); } } } ngs->renormalized = TRUE; } int ngram_fwdflat_search(ngram_search_t *ngs, int frame_idx) { int16 const *senscr; int32 nf, i, j; int32 *nawl; /* Activate our HMMs for the current frame if need be. */ if (!ps_search_acmod(ngs)->compallsen) compute_fwdflat_sen_active(ngs, frame_idx); /* Compute GMM scores for the current frame. */ senscr = acmod_score(ps_search_acmod(ngs), &frame_idx); ngs->st.n_senone_active_utt += ps_search_acmod(ngs)->n_senone_active; /* Mark backpointer table for current frame. */ ngram_search_mark_bptable(ngs, frame_idx); /* If the best score is equal to or worse than WORST_SCORE, * recognition has failed, don't bother to keep trying. */ if (ngs->best_score == WORST_SCORE || ngs->best_score WORSE_THAN WORST_SCORE) return 0; /* Renormalize if necessary */ if (ngs->best_score + (2 * ngs->beam) WORSE_THAN WORST_SCORE) { E_INFO("Renormalizing Scores at frame %d, best score %d\n", frame_idx, ngs->best_score); fwdflat_renormalize_scores(ngs, frame_idx, ngs->best_score); } ngs->best_score = WORST_SCORE; hmm_context_set_senscore(ngs->hmmctx, senscr); /* Evaluate HMMs */ fwdflat_eval_chan(ngs, frame_idx); /* Prune HMMs and do phone transitions. */ fwdflat_prune_chan(ngs, frame_idx); /* Do word transitions. */ fwdflat_word_transition(ngs, frame_idx); /* Create next active word list, skip fillers */ nf = frame_idx + 1; nawl = ngs->active_word_list[nf & 0x1]; for (i = 0, j = 0; ngs->fwdflat_wordlist[i] >= 0; i++) { int32 wid = ngs->fwdflat_wordlist[i]; if (bitvec_is_set(ngs->word_active, wid) && wid < ps_search_start_wid(ngs)) { *(nawl++) = wid; j++; } } /* Add fillers */ for (i = ps_search_start_wid(ngs); i < ps_search_n_words(ngs); i++) { if (bitvec_is_set(ngs->word_active, i)) { *(nawl++) = i; j++; } } if (!ngs->fwdtree) ++ngs->n_frame; ngs->n_active_word[nf & 0x1] = j; /* Return the number of frames processed. */ return 1; } /** * Destroy wordlist from the current utterance. */ static void destroy_fwdflat_wordlist(ngram_search_t *ngs) { ps_latnode_t *node, *tnode; int32 f; if (!ngs->fwdtree) return; for (f = 0; f < ngs->n_frame; f++) { for (node = ngs->frm_wordlist[f]; node; node = tnode) { tnode = node->next; listelem_free(ngs->latnode_alloc, node); } } } /** * Free HMM network for one utterance of fwdflat search. */ static void destroy_fwdflat_chan(ngram_search_t *ngs) { int32 i, wid; for (i = 0; ngs->fwdflat_wordlist[i] >= 0; i++) { root_chan_t *rhmm; chan_t *thmm; wid = ngs->fwdflat_wordlist[i]; if (dict_is_single_phone(ps_search_dict(ngs),wid)) continue; assert(ngs->word_chan[wid] != NULL); /* The first HMM in ngs->word_chan[wid] was allocated with * ngs->root_chan_alloc, but this will attempt to free it * using ngs->chan_alloc, which will not work. Therefore we * free it manually and move the list forward before handing * it off. */ rhmm = (root_chan_t *)ngs->word_chan[wid]; thmm = rhmm->next; listelem_free(ngs->root_chan_alloc, rhmm); ngs->word_chan[wid] = thmm; ngram_search_free_all_rc(ngs, wid); } } void ngram_fwdflat_finish(ngram_search_t *ngs) { int32 cf; destroy_fwdflat_chan(ngs); destroy_fwdflat_wordlist(ngs); bitvec_clear_all(ngs->word_active, ps_search_n_words(ngs)); /* This is the number of frames processed. */ cf = ps_search_acmod(ngs)->output_frame; /* Add a mark in the backpointer table for one past the final frame. */ ngram_search_mark_bptable(ngs, cf); ptmr_stop(&ngs->fwdflat_perf); /* Print out some statistics. */ if (cf > 0) { double n_speech = (double)(cf + 1) / cmd_ln_int32_r(ps_search_config(ngs), "-frate"); E_INFO("%8d words recognized (%d/fr)\n", ngs->bpidx, (ngs->bpidx + (cf >> 1)) / (cf + 1)); E_INFO("%8d senones evaluated (%d/fr)\n", ngs->st.n_senone_active_utt, (ngs->st.n_senone_active_utt + (cf >> 1)) / (cf + 1)); E_INFO("%8d channels searched (%d/fr)\n", ngs->st.n_fwdflat_chan, ngs->st.n_fwdflat_chan / (cf + 1)); E_INFO("%8d words searched (%d/fr)\n", ngs->st.n_fwdflat_words, ngs->st.n_fwdflat_words / (cf + 1)); E_INFO("%8d word transitions (%d/fr)\n", ngs->st.n_fwdflat_word_transition, ngs->st.n_fwdflat_word_transition / (cf + 1)); E_INFO("fwdflat %.2f CPU %.3f xRT\n", ngs->fwdflat_perf.t_cpu, ngs->fwdflat_perf.t_cpu / n_speech); E_INFO("fwdflat %.2f wall %.3f xRT\n", ngs->fwdflat_perf.t_elapsed, ngs->fwdflat_perf.t_elapsed / n_speech); } }
michael-chi/jumbo
v1/robot-node/stt/pocketsphinx/src/libpocketsphinx/ngram_search_fwdflat.c
C
gpl-3.0
33,675
/************************************************************************************************** Survey changes: copyright (c) 2010, Fryslan Webservices TM (http://survey.codeplex.com) NSurvey - The web survey and form engine Copyright (c) 2004, 2005 Thomas Zumbrunn. (http://www.nsurvey.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ************************************************************************************************/ using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Votations.NSurvey.DataAccess; using Votations.NSurvey.Data; using Votations.NSurvey.UserProvider; using Votations.NSurvey.WebAdmin.UserControls; namespace Votations.NSurvey.WebAdmin { /// <summary> /// Display the user editor /// </summary> public partial class UsersManager : PageBase { protected System.Web.UI.WebControls.Label MessageLabel; new protected HeaderControl Header; Votations.NSurvey.SQLServerDAL.User UsersData; public int selectedTabIndex = 0; private void Page_Load(object sender, System.EventArgs e) { SetupSecurity(); LocalizePage(); // Get selected tab if (!string.IsNullOrEmpty(Request.Params["tabindex"])) { string[] idx = Request.Params["tabindex"].Split(','); selectedTabIndex = int.Parse(idx[idx.Length - 1]); } if (selectedTabIndex > 0) btnBack.Visible = false; UsersData = new Votations.NSurvey.SQLServerDAL.User(); SwitchModeDependingOnprevTab(); if (!Page.IsPostBack) { BindFields(); } else BindGrid(); // postback could be import users } private void SwitchModeDependingOnprevTab() { if (ViewState["UMPREVTAB"] != null && Convert.ToInt32(ViewState["UMPREVTAB"])>0 && selectedTabIndex==0) SwitchToListMode(); ViewState["UMPREVTAB"] = selectedTabIndex; } private void SetupSecurity() { CheckRight(NSurveyRights.AccessUserManager, true); IsSingleUserMode(true); } private void LocalizePage() { UserListTitleLabel.Text = ((PageBase)Page).GetPageResource("UserListTitle"); UserlistFilterOptionLiteral.Text = ((PageBase)Page).GetPageResource("UserlistFilterOptionLiteral"); } public bool IsAdmin(int userId) { return UsersData.IsAdministrator(userId); } public void OnUserEdit(Object sender, CommandEventArgs e) { UsersOptionsControl1.UserId = int.Parse(e.CommandArgument.ToString()); UsersOptionsControl1.BindFields(); phUsersList.Visible = false; btnBack.Visible = true; } public void EditBackButton(object sender, CommandEventArgs e) { SwitchToListMode(); } private void SwitchToListMode() { UsersOptionsControl1.UserId = -1; UsersOptionsControl1.BindFields(); phUsersList.Visible = true; BindGrid(); btnBack.Visible = false; } /// <summary> /// Get the current DB data and fill /// the fields with them /// </summary> private void BindFields() { // Header.SurveyId = SurveyId; ((Wap)Master).HeaderControl.SurveyId = getSurveyId(); BindGrid(); btnApplyfilter.Text = GetPageResource("UsersTabApplyFilter"); } private void BindGrid() { int ?isAdmin = chkAdmin.Checked ? 1: (int?)null; gvUsers.DataSource = UsersData.GetAllUsersListByFilter(txtUserName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, isAdmin); gvUsers.DataBind(); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); GridViewRow pagerRow = (GridViewRow)gvUsers.BottomPagerRow; if (pagerRow != null && pagerRow.Visible == false) pagerRow.Visible = true; } public void gvUsers_PageIndexChanged(Object sender, EventArgs e) { BindGrid(); } public void gvUsers_PageIndexChanging(Object sender, GridViewPageEventArgs e) { gvUsers.PageIndex = e.NewPageIndex; } public void OnApplyFilter(Object sender, EventArgs e) { BindGrid(); } /// <summary> /// Triggered by the type option user control /// in case anything was changed we will need to /// rebind to display the updates to the user /// </summary> private void UsersManager_OptionChanged(object sender, EventArgs e) { BindFields(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private IUserProvider _userProvider = UserFactory.Create(); } }
samdubey/surveyproject_main_public
SurveyWAP/NSurveyAdmin/UsersManager.aspx.cs
C#
gpl-3.0
5,993
#include "FvSTLAssisstant.h"
Kiddinglife/gecoengine
thirdparty/FutureVisionCore/InnerCoreLibs/FvLogicCommon/FvSTLAssisstant.cpp
C++
gpl-3.0
34
define(["ng", "lodash"], function(ng, _){ "use strict"; var DashboardVM = function DashboardVM($scope, $rootScope){ var _self = this; this.toggleHStretch = function(isOn){ _self.setOptions(options); }; this.updateOptions = function(options){ ng.extend(_self, options); }; this.resetOptions = function(){ _self.updateOptions(_self.attr); }; this.setAttr = function(attr){ _self.attr=attr; _self.updateOptions(attr); }; this.remove = function(target){ // _.remove(_self.items, {name: target}); delete _self.items[target]; console.debug("remove _self.items", _self.items); }; this.items = $scope.dashboardItems; // this.items = [ // { // name: "survival1", // title: "survival1", // content: "moving around" // }, // { // name: "hcl1", // title: "hcl1", // content: "moving around" // }, // { // name: "ttest1", // title: "ttest1", // content: "moving around" // }, // { // name: "limma1", // title: "limma1", // content: "moving around" // }, // { // name: "deseq1", // title: "deseq1", // content: "moving around" // }, // { // name: "nmf", // title: "nmf", // content: "moving around" // }, // { // name: "kmeans1", // title: "kmeans1", // content: "moving around" // } // ]; $scope.$on("ui:dashboard:addItem", function($event, data){ var exists = _.find(_self.items, {name: data.name}); if(exists){ $rootScope.$broadcast("ui:analysisLog.append", "info", "Cannot add analysis '" + data.name + "' to the dashboard. It is already there."); }else{ _self.items.$add(data); } }); $scope.$on("ui:dashboard:removeItem", function($event, data){ console.debug("on ui:dashboard:removeItem", $event, data); _self.remove(data.name); }); }; DashboardVM.$inject=["$scope", "$rootScope"]; DashboardVM.$name="DashboardVMController"; return DashboardVM; });
apartensky/mev
web/src/main/javascript/edu/dfci/cccb/mev/web/ui/app/widgets/dashboard/controllers/DashboardVM.js
JavaScript
gpl-3.0
1,974
<?php namespace SMW\Tests\SPARQLStore; use SMW\SPARQLStore\SPARQLStore; use SMW\DIWikiPage; use SMW\SemanticData; use SMWExporter as Exporter; use SMWTurtleSerializer as TurtleSerializer; use Title; /** * @covers \SMW\SPARQLStore\SPARQLStore * * @ingroup Test * * @group SMW * @group SMWExtension * * @license GNU GPL v2+ * @since 1.9.2 * * @author mwjames */ class SPARQLStoreTest extends \PHPUnit_Framework_TestCase { public function testCanConstruct() { $this->assertInstanceOf( '\SMW\SPARQLStore\SPARQLStore', new SPARQLStore() ); // Legacy $this->assertInstanceOf( '\SMW\SPARQLStore\SPARQLStore', new \SMWSPARQLStore() ); } public function testGetSemanticDataOnMockBaseStore() { $subject = DIWikiPage::newFromTitle( Title::newFromText( __METHOD__ ) ); $semanticData = $this->getMockBuilder( '\SMW\SemanticData' ) ->disableOriginalConstructor() ->getMock(); $baseStore = $this->getMockBuilder( '\SMWStore' ) ->disableOriginalConstructor() ->getMockForAbstractClass(); $baseStore->expects( $this->once() ) ->method( 'getSemanticData' ) ->with( $this->equalTo( $subject ) ) ->will( $this->returnValue( $semanticData ) ); $instance = new SPARQLStore( $baseStore ); $this->assertInstanceOf( '\SMW\SemanticData', $instance->getSemanticData( $subject ) ); } public function testDeleteSubjectOnMockBaseStore() { $title = Title::newFromText( 'DeleteSubjectOnMockBaseStore' ); $expResource = Exporter::getDataItemExpElement( DIWikiPage::newFromTitle( $title ) ); $resourceUri = TurtleSerializer::getTurtleNameForExpElement( $expResource ); $extraNamespaces = array( $expResource->getNamespaceId() => $expResource->getNamespace() ); $baseStore = $this->getMockBuilder( '\SMWStore' ) ->disableOriginalConstructor() ->getMockForAbstractClass(); $baseStore->expects( $this->once() ) ->method( 'deleteSubject' ) ->with( $this->equalTo( $title ) ) ->will( $this->returnValue( true ) ); $sparqlDatabase = $this->getMockBuilder( '\SMWSparqlDatabase' ) ->disableOriginalConstructor() ->getMock(); $sparqlDatabase->expects( $this->once() ) ->method( 'deleteContentByValue' ) ->will( $this->returnValue( true ) ); $sparqlDatabase->expects( $this->once() ) ->method( 'delete' ) ->with( $this->equalTo( "{$resourceUri} ?p ?o" ), $this->equalTo( "{$resourceUri} ?p ?o" ), $this->equalTo( $extraNamespaces ) ) ->will( $this->returnValue( true ) ); $instance = new SPARQLStore( $baseStore ); $instance->setSparqlDatabase( $sparqlDatabase ); $instance->deleteSubject( $title ); } public function testDoSparqlDataUpdateOnMockBaseStore() { $semanticData = new SemanticData( new DIWikiPage( 'Foo', NS_MAIN, '' ) ); $listReturnValue = $this->getMockBuilder( '\SMW\SPARQLStore\QueryEngine\FederateResultList' ) ->disableOriginalConstructor() ->getMock(); $baseStore = $this->getMockBuilder( '\SMW\Store' ) ->disableOriginalConstructor() ->getMockForAbstractClass(); $sparqlDatabase = $this->getMockBuilder( '\SMWSparqlDatabase' ) ->disableOriginalConstructor() ->getMock(); $sparqlDatabase->expects( $this->atLeastOnce() ) ->method( 'select' ) ->will( $this->returnValue( $listReturnValue ) ); $sparqlDatabase->expects( $this->once() ) ->method( 'insertData' ); $instance = new SPARQLStore( $baseStore ); $instance->setSparqlDatabase( $sparqlDatabase ); $instance->doSparqlDataUpdate( $semanticData ); } }
tectronics/bioladder
wiki/extensions/SemanticMediaWiki/tests/phpunit/includes/SPARQLStore/SparqlStoreTest.php
PHP
gpl-3.0
3,521
# Reddit Enhancement Suite [![Travis Build Status](https://travis-ci.org/honestbleeps/Reddit-Enhancement-Suite.svg?branch=master)](https://travis-ci.org/honestbleeps/Reddit-Enhancement-Suite) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/honestbleeps/Reddit-Enhancement-Suite?branch=master&svg=true)](https://ci.appveyor.com/project/honestbleeps/Reddit-Enhancement-Suite) [![Coverage Status](https://coveralls.io/repos/github/honestbleeps/Reddit-Enhancement-Suite/badge.svg?branch=master)](https://coveralls.io/github/honestbleeps/Reddit-Enhancement-Suite?branch=master) [![Code Climate](https://codeclimate.com/github/honestbleeps/Reddit-Enhancement-Suite/badges/gpa.svg)](https://codeclimate.com/github/honestbleeps/Reddit-Enhancement-Suite) [![devDependency Status](https://david-dm.org/honestbleeps/Reddit-Enhancement-Suite/dev-status.svg)](https://david-dm.org/honestbleeps/Reddit-Enhancement-Suite#info=devDependencies) [![Chat on IRC](https://img.shields.io/badge/irc-%23enhancement-blue.svg)](http://webchat.snoonet.org/#enhancement) Reddit Enhancement Suite (RES) is a suite of modules that enhances your Reddit browsing experience. For general documentation, visit the [Reddit Enhancement Suite Wiki](https://www.reddit.com/r/Enhancement/wiki/index). ## Introduction Hi there! Thanks for checking out RES on GitHub. A few important notes: 1. RES is licensed under GPLv3, which means you're technically free to do whatever you wish in terms of redistribution as long as you maintain GPLv3 licensing. However, I ask out of courtesy that should you choose to release your own, separate distribution of RES, you please name it something else entirely. Unfortunately, I have run into problems in the past with people redistributing under the same name, and causing me tech support headaches. 2. I ask that you please do not distribute your own binaries of RES (e.g. with bugfixes, etc). The version numbers in RES are important references for tech support so that we can replicate bugs that users report using the same version they are, and when you distribute your own - you run the risk of polluting/confusing that. In addition, if a user overwrites his/her extension with your distributed copy, it may not properly retain their RES settings/data depending on the developer ID used, etc. I can't stop you from doing any of this. I'm just asking out of courtesy because I already spend a great deal of time providing tech support and chasing down bugs, and it's much harder when people think I'm the support guy for a separate branch of code. Thanks! Steve Sobel steve@honestbleeps.com ## Contributor guidelines Thinking about contributing to RES? Awesome! We just ask that you follow a few simple guidelines: 1. RES has grown quite large, so we do have to pick and choose what features we should add. Code bloat is always a concern, and RES is already rather hefty. If you're unsure if your feature would appeal to a wide audience, please post about it on [/r/Enhancement](https://www.reddit.com/r/Enhancement/) or [contact @honestbleeps](https://www.reddit.com/message/compose/?to=honestbleeps) directly to ask. 2. There are a few features we have made a conscious choice not to add to RES, so make sure whatever you'd like to contribute [isn't on that list](https://www.reddit.com/r/Enhancement/wiki/rejectedfeaturerequests). 3. It would be greatly appreciated if you could stick to a few style guidelines: - please use tabs for indentation - please use spaces in your `if` statements, e.g. `if (foo === bar)`, not `if(foo===bar)` - please use single quotes `'` and not double quotes `"` for strings - please comment your code! - please consider using `npm run lint` ([see below](#details-and-advanced-usage)) to verify your code style 4. If you're adding new modules or hosts, [see below](#adding-new-files). ## Project structure ##### Top level files and folders - `assets/`: RES logo source - `chrome/`: Chrome-specific RES files - `dist/`: build output - `edge/`: Microsoft Edge-specific RES files - `examples/`: example code for new hosts/modules - `firefox/`: Firefox-specific RES files - `images/`: Images for RES logo and CSS icons - `lib/`: all RES code - `lib/core/`: core RES code - `lib/css/`: RES css - `lib/environment/`: RES environment code - `lib/images/`: RES images - `lib/modules/`: RES modules - `lib/templates/`: RES templates - `lib/utils/`: RES utilities - `lib/vendor/`: RES vendor libraries - `node/`: Node files - `safari/`: Safari-specific RES files - `utils/`: Misc RES utilities - `CHANGELOG.md`: self-explanatory - `README.md`: YOU ARE HERE, unless you're browsing on GitHub - `gulpfile.babel.js`: post-build script for zipping folders. - `package.json`: package info, dependencies - `webpack.config.babel.js`: build script - `**/__tests__`: unit tests ##### Chrome files - `background.entry.js`: the "background page" for RES, necessary for Chrome extensions - `environment.js`: specific environment settings for Chrome - `manifest.json`: the project manifest - `options.html`: options page for chrome extensions ##### Microsoft Edge files - `background-edge.html`: the "background page" for RES, necessary for Microsoft Edge extensions - `edge.entry.js`: shim to allow chrome extension code usage - `environment.js`: Edge-specific overrides of the Chrome environment - `manifest.json`: the project manifest ##### Firefox files - `background.entry.js`: the "background page" for RES, necessary for Firefox extensions - `environment.js`: specific environment settings for Firefox - `package.json`: the project manifest for the Firefox add-on ##### Safari files - `Info.plist`: the project manifest - `background-safari.html`: the "background html page" for RES, necessary for Safari extensions - `background.entry.js`: the "background page" for RES, necessary for Safari extensions - `environment.js`: specific environment settings for Safari ## Building development versions of the extension First time installation: 1. Install [git](https://git-scm.com/). 1. Install [node.js](https://nodejs.org) (version >= 6). 1. Install [Python 2](https://www.python.org/downloads/) (*not* version 3). 1. Navigate to your RES folder. 1. Run `npm install`. Once done, you can build the extension by running `npm start`. This will also start a watch task that will rebuild RES when you make changes (see [Advanced Usage](#details-and-advanced-usage) for more details). To load the extension into your browser, see [the sections below](#building-in-chrome). #### Details and advanced usage **`npm start [-- <browsers>]`** will clean `dist/`, then build RES (dev mode), and start a watch task that will rebuild RES when you make changes. Only changed files will be rebuilt. **`npm run once [-- <browsers>]`** will clean `dist/`, then build RES (dev mode) a single time. **`npm run build [-- <browsers>]`** will clean `dist/`, then build RES (release mode). Each build output will be compressed to a .zip file in `dist/zip/`. `<browsers>` is a comma-separated list of browsers to target, e.g. `chrome,firefox,safari,node`. `all` will build all targets. By default, `chrome` will be targeted. **`npm run lint`** will verify the code style (and point out any errors) of all `.js` files in `lib/` (except `lib/vendor/`) using [ESLint](http://eslint.org/), as well as all `.scss` files with [sass-lint](https://github.com/sasstools/sass-lint). **`npm run lint-fix`** will autofix any [fixable](http://eslint.org/docs/user-guide/command-line-interface#fix) lint issues. **`npm test`** will run unit tests (in `__tests__` directories). ##### Building in Chrome 1. Go to `Menu->Tools->Extensions` and tick the `Developer Mode` checkbox 2. Choose `Load unpacked extension` and point it to the `dist/chrome` folder. Make sure you only have one RES version running at a time. 3. Any time you make changes to the script, you must go back to the `Menu->Tools->Extensions` page and `Reload` the extension. ##### Building in Microsoft Edge 1. Go to `about:flags` and tick the `Enable extension developer features` checkbox. 2. Choose `Load extension` on the extensions menu and select your extensions folder. 3. Any time you make changes to the extension, you must go back to the `Menu->Extensions` page, go to the extensions settings and `Reload` the extension. ##### Building in Firefox 1. Install [jpm](https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/jpm) using `npm`: `npm install -g jpm` 2. Navigate to `dist/firefox` and run the command `jpm run`, which should launch a new Firefox browser using a temporary profile with only RES installed. ##### Building in Safari (assumes Mac) 1. Open the `Preferences` by going to `Safari->Preferences` or pressing `⌘,`, then go to `Advanced` and check the checkbox for `Show Develop menu in menu bar`. 2. Navigate to `Develop->Show Extension Builder` to open the extensions builder. Add a new extension by pressing the `+` in the bottom left and choosing `Add Extension`. 3. Navigate to the `dist/RES.safariextension` folder for RES and select it. 4. If you are using Safari 9+, you should be able to install the extension without enrolling in the [Apple Developer Program](https://developer.apple.com/programs/); however, the extension will be auto-uninstalled when you quit Safari. If you use an older version of Safari or find the auto-uninstall annoying, you need to purchase a proper certificate by signing up for the [Apple Developer Program](https://developer.apple.com/programs/) (currently $99/yr). #### Accessing nightly builds In addition to building your own version of RES, you can download older (or current) builds of RES for testing purposes. (Almost) every commit to master is quickly archived away at http://allthefoxes.me; if you would like access to this database, please contact [/u/allthefoxes on reddit](https://www.reddit.com/user/allthefoxes) or email [fox@allthefoxes.me](mailto:fox@allthefoxes.me). All that is asked is that you have at least one previous contribution to RES. ## Adding new files ##### Modules See [`examples/module.js`](https://github.com/honestbleeps/Reddit-Enhancement-Suite/blob/master/examples/module.js) for an example. Create a new `.js` file in `lib/modules`. It will automatically be loaded when the build script is restarted. ##### Inline image viewer hosts Please be sure that they support [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) so the sites do not need to be added as additional permissions, which has caused [headaches in the past](https://www.reddit.com/r/Enhancement/comments/1jskcm/announcement_chrome_users_did_your_res_turn_off/). See [`examples/host.js`](https://github.com/honestbleeps/Reddit-Enhancement-Suite/blob/master/examples/host.js) for an example. Create a new `.js` file in `lib/modules/hosts`. It will automatically be loaded when the build script is restarted. ##### Stylesheets Create a new Sass partial under `lib/css/modules/` (with a leading underscore, e.g. `_myPartial.scss`). Import the file in `lib/css/res.scss` (i.e. `@import 'modules/myPartial';`—do not include the underscore or file extension). Body classes will be automatically added for boolean and enum options with the property `bodyClass: true`, in the form `.res-moduleId-optionKey` for boolean options (only when they're enabled), and `.res-moduleId-optionKey-optionValue` for enums. This is the preferred way to create optional CSS; do not use `addCSS()` unless absolutely necessary (i.e. variable color, size, etc.).
klpl/Reddit-Enhancement-Suite
README.md
Markdown
gpl-3.0
11,677
/* * Copyright (c) 2002-2008 LWJGL Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lwjgl.opengl; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Canvas; import org.lwjgl.LWJGLException; /** * * @author elias_naur <elias_naur@users.sourceforge.net> * @version $Revision: 3632 $ * $Id: MacOSXCanvasImplementation.java 3632 2011-09-03 18:52:45Z spasi $ */ final class MacOSXCanvasImplementation implements AWTCanvasImplementation { public PeerInfo createPeerInfo(Canvas component, PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException { try { return new MacOSXAWTGLCanvasPeerInfo(component, pixel_format, attribs, true); } catch (LWJGLException e) { return new MacOSXAWTGLCanvasPeerInfo(component, pixel_format, attribs, false); } } /** * Find a proper GraphicsConfiguration from the given GraphicsDevice and PixelFormat. * * @return The GraphicsConfiguration corresponding to a visual that matches the pixel format. */ public GraphicsConfiguration findConfiguration(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException { /* * It seems like the best way is to simply return null */ return null; } }
kevinwang/minecarft
lwjgl-source-2.8.2/src/java/org/lwjgl/opengl/MacOSXCanvasImplementation.java
Java
gpl-3.0
2,780
<?php /* * Copyright (C) 2013 Mailgun * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ namespace Mailgun\HttpClient\Plugin; use Http\Client\Common\Plugin; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\UriInterface; /** * Replaces a URI with a new one. Good for debugging. * * @author Tobias Nyholm <tobias.nyholm@gmail.com> */ final class ReplaceUriPlugin implements Plugin { /** * @var UriInterface */ private $uri; /** * @param UriInterface $uri */ public function __construct(UriInterface $uri) { $this->uri = $uri; } /** * {@inheritdoc} */ public function handleRequest(RequestInterface $request, callable $next, callable $first) { $request = $request->withUri($this->uri); return $next($request); } }
growlingfish/giftplatform
vendor/mailgun/mailgun-php/src/Mailgun/HttpClient/Plugin/ReplaceUriPlugin.php
PHP
gpl-3.0
906
// Copyright 2019-2020 CERN and copyright holders of ALICE O2. // See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. // All rights not expressly granted are reserved. // // This software is distributed under the terms of the GNU General Public // License v3 (GPL Version 3), copied verbatim in the file "COPYING". // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. /// \file TopologyDictionary.h /// \brief Definition of the ClusterTopology class. /// /// \author Luca Barioglio, University and INFN of Torino /// /// Short TopologyDictionary descritpion /// /// The entries of the dictionaries are the cluster topologies, with all the information /// which is common to the clusters with the same topology: /// - number of rows /// - number of columns /// - pixel bitmask /// - position of the Centre Of Gravity (COG) wrt the bottom left corner pixel of the bounding box /// - error associated to the position of the hit point /// Rare topologies, i.e. with a frequency below a threshold defined a priori, have not their own entries /// in the dictionaries, but are grouped together with topologies with similar dimensions. /// For the groups of rare topollogies a dummy bitmask is used. #ifndef ALICEO2_ITSMFT_TOPOLOGYDICTIONARY_H #define ALICEO2_ITSMFT_TOPOLOGYDICTIONARY_H #include "DataFormatsITSMFT/ClusterPattern.h" #include "Framework/Logger.h" #include <fstream> #include <string> #include <unordered_map> #include <vector> #include "MathUtils/Cartesian.h" #include "DataFormatsITSMFT/CompCluster.h" #include "TH1F.h" namespace o2 { namespace itsmft { class BuildTopologyDictionary; class LookUp; class TopologyFastSimulation; /// Structure containing the most relevant pieces of information of a topology struct GroupStruct { unsigned long mHash; ///< Hashcode float mErrX; ///< Error associated to the hit point in the x direction. float mErrZ; ///< Error associated to the hit point in the z direction. float mErr2X; ///< Squared Error associated to the hit point in the x direction. float mErr2Z; ///< Squared Error associated to the hit point in the z direction. float mXCOG; ///< x position of te COG wrt the boottom left corner of the bounding box float mZCOG; ///< z position of te COG wrt the boottom left corner of the bounding box int mNpixels; ///< Number of fired pixels ClusterPattern mPattern; ///< Bitmask of pixels. For groups the biggest bounding box for the group is taken, with all ///the bits set to 1. double mFrequency; ///< Frequency of the topology bool mIsGroup; ///< false: common topology; true: group of rare topologies ClassDefNV(GroupStruct, 3); }; class TopologyDictionary { public: /// Default constructor TopologyDictionary(); /// Constructor TopologyDictionary(const std::string& fileName); /// constexpr for the definition of the groups of rare topologies. /// The attritbution of the group ID is stringly dependent on the following parameters: it must be a power of 2. static constexpr int RowClassSpan = 4; ///< Row span of the classes of rare topologies static constexpr int ColClassSpan = 4; ///< Column span of the classes of rare topologies static constexpr int MaxNumberOfRowClasses = 1 + (ClusterPattern::MaxRowSpan - 1) / RowClassSpan; ///< Maximum number of row classes for the groups of rare topologies static constexpr int MaxNumberOfColClasses = 1 + (ClusterPattern::MaxColSpan - 1) / ColClassSpan; ///< Maximum number of col classes for the groups of rare topologies static constexpr int NumberOfRareGroups = MaxNumberOfRowClasses * MaxNumberOfColClasses; ///< Number of entries corresponding to groups of rare topologies (those whos matrix exceed the max number of bytes are empty). /// Prints the dictionary friend std::ostream& operator<<(std::ostream& os, const TopologyDictionary& dictionary); /// Prints the dictionary in a binary file void writeBinaryFile(const std::string& outputFile); /// Reads the dictionary from a binary file int readBinaryFile(const std::string& fileName); int readFromFile(const std::string& fileName); /// Returns the x position of the COG for the n_th element inline float getXCOG(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mXCOG; } /// Returns the error on the x position of the COG for the n_th element inline float getErrX(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErrX; } /// Returns the z position of the COG for the n_th element inline float getZCOG(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mZCOG; } /// Returns the error on the z position of the COG for the n_th element inline float getErrZ(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErrZ; } /// Returns the error^2 on the x position of the COG for the n_th element inline float getErr2X(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErr2X; } /// Returns the error^2 on the z position of the COG for the n_th element inline float getErr2Z(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErr2Z; } /// Returns the hash of the n_th element inline unsigned long getHash(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mHash; } /// Returns the number of fired pixels of the n_th element inline int getNpixels(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mNpixels; } /// Returns the frequency of the n_th element; inline double getFrequency(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mFrequency; } /// Returns true if the element corresponds to a group of rare topologies inline bool isGroup(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mIsGroup; } /// Returns the pattern of the topology inline const ClusterPattern& getPattern(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mPattern; } /// Fills a hostogram with the distribution of the IDs static void getTopologyDistribution(const TopologyDictionary& dict, TH1F*& histo, const char* histName); /// Returns the number of elements in the dicionary; int getSize() const { return (int)mVectorOfIDs.size(); } ///Returns the local position of a compact cluster math_utils::Point3D<float> getClusterCoordinates(const CompCluster& cl) const; ///Returns the local position of a compact cluster static math_utils::Point3D<float> getClusterCoordinates(const CompCluster& cl, const ClusterPattern& patt, bool isGroup = true); static TopologyDictionary* loadFrom(const std::string& fileName = "", const std::string& objName = "ccdb_object"); friend BuildTopologyDictionary; friend LookUp; friend TopologyFastSimulation; private: std::unordered_map<unsigned long, int> mCommonMap; ///< Map of pair <hash, position in mVectorOfIDs> std::unordered_map<int, int> mGroupMap; ///< Map of pair <groudID, position in mVectorOfIDs> int mSmallTopologiesLUT[8 * 255 + 1]; ///< Look-Up Table for the topologies with 1-byte linearised matrix std::vector<GroupStruct> mVectorOfIDs; ///< Vector of topologies and groups ClassDefNV(TopologyDictionary, 4); }; // namespace itsmft } // namespace itsmft } // namespace o2 #endif
noferini/AliceO2
DataFormats/Detectors/ITSMFT/common/include/DataFormatsITSMFT/TopologyDictionary.h
C
gpl-3.0
8,011
# -*- coding: utf-8 -*- # Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com> # Licensed under the MIT license. import sys import datetime from core.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT from core.transmissionrpc.utils import Field, format_timedelta from six import integer_types, string_types, text_type, iteritems def get_status_old(code): """Get the torrent status using old status codes""" mapping = { (1 << 0): 'check pending', (1 << 1): 'checking', (1 << 2): 'downloading', (1 << 3): 'seeding', (1 << 4): 'stopped', } return mapping[code] def get_status_new(code): """Get the torrent status using new status codes""" mapping = { 0: 'stopped', 1: 'check pending', 2: 'checking', 3: 'download pending', 4: 'downloading', 5: 'seed pending', 6: 'seeding', } return mapping[code] class Torrent(object): """ Torrent is a class holding the data received from Transmission regarding a bittorrent transfer. All fetched torrent fields are accessible through this class using attributes. This class has a few convenience properties using the torrent data. """ def __init__(self, client, fields): if 'id' not in fields: raise ValueError('Torrent requires an id') self._fields = {} self._update_fields(fields) self._incoming_pending = False self._outgoing_pending = False self._client = client def _get_name_string(self, codec=None): """Get the name""" if codec is None: codec = sys.getdefaultencoding() name = None # try to find name if 'name' in self._fields: name = self._fields['name'].value # if name is unicode, try to decode if isinstance(name, text_type): try: name = name.encode(codec) except UnicodeError: name = None return name def __repr__(self): tid = self._fields['id'].value name = self._get_name_string() if isinstance(name, str): return '<Torrent {0:d} \"{1}\">'.format(tid, name) else: return '<Torrent {0:d}>'.format(tid) def __str__(self): name = self._get_name_string() if isinstance(name, str): return 'Torrent \"{0}\"'.format(name) else: return 'Torrent' def __copy__(self): return Torrent(self._client, self._fields) def __getattr__(self, name): try: return self._fields[name].value except KeyError: raise AttributeError('No attribute {0}'.format(name)) def _rpc_version(self): """Get the Transmission RPC API version.""" if self._client: return self._client.rpc_version return 2 def _dirty_fields(self): """Enumerate changed fields""" outgoing_keys = ['bandwidthPriority', 'downloadLimit', 'downloadLimited', 'peer_limit', 'queuePosition', 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'uploadLimit', 'uploadLimited'] fields = [] for key in outgoing_keys: if key in self._fields and self._fields[key].dirty: fields.append(key) return fields def _push(self): """Push changed fields to the server""" dirty = self._dirty_fields() args = {} for key in dirty: args[key] = self._fields[key].value self._fields[key] = self._fields[key]._replace(dirty=False) if len(args) > 0: self._client.change_torrent(self.id, **args) def _update_fields(self, other): """ Update the torrent data from a Transmission JSON-RPC arguments dictionary """ if isinstance(other, dict): for key, value in iteritems(other): self._fields[key.replace('-', '_')] = Field(value, False) elif isinstance(other, Torrent): for key in list(other._fields.keys()): self._fields[key] = Field(other._fields[key].value, False) else: raise ValueError('Cannot update with supplied data') self._incoming_pending = False def _status(self): """Get the torrent status""" code = self._fields['status'].value if self._rpc_version() >= 14: return get_status_new(code) else: return get_status_old(code) def files(self): """ Get list of files for this torrent. This function returns a dictionary with file information for each file. The file information is has following fields: :: { <file id>: { 'name': <file name>, 'size': <file size in bytes>, 'completed': <bytes completed>, 'priority': <priority ('high'|'normal'|'low')>, 'selected': <selected for download> } ... } """ result = {} if 'files' in self._fields: files = self._fields['files'].value indices = range(len(files)) priorities = self._fields['priorities'].value wanted = self._fields['wanted'].value for item in zip(indices, files, priorities, wanted): selected = True if item[3] else False priority = PRIORITY[item[2]] result[item[0]] = { 'selected': selected, 'priority': priority, 'size': item[1]['length'], 'name': item[1]['name'], 'completed': item[1]['bytesCompleted']} return result @property def status(self): """ Returns the torrent status. Is either one of 'check pending', 'checking', 'downloading', 'seeding' or 'stopped'. The first two is related to verification. """ return self._status() @property def progress(self): """Get the download progress in percent.""" try: size = self._fields['sizeWhenDone'].value left = self._fields['leftUntilDone'].value return 100.0 * (size - left) / float(size) except ZeroDivisionError: return 0.0 @property def ratio(self): """Get the upload/download ratio.""" return float(self._fields['uploadRatio'].value) @property def eta(self): """Get the "eta" as datetime.timedelta.""" eta = self._fields['eta'].value if eta >= 0: return datetime.timedelta(seconds=eta) else: raise ValueError('eta not valid') @property def date_active(self): """Get the attribute "activityDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['activityDate'].value) @property def date_added(self): """Get the attribute "addedDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['addedDate'].value) @property def date_started(self): """Get the attribute "startDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['startDate'].value) @property def date_done(self): """Get the attribute "doneDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['doneDate'].value) def format_eta(self): """ Returns the attribute *eta* formatted as a string. * If eta is -1 the result is 'not available' * If eta is -2 the result is 'unknown' * Otherwise eta is formatted as <days> <hours>:<minutes>:<seconds>. """ eta = self._fields['eta'].value if eta == -1: return 'not available' elif eta == -2: return 'unknown' else: return format_timedelta(self.eta) def _get_download_limit(self): """ Get the download limit. Can be a number or None. """ if self._fields['downloadLimited'].value: return self._fields['downloadLimit'].value else: return None def _set_download_limit(self, limit): """ Get the download limit. Can be a number, 'session' or None. """ if isinstance(limit, integer_types): self._fields['downloadLimited'] = Field(True, True) self._fields['downloadLimit'] = Field(limit, True) self._push() elif limit is None: self._fields['downloadLimited'] = Field(False, True) self._push() else: raise ValueError("Not a valid limit") download_limit = property(_get_download_limit, _set_download_limit, None, "Download limit in Kbps or None. This is a mutator.") def _get_peer_limit(self): """ Get the peer limit. """ return self._fields['peer_limit'].value def _set_peer_limit(self, limit): """ Set the peer limit. """ if isinstance(limit, integer_types): self._fields['peer_limit'] = Field(limit, True) self._push() else: raise ValueError("Not a valid limit") peer_limit = property(_get_peer_limit, _set_peer_limit, None, "Peer limit. This is a mutator.") def _get_priority(self): """ Get the priority as string. Can be one of 'low', 'normal', 'high'. """ return PRIORITY[self._fields['bandwidthPriority'].value] def _set_priority(self, priority): """ Set the priority as string. Can be one of 'low', 'normal', 'high'. """ if isinstance(priority, string_types): self._fields['bandwidthPriority'] = Field(PRIORITY[priority], True) self._push() priority = property(_get_priority, _set_priority, None , "Bandwidth priority as string. Can be one of 'low', 'normal', 'high'. This is a mutator.") def _get_seed_idle_limit(self): """ Get the seed idle limit in minutes. """ return self._fields['seedIdleLimit'].value def _set_seed_idle_limit(self, limit): """ Set the seed idle limit in minutes. """ if isinstance(limit, integer_types): self._fields['seedIdleLimit'] = Field(limit, True) self._push() else: raise ValueError("Not a valid limit") seed_idle_limit = property(_get_seed_idle_limit, _set_seed_idle_limit, None , "Torrent seed idle limit in minutes. Also see seed_idle_mode. This is a mutator.") def _get_seed_idle_mode(self): """ Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ return IDLE_LIMIT[self._fields['seedIdleMode'].value] def _set_seed_idle_mode(self, mode): """ Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ if isinstance(mode, str): self._fields['seedIdleMode'] = Field(IDLE_LIMIT[mode], True) self._push() else: raise ValueError("Not a valid limit") seed_idle_mode = property(_get_seed_idle_mode, _set_seed_idle_mode, None, """ Seed idle mode as string. Can be one of 'global', 'single' or 'unlimited'. * global, use session seed idle limit. * single, use torrent seed idle limit. See seed_idle_limit. * unlimited, no seed idle limit. This is a mutator. """ ) def _get_seed_ratio_limit(self): """ Get the seed ratio limit as float. """ return float(self._fields['seedRatioLimit'].value) def _set_seed_ratio_limit(self, limit): """ Set the seed ratio limit as float. """ if isinstance(limit, (integer_types, float)) and limit >= 0.0: self._fields['seedRatioLimit'] = Field(float(limit), True) self._push() else: raise ValueError("Not a valid limit") seed_ratio_limit = property(_get_seed_ratio_limit, _set_seed_ratio_limit, None , "Torrent seed ratio limit as float. Also see seed_ratio_mode. This is a mutator.") def _get_seed_ratio_mode(self): """ Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ return RATIO_LIMIT[self._fields['seedRatioMode'].value] def _set_seed_ratio_mode(self, mode): """ Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ if isinstance(mode, str): self._fields['seedRatioMode'] = Field(RATIO_LIMIT[mode], True) self._push() else: raise ValueError("Not a valid limit") seed_ratio_mode = property(_get_seed_ratio_mode, _set_seed_ratio_mode, None, """ Seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. * global, use session seed ratio limit. * single, use torrent seed ratio limit. See seed_ratio_limit. * unlimited, no seed ratio limit. This is a mutator. """ ) def _get_upload_limit(self): """ Get the upload limit. Can be a number or None. """ if self._fields['uploadLimited'].value: return self._fields['uploadLimit'].value else: return None def _set_upload_limit(self, limit): """ Set the upload limit. Can be a number, 'session' or None. """ if isinstance(limit, integer_types): self._fields['uploadLimited'] = Field(True, True) self._fields['uploadLimit'] = Field(limit, True) self._push() elif limit is None: self._fields['uploadLimited'] = Field(False, True) self._push() else: raise ValueError("Not a valid limit") upload_limit = property(_get_upload_limit, _set_upload_limit, None, "Upload limit in Kbps or None. This is a mutator.") def _get_queue_position(self): """Get the queue position for this torrent.""" if self._rpc_version() >= 14: return self._fields['queuePosition'].value else: return 0 def _set_queue_position(self, position): """Set the queue position for this torrent.""" if self._rpc_version() >= 14: if isinstance(position, integer_types): self._fields['queuePosition'] = Field(position, True) self._push() else: raise ValueError("Not a valid position") else: pass queue_position = property(_get_queue_position, _set_queue_position, None, "Queue position") def update(self, timeout=None): """Update the torrent information.""" self._push() torrent = self._client.get_torrent(self.id, timeout=timeout) self._update_fields(torrent) def start(self, bypass_queue=False, timeout=None): """ Start the torrent. """ self._incoming_pending = True self._client.start_torrent(self.id, bypass_queue=bypass_queue, timeout=timeout) def stop(self, timeout=None): """Stop the torrent.""" self._incoming_pending = True self._client.stop_torrent(self.id, timeout=timeout) def move_data(self, location, timeout=None): """Move torrent data to location.""" self._incoming_pending = True self._client.move_torrent_data(self.id, location, timeout=timeout) def locate_data(self, location, timeout=None): """Locate torrent data at location.""" self._incoming_pending = True self._client.locate_torrent_data(self.id, location, timeout=timeout)
bbsan2k/nzbToMedia
core/transmissionrpc/torrent.py
Python
gpl-3.0
16,349
/* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project * ----------------------------------------------------------- * LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o * ----------------------------------------------------------- */ package com.secupwn.aimsicd.ui.drawer; import android.support.annotation.DrawableRes; public interface NavDrawerItem { int getId(); String getLabel(); void setLabel(String label); void setIconId(@DrawableRes int icon); int getType(); boolean isEnabled(); boolean updateActionBarTitle(); }
CellularPrivacy/Android-IMSI-Catcher-Detector
AIMSICD/src/main/java/com/secupwn/aimsicd/ui/drawer/NavDrawerItem.java
Java
gpl-3.0
575
## ## This file is part of the libopencm3 project. ## ## Copyright (C) 2009 Uwe Hermann <uwe@hermann-uwe.de> ## Copyright (C) 2013 Alexandru Gagniuc <mr.nuke.me@gmail.com> ## ## This library is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with this library. If not, see <http://www.gnu.org/licenses/>. ## LIBNAME = libopencm3_stm32f4 SRCLIBDIR ?= ../.. FP_FLAGS ?= -mfloat-abi=hard -mfpu=fpv4-sp-d16 CC = $(PREFIX)gcc AR = $(PREFIX)ar TGT_CFLAGS = -Os \ -Wall -Wextra -Wimplicit-function-declaration \ -Wredundant-decls -Wmissing-prototypes -Wstrict-prototypes \ -Wundef -Wshadow \ -I../../../include -fno-common \ -mcpu=cortex-m4 -mthumb $(FP_FLAGS) \ -Wstrict-prototypes \ -ffunction-sections -fdata-sections -MD -DSTM32F4 TGT_CFLAGS += $(DEBUG_FLAGS) TGT_CFLAGS += $(STANDARD_FLAGS) # ARFLAGS = rcsv ARFLAGS = rcs OBJS += adc_common_v1.o adc_common_v1_multi.o adc_common_f47.o OBJS += can.o OBJS += crc_common_all.o OBJS += crypto_common_f24.o crypto.o OBJS += dac_common_all.o OBJS += desig_common_all.o desig_common_v1.o OBJS += dma_common_f24.o OBJS += dma2d_common_f47.o OBJS += dsi_common_f47.o OBJS += exti_common_all.o OBJS += flash.o flash_common_all.o flash_common_f.o flash_common_f24.o OBJS += flash_common_idcache.o OBJS += fmc_common_f47.o OBJS += gpio_common_all.o gpio_common_f0234.o OBJS += hash_common_f24.o OBJS += i2c_common_v1.o OBJS += iwdg_common_all.o OBJS += lptimer_common_all.o OBJS += ltdc_common_f47.o OBJS += pwr_common_v1.o pwr.o OBJS += rcc_common_all.o rcc.o OBJS += rng_common_v1.o OBJS += rtc_common_l1f024.o rtc.o OBJS += spi_common_all.o spi_common_v1.o spi_common_v1_frf.o OBJS += timer_common_all.o timer_common_f0234.o timer_common_f24.o OBJS += usart_common_all.o usart_common_f124.o OBJS += usb.o usb_standard.o usb_control.o usb_msc.o OBJS += usb_hid.o OBJS += usb_dwc_common.o usb_f107.o usb_f207.o OBJS += mac.o phy.o mac_stm32fxx7.o phy_ksz80x1.o VPATH += ../../usb:../:../../cm3:../common VPATH += ../../ethernet include ../../Makefile.include
devanlai/libopencm3
lib/stm32/f4/Makefile
Makefile
gpl-3.0
2,577
#!/usr/bin/perl # This file is part of Koha. # # Copyright Paul Poulain 2002 # Parts Copyright Liblime 2007 # Copyright (C) 2013 Mark Tompsett # # Koha is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # Koha is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Koha; if not, see <http://www.gnu.org/licenses>. use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output; use C4::Auth; use C4::Koha; use C4::NewsChannels; # GetNewsToDisplay use C4::Suggestions qw/CountSuggestion/; use C4::Tags qw/get_count_by_tag_status/; use Koha::Patron::Modifications; use Koha::Patron::Discharge; use Koha::Reviews; use Koha::ArticleRequests; my $query = new CGI; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { template_name => "intranet-main.tt", query => $query, type => "intranet", authnotrequired => 0, flagsrequired => { catalogue => 1, }, } ); my $homebranch; if (C4::Context->userenv) { $homebranch = C4::Context->userenv->{'branch'}; } my $all_koha_news = &GetNewsToDisplay("koha",$homebranch); my $koha_news_count = scalar @$all_koha_news; $template->param( koha_news => $all_koha_news, koha_news_count => $koha_news_count ); my $branch = ( C4::Context->preference("IndependentBranchesPatronModifications") || C4::Context->preference("IndependentBranches") ) && !$flags->{'superlibrarian'} ? C4::Context->userenv()->{'branch'} : undef; my $pendingcomments = Koha::Reviews->search({ approved => 0 })->count; my $pendingtags = get_count_by_tag_status(0); my $pendingsuggestions = CountSuggestion("ASKED"); my $pending_borrower_modifications = Koha::Patron::Modifications->pending_count( $branch ); my $pending_discharge_requests = Koha::Patron::Discharge::count({ pending => 1 }); my $pending_article_requests = Koha::ArticleRequests->count( { status => Koha::ArticleRequest::Status::Pending, $branch ? ( branchcode => $branch ) : (), } ); $template->param( pendingcomments => $pendingcomments, pendingtags => $pendingtags, pendingsuggestions => $pendingsuggestions, pending_borrower_modifications => $pending_borrower_modifications, pending_discharge_requests => $pending_discharge_requests, pending_article_requests => $pending_article_requests, ); # # warn user if they are using mysql/admin login # unless ($loggedinuser) { $template->param(adminWarning => 1); } output_html_with_http_headers $query, $cookie, $template->output;
whitewabbit/project-test
mainpage.pl
Perl
gpl-3.0
3,036
<?php /** * PostSendFailed * * PHP version 5 * * @category Class * @package SendinBlue\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * SendinBlue API * * SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | * * OpenAPI spec version: 3.0.0 * Contact: contact@sendinblue.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.4.12 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace SendinBlue\Client\Model; use \ArrayAccess; use \SendinBlue\Client\ObjectSerializer; /** * PostSendFailed Class Doc Comment * * @category Class * @package SendinBlue\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class PostSendFailed implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'postSendFailed'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'code' => 'int', 'message' => 'string', 'unexistingEmails' => 'string[]', 'withoutListEmails' => 'string[]', 'blackListedEmails' => 'string[]' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'code' => 'int64', 'message' => null, 'unexistingEmails' => 'email', 'withoutListEmails' => 'email', 'blackListedEmails' => 'email' ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'code' => 'code', 'message' => 'message', 'unexistingEmails' => 'unexistingEmails', 'withoutListEmails' => 'withoutListEmails', 'blackListedEmails' => 'blackListedEmails' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'code' => 'setCode', 'message' => 'setMessage', 'unexistingEmails' => 'setUnexistingEmails', 'withoutListEmails' => 'setWithoutListEmails', 'blackListedEmails' => 'setBlackListedEmails' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'code' => 'getCode', 'message' => 'getMessage', 'unexistingEmails' => 'getUnexistingEmails', 'withoutListEmails' => 'getWithoutListEmails', 'blackListedEmails' => 'getBlackListedEmails' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['code'] = isset($data['code']) ? $data['code'] : null; $this->container['message'] = isset($data['message']) ? $data['message'] : null; $this->container['unexistingEmails'] = isset($data['unexistingEmails']) ? $data['unexistingEmails'] : null; $this->container['withoutListEmails'] = isset($data['withoutListEmails']) ? $data['withoutListEmails'] : null; $this->container['blackListedEmails'] = isset($data['blackListedEmails']) ? $data['blackListedEmails'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; if ($this->container['code'] === null) { $invalidProperties[] = "'code' can't be null"; } if ($this->container['message'] === null) { $invalidProperties[] = "'message' can't be null"; } return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets code * * @return int */ public function getCode() { return $this->container['code']; } /** * Sets code * * @param int $code Response code * * @return $this */ public function setCode($code) { $this->container['code'] = $code; return $this; } /** * Gets message * * @return string */ public function getMessage() { return $this->container['message']; } /** * Sets message * * @param string $message Response message * * @return $this */ public function setMessage($message) { $this->container['message'] = $message; return $this; } /** * Gets unexistingEmails * * @return string[] */ public function getUnexistingEmails() { return $this->container['unexistingEmails']; } /** * Sets unexistingEmails * * @param string[] $unexistingEmails unexistingEmails * * @return $this */ public function setUnexistingEmails($unexistingEmails) { $this->container['unexistingEmails'] = $unexistingEmails; return $this; } /** * Gets withoutListEmails * * @return string[] */ public function getWithoutListEmails() { return $this->container['withoutListEmails']; } /** * Sets withoutListEmails * * @param string[] $withoutListEmails withoutListEmails * * @return $this */ public function setWithoutListEmails($withoutListEmails) { $this->container['withoutListEmails'] = $withoutListEmails; return $this; } /** * Gets blackListedEmails * * @return string[] */ public function getBlackListedEmails() { return $this->container['blackListedEmails']; } /** * Sets blackListedEmails * * @param string[] $blackListedEmails blackListedEmails * * @return $this */ public function setBlackListedEmails($blackListedEmails) { $this->container['blackListedEmails'] = $blackListedEmails; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } }
madeITBelgium/WordPress-Forms
vendor/sendinblue/api-v3-sdk/lib/Model/PostSendFailed.php
PHP
gpl-3.0
10,449
package view.rendes; import java.awt.Graphics; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import javax.swing.JTextField; public class RoundJTextField extends JTextField { private Shape shape; public RoundJTextField(int size) { super(size); setOpaque(false); // As suggested by @AVD in comment. } protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); super.paintComponent(g); } protected void paintBorder(Graphics g) { g.setColor(getForeground()); g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); } public boolean contains(int x, int y) { if (shape == null || !shape.getBounds().equals(getBounds())) { shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15); } return shape.contains(x, y); } }
gihon19/postHotelSonrisa
postHotelSonrisa/src/view/rendes/RoundJTextField.java
Java
gpl-3.0
992
cd src make clean make clean 127mer=1
fw1121/Pandoras-Toolbox-for-Bioinformatics
src/SOAPdenovo2/SOAPdenovo-Trans-src-v1.04/clean.sh
Shell
gpl-3.0
39
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package com.sun.star.sdbcx.comp.hsqldb; import org.hsqldb.lib.FileAccess; import org.hsqldb.lib.FileSystemRuntimeException; @SuppressWarnings("ucd") public class StorageFileAccess implements org.hsqldb.lib.FileAccess{ static { NativeLibraries.load(); } String ds_name; String key; /** Creates a new instance of StorageFileAccess */ public StorageFileAccess(Object key) throws java.lang.Exception{ this.key = (String)key; } public void createParentDirs(String filename) { } public boolean isStreamElement(String elementName) { return isStreamElement(key,elementName); } public java.io.InputStream openInputStreamElement(String streamName) throws java.io.IOException { return new NativeInputStreamHelper(key,streamName); } public java.io.OutputStream openOutputStreamElement(String streamName) throws java.io.IOException { return new NativeOutputStreamHelper(key,streamName); } public void removeElement(String filename) throws java.util.NoSuchElementException { try { if ( isStreamElement(key,filename) ) removeElement(key,filename); } catch (java.io.IOException e) { throw new FileSystemRuntimeException( e ); } } public void renameElement(String oldName, String newName) throws java.util.NoSuchElementException { try { if ( isStreamElement(key,oldName) ){ removeElement(key,newName); renameElement(key,oldName, newName); } } catch (java.io.IOException e) { throw new FileSystemRuntimeException( e ); } } private class FileSync implements FileAccess.FileSync { private final NativeOutputStreamHelper os; private FileSync(NativeOutputStreamHelper _os) { os = _os; } public void sync() throws java.io.IOException { os.sync(); } } public FileAccess.FileSync getFileSync(java.io.OutputStream os) throws java.io.IOException { return new FileSync((NativeOutputStreamHelper)os); } static native boolean isStreamElement(String key,String elementName); static native void removeElement(String key,String filename) throws java.util.NoSuchElementException, java.io.IOException; static native void renameElement(String key,String oldName, String newName) throws java.util.NoSuchElementException, java.io.IOException; }
jvanz/core
connectivity/com/sun/star/sdbcx/comp/hsqldb/StorageFileAccess.java
Java
gpl-3.0
3,316
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>For More Information</title> <link rel="stylesheet" href="gettingStarted.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Getting Started with Berkeley DB Transaction Processing" /> <link rel="up" href="preface.html" title="Preface" /> <link rel="prev" href="preface.html" title="Preface" /> <link rel="next" href="introduction.html" title="Chapter 1. Introduction" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 12.1.6.1</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">For More Information</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="preface.html">Prev</a> </td> <th width="60%" align="center">Preface</th> <td width="20%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="moreinfo"></a>For More Information</h2> </div> </div> </div> <div class="toc"> <dl> <dt> <span class="sect2"> <a href="moreinfo.html#contact_us">Contact Us</a> </span> </dt> </dl> </div> <p> Beyond this manual, you may also find the following sources of information useful when building a transactional DB application: </p> <div class="itemizedlist"> <ul type="disc"> <li> <p> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/gsg/CXX/index.html" target="_top"> Getting Started with Berkeley DB for C++ </a> </p> </li> <li> <p> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/gsg_db_rep/CXX/index.html" target="_top"> Berkeley DB Getting Started with Replicated Applications for C++ </a> </p> </li> <li> <p> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/programmer_reference/index.html" target="_top"> Berkeley DB Programmer's Reference Guide </a> </p> </li> <li> <p> <span> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/api_reference/CXX/frame_main.html" target="_top"> Berkeley DB C++ API Reference Guide </a> </span> </p> </li> </ul> </div> <span> <p> To download the latest <span>Berkeley DB</span> documentation along with white papers and other collateral, visit <a class="ulink" href="http://www.oracle.com/technetwork/indexes/documentation/index.html" target="_top">http://www.oracle.com/technetwork/indexes/documentation/index.html</a>. </p> <p> For the latest version of the Oracle <span>Berkeley DB</span> downloads, visit <a class="ulink" href="http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html" target="_top">http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html</a>. </p> </span> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="contact_us"></a>Contact Us</h3> </div> </div> </div> <p> You can post your comments and questions at the Oracle Technology (OTN) forum for <span> Oracle Berkeley DB at: <a class="ulink" href="https://forums.oracle.com/forums/forum.jspa?forumID=271" target="_top">https://forums.oracle.com/forums/forum.jspa?forumID=271</a>, or for Oracle Berkeley DB High Availability at: <a class="ulink" href="https://forums.oracle.com/forums/forum.jspa?forumID=272" target="_top">https://forums.oracle.com/forums/forum.jspa?forumID=272</a>. </span> </p> <p> For sales or support information, email to: <a class="ulink" href="mailto:berkeleydb-info_us@oracle.com" target="_top">berkeleydb-info_us@oracle.com</a> You can subscribe to a low-volume email announcement list for the Berkeley DB product family by sending email to: <a class="ulink" href="mailto:bdb-join@oss.oracle.com" target="_top">bdb-join@oss.oracle.com</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="preface.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="preface.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">Preface </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> Chapter 1. Introduction</td> </tr> </table> </div> </body> </html>
apavlo/h-store
third_party/cpp/berkeleydb/docs/gsg_txn/CXX/moreinfo.html
HTML
gpl-3.0
6,524
<?php /** * Message translations. * * This file is automatically generated by 'yii message' command. * It contains the localizable messages extracted from source code. * You may modify this file by translating the extracted messages. * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of '@@' marks. * * Message string can be used with plural forms format. Check i18n section * of the guide for details. * * NOTE: this file must be saved in UTF-8 encoding. */ return [ '--- Select Course ---' => 'اختر الفرقة الدراسية', 'ADD' => 'أضف', 'Active' => 'نشط', 'Add' => 'أضف', 'Add Batch' => 'أضف عام دراسي', 'Add Course' => 'أضف مقرر', 'Add Section' => 'أضف مجموعة', 'Are you sure you want to delete this item?' => 'هل ترغب في حذف هذه الفرقة الدراسية بالفعل؟', 'Back' => 'عودة', 'Batch' => 'العام الدراسي', 'Batch Alias' => 'الاسم المختصر للعام الدراسي', 'Batch Course' => 'مقرر العام الدراسي', 'Batch ID' => 'كود العام الدراسي', 'Batch Name' => 'اسم العام الدراسي', 'Batches' => 'الدفعات', 'Cancel' => 'إلغاء', 'Course' => 'الفرقة', 'Course Alias' => 'مختصر اسم الفرقة الدراسية', 'Course Already Exists with this Course code.' => 'الفرقة الدراسية بموجودة بالفعل مع هذا الكود', 'Course Code' => 'كود الفرقة الدراسية', 'Course ID' => 'كود الفرقة الدراسية', 'Course Management' => 'إدارة الفرقة الدراسية', 'Course Name' => 'اسم الفرقة الدراسية', 'Create' => 'انشاء', 'Create New' => 'جديد', 'Create Section' => 'انشيء مجموعة', 'Created At' => 'انشئت في', 'Created By' => 'بمعرفة', 'Delete' => 'حذف', 'EXCEL' => 'EXCEL', 'Edit Batch Details' => 'تحرير تفاصيل العام الدراسي', 'Edit Course Details' => 'تحرير تفاصيل الفرقة الدراسية', 'Edit Section Details' => 'تحرير تفاصيل التخصص', 'End Date' => 'تاريخ الانتهاء', 'Inactive' => 'غير نشط', 'Initial Batch' => 'العام الدراسي الأولى', 'Initial Section' => 'التخصص الأولى', 'Intake' => 'العدد', 'Manage Batches' => 'إدارة الدفعات', 'Manage Course' => 'إدارة الفرقة الدراسية', 'Manage Course Modules' => 'إدارة موديولات الفرقة الدراسية', 'Manage Courses' => 'إدارة الفرق الدراسية', 'Manage Current Active Course' => 'إدارة الفرق الدراسية النشطة', 'Manage Section' => 'إدارة التخصص', 'Manage Sections' => 'إدارة التخصصات', 'No results found.' => 'لم يتم العثور على نتائج', 'PDF' => 'PDF', 'Section' => 'التخصص', 'Section Already Exists of this Batch.' => 'التخصص موجودة بالفعل في هذه العام الدراسي', 'Section Batch' => 'عام دراسي التخصص', 'Section ID' => 'كود التخصص', 'Section Name' => 'اسم التخصص', 'Start Date' => 'تاريخ الالتحاق', 'Status' => 'الحالة', 'Students' => 'الطلبة', 'Update' => 'تحديث', 'Update Batch' => 'تحديث العام الدراسي', 'Update Batches: ' => 'تحديث الدفعات', 'Update Course' => 'تحديث الفرقة الدراسية', 'Update Courses: ' => 'تحديث الفرقة الدراسيةات', 'Update Section' => 'تحديث التخصص', 'Update Section: ' => 'تحديث التخصص', 'Updated At' => 'تم التحديث في', 'Updated By' => 'بمعرفة', 'View Batch' => 'اظهار العام الدراسي', 'View Batch Details' => 'اظهار تفاصيل العام الدراسي', 'View Course' => 'اظهار الفرقة الدراسية', 'View Course Details' => 'إظهار تفاصيل الفرقة الدراسية', 'View Section' => 'إظهار التخصص', 'View Section Details' => 'إظهار تفاصيل التخصص', ];
linhnh5/edu01
messages/ar/course.php
PHP
gpl-3.0
4,555
// File: fig0621.cpp // Computer Systems, Fourth Edition // Figure 6.21 #include <iostream> using namespace std; int numPts; int value; int j; void printBar (int n) { int k; for (k = 1; k <= n; k++) { cout << '*'; } cout << endl; } int main () { cin >> numPts; for (j = 1; j <= numPts; j++) { cin >> value; printBar (value); } return 0; }
StanWarford/pep8
help/figures/fig0621.cpp
C++
gpl-3.0
385
// ---------------------------------------------------------------------- // <copyright file="TMAPcontrol.cs" company="none"> // Copyright (C) 2012 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // </copyright> // <author>pleoNeX</author> // <email>benito356@gmail.com</email> // <date>02/09/2012 3:53:19</date> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using Ekona; namespace NINOKUNI { public partial class TMAPcontrol : UserControl { TMAP tmap; IPluginHost pluginHost; public TMAPcontrol() { InitializeComponent(); } public TMAPcontrol(sFile cfile, IPluginHost pluginHost) { InitializeComponent(); this.pluginHost = pluginHost; tmap = new TMAP(cfile, pluginHost); numLayer_ValueChanged(null, null); } ~TMAPcontrol() { tmap = null; } private void numLayer_ValueChanged(object sender, EventArgs e) { picMap.Image = tmap.Get_Map((int)numLayer.Value); } private void btnSave_Click(object sender, EventArgs e) { SaveFileDialog o = new SaveFileDialog(); o.AddExtension = true; o.DefaultExt = ".png"; o.FileName = tmap.FileName + ".png"; o.Filter = "Portable Net Graphic (*.png)|*.png"; if (o.ShowDialog() != DialogResult.OK) return; picMap.Image.Save(o.FileName, System.Drawing.Imaging.ImageFormat.Png); o.Dispose(); o = null; } private void numPicMode_ValueChanged(object sender, EventArgs e) { picMap.SizeMode = (PictureBoxSizeMode)numPicMode.Value; } } }
pleonex/tinke
Plugins/NINOKUNI/NINOKUNI/TMAPcontrol.cs
C#
gpl-3.0
2,689
package cn.nukkit.redstone; import cn.nukkit.block.Block; import cn.nukkit.block.BlockRedstoneWire; import cn.nukkit.block.BlockSolid; import cn.nukkit.math.Vector3; import java.util.*; /** * author: Angelic47 * Nukkit Project */ public class Redstone { public static final int POWER_NONE = 0; public static final int POWER_WEAKEST = 1; public static final int POWER_STRONGEST = 16; //NOTICE: Here POWER_STRONGEST is 16, not 15. //I set it to 16 in order to calculate the energy in blocks, such as the redstone torch under the cobblestone. //At that time, the cobblestone's energy is 16, not 15. If you put a redstone wire next to it, the redstone wire will got 15 energy. //So, POWER_WEAKEST also means that energy in blocks, not redstone wire it self. So set it to 1. private static final Comparator<UpdateObject> orderIsdn = new Comparator<UpdateObject>() { @Override public int compare(UpdateObject o1, UpdateObject o2) { if (o1.getPopulation() > o2.getPopulation()) { return -1; } else if (o1.getPopulation() < o2.getPopulation()) { return 1; } else { return 0; } } }; public static void active(Block source) { Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); int currentLevel = source.getPowerLevel() - 1; if (currentLevel <= 0) { return; } addToQueue(updateQueue, source); while (!updateQueue.isEmpty()) { UpdateObject updatingObj = updateQueue.poll(); Block updating = updatingObj.getLocation(); currentLevel = updatingObj.getPopulation(); if (currentLevel > updating.getPowerLevel()) { updating.setPowerLevel(currentLevel); updating.getLevel().setBlock(updating, updating, true, true); addToQueue(updateQueue, updating); } } } public static void active(Block source, Map<String, Block> allBlocks) { Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); int currentLevel = source.getPowerLevel() - 1; if (currentLevel <= 0) { return; } addToQueue(updateQueue, source); while (!updateQueue.isEmpty()) { UpdateObject updatingObj = updateQueue.poll(); Block updating = updatingObj.getLocation(); currentLevel = updatingObj.getPopulation(); if (currentLevel > updating.getPowerLevel()) { updating.setPowerLevel(currentLevel); updating.getLevel().setBlock(updating, updating, true, true); if (allBlocks.containsKey(updating.getLocationHash())) { allBlocks.remove(updating.getLocationHash()); } addToQueue(updateQueue, updating); } } } public static void deactive(Block source, int updateLevel) { //Step 1: find blocks which need to update Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); Queue<UpdateObject> sourceList = new PriorityQueue<>(1, orderIsdn); Map<String, Block> updateMap = new HashMap<>(); Map<String, Block> closedMap = new HashMap<>(); int currentLevel = updateLevel; if (currentLevel <= 0) { return; } addToDeactiveQueue(updateQueue, source, closedMap, sourceList, currentLevel); while (!updateQueue.isEmpty()) { UpdateObject updateObject = updateQueue.poll(); Block updating = updateObject.getLocation(); currentLevel = updateObject.getPopulation(); if (currentLevel >= updating.getPowerLevel()) { updating.setPowerLevel(0); updateMap.put(updating.getLocationHash(), updating); addToDeactiveQueue(updateQueue, updating, closedMap, sourceList, currentLevel); } else { sourceList.add(new UpdateObject(updating.getPowerLevel(), updating)); } } //Step 2: recalculate redstone power while (!sourceList.isEmpty()) { active(sourceList.poll().getLocation(), updateMap); } for (Block block : updateMap.values()) { block.setPowerLevel(0); block.getLevel().setBlock(block, block, true, true); } } private static void addToQueue(Queue<UpdateObject> updateQueue, Block location) { if (location.getPowerLevel() <= 0) { return; } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST, Vector3.SIDE_UP, Vector3.SIDE_DOWN}) { if (location.getSide(side) instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, location.getSide(side))); } } if (location instanceof BlockRedstoneWire) { Block block = location.getSide(Vector3.SIDE_UP); if (!(block instanceof BlockSolid)) { for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { if (block.getSide(side) instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, block.getSide(side))); } } } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_WEST, Vector3.SIDE_EAST, Vector3.SIDE_SOUTH}) { block = location.getSide(side); if (!(block instanceof BlockSolid)) { Block blockDown; blockDown = block.getSide(Vector3.SIDE_DOWN); if (blockDown instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, blockDown)); } } } } } private static void addToDeactiveQueue(Queue<UpdateObject> updateQueue, Block location, Map<String, Block> closedMap, Queue<UpdateObject> sourceList, int updateLevel) { if (updateLevel < 0) { return; } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST, Vector3.SIDE_UP, Vector3.SIDE_DOWN}) { if (location.getSide(side).isPowerSource() || (updateLevel == 0 && location.getSide(side).isPowered())) { sourceList.add(new UpdateObject(location.getPowerLevel(side), location.getSide(side))); } else if (location.getSide(side) instanceof BlockRedstoneWire) { if (!closedMap.containsKey(location.getSide(side).getLocationHash())) { closedMap.put(location.getSide(side).getLocationHash(), location.getSide(side)); updateQueue.add(new UpdateObject(updateLevel - 1, location.getSide(side))); } } } if (location instanceof BlockRedstoneWire) { Block block = location.getSide(Vector3.SIDE_UP); for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { if (block.getSide(side) instanceof BlockRedstoneWire) { if (!closedMap.containsKey(block.getSide(side).getLocationHash())) { closedMap.put(block.getSide(side).getLocationHash(), block.getSide(side)); updateQueue.add(new UpdateObject(updateLevel - 1, block.getSide(side))); } } } Block blockDown; for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { block = location.getSide(side); blockDown = block.getSide(Vector3.SIDE_DOWN); if (blockDown instanceof BlockRedstoneWire) { if (!closedMap.containsKey(blockDown.getLocationHash())) { closedMap.put(blockDown.getLocationHash(), blockDown); updateQueue.add(new UpdateObject(updateLevel - 1, blockDown)); } } } } } }
Niall7459/Nukkit
src/main/java/cn/nukkit/redstone/Redstone.java
Java
gpl-3.0
8,365
include("dat/factions/spawn/common.lua") include("dat/factions/spawn/mercenary_helper.lua") -- @brief Spawns a small patrol fleet. function spawn_patrol () local pilots = {} local r = rnd.rnd() if r < pbm then pilots = spawnLtMerc("Frontier") elseif r < 0.5 then scom.addPilot( pilots, "Frontier Lancelot", 30 ); elseif r < 0.8 then scom.addPilot( pilots, "Frontier Hyena", 20 ); scom.addPilot( pilots, "Frontier Lancelot", 30 ); else scom.addPilot( pilots, "Frontier Hyena", 20 ); scom.addPilot( pilots, "Frontier Ancestor", 25 ); end return pilots end -- @brief Spawns a medium sized squadron. function spawn_squad () local pilots = {} local r = rnd.rnd() if r < pbm then pilots = spawnMdMerc("Frontier") elseif r < 0.5 then scom.addPilot( pilots, "Frontier Lancelot", 30 ); scom.addPilot( pilots, "Frontier Phalanx", 55 ); else scom.addPilot( pilots, "Frontier Lancelot", 30 ); scom.addPilot( pilots, "Frontier Lancelot", 30 ); scom.addPilot( pilots, "Frontier Ancestor", 25 ); end return pilots end -- @brief Creation hook. function create ( max ) local weights = {} -- Create weights for spawn table weights[ spawn_patrol ] = 100 weights[ spawn_squad ] = 0.33*max -- Create spawn table base on weights spawn_table = scom.createSpawnTable( weights ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( 0, scom.presence(spawn_data), max ) end -- @brief Spawning hook function spawn ( presence, max ) local pilots -- Over limit if presence > max then return 5 end -- Actually spawn the pilots pilots = scom.spawn( spawn_data, "Frontier" ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots end
jayman39tx/naev
dat/factions/spawn/frontier.lua
Lua
gpl-3.0
1,978
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import time import numpy from nupic.bindings.math import GetNTAReal from nupic.research.monitor_mixin.monitor_mixin_base import MonitorMixinBase from nupic.research.monitor_mixin.temporal_memory_monitor_mixin import ( TemporalMemoryMonitorMixin) from sensorimotor.fast_general_temporal_memory import ( FastGeneralTemporalMemory as GeneralTemporalMemory) # Uncomment the line below to use GeneralTemporalMemory # from sensorimotor.general_temporal_memory import GeneralTemporalMemory from sensorimotor.temporal_pooler import TemporalPooler # Uncomment the line below to use SpatialTemporalPooler # from sensorimotor.spatial_temporal_pooler import SpatialTemporalPooler as TemporalPooler from sensorimotor.temporal_pooler_monitor_mixin import ( TemporalPoolerMonitorMixin) class MonitoredGeneralTemporalMemory(TemporalMemoryMonitorMixin, GeneralTemporalMemory): pass class MonitoredTemporalPooler(TemporalPoolerMonitorMixin, TemporalPooler): pass """ Experiment runner class for running networks with layer 4 and layer 3. The client is responsible for setting up universes, agents, and worlds. This class just sets up and runs the HTM learning algorithms. """ realDType = GetNTAReal() class SensorimotorExperimentRunner(object): DEFAULT_TM_PARAMS = { # These should be decent for most experiments, shouldn't need to override # these too often. Might want to increase cellsPerColumn for capacity # experiments. "cellsPerColumn": 8, "initialPermanence": 0.5, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, # We will force client to override these "columnDimensions": "Sorry", "minThreshold": "Sorry", "maxNewSynapseCount": "Sorry", "activationThreshold": "Sorry", } DEFAULT_TP_PARAMS = { # Need to check these parameters and find stable values that will be # consistent across most experiments. "synPermInactiveDec": 0, # TODO: Check we can use class default here. "synPermActiveInc": 0.001, # TODO: Check we can use class default here. "synPredictedInc": 0.5, # TODO: Why so high?? "potentialPct": 0.9, # TODO: need to check impact of this for pooling "initConnectedPct": 0.5, # TODO: need to check impact of this for pooling "poolingThreshUnpredicted": 0.0, # We will force client to override these "numActiveColumnsPerInhArea": "Sorry", } def __init__(self, tmOverrides=None, tpOverrides=None, seed=42): # Initialize Layer 4 temporal memory params = dict(self.DEFAULT_TM_PARAMS) params.update(tmOverrides or {}) params["seed"] = seed self._checkParams(params) self.tm = MonitoredGeneralTemporalMemory(mmName="TM", **params) # Initialize Layer 3 temporal pooler params = dict(self.DEFAULT_TP_PARAMS) params["inputDimensions"] = [self.tm.numberOfCells()] params["potentialRadius"] = self.tm.numberOfCells() params["seed"] = seed params.update(tpOverrides or {}) self._checkParams(params) self.tp = MonitoredTemporalPooler(mmName="TP", **params) def _checkParams(self, params): for k,v in params.iteritems(): if v == "Sorry": raise RuntimeError("Param "+k+" must be specified") def feedTransition(self, sensorPattern, motorPattern, sensorimotorPattern, tmLearn=True, tpLearn=None, sequenceLabel=None): if sensorPattern is None: self.tm.reset() self.tp.reset() else: # Feed the TM self.tm.compute(sensorPattern, activeExternalCells=motorPattern, formInternalConnections=True, learn=tmLearn, sequenceLabel=sequenceLabel) # If requested, feed the TP if tpLearn is not None: tpInputVector, burstingColumns, correctlyPredictedCells = ( self.formatInputForTP()) activeArray = numpy.zeros(self.tp.getNumColumns()) self.tp.compute(tpInputVector, tpLearn, activeArray, burstingColumns, correctlyPredictedCells, sequenceLabel=sequenceLabel) def feedLayers(self, sequences, tmLearn=True, tpLearn=None, verbosity=0, showProgressInterval=None): """ Feed the given sequences to the HTM algorithms. @param tmLearn: (bool) Either False, or True @param tpLearn: (None,bool) Either None, False, or True. If None, temporal pooler will be skipped. @param showProgressInterval: (int) Prints progress every N iterations, where N is the value of this param """ (sensorSequence, motorSequence, sensorimotorSequence, sequenceLabels) = sequences currentTime = time.time() for i in xrange(len(sensorSequence)): sensorPattern = sensorSequence[i] motorPattern = motorSequence[i] sensorimotorPattern = sensorimotorSequence[i] sequenceLabel = sequenceLabels[i] self.feedTransition(sensorPattern, motorPattern, sensorimotorPattern, tmLearn=tmLearn, tpLearn=tpLearn, sequenceLabel=sequenceLabel) if (showProgressInterval is not None and i > 0 and i % showProgressInterval == 0): print ("Fed {0} / {1} elements of the sequence " "in {2:0.2f} seconds.".format( i, len(sensorSequence), time.time() - currentTime)) currentTime = time.time() if verbosity >= 2: # Print default TM traces traces = self.tm.mmGetDefaultTraces(verbosity=verbosity) print MonitorMixinBase.mmPrettyPrintTraces(traces, breakOnResets= self.tm.mmGetTraceResets()) if tpLearn is not None: # Print default TP traces traces = self.tp.mmGetDefaultTraces(verbosity=verbosity) print MonitorMixinBase.mmPrettyPrintTraces(traces, breakOnResets= self.tp.mmGetTraceResets()) print @staticmethod def generateSequences(length, agents, numSequences=1, verbosity=0): """ @param length (int) Length of each sequence to generate, one for each agent @param agents (AbstractAgent) Agents acting in their worlds @return (tuple) (sensor sequence, motor sequence, sensorimotor sequence, sequence labels) """ sensorSequence = [] motorSequence = [] sensorimotorSequence = [] sequenceLabels = [] for _ in xrange(numSequences): for agent in agents: s,m,sm = agent.generateSensorimotorSequence(length, verbosity=verbosity) sensorSequence += s motorSequence += m sensorimotorSequence += sm sequenceLabels += [agent.world.toString()] * length sensorSequence.append(None) motorSequence.append(None) sensorimotorSequence.append(None) sequenceLabels.append(None) return sensorSequence, motorSequence, sensorimotorSequence, sequenceLabels def formatInputForTP(self): """ Given an instance of the TM, format the information we need to send to the TP. """ # all currently active cells in layer 4 tpInputVector = numpy.zeros( self.tm.numberOfCells()).astype(realDType) tpInputVector[list(self.tm.activeCellsIndices())] = 1 # bursting columns in layer 4 burstingColumns = numpy.zeros( self.tm.numberOfColumns()).astype(realDType) burstingColumns[list(self.tm.unpredictedActiveColumns)] = 1 # correctly predicted cells in layer 4 correctlyPredictedCells = numpy.zeros( self.tm.numberOfCells()).astype(realDType) correctlyPredictedCells[list(self.tm.predictedActiveCellsIndices())] = 1 return tpInputVector, burstingColumns, correctlyPredictedCells def formatRow(self, x, formatString = "%d", rowSize = 700): """ Utility routine for pretty printing large vectors """ s = '' for c,v in enumerate(x): if c > 0 and c % 7 == 0: s += ' ' if c > 0 and c % rowSize == 0: s += '\n' s += formatString % v s += ' ' return s
pford68/nupic.research
sensorimotor/sensorimotor/sensorimotor_experiment_runner.py
Python
gpl-3.0
9,403
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "resizecontroller.h" #include "formeditoritem.h" #include "layeritem.h" #include <resizehandleitem.h> #include <QCursor> #include <QGraphicsScene> namespace QmlDesigner { class ResizeControllerData { public: ResizeControllerData(LayerItem *layerItem, FormEditorItem *formEditorItem); ResizeControllerData(const ResizeControllerData &other); ~ResizeControllerData(); QPointer<LayerItem> layerItem; FormEditorItem *formEditorItem = nullptr; QSharedPointer<ResizeHandleItem> topLeftItem; QSharedPointer<ResizeHandleItem> topRightItem; QSharedPointer<ResizeHandleItem> bottomLeftItem; QSharedPointer<ResizeHandleItem> bottomRightItem; QSharedPointer<ResizeHandleItem> topItem; QSharedPointer<ResizeHandleItem> leftItem; QSharedPointer<ResizeHandleItem> rightItem; QSharedPointer<ResizeHandleItem> bottomItem; }; ResizeControllerData::ResizeControllerData(LayerItem *layerItem, FormEditorItem *formEditorItem) : layerItem(layerItem), formEditorItem(formEditorItem), topLeftItem(nullptr), topRightItem(nullptr), bottomLeftItem(nullptr), bottomRightItem(nullptr), topItem(nullptr), leftItem(nullptr), rightItem(nullptr), bottomItem(nullptr) { } ResizeControllerData::ResizeControllerData(const ResizeControllerData &other) = default; ResizeControllerData::~ResizeControllerData() { if (layerItem) { QGraphicsScene *scene = layerItem->scene(); scene->removeItem(topLeftItem.data()); scene->removeItem(topRightItem.data()); scene->removeItem(bottomLeftItem.data()); scene->removeItem(bottomRightItem.data()); scene->removeItem(topItem.data()); scene->removeItem(leftItem.data()); scene->removeItem(rightItem.data()); scene->removeItem(bottomItem.data()); } } ResizeController::ResizeController() : m_data(new ResizeControllerData(nullptr, nullptr)) { } ResizeController::ResizeController(const QSharedPointer<ResizeControllerData> &data) : m_data(data) { } ResizeController::ResizeController(LayerItem *layerItem, FormEditorItem *formEditorItem) : m_data(new ResizeControllerData(layerItem, formEditorItem)) { m_data->topLeftItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->topLeftItem->setZValue(302); m_data->topLeftItem->setCursor(Qt::SizeFDiagCursor); m_data->topRightItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->topRightItem->setZValue(301); m_data->topRightItem->setCursor(Qt::SizeBDiagCursor); m_data->bottomLeftItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->bottomLeftItem->setZValue(301); m_data->bottomLeftItem->setCursor(Qt::SizeBDiagCursor); m_data->bottomRightItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->bottomRightItem->setZValue(305); m_data->bottomRightItem->setCursor(Qt::SizeFDiagCursor); m_data->topItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->topItem->setZValue(300); m_data->topItem->setCursor(Qt::SizeVerCursor); m_data->leftItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->leftItem->setZValue(300); m_data->leftItem->setCursor(Qt::SizeHorCursor); m_data->rightItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->rightItem->setZValue(300); m_data->rightItem->setCursor(Qt::SizeHorCursor); m_data->bottomItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->bottomItem->setZValue(300); m_data->bottomItem->setCursor(Qt::SizeVerCursor); updatePosition(); } ResizeController::ResizeController(const ResizeController &other) = default; ResizeController::ResizeController(const WeakResizeController &resizeController) : m_data(resizeController.m_data.toStrongRef()) { } ResizeController::~ResizeController() = default; ResizeController &ResizeController::operator =(const ResizeController &other) { if (this != &other) m_data = other.m_data; return *this; } bool ResizeController::isValid() const { return m_data->formEditorItem && m_data->formEditorItem->qmlItemNode().isValid(); } void ResizeController::show() { m_data->topLeftItem->show(); m_data->topRightItem->show(); m_data->bottomLeftItem->show(); m_data->bottomRightItem->show(); m_data->topItem->show(); m_data->leftItem->show(); m_data->rightItem->show(); m_data->bottomItem->show(); } void ResizeController::hide() { m_data->topLeftItem->hide(); m_data->topRightItem->hide(); m_data->bottomLeftItem->hide(); m_data->bottomRightItem->hide(); m_data->topItem->hide(); m_data->leftItem->hide(); m_data->rightItem->hide(); m_data->bottomItem->hide(); } static QPointF topCenter(const QRectF &rect) { return {rect.center().x(), rect.top()}; } static QPointF leftCenter(const QRectF &rect) { return {rect.left(), rect.center().y()}; } static QPointF rightCenter(const QRectF &rect) { return {rect.right(), rect.center().y()}; } static QPointF bottomCenter(const QRectF &rect) { return {rect.center().x(), rect.bottom()}; } void ResizeController::updatePosition() { if (isValid()) { QRectF boundingRect = m_data->formEditorItem->qmlItemNode().instanceBoundingRect(); QPointF topLeftPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.topLeft())); QPointF topRightPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.topRight())); QPointF bottomLeftPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.bottomLeft())); QPointF bottomRightPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.bottomRight())); QPointF topPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), topCenter(boundingRect))); QPointF leftPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), leftCenter(boundingRect))); QPointF rightPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), rightCenter(boundingRect))); QPointF bottomPointInLayerSpace(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), bottomCenter(boundingRect))); m_data->topRightItem->setHandlePosition(topRightPointInLayerSpace, boundingRect.topRight()); m_data->topLeftItem->setHandlePosition(topLeftPointInLayerSpace, boundingRect.topLeft()); m_data->bottomLeftItem->setHandlePosition(bottomLeftPointInLayerSpace, boundingRect.bottomLeft()); m_data->bottomRightItem->setHandlePosition(bottomRightPointInLayerSpace, boundingRect.bottomRight()); m_data->topItem->setHandlePosition(topPointInLayerSpace, topCenter(boundingRect)); m_data->leftItem->setHandlePosition(leftPointInLayerSpace, leftCenter(boundingRect)); m_data->rightItem->setHandlePosition(rightPointInLayerSpace, rightCenter(boundingRect)); m_data->bottomItem->setHandlePosition(bottomPointInLayerSpace, bottomCenter(boundingRect)); } } FormEditorItem* ResizeController::formEditorItem() const { return m_data->formEditorItem; } bool ResizeController::isTopLeftHandle(const ResizeHandleItem *handle) const { return handle == m_data->topLeftItem; } bool ResizeController::isTopRightHandle(const ResizeHandleItem *handle) const { return handle == m_data->topRightItem; } bool ResizeController::isBottomLeftHandle(const ResizeHandleItem *handle) const { return handle == m_data->bottomLeftItem; } bool ResizeController::isBottomRightHandle(const ResizeHandleItem *handle) const { return handle == m_data->bottomRightItem; } bool ResizeController::isTopHandle(const ResizeHandleItem *handle) const { return handle == m_data->topItem; } bool ResizeController::isLeftHandle(const ResizeHandleItem *handle) const { return handle == m_data->leftItem; } bool ResizeController::isRightHandle(const ResizeHandleItem *handle) const { return handle == m_data->rightItem; } bool ResizeController::isBottomHandle(const ResizeHandleItem *handle) const { return handle == m_data->bottomItem; } WeakResizeController ResizeController::toWeakResizeController() const { return WeakResizeController(*this); } WeakResizeController::WeakResizeController() = default; WeakResizeController::WeakResizeController(const WeakResizeController &resizeController) = default; WeakResizeController::WeakResizeController(const ResizeController &resizeController) : m_data(resizeController.m_data.toWeakRef()) { } WeakResizeController::~WeakResizeController() = default; WeakResizeController &WeakResizeController::operator =(const WeakResizeController &other) { if (m_data != other.m_data) m_data = other.m_data; return *this; } ResizeController WeakResizeController::toResizeController() const { return ResizeController(*this); } }
qtproject/qt-creator
src/plugins/qmldesigner/components/formeditor/resizecontroller.cpp
C++
gpl-3.0
11,008
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkPathEffect.h" #include "SkPictureRecorder.h" #include "SkShadowPaintFilterCanvas.h" #include "SkShadowShader.h" #include "SkSurface.h" #ifdef SK_EXPERIMENTAL_SHADOWING static sk_sp<SkPicture> make_test_picture(int width, int height) { SkPictureRecorder recorder; // LONG RANGE TODO: eventually add SkBBHFactory (bounding box factory) SkCanvas* canvas = recorder.beginRecording(SkRect::MakeIWH(width, height)); SkASSERT(canvas->getTotalMatrix().isIdentity()); SkPaint paint; paint.setColor(SK_ColorGRAY); // LONG RANGE TODO: tag occluders // LONG RANGE TODO: track number of IDs we need (hopefully less than 256) // and determinate the mapping from z to id // universal receiver, "ground" canvas->drawRect(SkRect::MakeIWH(width, height), paint); // TODO: Maybe add the ID here along with the depth paint.setColor(0xFFEE8888); canvas->translateZ(80); canvas->drawRect(SkRect::MakeLTRB(200,150,350,300), paint); paint.setColor(0xFF88EE88); canvas->translateZ(80); canvas->drawRect(SkRect::MakeLTRB(150,200,300,350), paint); paint.setColor(0xFF8888EE); canvas->translateZ(80); canvas->drawRect(SkRect::MakeLTRB(100,100,250,250), paint); // TODO: Add an assert that Z order matches painter's order // TODO: think about if the Z-order always matching painting order is too strict return recorder.finishRecordingAsPicture(); } namespace skiagm { class ShadowMapsGM : public GM { public: ShadowMapsGM() { this->setBGColor(sk_tool_utils::color_to_565(0xFFCCCCCC)); } void onOnceBeforeDraw() override { // Create a light set consisting of // - bluish directional light pointing more right than down // - reddish directional light pointing more down than right // - soft white ambient light SkLights::Builder builder; builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(0.2f, 0.3f, 0.4f), SkVector3::Make(0.2f, 0.1f, 1.0f))); builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(0.4f, 0.3f, 0.2f), SkVector3::Make(0.1f, 0.2f, 1.0f))); builder.setAmbientLightColor(SkColor3f::Make(0.4f, 0.4f, 0.4f)); fLights = builder.finish(); fShadowParams.fShadowRadius = 4.0f; fShadowParams.fBiasingConstant = 0.3f; fShadowParams.fMinVariance = 1024; fShadowParams.fType = SkShadowParams::kVariance_ShadowType; } protected: static constexpr int kWidth = 400; static constexpr int kHeight = 400; SkString onShortName() override { return SkString("shadowmaps"); } SkISize onISize() override { return SkISize::Make(kWidth, kHeight); } void onDraw(SkCanvas* canvas) override { // This picture stores the picture of the scene. // It's used to generate the depth maps. sk_sp<SkPicture> pic(make_test_picture(kWidth, kHeight)); canvas->setLights(fLights); canvas->drawShadowedPicture(pic, nullptr, nullptr, fShadowParams); } private: sk_sp<SkLights> fLights; SkShadowParams fShadowParams; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ShadowMapsGM;) } #endif
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/skia/gm/shadowmaps.cpp
C++
gpl-3.0
3,576
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2019 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package main import ( "errors" "fmt" "strings" "time" "github.com/jessevdk/go-flags" "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" ) var ( shortModelHelp = i18n.G("Get the active model for this device") longModelHelp = i18n.G(` The model command returns the active model assertion information for this device. By default, only the essential model identification information is included in the output, but this can be expanded to include all of an assertion's non-meta headers. The verbose output is presented in a structured, yaml-like format. Similarly, the active serial assertion can be used for the output instead of the model assertion. `) invalidTypeMessage = i18n.G("invalid type for %q header") errNoMainAssertion = errors.New(i18n.G("device not ready yet (no assertions found)")) errNoSerial = errors.New(i18n.G("device not registered yet (no serial assertion found)")) errNoVerboseAssertion = errors.New(i18n.G("cannot use --verbose with --assertion")) // this list is a "nice" "human" "readable" "ordering" of headers to print // off, sorted in lexical order with meta headers and primary key headers // removed, and big nasty keys such as device-key-sha3-384 and // device-key at the bottom // it also contains both serial and model assertion headers, but we // follow the same code path for both assertion types and some of the // headers are shared between the two, so it still works out correctly niceOrdering = [...]string{ "architecture", "base", "classic", "display-name", "gadget", "kernel", "revision", "store", "system-user-authority", "timestamp", "required-snaps", // for uc16 and uc18 models "snaps", // for uc20 models "device-key-sha3-384", "device-key", } ) type cmdModel struct { clientMixin timeMixin colorMixin Serial bool `long:"serial"` Verbose bool `long:"verbose"` Assertion bool `long:"assertion"` } func init() { addCommand("model", shortModelHelp, longModelHelp, func() flags.Commander { return &cmdModel{} }, colorDescs.also(timeDescs).also(map[string]string{ "assertion": i18n.G("Print the raw assertion."), "verbose": i18n.G("Print all specific assertion fields."), "serial": i18n.G( "Print the serial assertion instead of the model assertion."), }), []argDesc{}, ) } func (x *cmdModel) Execute(args []string) error { if x.Verbose && x.Assertion { // can't do a verbose mode for the assertion return errNoVerboseAssertion } var mainAssertion asserts.Assertion serialAssertion, serialErr := x.client.CurrentSerialAssertion() modelAssertion, modelErr := x.client.CurrentModelAssertion() // if we didn't get a model assertion bail early if modelErr != nil { if client.IsAssertionNotFoundError(modelErr) { // device is not registered yet - use specific error message return errNoMainAssertion } return modelErr } // if the serial assertion error is anything other than not found, also // bail early // the serial assertion not being found may not be fatal if serialErr != nil && !client.IsAssertionNotFoundError(serialErr) { return serialErr } if x.Serial { mainAssertion = serialAssertion } else { mainAssertion = modelAssertion } if x.Assertion { // if we are using the serial assertion and we specifically didn't find the // serial assertion, bail with specific error if x.Serial && client.IsAssertionNotFoundError(serialErr) { return errNoMainAssertion } _, err := Stdout.Write(asserts.Encode(mainAssertion)) return err } termWidth, _ := termSize() termWidth -= 3 if termWidth > 100 { // any wider than this and it gets hard to read termWidth = 100 } esc := x.getEscapes() w := tabWriter() if x.Serial && client.IsAssertionNotFoundError(serialErr) { // for serial assertion, the primary keys are output (model and // brand-id), but if we didn't find the serial assertion then we still // output the brand-id and model from the model assertion, but also // return a devNotReady error fmt.Fprintf(w, "brand-id:\t%s\n", modelAssertion.HeaderString("brand-id")) fmt.Fprintf(w, "model:\t%s\n", modelAssertion.HeaderString("model")) w.Flush() return errNoSerial } // the rest of this function is the main flow for outputting either the // model or serial assertion in normal or verbose mode // for the `snap model` case with no options, we don't want colons, we want // to be like `snap version` separator := ":" if !x.Verbose && !x.Serial { separator = "" } // ordering of the primary keys for model: brand, model, serial // ordering of primary keys for serial is brand-id, model, serial // output brand/brand-id brandIDHeader := mainAssertion.HeaderString("brand-id") modelHeader := mainAssertion.HeaderString("model") // for the serial header, if there's no serial yet, it's not an error for // model (and we already handled the serial error above) but need to add a // parenthetical about the device not being registered yet var serial string if client.IsAssertionNotFoundError(serialErr) { if x.Verbose || x.Serial { // verbose and serial are yamlish, so we need to escape the dash serial = esc.dash } else { serial = "-" } serial += " (device not registered yet)" } else { serial = serialAssertion.HeaderString("serial") } // handle brand/brand-id and model/model + display-name differently on just // `snap model` w/o opts if x.Serial || x.Verbose { fmt.Fprintf(w, "brand-id:\t%s\n", brandIDHeader) fmt.Fprintf(w, "model:\t%s\n", modelHeader) } else { // for the model command (not --serial) we want to show a publisher // style display of "brand" instead of just "brand-id" storeAccount, err := x.client.StoreAccount(brandIDHeader) if err != nil { return err } // use the longPublisher helper to format the brand store account // like we do in `snap info` fmt.Fprintf(w, "brand%s\t%s\n", separator, longPublisher(x.getEscapes(), storeAccount)) // for model, if there's a display-name, we show that first with the // real model in parenthesis if displayName := modelAssertion.HeaderString("display-name"); displayName != "" { modelHeader = fmt.Sprintf("%s (%s)", displayName, modelHeader) } fmt.Fprintf(w, "model%s\t%s\n", separator, modelHeader) } // only output the grade if it is non-empty, either it is not in the model // assertion for all non-uc20 model assertions, or it is non-empty and // required for uc20 model assertions grade := modelAssertion.HeaderString("grade") if grade != "" { fmt.Fprintf(w, "grade%s\t%s\n", separator, grade) } storageSafety := modelAssertion.HeaderString("storage-safety") if storageSafety != "" { fmt.Fprintf(w, "storage-safety%s\t%s\n", separator, storageSafety) } // serial is same for all variants fmt.Fprintf(w, "serial%s\t%s\n", separator, serial) // --verbose means output more information if x.Verbose { allHeadersMap := mainAssertion.Headers() for _, headerName := range niceOrdering { invalidTypeErr := fmt.Errorf(invalidTypeMessage, headerName) headerValue, ok := allHeadersMap[headerName] // make sure the header is in the map if !ok { continue } // switch on which header it is to handle some special cases switch headerName { // list of scalars case "required-snaps", "system-user-authority": headerIfaceList, ok := headerValue.([]interface{}) if !ok { return invalidTypeErr } if len(headerIfaceList) == 0 { continue } fmt.Fprintf(w, "%s:\t\n", headerName) for _, elem := range headerIfaceList { headerStringElem, ok := elem.(string) if !ok { return invalidTypeErr } // note we don't wrap these, since for now this is // specifically just required-snaps and so all of these // will be snap names which are required to be short fmt.Fprintf(w, " - %s\n", headerStringElem) } //timestamp needs to be formatted with fmtTime from the timeMixin case "timestamp": timestamp, ok := headerValue.(string) if !ok { return invalidTypeErr } // parse the time string as RFC3339, which is what the format is // always in for assertions t, err := time.Parse(time.RFC3339, timestamp) if err != nil { return err } fmt.Fprintf(w, "timestamp:\t%s\n", x.fmtTime(t)) // long string key we don't want to rewrap but can safely handle // on "reasonable" width terminals case "device-key-sha3-384": // also flush the writer before continuing so the previous keys // don't try to align with this key w.Flush() headerString, ok := headerValue.(string) if !ok { return invalidTypeErr } switch { case termWidth > 86: fmt.Fprintf(w, "device-key-sha3-384: %s\n", headerString) case termWidth <= 86 && termWidth > 66: fmt.Fprintln(w, "device-key-sha3-384: |") wrapLine(w, []rune(headerString), " ", termWidth) } case "snaps": // also flush the writer before continuing so the previous keys // don't try to align with this key w.Flush() snapsHeader, ok := headerValue.([]interface{}) if !ok { return invalidTypeErr } if len(snapsHeader) == 0 { // unexpected why this is an empty list, but just ignore for // now continue } fmt.Fprintf(w, "snaps:\n") for _, sn := range snapsHeader { snMap, ok := sn.(map[string]interface{}) if !ok { return invalidTypeErr } // iterate over all keys in the map in a stable, visually // appealing ordering // first do snap name, which will always be present since we // parsed a valid assertion name := snMap["name"].(string) fmt.Fprintf(w, " - name:\t%s\n", name) // the rest of these may be absent, but they are all still // simple strings for _, snKey := range []string{"id", "type", "default-channel", "presence"} { snValue, ok := snMap[snKey] if !ok { continue } snStrValue, ok := snValue.(string) if !ok { return invalidTypeErr } if snStrValue != "" { fmt.Fprintf(w, " %s:\t%s\n", snKey, snStrValue) } } // finally handle "modes" which is a list modes, ok := snMap["modes"] if !ok { continue } modesSlice, ok := modes.([]interface{}) if !ok { return invalidTypeErr } if len(modesSlice) == 0 { continue } modeStrSlice := make([]string, 0, len(modesSlice)) for _, mode := range modesSlice { modeStr, ok := mode.(string) if !ok { return invalidTypeErr } modeStrSlice = append(modeStrSlice, modeStr) } modesSliceYamlStr := "[" + strings.Join(modeStrSlice, ", ") + "]" fmt.Fprintf(w, " modes:\t%s\n", modesSliceYamlStr) } // long base64 key we can rewrap safely case "device-key": headerString, ok := headerValue.(string) if !ok { return invalidTypeErr } // the string value here has newlines inserted as part of the // raw assertion, but base64 doesn't care about whitespace, so // it's safe to split by newlines and re-wrap to make it // prettier headerString = strings.Join( strings.Split(headerString, "\n"), "") fmt.Fprintln(w, "device-key: |") wrapLine(w, []rune(headerString), " ", termWidth) // the default is all the rest of short scalar values, which all // should be strings default: headerString, ok := headerValue.(string) if !ok { return invalidTypeErr } fmt.Fprintf(w, "%s:\t%s\n", headerName, headerString) } } } return w.Flush() }
mvo5/snappy
cmd/snap/cmd_model.go
GO
gpl-3.0
12,390
using System.Collections.Generic; using System.Linq; namespace PKHeX.Core { /// <summary> /// Editor object that unpacks <see cref="EventWork{T}"/> into flags & work groups, and handles value get/set operations. /// </summary> /// <typeparam name="T"></typeparam> public sealed class SplitEventEditor<T> where T : struct { public readonly IList<EventVarGroup> Work; public readonly IList<EventVarGroup> Flag; public readonly IEventVar<T> Block; public SplitEventEditor(IEventVar<T> block, IEnumerable<string> work, IEnumerable<string> flag) { Block = block; // load lines var workLines = work.Where(z => !string.IsNullOrWhiteSpace(z) && z.Length > 5); Work = EventWorkUtil.GetVars(workLines, (index, t, data) => new EventWork<T>(index, t, data)); var flagLines = flag.Where(z => !string.IsNullOrWhiteSpace(z) && z.Length > 5); Flag = EventWorkUtil.GetVars(flagLines, (index, t, data) => new EventFlag(index, t, data)); // initialize lines foreach (var group in Work) { foreach (var item in group.Vars) { item.RawIndex = block.GetWorkRawIndex(item.Type, item.RelativeIndex); ((EventWork<T>)item).Value = block.GetWork(item.RawIndex); } } foreach (var group in Flag) { foreach (var item in group.Vars) { item.RawIndex = block.GetFlagRawIndex(item.Type, item.RelativeIndex); ((EventFlag)item).Flag = block.GetFlag(item.RawIndex); } } } /// <summary> /// Writes all of the updated event values back to the block. /// </summary> public void Save() { foreach (var g in Work) { foreach (var item in g.Vars) { var value = ((EventWork<T>)item).Value; Block.SetWork(item.RawIndex, value); } } foreach (var g in Flag) { foreach (var item in g.Vars) { var value = ((EventFlag)item).Flag; Block.SetFlag(item.RawIndex, value); } } } } }
ReignOfComputer/PKHeX
PKHeX.Core/Editing/Saves/Editors/EventWork/SplitEventEditor.cs
C#
gpl-3.0
2,434
/*! * Bootswatch v4.0.0-alpha.6 * Homepage: https://bootswatch.com * Copyright 2012-2017 Thomas Park * Licensed under MIT * Based on Bootstrap */ /*! * Bootstrap v4.0.0-alpha.6 (https://getbootstrap.com) * Copyright 2011-2017 The Bootstrap Authors * Copyright 2011-2017 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! normalize.css v5.0.0 | MIT License | github.com/necolas/normalize.css */ @import url("https://fonts.googleapis.com/css?family=Ubuntu:400,700"); html { font-family: sans-serif; line-height: 1.15; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } body { margin: 0; } article, aside, footer, header, nav, section { display: block; } h1 { font-size: 2em; margin: 0.67em 0; } figcaption, figure, main { display: block; } figure { margin: 1em 40px; } hr { -webkit-box-sizing: content-box; box-sizing: content-box; height: 0; overflow: visible; } pre { font-family: monospace, monospace; font-size: 1em; } a { background-color: transparent; -webkit-text-decoration-skip: objects; } a:active, a:hover { outline-width: 0; } abbr[title] { border-bottom: none; text-decoration: underline; text-decoration: underline dotted; } b, strong { font-weight: inherit; } b, strong { font-weight: bolder; } code, kbd, samp { font-family: monospace, monospace; font-size: 1em; } dfn { font-style: italic; } mark { background-color: #ff0; color: #000; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } audio, video { display: inline-block; } audio:not([controls]) { display: none; height: 0; } img { border-style: none; } svg:not(:root) { overflow: hidden; } button, input, optgroup, select, textarea { font-family: sans-serif; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } button, select { text-transform: none; } button, html [type="button"], [type="reset"], [type="submit"] { -webkit-appearance: button; } button::-moz-focus-inner, [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner { border-style: none; padding: 0; } button:-moz-focusring, [type="button"]:-moz-focusring, [type="reset"]:-moz-focusring, [type="submit"]:-moz-focusring { outline: 1px dotted ButtonText; } fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } legend { -webkit-box-sizing: border-box; box-sizing: border-box; color: inherit; display: table; max-width: 100%; padding: 0; white-space: normal; } progress { display: inline-block; vertical-align: baseline; } textarea { overflow: auto; } [type="checkbox"], [type="radio"] { -webkit-box-sizing: border-box; box-sizing: border-box; padding: 0; } [type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button { height: auto; } [type="search"] { -webkit-appearance: textfield; outline-offset: -2px; } [type="search"]::-webkit-search-cancel-button, [type="search"]::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-file-upload-button { -webkit-appearance: button; font: inherit; } details, menu { display: block; } summary { display: list-item; } canvas { display: inline-block; } template { display: none; } [hidden] { display: none; } @media print { *, *::before, *::after, p::first-letter, div::first-letter, blockquote::first-letter, li::first-letter, p::first-line, div::first-line, blockquote::first-line, li::first-line { text-shadow: none !important; -webkit-box-shadow: none !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } abbr[title]::after { content: " (" attr(title) ")"; } pre { white-space: pre-wrap !important; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } .navbar { display: none; } .badge { border: 1px solid #000; } .table { border-collapse: collapse !important; } .table td, .table th { background-color: #fff !important; } .table-bordered th, .table-bordered td { border: 1px solid #ddd !important; } } html { -webkit-box-sizing: border-box; box-sizing: border-box; } *, *::before, *::after { -webkit-box-sizing: inherit; box-sizing: inherit; } @-ms-viewport { width: device-width; } html { -ms-overflow-style: scrollbar; -webkit-tap-highlight-color: transparent; } body { font-family: "Ubuntu", Tahoma, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 1rem; font-weight: normal; line-height: 1.5; color: #333; background-color: #fff; } [tabindex="-1"]:focus { outline: none !important; } h1, h2, h3, h4, h5, h6 { margin-top: 0; margin-bottom: .5rem; } p { margin-top: 0; margin-bottom: 1rem; } abbr[title], abbr[data-original-title] { cursor: help; } address { margin-bottom: 1rem; font-style: normal; line-height: inherit; } ol, ul, dl { margin-top: 0; margin-bottom: 1rem; } ol ol, ul ul, ol ul, ul ol { margin-bottom: 0; } dt { font-weight: bold; } dd { margin-bottom: .5rem; margin-left: 0; } blockquote { margin: 0 0 1rem; } a { color: #E95420; text-decoration: none; } a:focus, a:hover { color: #ac3911; text-decoration: underline; } a:not([href]):not([tabindex]) { color: inherit; text-decoration: none; } a:not([href]):not([tabindex]):focus, a:not([href]):not([tabindex]):hover { color: inherit; text-decoration: none; } a:not([href]):not([tabindex]):focus { outline: 0; } pre { margin-top: 0; margin-bottom: 1rem; overflow: auto; } figure { margin: 0 0 1rem; } img { vertical-align: middle; } [role="button"] { cursor: pointer; } a, area, button, [role="button"], input, label, select, summary, textarea { -ms-touch-action: manipulation; touch-action: manipulation; } table { border-collapse: collapse; background-color: transparent; } caption { padding-top: 0.75rem; padding-bottom: 0.75rem; color: #777; text-align: left; caption-side: bottom; } th { text-align: left; } label { display: inline-block; margin-bottom: .5rem; } button:focus { outline: 1px dotted; outline: 5px auto -webkit-focus-ring-color; } input, button, select, textarea { line-height: inherit; } input[type="radio"]:disabled, input[type="checkbox"]:disabled { cursor: not-allowed; } input[type="date"], input[type="time"], input[type="datetime-local"], input[type="month"] { -webkit-appearance: listbox; } textarea { resize: vertical; } fieldset { min-width: 0; padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: .5rem; font-size: 1.5rem; line-height: inherit; } input[type="search"] { -webkit-appearance: none; } output { display: inline-block; } [hidden] { display: none !important; } h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { margin-bottom: 0.5rem; font-family: inherit; font-weight: 500; line-height: 1.1; color: inherit; } h1, .h1 { font-size: 2.5rem; } h2, .h2 { font-size: 2rem; } h3, .h3 { font-size: 1.75rem; } h4, .h4 { font-size: 1.5rem; } h5, .h5 { font-size: 1.25rem; } h6, .h6 { font-size: 1rem; } .lead { font-size: 1.25rem; font-weight: 300; } .display-1 { font-size: 6rem; font-weight: 300; line-height: 1.1; } .display-2 { font-size: 5.5rem; font-weight: 300; line-height: 1.1; } .display-3 { font-size: 4.5rem; font-weight: 300; line-height: 1.1; } .display-4 { font-size: 3.5rem; font-weight: 300; line-height: 1.1; } hr { margin-top: 1rem; margin-bottom: 1rem; border: 0; border-top: 1px solid rgba(0, 0, 0, 0.1); } small, .small { font-size: 80%; font-weight: normal; } mark, .mark { padding: 0.2em; background-color: #fcf8e3; } .list-unstyled { padding-left: 0; list-style: none; } .list-inline { padding-left: 0; list-style: none; } .list-inline-item { display: inline-block; } .list-inline-item:not(:last-child) { margin-right: 5px; } .initialism { font-size: 90%; text-transform: uppercase; } .blockquote { padding: 0.5rem 1rem; margin-bottom: 1rem; font-size: 1.25rem; border-left: 0.25rem solid #AEA79F; } .blockquote-footer { display: block; font-size: 80%; color: #777; } .blockquote-footer::before { content: "\2014 \00A0"; } .blockquote-reverse { padding-right: 1rem; padding-left: 0; text-align: right; border-right: 0.25rem solid #AEA79F; border-left: 0; } .blockquote-reverse .blockquote-footer::before { content: ""; } .blockquote-reverse .blockquote-footer::after { content: "\00A0 \2014"; } .img-fluid { max-width: 100%; height: auto; } .img-thumbnail { padding: 0.25rem; background-color: #fff; border: 1px solid #ddd; border-radius: 0.25rem; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; max-width: 100%; height: auto; } .figure { display: inline-block; } .figure-img { margin-bottom: 0.5rem; line-height: 1; } .figure-caption { font-size: 90%; color: #777; } code, kbd, pre, samp { font-family: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } code { padding: 0.2rem 0.4rem; font-size: 90%; color: #bd4147; background-color: #eee; border-radius: 0.25rem; } a > code { padding: 0; color: inherit; background-color: inherit; } kbd { padding: 0.2rem 0.4rem; font-size: 90%; color: #fff; background-color: #222; border-radius: 0.2rem; } kbd kbd { padding: 0; font-size: 100%; font-weight: bold; } pre { display: block; margin-top: 0; margin-bottom: 1rem; font-size: 90%; color: #222; } pre code { padding: 0; font-size: inherit; color: inherit; background-color: transparent; border-radius: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } .container { position: relative; margin-left: auto; margin-right: auto; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 576px) { .container { width: 540px; max-width: 100%; } } @media (min-width: 768px) { .container { width: 720px; max-width: 100%; } } @media (min-width: 992px) { .container { width: 960px; max-width: 100%; } } @media (min-width: 1200px) { .container { width: 1140px; max-width: 100%; } } .container-fluid { position: relative; margin-left: auto; margin-right: auto; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } .row { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } @media (min-width: 576px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 768px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 992px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 1200px) { .row { margin-right: -15px; margin-left: -15px; } } .no-gutters { margin-right: 0; margin-left: 0; } .no-gutters > .col, .no-gutters > [class*="col-"] { padding-right: 0; padding-left: 0; } .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { position: relative; width: 100%; min-height: 1px; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } .col { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-0 { right: auto; } .pull-1 { right: 8.33333333%; } .pull-2 { right: 16.66666667%; } .pull-3 { right: 25%; } .pull-4 { right: 33.33333333%; } .pull-5 { right: 41.66666667%; } .pull-6 { right: 50%; } .pull-7 { right: 58.33333333%; } .pull-8 { right: 66.66666667%; } .pull-9 { right: 75%; } .pull-10 { right: 83.33333333%; } .pull-11 { right: 91.66666667%; } .pull-12 { right: 100%; } .push-0 { left: auto; } .push-1 { left: 8.33333333%; } .push-2 { left: 16.66666667%; } .push-3 { left: 25%; } .push-4 { left: 33.33333333%; } .push-5 { left: 41.66666667%; } .push-6 { left: 50%; } .push-7 { left: 58.33333333%; } .push-8 { left: 66.66666667%; } .push-9 { left: 75%; } .push-10 { left: 83.33333333%; } .push-11 { left: 91.66666667%; } .push-12 { left: 100%; } .offset-1 { margin-left: 8.33333333%; } .offset-2 { margin-left: 16.66666667%; } .offset-3 { margin-left: 25%; } .offset-4 { margin-left: 33.33333333%; } .offset-5 { margin-left: 41.66666667%; } .offset-6 { margin-left: 50%; } .offset-7 { margin-left: 58.33333333%; } .offset-8 { margin-left: 66.66666667%; } .offset-9 { margin-left: 75%; } .offset-10 { margin-left: 83.33333333%; } .offset-11 { margin-left: 91.66666667%; } @media (min-width: 576px) { .col-sm { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-sm-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-sm-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-sm-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-sm-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-sm-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-sm-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-sm-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-sm-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-sm-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-sm-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-sm-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-sm-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-sm-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-sm-0 { right: auto; } .pull-sm-1 { right: 8.33333333%; } .pull-sm-2 { right: 16.66666667%; } .pull-sm-3 { right: 25%; } .pull-sm-4 { right: 33.33333333%; } .pull-sm-5 { right: 41.66666667%; } .pull-sm-6 { right: 50%; } .pull-sm-7 { right: 58.33333333%; } .pull-sm-8 { right: 66.66666667%; } .pull-sm-9 { right: 75%; } .pull-sm-10 { right: 83.33333333%; } .pull-sm-11 { right: 91.66666667%; } .pull-sm-12 { right: 100%; } .push-sm-0 { left: auto; } .push-sm-1 { left: 8.33333333%; } .push-sm-2 { left: 16.66666667%; } .push-sm-3 { left: 25%; } .push-sm-4 { left: 33.33333333%; } .push-sm-5 { left: 41.66666667%; } .push-sm-6 { left: 50%; } .push-sm-7 { left: 58.33333333%; } .push-sm-8 { left: 66.66666667%; } .push-sm-9 { left: 75%; } .push-sm-10 { left: 83.33333333%; } .push-sm-11 { left: 91.66666667%; } .push-sm-12 { left: 100%; } .offset-sm-0 { margin-left: 0%; } .offset-sm-1 { margin-left: 8.33333333%; } .offset-sm-2 { margin-left: 16.66666667%; } .offset-sm-3 { margin-left: 25%; } .offset-sm-4 { margin-left: 33.33333333%; } .offset-sm-5 { margin-left: 41.66666667%; } .offset-sm-6 { margin-left: 50%; } .offset-sm-7 { margin-left: 58.33333333%; } .offset-sm-8 { margin-left: 66.66666667%; } .offset-sm-9 { margin-left: 75%; } .offset-sm-10 { margin-left: 83.33333333%; } .offset-sm-11 { margin-left: 91.66666667%; } } @media (min-width: 768px) { .col-md { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-md-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-md-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-md-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-md-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-md-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-md-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-md-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-md-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-md-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-md-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-md-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-md-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-md-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-md-0 { right: auto; } .pull-md-1 { right: 8.33333333%; } .pull-md-2 { right: 16.66666667%; } .pull-md-3 { right: 25%; } .pull-md-4 { right: 33.33333333%; } .pull-md-5 { right: 41.66666667%; } .pull-md-6 { right: 50%; } .pull-md-7 { right: 58.33333333%; } .pull-md-8 { right: 66.66666667%; } .pull-md-9 { right: 75%; } .pull-md-10 { right: 83.33333333%; } .pull-md-11 { right: 91.66666667%; } .pull-md-12 { right: 100%; } .push-md-0 { left: auto; } .push-md-1 { left: 8.33333333%; } .push-md-2 { left: 16.66666667%; } .push-md-3 { left: 25%; } .push-md-4 { left: 33.33333333%; } .push-md-5 { left: 41.66666667%; } .push-md-6 { left: 50%; } .push-md-7 { left: 58.33333333%; } .push-md-8 { left: 66.66666667%; } .push-md-9 { left: 75%; } .push-md-10 { left: 83.33333333%; } .push-md-11 { left: 91.66666667%; } .push-md-12 { left: 100%; } .offset-md-0 { margin-left: 0%; } .offset-md-1 { margin-left: 8.33333333%; } .offset-md-2 { margin-left: 16.66666667%; } .offset-md-3 { margin-left: 25%; } .offset-md-4 { margin-left: 33.33333333%; } .offset-md-5 { margin-left: 41.66666667%; } .offset-md-6 { margin-left: 50%; } .offset-md-7 { margin-left: 58.33333333%; } .offset-md-8 { margin-left: 66.66666667%; } .offset-md-9 { margin-left: 75%; } .offset-md-10 { margin-left: 83.33333333%; } .offset-md-11 { margin-left: 91.66666667%; } } @media (min-width: 992px) { .col-lg { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-lg-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-lg-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-lg-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-lg-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-lg-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-lg-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-lg-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-lg-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-lg-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-lg-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-lg-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-lg-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-lg-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-lg-0 { right: auto; } .pull-lg-1 { right: 8.33333333%; } .pull-lg-2 { right: 16.66666667%; } .pull-lg-3 { right: 25%; } .pull-lg-4 { right: 33.33333333%; } .pull-lg-5 { right: 41.66666667%; } .pull-lg-6 { right: 50%; } .pull-lg-7 { right: 58.33333333%; } .pull-lg-8 { right: 66.66666667%; } .pull-lg-9 { right: 75%; } .pull-lg-10 { right: 83.33333333%; } .pull-lg-11 { right: 91.66666667%; } .pull-lg-12 { right: 100%; } .push-lg-0 { left: auto; } .push-lg-1 { left: 8.33333333%; } .push-lg-2 { left: 16.66666667%; } .push-lg-3 { left: 25%; } .push-lg-4 { left: 33.33333333%; } .push-lg-5 { left: 41.66666667%; } .push-lg-6 { left: 50%; } .push-lg-7 { left: 58.33333333%; } .push-lg-8 { left: 66.66666667%; } .push-lg-9 { left: 75%; } .push-lg-10 { left: 83.33333333%; } .push-lg-11 { left: 91.66666667%; } .push-lg-12 { left: 100%; } .offset-lg-0 { margin-left: 0%; } .offset-lg-1 { margin-left: 8.33333333%; } .offset-lg-2 { margin-left: 16.66666667%; } .offset-lg-3 { margin-left: 25%; } .offset-lg-4 { margin-left: 33.33333333%; } .offset-lg-5 { margin-left: 41.66666667%; } .offset-lg-6 { margin-left: 50%; } .offset-lg-7 { margin-left: 58.33333333%; } .offset-lg-8 { margin-left: 66.66666667%; } .offset-lg-9 { margin-left: 75%; } .offset-lg-10 { margin-left: 83.33333333%; } .offset-lg-11 { margin-left: 91.66666667%; } } @media (min-width: 1200px) { .col-xl { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-xl-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-xl-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-xl-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-xl-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-xl-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-xl-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-xl-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-xl-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-xl-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-xl-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-xl-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-xl-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-xl-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-xl-0 { right: auto; } .pull-xl-1 { right: 8.33333333%; } .pull-xl-2 { right: 16.66666667%; } .pull-xl-3 { right: 25%; } .pull-xl-4 { right: 33.33333333%; } .pull-xl-5 { right: 41.66666667%; } .pull-xl-6 { right: 50%; } .pull-xl-7 { right: 58.33333333%; } .pull-xl-8 { right: 66.66666667%; } .pull-xl-9 { right: 75%; } .pull-xl-10 { right: 83.33333333%; } .pull-xl-11 { right: 91.66666667%; } .pull-xl-12 { right: 100%; } .push-xl-0 { left: auto; } .push-xl-1 { left: 8.33333333%; } .push-xl-2 { left: 16.66666667%; } .push-xl-3 { left: 25%; } .push-xl-4 { left: 33.33333333%; } .push-xl-5 { left: 41.66666667%; } .push-xl-6 { left: 50%; } .push-xl-7 { left: 58.33333333%; } .push-xl-8 { left: 66.66666667%; } .push-xl-9 { left: 75%; } .push-xl-10 { left: 83.33333333%; } .push-xl-11 { left: 91.66666667%; } .push-xl-12 { left: 100%; } .offset-xl-0 { margin-left: 0%; } .offset-xl-1 { margin-left: 8.33333333%; } .offset-xl-2 { margin-left: 16.66666667%; } .offset-xl-3 { margin-left: 25%; } .offset-xl-4 { margin-left: 33.33333333%; } .offset-xl-5 { margin-left: 41.66666667%; } .offset-xl-6 { margin-left: 50%; } .offset-xl-7 { margin-left: 58.33333333%; } .offset-xl-8 { margin-left: 66.66666667%; } .offset-xl-9 { margin-left: 75%; } .offset-xl-10 { margin-left: 83.33333333%; } .offset-xl-11 { margin-left: 91.66666667%; } } .table { width: 100%; max-width: 100%; margin-bottom: 1rem; } .table th, .table td { padding: 0.75rem; vertical-align: top; border-top: 1px solid #AEA79F; } .table thead th { vertical-align: bottom; border-bottom: 2px solid #AEA79F; } .table tbody + tbody { border-top: 2px solid #AEA79F; } .table .table { background-color: #fff; } .table-sm th, .table-sm td { padding: 0.3rem; } .table-bordered { border: 1px solid #AEA79F; } .table-bordered th, .table-bordered td { border: 1px solid #AEA79F; } .table-bordered thead th, .table-bordered thead td { border-bottom-width: 2px; } .table-striped tbody tr:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); } .table-hover tbody tr:hover { background-color: rgba(0, 0, 0, 0.075); } .table-active, .table-active > th, .table-active > td { background-color: rgba(0, 0, 0, 0.075); } .table-hover .table-active:hover { background-color: rgba(0, 0, 0, 0.075); } .table-hover .table-active:hover > td, .table-hover .table-active:hover > th { background-color: rgba(0, 0, 0, 0.075); } .table-success, .table-success > th, .table-success > td { background-color: #dff0d8; } .table-hover .table-success:hover { background-color: #d0e9c6; } .table-hover .table-success:hover > td, .table-hover .table-success:hover > th { background-color: #d0e9c6; } .table-info, .table-info > th, .table-info > td { background-color: #d9edf7; } .table-hover .table-info:hover { background-color: #c4e3f3; } .table-hover .table-info:hover > td, .table-hover .table-info:hover > th { background-color: #c4e3f3; } .table-warning, .table-warning > th, .table-warning > td { background-color: #fcf8e3; } .table-hover .table-warning:hover { background-color: #faf2cc; } .table-hover .table-warning:hover > td, .table-hover .table-warning:hover > th { background-color: #faf2cc; } .table-danger, .table-danger > th, .table-danger > td { background-color: #f2dede; } .table-hover .table-danger:hover { background-color: #ebcccc; } .table-hover .table-danger:hover > td, .table-hover .table-danger:hover > th { background-color: #ebcccc; } .thead-inverse th { color: #fff; background-color: #222; } .thead-default th { color: #333; background-color: #AEA79F; } .table-inverse { color: #fff; background-color: #222; } .table-inverse th, .table-inverse td, .table-inverse thead th { border-color: #fff; } .table-inverse.table-bordered { border: 0; } .table-responsive { display: block; width: 100%; overflow-x: auto; -ms-overflow-style: -ms-autohiding-scrollbar; } .table-responsive.table-bordered { border: 0; } .form-control { display: block; width: 100%; padding: 0.5rem 0.75rem; font-size: 1rem; line-height: 1.25; color: #333; background-color: #fff; background-image: none; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; -webkit-transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; -o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; } .form-control::-ms-expand { background-color: transparent; border: 0; } .form-control:focus { color: #333; background-color: #fff; border-color: #f4ad94; outline: none; } .form-control::-webkit-input-placeholder { color: #777; opacity: 1; } .form-control::-moz-placeholder { color: #777; opacity: 1; } .form-control:-ms-input-placeholder { color: #777; opacity: 1; } .form-control::placeholder { color: #777; opacity: 1; } .form-control:disabled, .form-control[readonly] { background-color: #eee; opacity: 1; } .form-control:disabled { cursor: not-allowed; } select.form-control:not([size]):not([multiple]) { height: calc(2.25rem + 2px); } select.form-control:focus::-ms-value { color: #333; background-color: #fff; } .form-control-file, .form-control-range { display: block; } .col-form-label { padding-top: calc(0.5rem - 1px * 2); padding-bottom: calc(0.5rem - 1px * 2); margin-bottom: 0; } .col-form-label-lg { padding-top: calc(0.75rem - 1px * 2); padding-bottom: calc(0.75rem - 1px * 2); font-size: 1.25rem; } .col-form-label-sm { padding-top: calc(0.25rem - 1px * 2); padding-bottom: calc(0.25rem - 1px * 2); font-size: 0.875rem; } .col-form-legend { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-bottom: 0; font-size: 1rem; } .form-control-static { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-bottom: 0; line-height: 1.25; border: solid transparent; border-width: 1px 0; } .form-control-static.form-control-sm, .input-group-sm > .form-control-static.form-control, .input-group-sm > .form-control-static.input-group-addon, .input-group-sm > .input-group-btn > .form-control-static.btn, .form-control-static.form-control-lg, .input-group-lg > .form-control-static.form-control, .input-group-lg > .form-control-static.input-group-addon, .input-group-lg > .input-group-btn > .form-control-static.btn { padding-right: 0; padding-left: 0; } .form-control-sm, .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } select.form-control-sm:not([size]):not([multiple]), .input-group-sm > select.form-control:not([size]):not([multiple]), .input-group-sm > select.input-group-addon:not([size]):not([multiple]), .input-group-sm > .input-group-btn > select.btn:not([size]):not([multiple]) { height: 1.8125rem; } .form-control-lg, .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } select.form-control-lg:not([size]):not([multiple]), .input-group-lg > select.form-control:not([size]):not([multiple]), .input-group-lg > select.input-group-addon:not([size]):not([multiple]), .input-group-lg > .input-group-btn > select.btn:not([size]):not([multiple]) { height: 3.16666667rem; } .form-group { margin-bottom: 1rem; } .form-text { display: block; margin-top: 0.25rem; } .form-check { position: relative; display: block; margin-bottom: 0.5rem; } .form-check.disabled .form-check-label { color: #777; cursor: not-allowed; } .form-check-label { padding-left: 1.25rem; margin-bottom: 0; cursor: pointer; } .form-check-input { position: absolute; margin-top: 0.25rem; margin-left: -1.25rem; } .form-check-input:only-child { position: static; } .form-check-inline { display: inline-block; } .form-check-inline .form-check-label { vertical-align: middle; } .form-check-inline + .form-check-inline { margin-left: 0.75rem; } .form-control-feedback { margin-top: 0.25rem; } .form-control-success, .form-control-warning, .form-control-danger { padding-right: 2.25rem; background-repeat: no-repeat; background-position: center right 0.5625rem; -webkit-background-size: 1.125rem 1.125rem; background-size: 1.125rem 1.125rem; } .has-success .form-control-feedback, .has-success .form-control-label, .has-success .col-form-label, .has-success .form-check-label, .has-success .custom-control { color: #38B44A; } .has-success .form-control { border-color: #38B44A; } .has-success .input-group-addon { color: #38B44A; border-color: #38B44A; background-color: #caeecf; } .has-success .form-control-success { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%2338B44A' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3E%3C/svg%3E"); } .has-warning .form-control-feedback, .has-warning .form-control-label, .has-warning .col-form-label, .has-warning .form-check-label, .has-warning .custom-control { color: #EFB73E; } .has-warning .form-control { border-color: #EFB73E; } .has-warning .input-group-addon { color: #EFB73E; border-color: #EFB73E; background-color: #fffdfa; } .has-warning .form-control-warning { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23EFB73E' d='M4.4 5.324h-.8v-2.46h.8zm0 1.42h-.8V5.89h.8zM3.76.63L.04 7.075c-.115.2.016.425.26.426h7.397c.242 0 .372-.226.258-.426C6.726 4.924 5.47 2.79 4.253.63c-.113-.174-.39-.174-.494 0z'/%3E%3C/svg%3E"); } .has-danger .form-control-feedback, .has-danger .form-control-label, .has-danger .col-form-label, .has-danger .form-check-label, .has-danger .custom-control { color: #DF382C; } .has-danger .form-control { border-color: #DF382C; } .has-danger .input-group-addon { color: #DF382C; border-color: #DF382C; background-color: #fadfdd; } .has-danger .form-control-danger { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23DF382C' viewBox='-2 -2 7 7'%3E%3Cpath stroke='%23d9534f' d='M0 0l3 3m0-3L0 3'/%3E%3Ccircle r='.5'/%3E%3Ccircle cx='3' r='.5'/%3E%3Ccircle cy='3' r='.5'/%3E%3Ccircle cx='3' cy='3' r='.5'/%3E%3C/svg%3E"); } .form-inline { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .form-inline .form-check { width: 100%; } @media (min-width: 576px) { .form-inline label { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; margin-bottom: 0; } .form-inline .form-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; margin-bottom: 0; } .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; } .form-inline .form-control-static { display: inline-block; } .form-inline .input-group { width: auto; } .form-inline .form-control-label { margin-bottom: 0; vertical-align: middle; } .form-inline .form-check { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; width: auto; margin-top: 0; margin-bottom: 0; } .form-inline .form-check-label { padding-left: 0; } .form-inline .form-check-input { position: relative; margin-top: 0; margin-right: 0.25rem; margin-left: 0; } .form-inline .custom-control { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; padding-left: 0; } .form-inline .custom-control-indicator { position: static; display: inline-block; margin-right: 0.25rem; vertical-align: text-bottom; } .form-inline .has-feedback .form-control-feedback { top: 0; } } .btn { display: inline-block; font-weight: normal; line-height: 1.25; text-align: center; white-space: nowrap; vertical-align: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; border: 1px solid transparent; padding: 0.5rem 1rem; font-size: 1rem; border-radius: 0.25rem; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .btn:focus, .btn:hover { text-decoration: none; } .btn:focus, .btn.focus { outline: 0; -webkit-box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.25); box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.25); } .btn.disabled, .btn:disabled { cursor: not-allowed; opacity: .65; } .btn:active, .btn.active { background-image: none; } a.btn.disabled, fieldset[disabled] a.btn { pointer-events: none; } .btn-primary { color: #fff; background-color: #E95420; border-color: #E95420; } .btn-primary:hover { color: #fff; background-color: #c34113; border-color: #b93e12; } .btn-primary:focus, .btn-primary.focus { -webkit-box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); } .btn-primary.disabled, .btn-primary:disabled { background-color: #E95420; border-color: #E95420; } .btn-primary:active, .btn-primary.active, .show > .btn-primary.dropdown-toggle { color: #fff; background-color: #c34113; background-image: none; border-color: #b93e12; } .btn-secondary { color: #fff; background-color: #AEA79F; border-color: #AEA79F; } .btn-secondary:hover { color: #fff; background-color: #978e83; border-color: #92897e; } .btn-secondary:focus, .btn-secondary.focus { -webkit-box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); } .btn-secondary.disabled, .btn-secondary:disabled { background-color: #AEA79F; border-color: #AEA79F; } .btn-secondary:active, .btn-secondary.active, .show > .btn-secondary.dropdown-toggle { color: #fff; background-color: #978e83; background-image: none; border-color: #92897e; } .btn-info { color: #fff; background-color: #772953; border-color: #772953; } .btn-info:hover { color: #fff; background-color: #511c39; border-color: #491933; } .btn-info:focus, .btn-info.focus { -webkit-box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); } .btn-info.disabled, .btn-info:disabled { background-color: #772953; border-color: #772953; } .btn-info:active, .btn-info.active, .show > .btn-info.dropdown-toggle { color: #fff; background-color: #511c39; background-image: none; border-color: #491933; } .btn-success { color: #fff; background-color: #38B44A; border-color: #38B44A; } .btn-success:hover { color: #fff; background-color: #2c8d3a; border-color: #298537; } .btn-success:focus, .btn-success.focus { -webkit-box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); } .btn-success.disabled, .btn-success:disabled { background-color: #38B44A; border-color: #38B44A; } .btn-success:active, .btn-success.active, .show > .btn-success.dropdown-toggle { color: #fff; background-color: #2c8d3a; background-image: none; border-color: #298537; } .btn-warning { color: #fff; background-color: #EFB73E; border-color: #EFB73E; } .btn-warning:hover { color: #fff; background-color: #e7a413; border-color: #dd9d12; } .btn-warning:focus, .btn-warning.focus { -webkit-box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); } .btn-warning.disabled, .btn-warning:disabled { background-color: #EFB73E; border-color: #EFB73E; } .btn-warning:active, .btn-warning.active, .show > .btn-warning.dropdown-toggle { color: #fff; background-color: #e7a413; background-image: none; border-color: #dd9d12; } .btn-danger { color: #fff; background-color: #DF382C; border-color: #DF382C; } .btn-danger:hover { color: #fff; background-color: #bc271c; border-color: #b3251b; } .btn-danger:focus, .btn-danger.focus { -webkit-box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); } .btn-danger.disabled, .btn-danger:disabled { background-color: #DF382C; border-color: #DF382C; } .btn-danger:active, .btn-danger.active, .show > .btn-danger.dropdown-toggle { color: #fff; background-color: #bc271c; background-image: none; border-color: #b3251b; } .btn-outline-primary { color: #E95420; background-image: none; background-color: transparent; border-color: #E95420; } .btn-outline-primary:hover { color: #fff; background-color: #E95420; border-color: #E95420; } .btn-outline-primary:focus, .btn-outline-primary.focus { -webkit-box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); } .btn-outline-primary.disabled, .btn-outline-primary:disabled { color: #E95420; background-color: transparent; } .btn-outline-primary:active, .btn-outline-primary.active, .show > .btn-outline-primary.dropdown-toggle { color: #fff; background-color: #E95420; border-color: #E95420; } .btn-outline-secondary { color: #AEA79F; background-image: none; background-color: transparent; border-color: #AEA79F; } .btn-outline-secondary:hover { color: #fff; background-color: #AEA79F; border-color: #AEA79F; } .btn-outline-secondary:focus, .btn-outline-secondary.focus { -webkit-box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); } .btn-outline-secondary.disabled, .btn-outline-secondary:disabled { color: #AEA79F; background-color: transparent; } .btn-outline-secondary:active, .btn-outline-secondary.active, .show > .btn-outline-secondary.dropdown-toggle { color: #fff; background-color: #AEA79F; border-color: #AEA79F; } .btn-outline-info { color: #772953; background-image: none; background-color: transparent; border-color: #772953; } .btn-outline-info:hover { color: #fff; background-color: #772953; border-color: #772953; } .btn-outline-info:focus, .btn-outline-info.focus { -webkit-box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); } .btn-outline-info.disabled, .btn-outline-info:disabled { color: #772953; background-color: transparent; } .btn-outline-info:active, .btn-outline-info.active, .show > .btn-outline-info.dropdown-toggle { color: #fff; background-color: #772953; border-color: #772953; } .btn-outline-success { color: #38B44A; background-image: none; background-color: transparent; border-color: #38B44A; } .btn-outline-success:hover { color: #fff; background-color: #38B44A; border-color: #38B44A; } .btn-outline-success:focus, .btn-outline-success.focus { -webkit-box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); } .btn-outline-success.disabled, .btn-outline-success:disabled { color: #38B44A; background-color: transparent; } .btn-outline-success:active, .btn-outline-success.active, .show > .btn-outline-success.dropdown-toggle { color: #fff; background-color: #38B44A; border-color: #38B44A; } .btn-outline-warning { color: #EFB73E; background-image: none; background-color: transparent; border-color: #EFB73E; } .btn-outline-warning:hover { color: #fff; background-color: #EFB73E; border-color: #EFB73E; } .btn-outline-warning:focus, .btn-outline-warning.focus { -webkit-box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); } .btn-outline-warning.disabled, .btn-outline-warning:disabled { color: #EFB73E; background-color: transparent; } .btn-outline-warning:active, .btn-outline-warning.active, .show > .btn-outline-warning.dropdown-toggle { color: #fff; background-color: #EFB73E; border-color: #EFB73E; } .btn-outline-danger { color: #DF382C; background-image: none; background-color: transparent; border-color: #DF382C; } .btn-outline-danger:hover { color: #fff; background-color: #DF382C; border-color: #DF382C; } .btn-outline-danger:focus, .btn-outline-danger.focus { -webkit-box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); } .btn-outline-danger.disabled, .btn-outline-danger:disabled { color: #DF382C; background-color: transparent; } .btn-outline-danger:active, .btn-outline-danger.active, .show > .btn-outline-danger.dropdown-toggle { color: #fff; background-color: #DF382C; border-color: #DF382C; } .btn-link { font-weight: normal; color: #E95420; border-radius: 0; } .btn-link, .btn-link:active, .btn-link.active, .btn-link:disabled { background-color: transparent; } .btn-link, .btn-link:focus, .btn-link:active { border-color: transparent; } .btn-link:hover { border-color: transparent; } .btn-link:focus, .btn-link:hover { color: #ac3911; text-decoration: underline; background-color: transparent; } .btn-link:disabled { color: #777; } .btn-link:disabled:focus, .btn-link:disabled:hover { text-decoration: none; } .btn-lg, .btn-group-lg > .btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } .btn-sm, .btn-group-sm > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } .btn-block { display: block; width: 100%; } .btn-block + .btn-block { margin-top: 0.5rem; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; -o-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.show { opacity: 1; } .collapse { display: none; } .collapse.show { display: block; } tr.collapse.show { display: table-row; } tbody.collapse.show { display: table-row-group; } .collapsing { position: relative; height: 0; overflow: hidden; -webkit-transition: height 0.35s ease; -o-transition: height 0.35s ease; transition: height 0.35s ease; } .dropup, .dropdown { position: relative; } .dropdown-toggle::after { display: inline-block; width: 0; height: 0; margin-left: 0.3em; vertical-align: middle; content: ""; border-top: 0.3em solid; border-right: 0.3em solid transparent; border-left: 0.3em solid transparent; } .dropdown-toggle:focus { outline: 0; } .dropup .dropdown-toggle::after { border-top: 0; border-bottom: 0.3em solid; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 10rem; padding: 0.5rem 0; margin: 0.125rem 0 0; font-size: 1rem; color: #333; text-align: left; list-style: none; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .dropdown-divider { height: 1px; margin: 0.5rem 0; overflow: hidden; background-color: #AEA79F; } .dropdown-item { display: block; width: 100%; padding: 3px 1.5rem; clear: both; font-weight: normal; color: #222; text-align: inherit; white-space: nowrap; background: none; border: 0; } .dropdown-item:focus, .dropdown-item:hover { color: #151515; text-decoration: none; background-color: #eee; } .dropdown-item.active, .dropdown-item:active { color: #fff; text-decoration: none; background-color: #E95420; } .dropdown-item.disabled, .dropdown-item:disabled { color: #777; cursor: not-allowed; background-color: transparent; } .show > .dropdown-menu { display: block; } .show > a { outline: 0; } .dropdown-menu-right { right: 0; left: auto; } .dropdown-menu-left { right: auto; left: 0; } .dropdown-header { display: block; padding: 0.5rem 1.5rem; margin-bottom: 0; font-size: 0.875rem; color: #777; white-space: nowrap; } .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 990; } .dropup .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 0.125rem; } .btn-group, .btn-group-vertical { position: relative; display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; vertical-align: middle; } .btn-group > .btn, .btn-group-vertical > .btn { position: relative; -webkit-box-flex: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; } .btn-group > .btn:hover, .btn-group-vertical > .btn:hover { z-index: 2; } .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn:focus, .btn-group-vertical > .btn:active, .btn-group-vertical > .btn.active { z-index: 2; } .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group, .btn-group-vertical .btn + .btn, .btn-group-vertical .btn + .btn-group, .btn-group-vertical .btn-group + .btn, .btn-group-vertical .btn-group + .btn-group { margin-left: -1px; } .btn-toolbar { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -webkit-justify-content: flex-start; -ms-flex-pack: start; justify-content: flex-start; } .btn-toolbar .input-group { width: auto; } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } .btn-group > .btn:first-child { margin-left: 0; } .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-bottom-right-radius: 0; border-top-right-radius: 0; } .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-top-right-radius: 0; } .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn + .dropdown-toggle-split { padding-right: 0.75rem; padding-left: 0.75rem; } .btn + .dropdown-toggle-split::after { margin-left: 0; } .btn-sm + .dropdown-toggle-split, .btn-group-sm > .btn + .dropdown-toggle-split { padding-right: 0.375rem; padding-left: 0.375rem; } .btn-lg + .dropdown-toggle-split, .btn-group-lg > .btn + .dropdown-toggle-split { padding-right: 1.125rem; padding-left: 1.125rem; } .btn-group-vertical { display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-align: start; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .btn-group-vertical .btn, .btn-group-vertical .btn-group { width: 100%; } .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; } .btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; } .btn-group-vertical > .btn:first-child:not(:last-child) { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn:last-child:not(:first-child) { border-top-right-radius: 0; border-top-left-radius: 0; } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { border-top-right-radius: 0; border-top-left-radius: 0; } [data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { position: absolute; clip: rect(0, 0, 0, 0); pointer-events: none; } .input-group { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; width: 100%; } .input-group .form-control { position: relative; z-index: 2; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } .input-group .form-control:focus, .input-group .form-control:active, .input-group .form-control:hover { z-index: 3; } .input-group-addon, .input-group-btn, .input-group .form-control { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { border-radius: 0; } .input-group-addon, .input-group-btn { white-space: nowrap; vertical-align: middle; } .input-group-addon { padding: 0.5rem 0.75rem; margin-bottom: 0; font-size: 1rem; font-weight: normal; line-height: 1.25; color: #333; text-align: center; background-color: #eee; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .input-group-addon.form-control-sm, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .input-group-addon.btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } .input-group-addon.form-control-lg, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .input-group-addon.btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { margin-top: 0; } .input-group .form-control:not(:last-child), .input-group-addon:not(:last-child), .input-group-btn:not(:last-child) > .btn, .input-group-btn:not(:last-child) > .btn-group > .btn, .input-group-btn:not(:last-child) > .dropdown-toggle, .input-group-btn:not(:first-child) > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:not(:first-child) > .btn-group:not(:last-child) > .btn { border-bottom-right-radius: 0; border-top-right-radius: 0; } .input-group-addon:not(:last-child) { border-right: 0; } .input-group .form-control:not(:first-child), .input-group-addon:not(:first-child), .input-group-btn:not(:first-child) > .btn, .input-group-btn:not(:first-child) > .btn-group > .btn, .input-group-btn:not(:first-child) > .dropdown-toggle, .input-group-btn:not(:last-child) > .btn:not(:first-child), .input-group-btn:not(:last-child) > .btn-group:not(:first-child) > .btn { border-bottom-left-radius: 0; border-top-left-radius: 0; } .form-control + .input-group-addon:not(:first-child) { border-left: 0; } .input-group-btn { position: relative; font-size: 0; white-space: nowrap; } .input-group-btn > .btn { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 0%; -ms-flex: 1 1 0%; flex: 1 1 0%; } .input-group-btn > .btn + .btn { margin-left: -1px; } .input-group-btn > .btn:focus, .input-group-btn > .btn:active, .input-group-btn > .btn:hover { z-index: 3; } .input-group-btn:not(:last-child) > .btn, .input-group-btn:not(:last-child) > .btn-group { margin-right: -1px; } .input-group-btn:not(:first-child) > .btn, .input-group-btn:not(:first-child) > .btn-group { z-index: 2; margin-left: -1px; } .input-group-btn:not(:first-child) > .btn:focus, .input-group-btn:not(:first-child) > .btn:active, .input-group-btn:not(:first-child) > .btn:hover, .input-group-btn:not(:first-child) > .btn-group:focus, .input-group-btn:not(:first-child) > .btn-group:active, .input-group-btn:not(:first-child) > .btn-group:hover { z-index: 3; } .custom-control { position: relative; display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; min-height: 1.5rem; padding-left: 1.5rem; margin-right: 1rem; cursor: pointer; } .custom-control-input { position: absolute; z-index: -1; opacity: 0; } .custom-control-input:checked ~ .custom-control-indicator { color: #fff; background-color: #E95420; } .custom-control-input:focus ~ .custom-control-indicator { -webkit-box-shadow: 0 0 0 1px #fff, 0 0 0 3px #E95420; box-shadow: 0 0 0 1px #fff, 0 0 0 3px #E95420; } .custom-control-input:active ~ .custom-control-indicator { color: #fff; background-color: #f9d1c2; } .custom-control-input:disabled ~ .custom-control-indicator { cursor: not-allowed; background-color: #AEA79F; } .custom-control-input:disabled ~ .custom-control-description { color: #777; cursor: not-allowed; } .custom-control-indicator { position: absolute; top: 0.25rem; left: 0; display: block; width: 1rem; height: 1rem; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: #ddd; background-repeat: no-repeat; background-position: center center; -webkit-background-size: 50% 50%; background-size: 50% 50%; } .custom-checkbox .custom-control-indicator { border-radius: 0.25rem; } .custom-checkbox .custom-control-input:checked ~ .custom-control-indicator { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E"); } .custom-checkbox .custom-control-input:indeterminate ~ .custom-control-indicator { background-color: #E95420; background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3E%3Cpath stroke='%23fff' d='M0 2h4'/%3E%3C/svg%3E"); } .custom-radio .custom-control-indicator { border-radius: 50%; } .custom-radio .custom-control-input:checked ~ .custom-control-indicator { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3E%3Ccircle r='3' fill='%23fff'/%3E%3C/svg%3E"); } .custom-controls-stacked { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .custom-controls-stacked .custom-control { margin-bottom: 0.25rem; } .custom-controls-stacked .custom-control + .custom-control { margin-left: 0; } .custom-select { display: inline-block; max-width: 100%; height: calc(2.25rem + 2px); padding: 0.375rem 1.75rem 0.375rem 0.75rem; line-height: 1.25; color: #333; vertical-align: middle; background: #fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23333' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right 0.75rem center; -webkit-background-size: 8px 10px; background-size: 8px 10px; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; -moz-appearance: none; -webkit-appearance: none; } .custom-select:focus { border-color: #f4ad94; outline: none; } .custom-select:focus::-ms-value { color: #333; background-color: #fff; } .custom-select:disabled { color: #777; cursor: not-allowed; background-color: #AEA79F; } .custom-select::-ms-expand { opacity: 0; } .custom-select-sm { padding-top: 0.375rem; padding-bottom: 0.375rem; font-size: 75%; } .custom-file { position: relative; display: inline-block; max-width: 100%; height: 2.5rem; margin-bottom: 0; cursor: pointer; } .custom-file-input { min-width: 14rem; max-width: 100%; height: 2.5rem; margin: 0; filter: alpha(opacity=0); opacity: 0; } .custom-file-control { position: absolute; top: 0; right: 0; left: 0; z-index: 5; height: 2.5rem; padding: 0.5rem 1rem; line-height: 1.5; color: #333; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .custom-file-control:lang(en)::after { content: "Choose file..."; } .custom-file-control::before { position: absolute; top: -1px; right: -1px; bottom: -1px; z-index: 6; display: block; height: 2.5rem; padding: 0.5rem 1rem; line-height: 1.5; color: #333; background-color: #AEA79F; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0 0.25rem 0.25rem 0; } .custom-file-control:lang(en)::before { content: "Browse"; } .nav { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding-left: 0; margin-bottom: 0; list-style: none; } .nav-link { display: block; padding: 0.5em 1em; } .nav-link:focus, .nav-link:hover { text-decoration: none; } .nav-link.disabled { color: #777; cursor: not-allowed; } .nav-tabs { border-bottom: 1px solid #ddd; } .nav-tabs .nav-item { margin-bottom: -1px; } .nav-tabs .nav-link { border: 1px solid transparent; border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .nav-tabs .nav-link:focus, .nav-tabs .nav-link:hover { border-color: #AEA79F #AEA79F #ddd; } .nav-tabs .nav-link.disabled { color: #777; background-color: transparent; border-color: transparent; } .nav-tabs .nav-link.active, .nav-tabs .nav-item.show .nav-link { color: #333; background-color: #fff; border-color: #ddd #ddd #fff; } .nav-tabs .dropdown-menu { margin-top: -1px; border-top-right-radius: 0; border-top-left-radius: 0; } .nav-pills .nav-link { border-radius: 0.25rem; } .nav-pills .nav-link.active, .nav-pills .nav-item.show .nav-link { color: #fff; cursor: default; background-color: #E95420; } .nav-fill .nav-item { -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; text-align: center; } .nav-justified .nav-item { -webkit-box-flex: 1; -webkit-flex: 1 1 100%; -ms-flex: 1 1 100%; flex: 1 1 100%; text-align: center; } .tab-content > .tab-pane { display: none; } .tab-content > .active { display: block; } .navbar { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; padding: 0.5rem 1rem; } .navbar-brand { display: inline-block; padding-top: .25rem; padding-bottom: .25rem; margin-right: 1rem; font-size: 1.25rem; line-height: inherit; white-space: nowrap; } .navbar-brand:focus, .navbar-brand:hover { text-decoration: none; } .navbar-nav { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; list-style: none; } .navbar-nav .nav-link { padding-right: 0; padding-left: 0; } .navbar-text { display: inline-block; padding-top: .425rem; padding-bottom: .425rem; } .navbar-toggler { -webkit-align-self: flex-start; -ms-flex-item-align: start; align-self: flex-start; padding: 0.25rem 0.75rem; font-size: 1.25rem; line-height: 1; background: transparent; border: 1px solid transparent; border-radius: 0.25rem; } .navbar-toggler:focus, .navbar-toggler:hover { text-decoration: none; } .navbar-toggler-icon { display: inline-block; width: 1.5em; height: 1.5em; vertical-align: middle; content: ""; background: no-repeat center center; -webkit-background-size: 100% 100%; background-size: 100% 100%; } .navbar-toggler-left { position: absolute; left: 1rem; } .navbar-toggler-right { position: absolute; right: 1rem; } @media (max-width: 575px) { .navbar-toggleable .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 576px) { .navbar-toggleable { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable .navbar-toggler { display: none; } } @media (max-width: 767px) { .navbar-toggleable-sm .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-sm > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 768px) { .navbar-toggleable-sm { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-sm .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-sm .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-sm > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-sm .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-sm .navbar-toggler { display: none; } } @media (max-width: 991px) { .navbar-toggleable-md .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-md > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 992px) { .navbar-toggleable-md { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-md .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-md .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-md > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-md .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-md .navbar-toggler { display: none; } } @media (max-width: 1199px) { .navbar-toggleable-lg .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-lg > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 1200px) { .navbar-toggleable-lg { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-lg .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-lg .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-lg > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-lg .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-lg .navbar-toggler { display: none; } } .navbar-toggleable-xl { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-xl .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-xl > .container { padding-right: 0; padding-left: 0; } .navbar-toggleable-xl .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-xl .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-xl > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-xl .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-xl .navbar-toggler { display: none; } .navbar-light .navbar-brand, .navbar-light .navbar-toggler { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-brand:focus, .navbar-light .navbar-brand:hover, .navbar-light .navbar-toggler:focus, .navbar-light .navbar-toggler:hover { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-nav .nav-link { color: rgba(0, 0, 0, 0.5); } .navbar-light .navbar-nav .nav-link:focus, .navbar-light .navbar-nav .nav-link:hover { color: rgba(0, 0, 0, 0.7); } .navbar-light .navbar-nav .nav-link.disabled { color: rgba(0, 0, 0, 0.3); } .navbar-light .navbar-nav .open > .nav-link, .navbar-light .navbar-nav .active > .nav-link, .navbar-light .navbar-nav .nav-link.open, .navbar-light .navbar-nav .nav-link.active { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-toggler { border-color: rgba(0, 0, 0, 0.1); } .navbar-light .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E"); } .navbar-light .navbar-text { color: rgba(0, 0, 0, 0.5); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-toggler { color: white; } .navbar-inverse .navbar-brand:focus, .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-toggler:focus, .navbar-inverse .navbar-toggler:hover { color: white; } .navbar-inverse .navbar-nav .nav-link { color: rgba(255, 255, 255, 0.75); } .navbar-inverse .navbar-nav .nav-link:focus, .navbar-inverse .navbar-nav .nav-link:hover { color: white; } .navbar-inverse .navbar-nav .nav-link.disabled { color: rgba(255, 255, 255, 0.25); } .navbar-inverse .navbar-nav .open > .nav-link, .navbar-inverse .navbar-nav .active > .nav-link, .navbar-inverse .navbar-nav .nav-link.open, .navbar-inverse .navbar-nav .nav-link.active { color: white; } .navbar-inverse .navbar-toggler { border-color: rgba(255, 255, 255, 0.1); } .navbar-inverse .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255, 255, 255, 0.75)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E"); } .navbar-inverse .navbar-text { color: rgba(255, 255, 255, 0.75); } .card { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); border-radius: 0.25rem; } .card-block { -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 1.25rem; } .card-title { margin-bottom: 0.75rem; } .card-subtitle { margin-top: -0.375rem; margin-bottom: 0; } .card-text:last-child { margin-bottom: 0; } .card-link:hover { text-decoration: none; } .card-link + .card-link { margin-left: 1.25rem; } .card > .list-group:first-child .list-group-item:first-child { border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .card > .list-group:last-child .list-group-item:last-child { border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .card-header { padding: 0.75rem 1.25rem; margin-bottom: 0; background-color: #eee; border-bottom: 1px solid rgba(0, 0, 0, 0.125); } .card-header:first-child { border-radius: calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0; } .card-footer { padding: 0.75rem 1.25rem; background-color: #eee; border-top: 1px solid rgba(0, 0, 0, 0.125); } .card-footer:last-child { border-radius: 0 0 calc(0.25rem - 1px) calc(0.25rem - 1px); } .card-header-tabs { margin-right: -0.625rem; margin-bottom: -0.75rem; margin-left: -0.625rem; border-bottom: 0; } .card-header-pills { margin-right: -0.625rem; margin-left: -0.625rem; } .card-primary { background-color: #E95420; border-color: #E95420; } .card-primary .card-header, .card-primary .card-footer { background-color: transparent; } .card-success { background-color: #38B44A; border-color: #38B44A; } .card-success .card-header, .card-success .card-footer { background-color: transparent; } .card-info { background-color: #772953; border-color: #772953; } .card-info .card-header, .card-info .card-footer { background-color: transparent; } .card-warning { background-color: #EFB73E; border-color: #EFB73E; } .card-warning .card-header, .card-warning .card-footer { background-color: transparent; } .card-danger { background-color: #DF382C; border-color: #DF382C; } .card-danger .card-header, .card-danger .card-footer { background-color: transparent; } .card-outline-primary { background-color: transparent; border-color: #E95420; } .card-outline-secondary { background-color: transparent; border-color: #AEA79F; } .card-outline-info { background-color: transparent; border-color: #772953; } .card-outline-success { background-color: transparent; border-color: #38B44A; } .card-outline-warning { background-color: transparent; border-color: #EFB73E; } .card-outline-danger { background-color: transparent; border-color: #DF382C; } .card-inverse { color: rgba(255, 255, 255, 0.65); } .card-inverse .card-header, .card-inverse .card-footer { background-color: transparent; border-color: rgba(255, 255, 255, 0.2); } .card-inverse .card-header, .card-inverse .card-footer, .card-inverse .card-title, .card-inverse .card-blockquote { color: #fff; } .card-inverse .card-link, .card-inverse .card-text, .card-inverse .card-subtitle, .card-inverse .card-blockquote .blockquote-footer { color: rgba(255, 255, 255, 0.65); } .card-inverse .card-link:focus, .card-inverse .card-link:hover { color: #fff; } .card-blockquote { padding: 0; margin-bottom: 0; border-left: 0; } .card-img { border-radius: calc(0.25rem - 1px); } .card-img-overlay { position: absolute; top: 0; right: 0; bottom: 0; left: 0; padding: 1.25rem; } .card-img-top { border-top-right-radius: calc(0.25rem - 1px); border-top-left-radius: calc(0.25rem - 1px); } .card-img-bottom { border-bottom-right-radius: calc(0.25rem - 1px); border-bottom-left-radius: calc(0.25rem - 1px); } @media (min-width: 576px) { .card-deck { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; } .card-deck .card { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -webkit-flex: 1 0 0%; -ms-flex: 1 0 0%; flex: 1 0 0%; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .card-deck .card:not(:first-child) { margin-left: 15px; } .card-deck .card:not(:last-child) { margin-right: 15px; } } @media (min-width: 576px) { .card-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; } .card-group .card { -webkit-box-flex: 1; -webkit-flex: 1 0 0%; -ms-flex: 1 0 0%; flex: 1 0 0%; } .card-group .card + .card { margin-left: 0; border-left: 0; } .card-group .card:first-child { border-bottom-right-radius: 0; border-top-right-radius: 0; } .card-group .card:first-child .card-img-top { border-top-right-radius: 0; } .card-group .card:first-child .card-img-bottom { border-bottom-right-radius: 0; } .card-group .card:last-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } .card-group .card:last-child .card-img-top { border-top-left-radius: 0; } .card-group .card:last-child .card-img-bottom { border-bottom-left-radius: 0; } .card-group .card:not(:first-child):not(:last-child) { border-radius: 0; } .card-group .card:not(:first-child):not(:last-child) .card-img-top, .card-group .card:not(:first-child):not(:last-child) .card-img-bottom { border-radius: 0; } } @media (min-width: 576px) { .card-columns { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 1.25rem; -moz-column-gap: 1.25rem; column-gap: 1.25rem; } .card-columns .card { display: inline-block; width: 100%; margin-bottom: 0.75rem; } } .breadcrumb { padding: 0.75rem 1rem; margin-bottom: 1rem; list-style: none; background-color: #eee; border-radius: 0.25rem; } .breadcrumb::after { display: block; content: ""; clear: both; } .breadcrumb-item { float: left; } .breadcrumb-item + .breadcrumb-item::before { display: inline-block; padding-right: 0.5rem; padding-left: 0.5rem; color: #777; content: "/"; } .breadcrumb-item + .breadcrumb-item:hover::before { text-decoration: underline; } .breadcrumb-item + .breadcrumb-item:hover::before { text-decoration: none; } .breadcrumb-item.active { color: #777; } .pagination { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding-left: 0; list-style: none; border-radius: 0.25rem; } .page-item:first-child .page-link { margin-left: 0; border-bottom-left-radius: 0.25rem; border-top-left-radius: 0.25rem; } .page-item:last-child .page-link { border-bottom-right-radius: 0.25rem; border-top-right-radius: 0.25rem; } .page-item.active .page-link { z-index: 2; color: #fff; background-color: #E95420; border-color: #E95420; } .page-item.disabled .page-link { color: #777; pointer-events: none; cursor: not-allowed; background-color: #fff; border-color: #ddd; } .page-link { position: relative; display: block; padding: 0.5rem 0.75rem; margin-left: -1px; line-height: 1.25; color: #E95420; background-color: #fff; border: 1px solid #ddd; } .page-link:focus, .page-link:hover { color: #ac3911; text-decoration: none; background-color: #AEA79F; border-color: #ddd; } .pagination-lg .page-link { padding: 0.75rem 1.5rem; font-size: 1.25rem; } .pagination-lg .page-item:first-child .page-link { border-bottom-left-radius: 0.3rem; border-top-left-radius: 0.3rem; } .pagination-lg .page-item:last-child .page-link { border-bottom-right-radius: 0.3rem; border-top-right-radius: 0.3rem; } .pagination-sm .page-link { padding: 0.25rem 0.5rem; font-size: 0.875rem; } .pagination-sm .page-item:first-child .page-link { border-bottom-left-radius: 0.2rem; border-top-left-radius: 0.2rem; } .pagination-sm .page-item:last-child .page-link { border-bottom-right-radius: 0.2rem; border-top-right-radius: 0.2rem; } .badge { display: inline-block; padding: 0.25em 0.4em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: 0.25rem; } .badge:empty { display: none; } .btn .badge { position: relative; top: -1px; } a.badge:focus, a.badge:hover { color: #fff; text-decoration: none; cursor: pointer; } .badge-pill { padding-right: 0.6em; padding-left: 0.6em; border-radius: 10rem; } .badge-default { background-color: #777; } .badge-default[href]:focus, .badge-default[href]:hover { background-color: #5e5e5e; } .badge-primary { background-color: #E95420; } .badge-primary[href]:focus, .badge-primary[href]:hover { background-color: #c34113; } .badge-success { background-color: #38B44A; } .badge-success[href]:focus, .badge-success[href]:hover { background-color: #2c8d3a; } .badge-info { background-color: #772953; } .badge-info[href]:focus, .badge-info[href]:hover { background-color: #511c39; } .badge-warning { background-color: #EFB73E; } .badge-warning[href]:focus, .badge-warning[href]:hover { background-color: #e7a413; } .badge-danger { background-color: #DF382C; } .badge-danger[href]:focus, .badge-danger[href]:hover { background-color: #bc271c; } .jumbotron { padding: 2rem 1rem; margin-bottom: 2rem; background-color: #eee; border-radius: 0.3rem; } @media (min-width: 576px) { .jumbotron { padding: 4rem 2rem; } } .jumbotron-hr { border-top-color: #d5d5d5; } .jumbotron-fluid { padding-right: 0; padding-left: 0; border-radius: 0; } .alert { padding: 0.75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: 0.25rem; } .alert-heading { color: inherit; } .alert-link { font-weight: bold; } .alert-dismissible .close { position: relative; top: -0.75rem; right: -1.25rem; padding: 0.75rem 1.25rem; color: inherit; } .alert-success { background-color: #dff0d8; border-color: #d0e9c6; color: #3c763d; } .alert-success hr { border-top-color: #c1e2b3; } .alert-success .alert-link { color: #2b542c; } .alert-info { background-color: #d9edf7; border-color: #bcdff1; color: #31708f; } .alert-info hr { border-top-color: #a6d5ec; } .alert-info .alert-link { color: #245269; } .alert-warning { background-color: #fcf8e3; border-color: #faf2cc; color: #8a6d3b; } .alert-warning hr { border-top-color: #f7ecb5; } .alert-warning .alert-link { color: #66512c; } .alert-danger { background-color: #f2dede; border-color: #ebcccc; color: #a94442; } .alert-danger hr { border-top-color: #e4b9b9; } .alert-danger .alert-link { color: #843534; } @-webkit-keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; } } @-o-keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; } } @keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; } } .progress { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; overflow: hidden; font-size: 0.75rem; line-height: 1rem; text-align: center; background-color: #AEA79F; border-radius: 0.25rem; } .progress-bar { height: 1rem; color: #E95420; background-color: #E95420; } .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -webkit-background-size: 1rem 1rem; background-size: 1rem 1rem; } .progress-bar-animated { -webkit-animation: progress-bar-stripes 1s linear infinite; -o-animation: progress-bar-stripes 1s linear infinite; animation: progress-bar-stripes 1s linear infinite; } .media { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: start; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; } .media-body { -webkit-box-flex: 1; -webkit-flex: 1 1 0%; -ms-flex: 1 1 0%; flex: 1 1 0%; } .list-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; } .list-group-item-action { width: 100%; color: #333; text-align: inherit; } .list-group-item-action .list-group-item-heading { color: #222; } .list-group-item-action:focus, .list-group-item-action:hover { color: #333; text-decoration: none; background-color: #eee; } .list-group-item-action:active { color: #333; background-color: #AEA79F; } .list-group-item { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; padding: 0.75rem 1.25rem; margin-bottom: -1px; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); } .list-group-item:first-child { border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .list-group-item:last-child { margin-bottom: 0; border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .list-group-item:focus, .list-group-item:hover { text-decoration: none; } .list-group-item.disabled, .list-group-item:disabled { color: #777; cursor: not-allowed; background-color: #eee; } .list-group-item.disabled .list-group-item-heading, .list-group-item:disabled .list-group-item-heading { color: inherit; } .list-group-item.disabled .list-group-item-text, .list-group-item:disabled .list-group-item-text { color: #777; } .list-group-item.active { z-index: 2; color: #fff; background-color: #E95420; border-color: #E95420; } .list-group-item.active .list-group-item-heading, .list-group-item.active .list-group-item-heading > small, .list-group-item.active .list-group-item-heading > .small { color: inherit; } .list-group-item.active .list-group-item-text { color: white; } .list-group-flush .list-group-item { border-right: 0; border-left: 0; border-radius: 0; } .list-group-flush:first-child .list-group-item:first-child { border-top: 0; } .list-group-flush:last-child .list-group-item:last-child { border-bottom: 0; } .list-group-item-success { color: #3c763d; background-color: #dff0d8; } a.list-group-item-success, button.list-group-item-success { color: #3c763d; } a.list-group-item-success .list-group-item-heading, button.list-group-item-success .list-group-item-heading { color: inherit; } a.list-group-item-success:focus, a.list-group-item-success:hover, button.list-group-item-success:focus, button.list-group-item-success:hover { color: #3c763d; background-color: #d0e9c6; } a.list-group-item-success.active, button.list-group-item-success.active { color: #fff; background-color: #3c763d; border-color: #3c763d; } .list-group-item-info { color: #31708f; background-color: #d9edf7; } a.list-group-item-info, button.list-group-item-info { color: #31708f; } a.list-group-item-info .list-group-item-heading, button.list-group-item-info .list-group-item-heading { color: inherit; } a.list-group-item-info:focus, a.list-group-item-info:hover, button.list-group-item-info:focus, button.list-group-item-info:hover { color: #31708f; background-color: #c4e3f3; } a.list-group-item-info.active, button.list-group-item-info.active { color: #fff; background-color: #31708f; border-color: #31708f; } .list-group-item-warning { color: #8a6d3b; background-color: #fcf8e3; } a.list-group-item-warning, button.list-group-item-warning { color: #8a6d3b; } a.list-group-item-warning .list-group-item-heading, button.list-group-item-warning .list-group-item-heading { color: inherit; } a.list-group-item-warning:focus, a.list-group-item-warning:hover, button.list-group-item-warning:focus, button.list-group-item-warning:hover { color: #8a6d3b; background-color: #faf2cc; } a.list-group-item-warning.active, button.list-group-item-warning.active { color: #fff; background-color: #8a6d3b; border-color: #8a6d3b; } .list-group-item-danger { color: #a94442; background-color: #f2dede; } a.list-group-item-danger, button.list-group-item-danger { color: #a94442; } a.list-group-item-danger .list-group-item-heading, button.list-group-item-danger .list-group-item-heading { color: inherit; } a.list-group-item-danger:focus, a.list-group-item-danger:hover, button.list-group-item-danger:focus, button.list-group-item-danger:hover { color: #a94442; background-color: #ebcccc; } a.list-group-item-danger.active, button.list-group-item-danger.active { color: #fff; background-color: #a94442; border-color: #a94442; } .embed-responsive { position: relative; display: block; width: 100%; padding: 0; overflow: hidden; } .embed-responsive::before { display: block; content: ""; } .embed-responsive .embed-responsive-item, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object, .embed-responsive video { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } .embed-responsive-21by9::before { padding-top: 42.85714286%; } .embed-responsive-16by9::before { padding-top: 56.25%; } .embed-responsive-4by3::before { padding-top: 75%; } .embed-responsive-1by1::before { padding-top: 100%; } .close { float: right; font-size: 1.5rem; font-weight: bold; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; opacity: .5; } .close:focus, .close:hover { color: #000; text-decoration: none; cursor: pointer; opacity: .75; } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .modal-open { overflow: hidden; } .modal { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1050; display: none; overflow: hidden; outline: 0; } .modal.fade .modal-dialog { -webkit-transition: -webkit-transform 0.3s ease-out; transition: -webkit-transform 0.3s ease-out; -o-transition: -o-transform 0.3s ease-out; transition: transform 0.3s ease-out; transition: transform 0.3s ease-out, -webkit-transform 0.3s ease-out, -o-transform 0.3s ease-out; -webkit-transform: translate(0, -25%); -ms-transform: translate(0, -25%); -o-transform: translate(0, -25%); transform: translate(0, -25%); } .modal.show .modal-dialog { -webkit-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0); } .modal-open .modal { overflow-x: hidden; overflow-y: auto; } .modal-dialog { position: relative; width: auto; margin: 10px; } .modal-content { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 0.3rem; outline: 0; } .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000; } .modal-backdrop.fade { opacity: 0; } .modal-backdrop.show { opacity: 0.5; } .modal-header { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; padding: 15px; border-bottom: 1px solid #AEA79F; } .modal-title { margin-bottom: 0; line-height: 1.5; } .modal-body { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 15px; } .modal-footer { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: end; -webkit-justify-content: flex-end; -ms-flex-pack: end; justify-content: flex-end; padding: 15px; border-top: 1px solid #AEA79F; } .modal-footer > :not(:first-child) { margin-left: .25rem; } .modal-footer > :not(:last-child) { margin-right: .25rem; } .modal-scrollbar-measure { position: absolute; top: -9999px; width: 50px; height: 50px; overflow: scroll; } @media (min-width: 576px) { .modal-dialog { max-width: 500px; margin: 30px auto; } .modal-sm { max-width: 300px; } } @media (min-width: 992px) { .modal-lg { max-width: 800px; } } .tooltip { position: absolute; z-index: 1070; display: block; font-family: "Ubuntu", Tahoma, "Helvetica Neue", Helvetica, Arial, sans-serif; font-style: normal; font-weight: normal; letter-spacing: normal; line-break: auto; line-height: 1.5; text-align: left; text-align: start; text-decoration: none; text-shadow: none; text-transform: none; white-space: normal; word-break: normal; word-spacing: normal; font-size: 0.875rem; word-wrap: break-word; opacity: 0; } .tooltip.show { opacity: 0.9; } .tooltip.tooltip-top, .tooltip.bs-tether-element-attached-bottom { padding: 5px 0; margin-top: -3px; } .tooltip.tooltip-top .tooltip-inner::before, .tooltip.bs-tether-element-attached-bottom .tooltip-inner::before { bottom: 0; left: 50%; margin-left: -5px; content: ""; border-width: 5px 5px 0; border-top-color: #000; } .tooltip.tooltip-right, .tooltip.bs-tether-element-attached-left { padding: 0 5px; margin-left: 3px; } .tooltip.tooltip-right .tooltip-inner::before, .tooltip.bs-tether-element-attached-left .tooltip-inner::before { top: 50%; left: 0; margin-top: -5px; content: ""; border-width: 5px 5px 5px 0; border-right-color: #000; } .tooltip.tooltip-bottom, .tooltip.bs-tether-element-attached-top { padding: 5px 0; margin-top: 3px; } .tooltip.tooltip-bottom .tooltip-inner::before, .tooltip.bs-tether-element-attached-top .tooltip-inner::before { top: 0; left: 50%; margin-left: -5px; content: ""; border-width: 0 5px 5px; border-bottom-color: #000; } .tooltip.tooltip-left, .tooltip.bs-tether-element-attached-right { padding: 0 5px; margin-left: -3px; } .tooltip.tooltip-left .tooltip-inner::before, .tooltip.bs-tether-element-attached-right .tooltip-inner::before { top: 50%; right: 0; margin-top: -5px; content: ""; border-width: 5px 0 5px 5px; border-left-color: #000; } .tooltip-inner { max-width: 200px; padding: 3px 8px; color: #fff; text-align: center; background-color: #000; border-radius: 0.25rem; } .tooltip-inner::before { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover { position: absolute; top: 0; left: 0; z-index: 1060; display: block; max-width: 276px; padding: 1px; font-family: "Ubuntu", Tahoma, "Helvetica Neue", Helvetica, Arial, sans-serif; font-style: normal; font-weight: normal; letter-spacing: normal; line-break: auto; line-height: 1.5; text-align: left; text-align: start; text-decoration: none; text-shadow: none; text-transform: none; white-space: normal; word-break: normal; word-spacing: normal; font-size: 0.875rem; word-wrap: break-word; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 0.3rem; } .popover.popover-top, .popover.bs-tether-element-attached-bottom { margin-top: -10px; } .popover.popover-top::before, .popover.popover-top::after, .popover.bs-tether-element-attached-bottom::before, .popover.bs-tether-element-attached-bottom::after { left: 50%; border-bottom-width: 0; } .popover.popover-top::before, .popover.bs-tether-element-attached-bottom::before { bottom: -11px; margin-left: -11px; border-top-color: rgba(0, 0, 0, 0.25); } .popover.popover-top::after, .popover.bs-tether-element-attached-bottom::after { bottom: -10px; margin-left: -10px; border-top-color: #fff; } .popover.popover-right, .popover.bs-tether-element-attached-left { margin-left: 10px; } .popover.popover-right::before, .popover.popover-right::after, .popover.bs-tether-element-attached-left::before, .popover.bs-tether-element-attached-left::after { top: 50%; border-left-width: 0; } .popover.popover-right::before, .popover.bs-tether-element-attached-left::before { left: -11px; margin-top: -11px; border-right-color: rgba(0, 0, 0, 0.25); } .popover.popover-right::after, .popover.bs-tether-element-attached-left::after { left: -10px; margin-top: -10px; border-right-color: #fff; } .popover.popover-bottom, .popover.bs-tether-element-attached-top { margin-top: 10px; } .popover.popover-bottom::before, .popover.popover-bottom::after, .popover.bs-tether-element-attached-top::before, .popover.bs-tether-element-attached-top::after { left: 50%; border-top-width: 0; } .popover.popover-bottom::before, .popover.bs-tether-element-attached-top::before { top: -11px; margin-left: -11px; border-bottom-color: rgba(0, 0, 0, 0.25); } .popover.popover-bottom::after, .popover.bs-tether-element-attached-top::after { top: -10px; margin-left: -10px; border-bottom-color: #f7f7f7; } .popover.popover-bottom .popover-title::before, .popover.bs-tether-element-attached-top .popover-title::before { position: absolute; top: 0; left: 50%; display: block; width: 20px; margin-left: -10px; content: ""; border-bottom: 1px solid #f7f7f7; } .popover.popover-left, .popover.bs-tether-element-attached-right { margin-left: -10px; } .popover.popover-left::before, .popover.popover-left::after, .popover.bs-tether-element-attached-right::before, .popover.bs-tether-element-attached-right::after { top: 50%; border-right-width: 0; } .popover.popover-left::before, .popover.bs-tether-element-attached-right::before { right: -11px; margin-top: -11px; border-left-color: rgba(0, 0, 0, 0.25); } .popover.popover-left::after, .popover.bs-tether-element-attached-right::after { right: -10px; margin-top: -10px; border-left-color: #fff; } .popover-title { padding: 8px 14px; margin-bottom: 0; font-size: 1rem; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; border-top-right-radius: calc(0.3rem - 1px); border-top-left-radius: calc(0.3rem - 1px); } .popover-title:empty { display: none; } .popover-content { padding: 9px 14px; } .popover::before, .popover::after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover::before { content: ""; border-width: 11px; } .popover::after { content: ""; border-width: 10px; } .carousel { position: relative; } .carousel-inner { position: relative; width: 100%; overflow: hidden; } .carousel-item { position: relative; display: none; width: 100%; } @media (-webkit-transform-3d) { .carousel-item { -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: -webkit-transform 0.6s ease-in-out; -o-transition: -o-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out, -o-transform 0.6s ease-in-out; -webkit-backface-visibility: hidden; backface-visibility: hidden; -webkit-perspective: 1000px; perspective: 1000px; } } @supports ((-webkit-transform: translate3d(0, 0, 0)) or (transform: translate3d(0, 0, 0))) { .carousel-item { -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: -webkit-transform 0.6s ease-in-out; -o-transition: -o-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out, -o-transform 0.6s ease-in-out; -webkit-backface-visibility: hidden; backface-visibility: hidden; -webkit-perspective: 1000px; perspective: 1000px; } } .carousel-item.active, .carousel-item-next, .carousel-item-prev { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } .carousel-item-next, .carousel-item-prev { position: absolute; top: 0; } @media (-webkit-transform-3d) { .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .carousel-item-next, .active.carousel-item-right { -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-item-prev, .active.carousel-item-left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } @supports ((-webkit-transform: translate3d(0, 0, 0)) or (transform: translate3d(0, 0, 0))) { .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .carousel-item-next, .active.carousel-item-right { -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-item-prev, .active.carousel-item-left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } .carousel-control-prev, .carousel-control-next { position: absolute; top: 0; bottom: 0; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; width: 15%; color: #fff; text-align: center; opacity: 0.5; } .carousel-control-prev:focus, .carousel-control-prev:hover, .carousel-control-next:focus, .carousel-control-next:hover { color: #fff; text-decoration: none; outline: 0; opacity: .9; } .carousel-control-prev { left: 0; } .carousel-control-next { right: 0; } .carousel-control-prev-icon, .carousel-control-next-icon { display: inline-block; width: 20px; height: 20px; background: transparent no-repeat center center; -webkit-background-size: 100% 100%; background-size: 100% 100%; } .carousel-control-prev-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M4 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); } .carousel-control-next-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M1.5 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E"); } .carousel-indicators { position: absolute; right: 0; bottom: 10px; left: 0; z-index: 15; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; padding-left: 0; margin-right: 15%; margin-left: 15%; list-style: none; } .carousel-indicators li { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 0 auto; -ms-flex: 1 0 auto; flex: 1 0 auto; max-width: 30px; height: 3px; margin-right: 3px; margin-left: 3px; text-indent: -999px; cursor: pointer; background-color: rgba(255, 255, 255, 0.5); } .carousel-indicators li::before { position: absolute; top: -10px; left: 0; display: inline-block; width: 100%; height: 10px; content: ""; } .carousel-indicators li::after { position: absolute; bottom: -10px; left: 0; display: inline-block; width: 100%; height: 10px; content: ""; } .carousel-indicators .active { background-color: #fff; } .carousel-caption { position: absolute; right: 15%; bottom: 20px; left: 15%; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: #fff; text-align: center; } .align-baseline { vertical-align: baseline !important; } .align-top { vertical-align: top !important; } .align-middle { vertical-align: middle !important; } .align-bottom { vertical-align: bottom !important; } .align-text-bottom { vertical-align: text-bottom !important; } .align-text-top { vertical-align: text-top !important; } .bg-faded { background-color: #f7f7f7; } .bg-primary { background-color: #E95420 !important; } a.bg-primary:focus, a.bg-primary:hover { background-color: #c34113 !important; } .bg-success { background-color: #38B44A !important; } a.bg-success:focus, a.bg-success:hover { background-color: #2c8d3a !important; } .bg-info { background-color: #772953 !important; } a.bg-info:focus, a.bg-info:hover { background-color: #511c39 !important; } .bg-warning { background-color: #EFB73E !important; } a.bg-warning:focus, a.bg-warning:hover { background-color: #e7a413 !important; } .bg-danger { background-color: #DF382C !important; } a.bg-danger:focus, a.bg-danger:hover { background-color: #bc271c !important; } .bg-inverse { background-color: #222 !important; } a.bg-inverse:focus, a.bg-inverse:hover { background-color: #090909 !important; } .border-0 { border: 0 !important; } .border-top-0 { border-top: 0 !important; } .border-right-0 { border-right: 0 !important; } .border-bottom-0 { border-bottom: 0 !important; } .border-left-0 { border-left: 0 !important; } .rounded { border-radius: 0.25rem; } .rounded-top { border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .rounded-right { border-bottom-right-radius: 0.25rem; border-top-right-radius: 0.25rem; } .rounded-bottom { border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .rounded-left { border-bottom-left-radius: 0.25rem; border-top-left-radius: 0.25rem; } .rounded-circle { border-radius: 50%; } .rounded-0 { border-radius: 0; } .clearfix::after { display: block; content: ""; clear: both; } .d-none { display: none !important; } .d-inline { display: inline !important; } .d-inline-block { display: inline-block !important; } .d-block { display: block !important; } .d-table { display: table !important; } .d-table-cell { display: table-cell !important; } .d-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } @media (min-width: 576px) { .d-sm-none { display: none !important; } .d-sm-inline { display: inline !important; } .d-sm-inline-block { display: inline-block !important; } .d-sm-block { display: block !important; } .d-sm-table { display: table !important; } .d-sm-table-cell { display: table-cell !important; } .d-sm-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-sm-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 768px) { .d-md-none { display: none !important; } .d-md-inline { display: inline !important; } .d-md-inline-block { display: inline-block !important; } .d-md-block { display: block !important; } .d-md-table { display: table !important; } .d-md-table-cell { display: table-cell !important; } .d-md-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-md-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 992px) { .d-lg-none { display: none !important; } .d-lg-inline { display: inline !important; } .d-lg-inline-block { display: inline-block !important; } .d-lg-block { display: block !important; } .d-lg-table { display: table !important; } .d-lg-table-cell { display: table-cell !important; } .d-lg-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-lg-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 1200px) { .d-xl-none { display: none !important; } .d-xl-inline { display: inline !important; } .d-xl-inline-block { display: inline-block !important; } .d-xl-block { display: block !important; } .d-xl-table { display: table !important; } .d-xl-table-cell { display: table-cell !important; } .d-xl-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-xl-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } .flex-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } @media (min-width: 576px) { .flex-sm-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-sm-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-sm-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-sm-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-sm-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-sm-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-sm-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-sm-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-sm-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-sm-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-sm-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-sm-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-sm-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-sm-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-sm-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-sm-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-sm-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-sm-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-sm-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-sm-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-sm-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-sm-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-sm-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-sm-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-sm-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-sm-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-sm-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-sm-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-sm-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-sm-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-sm-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-sm-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 768px) { .flex-md-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-md-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-md-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-md-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-md-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-md-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-md-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-md-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-md-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-md-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-md-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-md-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-md-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-md-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-md-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-md-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-md-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-md-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-md-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-md-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-md-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-md-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-md-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-md-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-md-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-md-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-md-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-md-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-md-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-md-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-md-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-md-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 992px) { .flex-lg-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-lg-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-lg-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-lg-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-lg-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-lg-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-lg-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-lg-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-lg-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-lg-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-lg-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-lg-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-lg-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-lg-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-lg-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-lg-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-lg-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-lg-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-lg-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-lg-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-lg-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-lg-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-lg-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-lg-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-lg-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-lg-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-lg-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-lg-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-lg-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-lg-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-lg-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-lg-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 1200px) { .flex-xl-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-xl-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-xl-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-xl-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-xl-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-xl-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-xl-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-xl-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-xl-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-xl-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-xl-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-xl-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-xl-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-xl-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-xl-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-xl-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-xl-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-xl-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-xl-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-xl-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-xl-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-xl-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-xl-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-xl-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-xl-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-xl-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-xl-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-xl-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-xl-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-xl-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-xl-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-xl-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } .float-left { float: left !important; } .float-right { float: right !important; } .float-none { float: none !important; } @media (min-width: 576px) { .float-sm-left { float: left !important; } .float-sm-right { float: right !important; } .float-sm-none { float: none !important; } } @media (min-width: 768px) { .float-md-left { float: left !important; } .float-md-right { float: right !important; } .float-md-none { float: none !important; } } @media (min-width: 992px) { .float-lg-left { float: left !important; } .float-lg-right { float: right !important; } .float-lg-none { float: none !important; } } @media (min-width: 1200px) { .float-xl-left { float: left !important; } .float-xl-right { float: right !important; } .float-xl-none { float: none !important; } } .fixed-top { position: fixed; top: 0; right: 0; left: 0; z-index: 1030; } .fixed-bottom { position: fixed; right: 0; bottom: 0; left: 0; z-index: 1030; } .sticky-top { position: -webkit-sticky; position: sticky; top: 0; z-index: 1030; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } .sr-only-focusable:active, .sr-only-focusable:focus { position: static; width: auto; height: auto; margin: 0; overflow: visible; clip: auto; } .w-25 { width: 25% !important; } .w-50 { width: 50% !important; } .w-75 { width: 75% !important; } .w-100 { width: 100% !important; } .h-25 { height: 25% !important; } .h-50 { height: 50% !important; } .h-75 { height: 75% !important; } .h-100 { height: 100% !important; } .mw-100 { max-width: 100% !important; } .mh-100 { max-height: 100% !important; } .m-0 { margin: 0 0 !important; } .mt-0 { margin-top: 0 !important; } .mr-0 { margin-right: 0 !important; } .mb-0 { margin-bottom: 0 !important; } .ml-0 { margin-left: 0 !important; } .mx-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-1 { margin: 0.25rem 0.25rem !important; } .mt-1 { margin-top: 0.25rem !important; } .mr-1 { margin-right: 0.25rem !important; } .mb-1 { margin-bottom: 0.25rem !important; } .ml-1 { margin-left: 0.25rem !important; } .mx-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-2 { margin: 0.5rem 0.5rem !important; } .mt-2 { margin-top: 0.5rem !important; } .mr-2 { margin-right: 0.5rem !important; } .mb-2 { margin-bottom: 0.5rem !important; } .ml-2 { margin-left: 0.5rem !important; } .mx-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-3 { margin: 1rem 1rem !important; } .mt-3 { margin-top: 1rem !important; } .mr-3 { margin-right: 1rem !important; } .mb-3 { margin-bottom: 1rem !important; } .ml-3 { margin-left: 1rem !important; } .mx-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-4 { margin: 1.5rem 1.5rem !important; } .mt-4 { margin-top: 1.5rem !important; } .mr-4 { margin-right: 1.5rem !important; } .mb-4 { margin-bottom: 1.5rem !important; } .ml-4 { margin-left: 1.5rem !important; } .mx-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-5 { margin: 3rem 3rem !important; } .mt-5 { margin-top: 3rem !important; } .mr-5 { margin-right: 3rem !important; } .mb-5 { margin-bottom: 3rem !important; } .ml-5 { margin-left: 3rem !important; } .mx-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-0 { padding: 0 0 !important; } .pt-0 { padding-top: 0 !important; } .pr-0 { padding-right: 0 !important; } .pb-0 { padding-bottom: 0 !important; } .pl-0 { padding-left: 0 !important; } .px-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-1 { padding: 0.25rem 0.25rem !important; } .pt-1 { padding-top: 0.25rem !important; } .pr-1 { padding-right: 0.25rem !important; } .pb-1 { padding-bottom: 0.25rem !important; } .pl-1 { padding-left: 0.25rem !important; } .px-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-2 { padding: 0.5rem 0.5rem !important; } .pt-2 { padding-top: 0.5rem !important; } .pr-2 { padding-right: 0.5rem !important; } .pb-2 { padding-bottom: 0.5rem !important; } .pl-2 { padding-left: 0.5rem !important; } .px-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-3 { padding: 1rem 1rem !important; } .pt-3 { padding-top: 1rem !important; } .pr-3 { padding-right: 1rem !important; } .pb-3 { padding-bottom: 1rem !important; } .pl-3 { padding-left: 1rem !important; } .px-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-4 { padding: 1.5rem 1.5rem !important; } .pt-4 { padding-top: 1.5rem !important; } .pr-4 { padding-right: 1.5rem !important; } .pb-4 { padding-bottom: 1.5rem !important; } .pl-4 { padding-left: 1.5rem !important; } .px-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-5 { padding: 3rem 3rem !important; } .pt-5 { padding-top: 3rem !important; } .pr-5 { padding-right: 3rem !important; } .pb-5 { padding-bottom: 3rem !important; } .pl-5 { padding-left: 3rem !important; } .px-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-auto { margin: auto !important; } .mt-auto { margin-top: auto !important; } .mr-auto { margin-right: auto !important; } .mb-auto { margin-bottom: auto !important; } .ml-auto { margin-left: auto !important; } .mx-auto { margin-right: auto !important; margin-left: auto !important; } .my-auto { margin-top: auto !important; margin-bottom: auto !important; } @media (min-width: 576px) { .m-sm-0 { margin: 0 0 !important; } .mt-sm-0 { margin-top: 0 !important; } .mr-sm-0 { margin-right: 0 !important; } .mb-sm-0 { margin-bottom: 0 !important; } .ml-sm-0 { margin-left: 0 !important; } .mx-sm-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-sm-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-sm-1 { margin: 0.25rem 0.25rem !important; } .mt-sm-1 { margin-top: 0.25rem !important; } .mr-sm-1 { margin-right: 0.25rem !important; } .mb-sm-1 { margin-bottom: 0.25rem !important; } .ml-sm-1 { margin-left: 0.25rem !important; } .mx-sm-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-sm-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-sm-2 { margin: 0.5rem 0.5rem !important; } .mt-sm-2 { margin-top: 0.5rem !important; } .mr-sm-2 { margin-right: 0.5rem !important; } .mb-sm-2 { margin-bottom: 0.5rem !important; } .ml-sm-2 { margin-left: 0.5rem !important; } .mx-sm-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-sm-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-sm-3 { margin: 1rem 1rem !important; } .mt-sm-3 { margin-top: 1rem !important; } .mr-sm-3 { margin-right: 1rem !important; } .mb-sm-3 { margin-bottom: 1rem !important; } .ml-sm-3 { margin-left: 1rem !important; } .mx-sm-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-sm-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-sm-4 { margin: 1.5rem 1.5rem !important; } .mt-sm-4 { margin-top: 1.5rem !important; } .mr-sm-4 { margin-right: 1.5rem !important; } .mb-sm-4 { margin-bottom: 1.5rem !important; } .ml-sm-4 { margin-left: 1.5rem !important; } .mx-sm-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-sm-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-sm-5 { margin: 3rem 3rem !important; } .mt-sm-5 { margin-top: 3rem !important; } .mr-sm-5 { margin-right: 3rem !important; } .mb-sm-5 { margin-bottom: 3rem !important; } .ml-sm-5 { margin-left: 3rem !important; } .mx-sm-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-sm-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-sm-0 { padding: 0 0 !important; } .pt-sm-0 { padding-top: 0 !important; } .pr-sm-0 { padding-right: 0 !important; } .pb-sm-0 { padding-bottom: 0 !important; } .pl-sm-0 { padding-left: 0 !important; } .px-sm-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-sm-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-sm-1 { padding: 0.25rem 0.25rem !important; } .pt-sm-1 { padding-top: 0.25rem !important; } .pr-sm-1 { padding-right: 0.25rem !important; } .pb-sm-1 { padding-bottom: 0.25rem !important; } .pl-sm-1 { padding-left: 0.25rem !important; } .px-sm-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-sm-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-sm-2 { padding: 0.5rem 0.5rem !important; } .pt-sm-2 { padding-top: 0.5rem !important; } .pr-sm-2 { padding-right: 0.5rem !important; } .pb-sm-2 { padding-bottom: 0.5rem !important; } .pl-sm-2 { padding-left: 0.5rem !important; } .px-sm-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-sm-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-sm-3 { padding: 1rem 1rem !important; } .pt-sm-3 { padding-top: 1rem !important; } .pr-sm-3 { padding-right: 1rem !important; } .pb-sm-3 { padding-bottom: 1rem !important; } .pl-sm-3 { padding-left: 1rem !important; } .px-sm-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-sm-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-sm-4 { padding: 1.5rem 1.5rem !important; } .pt-sm-4 { padding-top: 1.5rem !important; } .pr-sm-4 { padding-right: 1.5rem !important; } .pb-sm-4 { padding-bottom: 1.5rem !important; } .pl-sm-4 { padding-left: 1.5rem !important; } .px-sm-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-sm-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-sm-5 { padding: 3rem 3rem !important; } .pt-sm-5 { padding-top: 3rem !important; } .pr-sm-5 { padding-right: 3rem !important; } .pb-sm-5 { padding-bottom: 3rem !important; } .pl-sm-5 { padding-left: 3rem !important; } .px-sm-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-sm-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-sm-auto { margin: auto !important; } .mt-sm-auto { margin-top: auto !important; } .mr-sm-auto { margin-right: auto !important; } .mb-sm-auto { margin-bottom: auto !important; } .ml-sm-auto { margin-left: auto !important; } .mx-sm-auto { margin-right: auto !important; margin-left: auto !important; } .my-sm-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 768px) { .m-md-0 { margin: 0 0 !important; } .mt-md-0 { margin-top: 0 !important; } .mr-md-0 { margin-right: 0 !important; } .mb-md-0 { margin-bottom: 0 !important; } .ml-md-0 { margin-left: 0 !important; } .mx-md-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-md-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-md-1 { margin: 0.25rem 0.25rem !important; } .mt-md-1 { margin-top: 0.25rem !important; } .mr-md-1 { margin-right: 0.25rem !important; } .mb-md-1 { margin-bottom: 0.25rem !important; } .ml-md-1 { margin-left: 0.25rem !important; } .mx-md-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-md-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-md-2 { margin: 0.5rem 0.5rem !important; } .mt-md-2 { margin-top: 0.5rem !important; } .mr-md-2 { margin-right: 0.5rem !important; } .mb-md-2 { margin-bottom: 0.5rem !important; } .ml-md-2 { margin-left: 0.5rem !important; } .mx-md-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-md-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-md-3 { margin: 1rem 1rem !important; } .mt-md-3 { margin-top: 1rem !important; } .mr-md-3 { margin-right: 1rem !important; } .mb-md-3 { margin-bottom: 1rem !important; } .ml-md-3 { margin-left: 1rem !important; } .mx-md-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-md-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-md-4 { margin: 1.5rem 1.5rem !important; } .mt-md-4 { margin-top: 1.5rem !important; } .mr-md-4 { margin-right: 1.5rem !important; } .mb-md-4 { margin-bottom: 1.5rem !important; } .ml-md-4 { margin-left: 1.5rem !important; } .mx-md-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-md-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-md-5 { margin: 3rem 3rem !important; } .mt-md-5 { margin-top: 3rem !important; } .mr-md-5 { margin-right: 3rem !important; } .mb-md-5 { margin-bottom: 3rem !important; } .ml-md-5 { margin-left: 3rem !important; } .mx-md-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-md-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-md-0 { padding: 0 0 !important; } .pt-md-0 { padding-top: 0 !important; } .pr-md-0 { padding-right: 0 !important; } .pb-md-0 { padding-bottom: 0 !important; } .pl-md-0 { padding-left: 0 !important; } .px-md-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-md-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-md-1 { padding: 0.25rem 0.25rem !important; } .pt-md-1 { padding-top: 0.25rem !important; } .pr-md-1 { padding-right: 0.25rem !important; } .pb-md-1 { padding-bottom: 0.25rem !important; } .pl-md-1 { padding-left: 0.25rem !important; } .px-md-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-md-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-md-2 { padding: 0.5rem 0.5rem !important; } .pt-md-2 { padding-top: 0.5rem !important; } .pr-md-2 { padding-right: 0.5rem !important; } .pb-md-2 { padding-bottom: 0.5rem !important; } .pl-md-2 { padding-left: 0.5rem !important; } .px-md-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-md-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-md-3 { padding: 1rem 1rem !important; } .pt-md-3 { padding-top: 1rem !important; } .pr-md-3 { padding-right: 1rem !important; } .pb-md-3 { padding-bottom: 1rem !important; } .pl-md-3 { padding-left: 1rem !important; } .px-md-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-md-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-md-4 { padding: 1.5rem 1.5rem !important; } .pt-md-4 { padding-top: 1.5rem !important; } .pr-md-4 { padding-right: 1.5rem !important; } .pb-md-4 { padding-bottom: 1.5rem !important; } .pl-md-4 { padding-left: 1.5rem !important; } .px-md-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-md-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-md-5 { padding: 3rem 3rem !important; } .pt-md-5 { padding-top: 3rem !important; } .pr-md-5 { padding-right: 3rem !important; } .pb-md-5 { padding-bottom: 3rem !important; } .pl-md-5 { padding-left: 3rem !important; } .px-md-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-md-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-md-auto { margin: auto !important; } .mt-md-auto { margin-top: auto !important; } .mr-md-auto { margin-right: auto !important; } .mb-md-auto { margin-bottom: auto !important; } .ml-md-auto { margin-left: auto !important; } .mx-md-auto { margin-right: auto !important; margin-left: auto !important; } .my-md-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 992px) { .m-lg-0 { margin: 0 0 !important; } .mt-lg-0 { margin-top: 0 !important; } .mr-lg-0 { margin-right: 0 !important; } .mb-lg-0 { margin-bottom: 0 !important; } .ml-lg-0 { margin-left: 0 !important; } .mx-lg-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-lg-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-lg-1 { margin: 0.25rem 0.25rem !important; } .mt-lg-1 { margin-top: 0.25rem !important; } .mr-lg-1 { margin-right: 0.25rem !important; } .mb-lg-1 { margin-bottom: 0.25rem !important; } .ml-lg-1 { margin-left: 0.25rem !important; } .mx-lg-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-lg-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-lg-2 { margin: 0.5rem 0.5rem !important; } .mt-lg-2 { margin-top: 0.5rem !important; } .mr-lg-2 { margin-right: 0.5rem !important; } .mb-lg-2 { margin-bottom: 0.5rem !important; } .ml-lg-2 { margin-left: 0.5rem !important; } .mx-lg-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-lg-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-lg-3 { margin: 1rem 1rem !important; } .mt-lg-3 { margin-top: 1rem !important; } .mr-lg-3 { margin-right: 1rem !important; } .mb-lg-3 { margin-bottom: 1rem !important; } .ml-lg-3 { margin-left: 1rem !important; } .mx-lg-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-lg-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-lg-4 { margin: 1.5rem 1.5rem !important; } .mt-lg-4 { margin-top: 1.5rem !important; } .mr-lg-4 { margin-right: 1.5rem !important; } .mb-lg-4 { margin-bottom: 1.5rem !important; } .ml-lg-4 { margin-left: 1.5rem !important; } .mx-lg-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-lg-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-lg-5 { margin: 3rem 3rem !important; } .mt-lg-5 { margin-top: 3rem !important; } .mr-lg-5 { margin-right: 3rem !important; } .mb-lg-5 { margin-bottom: 3rem !important; } .ml-lg-5 { margin-left: 3rem !important; } .mx-lg-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-lg-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-lg-0 { padding: 0 0 !important; } .pt-lg-0 { padding-top: 0 !important; } .pr-lg-0 { padding-right: 0 !important; } .pb-lg-0 { padding-bottom: 0 !important; } .pl-lg-0 { padding-left: 0 !important; } .px-lg-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-lg-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-lg-1 { padding: 0.25rem 0.25rem !important; } .pt-lg-1 { padding-top: 0.25rem !important; } .pr-lg-1 { padding-right: 0.25rem !important; } .pb-lg-1 { padding-bottom: 0.25rem !important; } .pl-lg-1 { padding-left: 0.25rem !important; } .px-lg-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-lg-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-lg-2 { padding: 0.5rem 0.5rem !important; } .pt-lg-2 { padding-top: 0.5rem !important; } .pr-lg-2 { padding-right: 0.5rem !important; } .pb-lg-2 { padding-bottom: 0.5rem !important; } .pl-lg-2 { padding-left: 0.5rem !important; } .px-lg-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-lg-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-lg-3 { padding: 1rem 1rem !important; } .pt-lg-3 { padding-top: 1rem !important; } .pr-lg-3 { padding-right: 1rem !important; } .pb-lg-3 { padding-bottom: 1rem !important; } .pl-lg-3 { padding-left: 1rem !important; } .px-lg-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-lg-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-lg-4 { padding: 1.5rem 1.5rem !important; } .pt-lg-4 { padding-top: 1.5rem !important; } .pr-lg-4 { padding-right: 1.5rem !important; } .pb-lg-4 { padding-bottom: 1.5rem !important; } .pl-lg-4 { padding-left: 1.5rem !important; } .px-lg-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-lg-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-lg-5 { padding: 3rem 3rem !important; } .pt-lg-5 { padding-top: 3rem !important; } .pr-lg-5 { padding-right: 3rem !important; } .pb-lg-5 { padding-bottom: 3rem !important; } .pl-lg-5 { padding-left: 3rem !important; } .px-lg-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-lg-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-lg-auto { margin: auto !important; } .mt-lg-auto { margin-top: auto !important; } .mr-lg-auto { margin-right: auto !important; } .mb-lg-auto { margin-bottom: auto !important; } .ml-lg-auto { margin-left: auto !important; } .mx-lg-auto { margin-right: auto !important; margin-left: auto !important; } .my-lg-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 1200px) { .m-xl-0 { margin: 0 0 !important; } .mt-xl-0 { margin-top: 0 !important; } .mr-xl-0 { margin-right: 0 !important; } .mb-xl-0 { margin-bottom: 0 !important; } .ml-xl-0 { margin-left: 0 !important; } .mx-xl-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-xl-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-xl-1 { margin: 0.25rem 0.25rem !important; } .mt-xl-1 { margin-top: 0.25rem !important; } .mr-xl-1 { margin-right: 0.25rem !important; } .mb-xl-1 { margin-bottom: 0.25rem !important; } .ml-xl-1 { margin-left: 0.25rem !important; } .mx-xl-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-xl-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-xl-2 { margin: 0.5rem 0.5rem !important; } .mt-xl-2 { margin-top: 0.5rem !important; } .mr-xl-2 { margin-right: 0.5rem !important; } .mb-xl-2 { margin-bottom: 0.5rem !important; } .ml-xl-2 { margin-left: 0.5rem !important; } .mx-xl-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-xl-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-xl-3 { margin: 1rem 1rem !important; } .mt-xl-3 { margin-top: 1rem !important; } .mr-xl-3 { margin-right: 1rem !important; } .mb-xl-3 { margin-bottom: 1rem !important; } .ml-xl-3 { margin-left: 1rem !important; } .mx-xl-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-xl-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-xl-4 { margin: 1.5rem 1.5rem !important; } .mt-xl-4 { margin-top: 1.5rem !important; } .mr-xl-4 { margin-right: 1.5rem !important; } .mb-xl-4 { margin-bottom: 1.5rem !important; } .ml-xl-4 { margin-left: 1.5rem !important; } .mx-xl-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-xl-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-xl-5 { margin: 3rem 3rem !important; } .mt-xl-5 { margin-top: 3rem !important; } .mr-xl-5 { margin-right: 3rem !important; } .mb-xl-5 { margin-bottom: 3rem !important; } .ml-xl-5 { margin-left: 3rem !important; } .mx-xl-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-xl-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-xl-0 { padding: 0 0 !important; } .pt-xl-0 { padding-top: 0 !important; } .pr-xl-0 { padding-right: 0 !important; } .pb-xl-0 { padding-bottom: 0 !important; } .pl-xl-0 { padding-left: 0 !important; } .px-xl-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-xl-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-xl-1 { padding: 0.25rem 0.25rem !important; } .pt-xl-1 { padding-top: 0.25rem !important; } .pr-xl-1 { padding-right: 0.25rem !important; } .pb-xl-1 { padding-bottom: 0.25rem !important; } .pl-xl-1 { padding-left: 0.25rem !important; } .px-xl-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-xl-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-xl-2 { padding: 0.5rem 0.5rem !important; } .pt-xl-2 { padding-top: 0.5rem !important; } .pr-xl-2 { padding-right: 0.5rem !important; } .pb-xl-2 { padding-bottom: 0.5rem !important; } .pl-xl-2 { padding-left: 0.5rem !important; } .px-xl-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-xl-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-xl-3 { padding: 1rem 1rem !important; } .pt-xl-3 { padding-top: 1rem !important; } .pr-xl-3 { padding-right: 1rem !important; } .pb-xl-3 { padding-bottom: 1rem !important; } .pl-xl-3 { padding-left: 1rem !important; } .px-xl-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-xl-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-xl-4 { padding: 1.5rem 1.5rem !important; } .pt-xl-4 { padding-top: 1.5rem !important; } .pr-xl-4 { padding-right: 1.5rem !important; } .pb-xl-4 { padding-bottom: 1.5rem !important; } .pl-xl-4 { padding-left: 1.5rem !important; } .px-xl-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-xl-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-xl-5 { padding: 3rem 3rem !important; } .pt-xl-5 { padding-top: 3rem !important; } .pr-xl-5 { padding-right: 3rem !important; } .pb-xl-5 { padding-bottom: 3rem !important; } .pl-xl-5 { padding-left: 3rem !important; } .px-xl-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-xl-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-xl-auto { margin: auto !important; } .mt-xl-auto { margin-top: auto !important; } .mr-xl-auto { margin-right: auto !important; } .mb-xl-auto { margin-bottom: auto !important; } .ml-xl-auto { margin-left: auto !important; } .mx-xl-auto { margin-right: auto !important; margin-left: auto !important; } .my-xl-auto { margin-top: auto !important; margin-bottom: auto !important; } } .text-justify { text-align: justify !important; } .text-nowrap { white-space: nowrap !important; } .text-truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .text-left { text-align: left !important; } .text-right { text-align: right !important; } .text-center { text-align: center !important; } @media (min-width: 576px) { .text-sm-left { text-align: left !important; } .text-sm-right { text-align: right !important; } .text-sm-center { text-align: center !important; } } @media (min-width: 768px) { .text-md-left { text-align: left !important; } .text-md-right { text-align: right !important; } .text-md-center { text-align: center !important; } } @media (min-width: 992px) { .text-lg-left { text-align: left !important; } .text-lg-right { text-align: right !important; } .text-lg-center { text-align: center !important; } } @media (min-width: 1200px) { .text-xl-left { text-align: left !important; } .text-xl-right { text-align: right !important; } .text-xl-center { text-align: center !important; } } .text-lowercase { text-transform: lowercase !important; } .text-uppercase { text-transform: uppercase !important; } .text-capitalize { text-transform: capitalize !important; } .font-weight-normal { font-weight: normal; } .font-weight-bold { font-weight: bold; } .font-italic { font-style: italic; } .text-white { color: #fff !important; } .text-muted { color: #777 !important; } a.text-muted:focus, a.text-muted:hover { color: #5e5e5e !important; } .text-primary { color: #E95420 !important; } a.text-primary:focus, a.text-primary:hover { color: #c34113 !important; } .text-success { color: #38B44A !important; } a.text-success:focus, a.text-success:hover { color: #2c8d3a !important; } .text-info { color: #772953 !important; } a.text-info:focus, a.text-info:hover { color: #511c39 !important; } .text-warning { color: #EFB73E !important; } a.text-warning:focus, a.text-warning:hover { color: #e7a413 !important; } .text-danger { color: #DF382C !important; } a.text-danger:focus, a.text-danger:hover { color: #bc271c !important; } .text-gray-dark { color: #222 !important; } a.text-gray-dark:focus, a.text-gray-dark:hover { color: #090909 !important; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .invisible { visibility: hidden !important; } .hidden-xs-up { display: none !important; } @media (max-width: 575px) { .hidden-xs-down { display: none !important; } } @media (min-width: 576px) { .hidden-sm-up { display: none !important; } } @media (max-width: 767px) { .hidden-sm-down { display: none !important; } } @media (min-width: 768px) { .hidden-md-up { display: none !important; } } @media (max-width: 991px) { .hidden-md-down { display: none !important; } } @media (min-width: 992px) { .hidden-lg-up { display: none !important; } } @media (max-width: 1199px) { .hidden-lg-down { display: none !important; } } @media (min-width: 1200px) { .hidden-xl-up { display: none !important; } } .hidden-xl-down { display: none !important; } .visible-print-block { display: none !important; } @media print { .visible-print-block { display: block !important; } } .visible-print-inline { display: none !important; } @media print { .visible-print-inline { display: inline !important; } } .visible-print-inline-block { display: none !important; } @media print { .visible-print-inline-block { display: inline-block !important; } } @media print { .hidden-print { display: none !important; } } .bg-inverse { background-color: #772953 !important; } .thead-inverse th { background-color: #772953; }
cleinias/blogstrap4
css/bootswatch/united/bootstrap.css
CSS
gpl-3.0
192,789
package net.minecraft.entity.monster; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; public abstract class EntityMob extends EntityCreature implements IMob { public EntityMob(World worldIn) { super(worldIn); this.experienceValue = 5; } public SoundCategory getSoundCategory() { return SoundCategory.HOSTILE; } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ public void onLivingUpdate() { this.updateArmSwingProgress(); float f = this.getBrightness(1.0F); if (f > 0.5F) { this.entityAge += 2; } super.onLivingUpdate(); } /** * Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL) { this.setDead(); } } protected SoundEvent getSwimSound() { return SoundEvents.entity_hostile_swim; } protected SoundEvent getSplashSound() { return SoundEvents.entity_hostile_splash; } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { return this.isEntityInvulnerable(source) ? false : super.attackEntityFrom(source, amount); } protected SoundEvent getHurtSound() { return SoundEvents.entity_hostile_hurt; } protected SoundEvent getDeathSound() { return SoundEvents.entity_hostile_death; } protected SoundEvent getFallSound(int heightIn) { return heightIn > 4 ? SoundEvents.entity_hostile_big_fall : SoundEvents.entity_hostile_small_fall; } public boolean attackEntityAsMob(Entity entityIn) { float f = (float)this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue(); int i = 0; if (entityIn instanceof EntityLivingBase) { f += EnchantmentHelper.getModifierForCreature(this.getHeldItemMainhand(), ((EntityLivingBase)entityIn).getCreatureAttribute()); i += EnchantmentHelper.getKnockbackModifier(this); } boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), f); if (flag) { if (i > 0 && entityIn instanceof EntityLivingBase) { ((EntityLivingBase)entityIn).knockBack(this, (float)i * 0.5F, (double)MathHelper.sin(this.rotationYaw * 0.017453292F), (double)(-MathHelper.cos(this.rotationYaw * 0.017453292F))); this.motionX *= 0.6D; this.motionZ *= 0.6D; } int j = EnchantmentHelper.getFireAspectModifier(this); if (j > 0) { entityIn.setFire(j * 4); } if (entityIn instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer)entityIn; ItemStack itemstack = this.getHeldItemMainhand(); ItemStack itemstack1 = entityplayer.isHandActive() ? entityplayer.getActiveItemStack() : null; if (itemstack != null && itemstack1 != null && itemstack.getItem() instanceof ItemAxe && itemstack1.getItem() == Items.shield) { float f1 = 0.25F + (float)EnchantmentHelper.getEfficiencyModifier(this) * 0.05F; if (this.rand.nextFloat() < f1) { entityplayer.getCooldownTracker().setCooldown(Items.shield, 100); this.worldObj.setEntityState(entityplayer, (byte)30); } } } this.applyEnchantments(this, entityIn); } return flag; } public float getBlockPathWeight(BlockPos pos) { return 0.5F - this.worldObj.getLightBrightness(pos); } /** * Checks to make sure the light is not too bright where the mob is spawning */ protected boolean isValidLightLevel() { BlockPos blockpos = new BlockPos(this.posX, this.getEntityBoundingBox().minY, this.posZ); if (this.worldObj.getLightFor(EnumSkyBlock.SKY, blockpos) > this.rand.nextInt(32)) { return false; } else { int i = this.worldObj.getLightFromNeighbors(blockpos); if (this.worldObj.isThundering()) { int j = this.worldObj.getSkylightSubtracted(); this.worldObj.setSkylightSubtracted(10); i = this.worldObj.getLightFromNeighbors(blockpos); this.worldObj.setSkylightSubtracted(j); } return i <= this.rand.nextInt(8); } } /** * Checks if the entity's current position is a valid location to spawn this entity. */ public boolean getCanSpawnHere() { return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL && this.isValidLightLevel() && super.getCanSpawnHere(); } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getAttributeMap().registerAttribute(SharedMonsterAttributes.ATTACK_DAMAGE); } /** * Entity won't drop items or experience points if this returns false */ protected boolean canDropLoot() { return true; } }
aebert1/BigTransport
build/tmp/recompileMc/sources/net/minecraft/entity/monster/EntityMob.java
Java
gpl-3.0
6,264
/****************************************************************************** * * Copyright (C) 2014 - 2015 Xilinx, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ /*****************************************************************************/ /** * @file vectors.h * * This file contains the C level vector prototypes for the ARM Cortex A53 core. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- --------------------------------------------------- * 5.00 pkp 05/29/14 First release * </pre> * * @note * * None. * ******************************************************************************/ #ifndef _VECTORS_H_ #define _VECTORS_H_ /***************************** Include Files *********************************/ #include "xil_types.h" #include "xil_assert.h" #ifdef __cplusplus extern "C" { #endif /***************** Macros (Inline Functions) Definitions *********************/ /**************************** Type Definitions *******************************/ /************************** Constant Definitions *****************************/ /************************** Function Prototypes ******************************/ void FIQInterrupt(void); void IRQInterrupt(void); void SynchronousInterrupt(void); void SErrorInterrupt(void); #ifdef __cplusplus } #endif #endif /* protection macro */
RobsonRojas/frertos-udemy
Keil-FreeRTOS-Sample-Project/Keil-FreeRTOS/FreeRTOSv9.0.0/FreeRTOS/Demo/CORTEX_A53_64-bit_UltraScale_MPSoC/RTOSDemo_A53_bsp/psu_cortexa53_0/libsrc/standalone_v5_4/src/vectors.h
C
gpl-3.0
2,825
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Vitaly A. Provodin */ /** * Created on 18.02.2005 */ package org.apache.harmony.jpda.tests.jdwp.ThreadReference; import org.apache.harmony.jpda.tests.framework.DebuggeeSynchronizer; import org.apache.harmony.jpda.tests.framework.LogWriter; import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer; import org.apache.harmony.jpda.tests.share.SyncDebuggee; /** * The class specifies debuggee for <code>org.apache.harmony.jpda.tests.jdwp.ThreadReference.ThreadGroupTest</code>. * This debuggee is started as follow: * <ol> * <li>the tested group <code>TESTED_GROUP</code> is created * <li>the tested thread <code>TESTED_THREAD</code> is started so this * thread belongs to that thread group * </ol> * For different goals of tests, the debuggee sends the <code>SGNL_READY</code> * signal to and waits for the <code>SGNL_CONTINUE</code> signal from debugger * in two places: * <ul> * <li>right away when the tested thread has been started * <li>when the tested thread has been finished * </ul> */ public class ThreadGroupDebuggee extends SyncDebuggee { public static final String TESTED_GROUP = "TestedGroup"; public static final String TESTED_THREAD = "TestedThread"; static Object waitForStart = new Object(); static Object waitForFinish = new Object(); static Object waitTimeObject = new Object(); static void waitMlsecsTime(long mlsecsTime) { synchronized(waitTimeObject) { try { waitTimeObject.wait(mlsecsTime); } catch (Throwable throwable) { // ignore } } } public void run() { ThreadGroup thrdGroup = new ThreadGroup(TESTED_GROUP); DebuggeeThread thrd = new DebuggeeThread(thrdGroup, TESTED_THREAD, logWriter, synchronizer); synchronized(waitForStart){ thrd.start(); try { waitForStart.wait(); } catch (InterruptedException e) { } } while ( thrd.isAlive() ) { waitMlsecsTime(100); } // synchronized(waitForFinish){ logWriter.println("thread is finished"); // } logWriter.println("send SGNL_READY"); synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_READY); synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE); } class DebuggeeThread extends Thread { LogWriter logWriter; DebuggeeSynchronizer synchronizer; public DebuggeeThread(ThreadGroup thrdGroup, String name, LogWriter logWriter, DebuggeeSynchronizer synchronizer) { super(thrdGroup, name); this.logWriter = logWriter; this.synchronizer = synchronizer; } public void run() { synchronized(ThreadGroupDebuggee.waitForFinish){ synchronized(ThreadGroupDebuggee.waitForStart){ ThreadGroupDebuggee.waitForStart.notifyAll(); logWriter.println(getName() + ": started"); synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_READY); logWriter.println(getName() + ": wait for SGNL_CONTINUE"); synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE); logWriter.println(getName() + ": finished"); } } } } public static void main(String [] args) { runDebuggee(ThreadGroupDebuggee.class); } }
s20121035/rk3288_android5.1_repo
external/apache-harmony/jdwp/src/test/java/org/apache/harmony/jpda/tests/jdwp/ThreadReference/ThreadGroupDebuggee.java
Java
gpl-3.0
4,431
#if defined(__ppc__) || defined(__ppc64__) /* ----------------------------------------------------------------------- ffi.c - Copyright (c) 1998 Geoffrey Keating PowerPC Foreign Function Interface Darwin ABI support (c) 2001 John Hornkvist AIX ABI support (c) 2002 Free Software Foundation, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include <ffi.h> #include <ffi_common.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <ppc-darwin.h> #include <architecture/ppc/mode_independent_asm.h> #if defined(POWERPC_DARWIN) #include <libkern/OSCacheControl.h> // for sys_icache_invalidate() #endif extern void ffi_closure_ASM(void); // The layout of a function descriptor. A C function pointer really // points to one of these. typedef struct aix_fd_struct { void* code_pointer; void* toc; } aix_fd; /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments. The stack layout we want looks like this: | Return address from ffi_call_DARWIN | higher addresses |--------------------------------------------| | Previous backchain pointer 4/8 | stack pointer here |--------------------------------------------|-\ <<< on entry to | Saved r28-r31 (4/8)*4 | | ffi_call_DARWIN |--------------------------------------------| | | Parameters (at least 8*(4/8)=32/64) | | (176) +112 - +288 |--------------------------------------------| | | Space for GPR2 4/8 | | |--------------------------------------------| | stack | | Reserved (4/8)*2 | | grows | |--------------------------------------------| | down V | Space for callee's LR 4/8 | | |--------------------------------------------| | lower addresses | Saved CR 4/8 | | |--------------------------------------------| | stack pointer here | Current backchain pointer 4/8 | | during |--------------------------------------------|-/ <<< ffi_call_DARWIN Note: ppc64 CR is saved in the low word of a long on the stack. */ /*@-exportheader@*/ void ffi_prep_args( extended_cif* inEcif, unsigned *const stack) /*@=exportheader@*/ { /* Copy the ecif to a local var so we can trample the arg. BC note: test this with GP later for possible problems... */ volatile extended_cif* ecif = inEcif; const unsigned bytes = ecif->cif->bytes; const unsigned flags = ecif->cif->flags; /* Cast the stack arg from int* to long*. sizeof(long) == 4 in 32-bit mode and 8 in 64-bit mode. */ unsigned long *const longStack = (unsigned long *const)stack; /* 'stacktop' points at the previous backchain pointer. */ #if defined(__ppc64__) // In ppc-darwin.s, an extra 96 bytes is reserved for the linkage area, // saved registers, and an extra FPR. unsigned long *const stacktop = (unsigned long *)(unsigned long)((char*)longStack + bytes + 96); #elif defined(__ppc__) unsigned long *const stacktop = longStack + (bytes / sizeof(long)); #else #error undefined architecture #endif /* 'fpr_base' points at the space for fpr1, and grows upwards as we use FPR registers. */ double* fpr_base = (double*)(stacktop - ASM_NEEDS_REGISTERS) - NUM_FPR_ARG_REGISTERS; #if defined(__ppc64__) // 64-bit saves an extra register, and uses an extra FPR. Knock fpr_base // down a couple pegs. fpr_base -= 2; #endif unsigned int fparg_count = 0; /* 'next_arg' grows up as we put parameters in it. */ unsigned long* next_arg = longStack + 6; /* 6 reserved positions. */ int i; double double_tmp; void** p_argv = ecif->avalue; unsigned long gprvalue; ffi_type** ptr = ecif->cif->arg_types; /* Check that everything starts aligned properly. */ FFI_ASSERT(stack == SF_ROUND(stack)); FFI_ASSERT(stacktop == SF_ROUND(stacktop)); FFI_ASSERT(bytes == SF_ROUND(bytes)); /* Deal with return values that are actually pass-by-reference. Rule: Return values are referenced by r3, so r4 is the first parameter. */ if (flags & FLAG_RETVAL_REFERENCE) *next_arg++ = (unsigned long)(char*)ecif->rvalue; /* Now for the arguments. */ for (i = ecif->cif->nargs; i > 0; i--, ptr++, p_argv++) { switch ((*ptr)->type) { /* If a floating-point parameter appears before all of the general- purpose registers are filled, the corresponding GPRs that match the size of the floating-point parameter are shadowed for the benefit of vararg and pre-ANSI functions. */ case FFI_TYPE_FLOAT: double_tmp = *(float*)*p_argv; if (fparg_count < NUM_FPR_ARG_REGISTERS) *fpr_base++ = double_tmp; *(double*)next_arg = double_tmp; next_arg++; fparg_count++; FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; case FFI_TYPE_DOUBLE: double_tmp = *(double*)*p_argv; if (fparg_count < NUM_FPR_ARG_REGISTERS) *fpr_base++ = double_tmp; *(double*)next_arg = double_tmp; next_arg += MODE_CHOICE(2,1); fparg_count++; FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: #if defined(__ppc64__) if (fparg_count < NUM_FPR_ARG_REGISTERS) *(long double*)fpr_base = *(long double*)*p_argv; #elif defined(__ppc__) if (fparg_count < NUM_FPR_ARG_REGISTERS - 1) *(long double*)fpr_base = *(long double*)*p_argv; else if (fparg_count == NUM_FPR_ARG_REGISTERS - 1) *(double*)fpr_base = *(double*)*p_argv; #else #error undefined architecture #endif *(long double*)next_arg = *(long double*)*p_argv; fparg_count += 2; fpr_base += 2; next_arg += MODE_CHOICE(4,2); FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: #if defined(__ppc64__) gprvalue = *(long long*)*p_argv; goto putgpr; #elif defined(__ppc__) *(long long*)next_arg = *(long long*)*p_argv; next_arg += 2; break; #else #error undefined architecture #endif case FFI_TYPE_POINTER: gprvalue = *(unsigned long*)*p_argv; goto putgpr; case FFI_TYPE_UINT8: gprvalue = *(unsigned char*)*p_argv; goto putgpr; case FFI_TYPE_SINT8: gprvalue = *(signed char*)*p_argv; goto putgpr; case FFI_TYPE_UINT16: gprvalue = *(unsigned short*)*p_argv; goto putgpr; case FFI_TYPE_SINT16: gprvalue = *(signed short*)*p_argv; goto putgpr; case FFI_TYPE_STRUCT: { #if defined(__ppc64__) unsigned int gprSize = 0; unsigned int fprSize = 0; ffi64_struct_to_reg_form(*ptr, (char*)*p_argv, NULL, &fparg_count, (char*)next_arg, &gprSize, (char*)fpr_base, &fprSize); next_arg += gprSize / sizeof(long); fpr_base += fprSize / sizeof(double); #elif defined(__ppc__) char* dest_cpy = (char*)next_arg; /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, SI 4 bytes) are aligned as if they were those modes. Structures with 3 byte in size are padded upwards. */ unsigned size_al = (*ptr)->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN((*ptr)->size, 8); if (ecif->cif->abi == FFI_DARWIN) { if (size_al < 3) dest_cpy += 4 - size_al; } memcpy((char*)dest_cpy, (char*)*p_argv, size_al); next_arg += (size_al + 3) / 4; #else #error undefined architecture #endif break; } case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: gprvalue = *(unsigned*)*p_argv; putgpr: *next_arg++ = gprvalue; break; default: break; } } /* Check that we didn't overrun the stack... */ //FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS); //FFI_ASSERT((unsigned *)fpr_base // <= stacktop - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS); //FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4); } #if defined(__ppc64__) bool ffi64_struct_contains_fp( const ffi_type* inType) { bool containsFP = false; unsigned int i; for (i = 0; inType->elements[i] != NULL && !containsFP; i++) { if (inType->elements[i]->type == FFI_TYPE_FLOAT || inType->elements[i]->type == FFI_TYPE_DOUBLE || inType->elements[i]->type == FFI_TYPE_LONGDOUBLE) containsFP = true; else if (inType->elements[i]->type == FFI_TYPE_STRUCT) containsFP = ffi64_struct_contains_fp(inType->elements[i]); } return containsFP; } #endif // defined(__ppc64__) /* Perform machine dependent cif processing. */ ffi_status ffi_prep_cif_machdep( ffi_cif* cif) { /* All this is for the DARWIN ABI. */ int i; ffi_type** ptr; int intarg_count = 0; int fparg_count = 0; unsigned int flags = 0; unsigned int size_al = 0; /* All the machine-independent calculation of cif->bytes will be wrong. Redo the calculation for DARWIN. */ /* Space for the frame pointer, callee's LR, CR, etc, and for the asm's temp regs. */ unsigned int bytes = (6 + ASM_NEEDS_REGISTERS) * sizeof(long); /* Return value handling. The rules are as follows: - 32-bit (or less) integer values are returned in gpr3; - Structures of size <= 4 bytes also returned in gpr3; - 64-bit integer values and structures between 5 and 8 bytes are returned in gpr3 and gpr4; - Single/double FP values are returned in fpr1; - Long double FP (if not equivalent to double) values are returned in fpr1 and fpr2; - Larger structures values are allocated space and a pointer is passed as the first argument. */ switch (cif->rtype->type) { #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: flags |= FLAG_RETURNS_128BITS; flags |= FLAG_RETURNS_FP; break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_DOUBLE: flags |= FLAG_RETURNS_64BITS; /* Fall through. */ case FFI_TYPE_FLOAT: flags |= FLAG_RETURNS_FP; break; #if defined(__ppc64__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: flags |= FLAG_RETURNS_64BITS; break; case FFI_TYPE_STRUCT: { #if defined(__ppc64__) if (ffi64_stret_needs_ptr(cif->rtype, NULL, NULL)) { flags |= FLAG_RETVAL_REFERENCE; flags |= FLAG_RETURNS_NOTHING; intarg_count++; } else { flags |= FLAG_RETURNS_STRUCT; if (ffi64_struct_contains_fp(cif->rtype)) flags |= FLAG_STRUCT_CONTAINS_FP; } #elif defined(__ppc__) flags |= FLAG_RETVAL_REFERENCE; flags |= FLAG_RETURNS_NOTHING; intarg_count++; #else #error undefined architecture #endif break; } case FFI_TYPE_VOID: flags |= FLAG_RETURNS_NOTHING; break; default: /* Returns 32-bit integer, or similar. Nothing to do here. */ break; } /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest goes on the stack. Structures are passed as a pointer to a copy of the structure. Stuff on the stack needs to keep proper alignment. */ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) { switch ((*ptr)->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: fparg_count++; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ if (fparg_count > NUM_FPR_ARG_REGISTERS && intarg_count % 2 != 0) intarg_count++; break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: fparg_count += 2; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ if ( #if defined(__ppc64__) fparg_count > NUM_FPR_ARG_REGISTERS + 1 #elif defined(__ppc__) fparg_count > NUM_FPR_ARG_REGISTERS #else #error undefined architecture #endif && intarg_count % 2 != 0) intarg_count++; intarg_count += 2; break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: /* 'long long' arguments are passed as two words, but either both words must fit in registers or both go on the stack. If they go on the stack, they must be 8-byte-aligned. */ if (intarg_count == NUM_GPR_ARG_REGISTERS - 1 || (intarg_count >= NUM_GPR_ARG_REGISTERS && intarg_count % 2 != 0)) intarg_count++; intarg_count += MODE_CHOICE(2,1); break; case FFI_TYPE_STRUCT: size_al = (*ptr)->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN((*ptr)->size, 8); #if defined(__ppc64__) // Look for FP struct members. unsigned int j; for (j = 0; (*ptr)->elements[j] != NULL; j++) { if ((*ptr)->elements[j]->type == FFI_TYPE_FLOAT || (*ptr)->elements[j]->type == FFI_TYPE_DOUBLE) { fparg_count++; if (fparg_count > NUM_FPR_ARG_REGISTERS) intarg_count++; } else if ((*ptr)->elements[j]->type == FFI_TYPE_LONGDOUBLE) { fparg_count += 2; if (fparg_count > NUM_FPR_ARG_REGISTERS + 1) intarg_count += 2; } else intarg_count++; } #elif defined(__ppc__) intarg_count += (size_al + 3) / 4; #else #error undefined architecture #endif break; default: /* Everything else is passed as a 4/8-byte word in a GPR, either the object itself or a pointer to it. */ intarg_count++; break; } } /* Space for the FPR registers, if needed. */ if (fparg_count != 0) { flags |= FLAG_FP_ARGUMENTS; #if defined(__ppc64__) bytes += (NUM_FPR_ARG_REGISTERS + 1) * sizeof(double); #elif defined(__ppc__) bytes += NUM_FPR_ARG_REGISTERS * sizeof(double); #else #error undefined architecture #endif } /* Stack space. */ #if defined(__ppc64__) if ((intarg_count + fparg_count) > NUM_GPR_ARG_REGISTERS) bytes += (intarg_count + fparg_count) * sizeof(long); #elif defined(__ppc__) if ((intarg_count + 2 * fparg_count) > NUM_GPR_ARG_REGISTERS) bytes += (intarg_count + 2 * fparg_count) * sizeof(long); #else #error undefined architecture #endif else bytes += NUM_GPR_ARG_REGISTERS * sizeof(long); /* The stack space allocated needs to be a multiple of 16/32 bytes. */ bytes = SF_ROUND(bytes); cif->flags = flags; cif->bytes = bytes; return FFI_OK; } /*@-declundef@*/ /*@-exportheader@*/ extern void ffi_call_AIX( /*@out@*/ extended_cif*, unsigned, unsigned, /*@out@*/ unsigned*, void (*fn)(void), void (*fn2)(extended_cif*, unsigned *const)); extern void ffi_call_DARWIN( /*@out@*/ extended_cif*, unsigned long, unsigned, /*@out@*/ unsigned*, void (*fn)(void), void (*fn2)(extended_cif*, unsigned *const)); /*@=declundef@*/ /*@=exportheader@*/ void ffi_call( /*@dependent@*/ ffi_cif* cif, void (*fn)(void), /*@out@*/ void* rvalue, /*@dependent@*/ void** avalue) { extended_cif ecif; ecif.cif = cif; ecif.avalue = avalue; /* If the return value is a struct and we don't have a return value address then we need to make one. */ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; switch (cif->abi) { case FFI_AIX: /*@-usedef@*/ ffi_call_AIX(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn, ffi_prep_args); /*@=usedef@*/ break; case FFI_DARWIN: /*@-usedef@*/ ffi_call_DARWIN(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn, ffi_prep_args); /*@=usedef@*/ break; default: FFI_ASSERT(0); break; } } /* here I'd like to add the stack frame layout we use in darwin_closure.S and aix_clsoure.S SP previous -> +---------------------------------------+ <--- child frame | back chain to caller 4 | +---------------------------------------+ 4 | saved CR 4 | +---------------------------------------+ 8 | saved LR 4 | +---------------------------------------+ 12 | reserved for compilers 4 | +---------------------------------------+ 16 | reserved for binders 4 | +---------------------------------------+ 20 | saved TOC pointer 4 | +---------------------------------------+ 24 | always reserved 8*4=32 (previous GPRs)| | according to the linkage convention | | from AIX | +---------------------------------------+ 56 | our FPR area 13*8=104 | | f1 | | . | | f13 | +---------------------------------------+ 160 | result area 8 | +---------------------------------------+ 168 | alignement to the next multiple of 16 | SP current --> +---------------------------------------+ 176 <- parent frame | back chain to caller 4 | +---------------------------------------+ 180 | saved CR 4 | +---------------------------------------+ 184 | saved LR 4 | +---------------------------------------+ 188 | reserved for compilers 4 | +---------------------------------------+ 192 | reserved for binders 4 | +---------------------------------------+ 196 | saved TOC pointer 4 | +---------------------------------------+ 200 | always reserved 8*4=32 we store our | | GPRs here | | r3 | | . | | r10 | +---------------------------------------+ 232 | overflow part | +---------------------------------------+ xxx | ???? | +---------------------------------------+ xxx */ #if !defined(POWERPC_DARWIN) #define MIN_LINE_SIZE 32 static void flush_icache( char* addr) { #ifndef _AIX __asm__ volatile ( "dcbf 0,%0\n" "sync\n" "icbi 0,%0\n" "sync\n" "isync" : : "r" (addr) : "memory"); #endif } static void flush_range( char* addr, int size) { int i; for (i = 0; i < size; i += MIN_LINE_SIZE) flush_icache(addr + i); flush_icache(addr + size - 1); } #endif // !defined(POWERPC_DARWIN) ffi_status ffi_prep_closure( ffi_closure* closure, ffi_cif* cif, void (*fun)(ffi_cif*, void*, void**, void*), void* user_data) { switch (cif->abi) { case FFI_DARWIN: { FFI_ASSERT (cif->abi == FFI_DARWIN); unsigned int* tramp = (unsigned int*)&closure->tramp[0]; #if defined(__ppc64__) tramp[0] = 0x7c0802a6; // mflr r0 tramp[1] = 0x429f0005; // bcl 20,31,+0x8 tramp[2] = 0x7d6802a6; // mflr r11 tramp[3] = 0x7c0803a6; // mtlr r0 tramp[4] = 0xe98b0018; // ld r12,24(r11) tramp[5] = 0x7d8903a6; // mtctr r12 tramp[6] = 0xe96b0020; // ld r11,32(r11) tramp[7] = 0x4e800420; // bctr *(unsigned long*)&tramp[8] = (unsigned long)ffi_closure_ASM; *(unsigned long*)&tramp[10] = (unsigned long)closure; #elif defined(__ppc__) tramp[0] = 0x7c0802a6; // mflr r0 tramp[1] = 0x429f0005; // bcl 20,31,+0x8 tramp[2] = 0x7d6802a6; // mflr r11 tramp[3] = 0x7c0803a6; // mtlr r0 tramp[4] = 0x818b0018; // lwz r12,24(r11) tramp[5] = 0x7d8903a6; // mtctr r12 tramp[6] = 0x816b001c; // lwz r11,28(r11) tramp[7] = 0x4e800420; // bctr tramp[8] = (unsigned long)ffi_closure_ASM; tramp[9] = (unsigned long)closure; #else #error undefined architecture #endif closure->cif = cif; closure->fun = fun; closure->user_data = user_data; // Flush the icache. Only necessary on Darwin. #if defined(POWERPC_DARWIN) sys_icache_invalidate(closure->tramp, FFI_TRAMPOLINE_SIZE); #else flush_range(closure->tramp, FFI_TRAMPOLINE_SIZE); #endif break; } case FFI_AIX: { FFI_ASSERT (cif->abi == FFI_AIX); ffi_aix_trampoline_struct* tramp_aix = (ffi_aix_trampoline_struct*)(closure->tramp); aix_fd* fd = (aix_fd*)(void*)ffi_closure_ASM; tramp_aix->code_pointer = fd->code_pointer; tramp_aix->toc = fd->toc; tramp_aix->static_chain = closure; closure->cif = cif; closure->fun = fun; closure->user_data = user_data; break; } default: return FFI_BAD_ABI; } return FFI_OK; } #if defined(__ppc__) typedef double ldbits[2]; typedef union { ldbits lb; long double ld; } ldu; #endif typedef union { float f; double d; } ffi_dblfl; /* The trampoline invokes ffi_closure_ASM, and on entry, r11 holds the address of the closure. After storing the registers that could possibly contain parameters to be passed into the stack frame and setting up space for a return value, ffi_closure_ASM invokes the following helper function to do most of the work. */ int ffi_closure_helper_DARWIN( ffi_closure* closure, void* rvalue, unsigned long* pgr, ffi_dblfl* pfr) { /* rvalue is the pointer to space for return value in closure assembly pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM. */ #if defined(__ppc__) ldu temp_ld; #endif double temp; unsigned int i; unsigned int nf = 0; /* number of FPRs already used. */ unsigned int ng = 0; /* number of GPRs already used. */ ffi_cif* cif = closure->cif; long avn = cif->nargs; void** avalue = alloca(cif->nargs * sizeof(void*)); ffi_type** arg_types = cif->arg_types; /* Copy the caller's structure return value address so that the closure returns the data directly to the caller. */ #if defined(__ppc64__) if (cif->rtype->type == FFI_TYPE_STRUCT && ffi64_stret_needs_ptr(cif->rtype, NULL, NULL)) #elif defined(__ppc__) if (cif->rtype->type == FFI_TYPE_STRUCT) #else #error undefined architecture #endif { rvalue = (void*)*pgr; pgr++; ng++; } /* Grab the addresses of the arguments from the stack frame. */ for (i = 0; i < avn; i++) { switch (arg_types[i]->type) { case FFI_TYPE_SINT8: case FFI_TYPE_UINT8: avalue[i] = (char*)pgr + MODE_CHOICE(3,7); ng++; pgr++; break; case FFI_TYPE_SINT16: case FFI_TYPE_UINT16: avalue[i] = (char*)pgr + MODE_CHOICE(2,6); ng++; pgr++; break; #if defined(__ppc__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: avalue[i] = (char*)pgr + MODE_CHOICE(0,4); ng++; pgr++; break; case FFI_TYPE_STRUCT: if (cif->abi == FFI_DARWIN) { #if defined(__ppc64__) unsigned int gprSize = 0; unsigned int fprSize = 0; unsigned int savedFPRSize = fprSize; avalue[i] = alloca(arg_types[i]->size); ffi64_struct_to_ram_form(arg_types[i], (const char*)pgr, &gprSize, (const char*)pfr, &fprSize, &nf, avalue[i], NULL); ng += gprSize / sizeof(long); pgr += gprSize / sizeof(long); pfr += (fprSize - savedFPRSize) / sizeof(double); #elif defined(__ppc__) /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, SI 4 bytes) are aligned as if they were those modes. */ unsigned int size_al = size_al = arg_types[i]->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if (arg_types[i]->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN(arg_types[i]->size, 8); if (size_al < 3) avalue[i] = (void*)pgr + MODE_CHOICE(4,8) - size_al; else avalue[i] = (void*)pgr; ng += (size_al + 3) / sizeof(long); pgr += (size_al + 3) / sizeof(long); #else #error undefined architecture #endif } break; #if defined(__ppc64__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: /* Long long ints are passed in 1 or 2 GPRs. */ avalue[i] = pgr; ng += MODE_CHOICE(2,1); pgr += MODE_CHOICE(2,1); break; case FFI_TYPE_FLOAT: /* A float value consumes a GPR. There are 13 64-bit floating point registers. */ if (nf < NUM_FPR_ARG_REGISTERS) { temp = pfr->d; pfr->f = (float)temp; avalue[i] = pfr; pfr++; } else avalue[i] = pgr; nf++; ng++; pgr++; break; case FFI_TYPE_DOUBLE: /* A double value consumes one or two GPRs. There are 13 64bit floating point registers. */ if (nf < NUM_FPR_ARG_REGISTERS) { avalue[i] = pfr; pfr++; } else avalue[i] = pgr; nf++; ng += MODE_CHOICE(2,1); pgr += MODE_CHOICE(2,1); break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: #if defined(__ppc64__) if (nf < NUM_FPR_ARG_REGISTERS) { avalue[i] = pfr; pfr += 2; } #elif defined(__ppc__) /* A long double value consumes 2/4 GPRs and 2 FPRs. There are 13 64bit floating point registers. */ if (nf < NUM_FPR_ARG_REGISTERS - 1) { avalue[i] = pfr; pfr += 2; } /* Here we have the situation where one part of the long double is stored in fpr13 and the other part is already on the stack. We use a union to pass the long double to avalue[i]. */ else if (nf == NUM_FPR_ARG_REGISTERS - 1) { memcpy (&temp_ld.lb[0], pfr, sizeof(temp_ld.lb[0])); memcpy (&temp_ld.lb[1], pgr + 2, sizeof(temp_ld.lb[1])); avalue[i] = &temp_ld.ld; } #else #error undefined architecture #endif else avalue[i] = pgr; nf += 2; ng += MODE_CHOICE(4,2); pgr += MODE_CHOICE(4,2); break; #endif /* FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE */ default: FFI_ASSERT(0); break; } } (closure->fun)(cif, rvalue, avalue, closure->user_data); /* Tell ffi_closure_ASM to perform return type promotions. */ return cif->rtype->type; } #if defined(__ppc64__) /* ffi64_struct_to_ram_form Rebuild a struct's natural layout from buffers of concatenated registers. Return the number of registers used. inGPRs[0-7] == r3, inFPRs[0-7] == f1 ... */ void ffi64_struct_to_ram_form( const ffi_type* inType, const char* inGPRs, unsigned int* ioGPRMarker, const char* inFPRs, unsigned int* ioFPRMarker, unsigned int* ioFPRsUsed, char* outStruct, // caller-allocated unsigned int* ioStructMarker) { unsigned int srcGMarker = 0; unsigned int srcFMarker = 0; unsigned int savedFMarker = 0; unsigned int fprsUsed = 0; unsigned int savedFPRsUsed = 0; unsigned int destMarker = 0; static unsigned int recurseCount = 0; if (ioGPRMarker) srcGMarker = *ioGPRMarker; if (ioFPRMarker) { srcFMarker = *ioFPRMarker; savedFMarker = srcFMarker; } if (ioFPRsUsed) { fprsUsed = *ioFPRsUsed; savedFPRsUsed = fprsUsed; } if (ioStructMarker) destMarker = *ioStructMarker; size_t i; switch (inType->size) { case 1: case 2: case 4: srcGMarker += 8 - inType->size; break; default: break; } for (i = 0; inType->elements[i] != NULL; i++) { switch (inType->elements[i]->type) { case FFI_TYPE_FLOAT: srcFMarker = ALIGN(srcFMarker, 4); srcGMarker = ALIGN(srcGMarker, 4); destMarker = ALIGN(destMarker, 4); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { *(float*)&outStruct[destMarker] = (float)*(double*)&inFPRs[srcFMarker]; srcFMarker += 8; fprsUsed++; } else *(float*)&outStruct[destMarker] = (float)*(double*)&inGPRs[srcGMarker]; srcGMarker += 4; destMarker += 4; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (destMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 4)) srcGMarker = ALIGN(srcGMarker, 8); } break; case FFI_TYPE_DOUBLE: srcFMarker = ALIGN(srcFMarker, 8); destMarker = ALIGN(destMarker, 8); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { *(double*)&outStruct[destMarker] = *(double*)&inFPRs[srcFMarker]; srcFMarker += 8; fprsUsed++; } else *(double*)&outStruct[destMarker] = *(double*)&inGPRs[srcGMarker]; destMarker += 8; // Skip next GPR srcGMarker += 8; srcGMarker = ALIGN(srcGMarker, 8); break; case FFI_TYPE_LONGDOUBLE: destMarker = ALIGN(destMarker, 16); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { srcFMarker = ALIGN(srcFMarker, 8); srcGMarker = ALIGN(srcGMarker, 8); *(long double*)&outStruct[destMarker] = *(long double*)&inFPRs[srcFMarker]; srcFMarker += 16; fprsUsed += 2; } else { srcFMarker = ALIGN(srcFMarker, 16); srcGMarker = ALIGN(srcGMarker, 16); *(long double*)&outStruct[destMarker] = *(long double*)&inGPRs[srcGMarker]; } destMarker += 16; // Skip next 2 GPRs srcGMarker += 16; srcGMarker = ALIGN(srcGMarker, 8); break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: { if (inType->alignment == 1) // chars only { if (inType->size == 1) outStruct[destMarker++] = inGPRs[srcGMarker++]; else if (inType->size == 2) { outStruct[destMarker++] = inGPRs[srcGMarker++]; outStruct[destMarker++] = inGPRs[srcGMarker++]; i++; } else { memcpy(&outStruct[destMarker], &inGPRs[srcGMarker], inType->size); srcGMarker += inType->size; destMarker += inType->size; i += inType->size - 1; } } else // chars and other stuff { outStruct[destMarker++] = inGPRs[srcGMarker++]; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (srcGMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 4)) srcGMarker = ALIGN(srcGMarker, inType->alignment); // was 8 } } break; } case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: srcGMarker = ALIGN(srcGMarker, 2); destMarker = ALIGN(destMarker, 2); *(short*)&outStruct[destMarker] = *(short*)&inGPRs[srcGMarker]; srcGMarker += 2; destMarker += 2; break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: srcGMarker = ALIGN(srcGMarker, 4); destMarker = ALIGN(destMarker, 4); *(int*)&outStruct[destMarker] = *(int*)&inGPRs[srcGMarker]; srcGMarker += 4; destMarker += 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: srcGMarker = ALIGN(srcGMarker, 8); destMarker = ALIGN(destMarker, 8); *(long long*)&outStruct[destMarker] = *(long long*)&inGPRs[srcGMarker]; srcGMarker += 8; destMarker += 8; break; case FFI_TYPE_STRUCT: recurseCount++; ffi64_struct_to_ram_form(inType->elements[i], inGPRs, &srcGMarker, inFPRs, &srcFMarker, &fprsUsed, outStruct, &destMarker); recurseCount--; break; default: FFI_ASSERT(0); // unknown element type break; } } srcGMarker = ALIGN(srcGMarker, inType->alignment); // Take care of the special case for 16-byte structs, but not for // nested structs. if (recurseCount == 0 && srcGMarker == 16) { *(long double*)&outStruct[0] = *(long double*)&inGPRs[0]; srcFMarker = savedFMarker; fprsUsed = savedFPRsUsed; } if (ioGPRMarker) *ioGPRMarker = ALIGN(srcGMarker, 8); if (ioFPRMarker) *ioFPRMarker = srcFMarker; if (ioFPRsUsed) *ioFPRsUsed = fprsUsed; if (ioStructMarker) *ioStructMarker = ALIGN(destMarker, 8); } /* ffi64_struct_to_reg_form Copy a struct's elements into buffers that can be sliced into registers. Return the sizes of the output buffers in bytes. Pass NULL buffer pointers to calculate size only. outGPRs[0-7] == r3, outFPRs[0-7] == f1 ... */ void ffi64_struct_to_reg_form( const ffi_type* inType, const char* inStruct, unsigned int* ioStructMarker, unsigned int* ioFPRsUsed, char* outGPRs, // caller-allocated unsigned int* ioGPRSize, char* outFPRs, // caller-allocated unsigned int* ioFPRSize) { size_t i; unsigned int srcMarker = 0; unsigned int destGMarker = 0; unsigned int destFMarker = 0; unsigned int savedFMarker = 0; unsigned int fprsUsed = 0; unsigned int savedFPRsUsed = 0; static unsigned int recurseCount = 0; if (ioStructMarker) srcMarker = *ioStructMarker; if (ioFPRsUsed) { fprsUsed = *ioFPRsUsed; savedFPRsUsed = fprsUsed; } if (ioGPRSize) destGMarker = *ioGPRSize; if (ioFPRSize) { destFMarker = *ioFPRSize; savedFMarker = destFMarker; } switch (inType->size) { case 1: case 2: case 4: destGMarker += 8 - inType->size; break; default: break; } for (i = 0; inType->elements[i] != NULL; i++) { switch (inType->elements[i]->type) { // Shadow floating-point types in GPRs for vararg and pre-ANSI // functions. case FFI_TYPE_FLOAT: // Nudge markers to next 4/8-byte boundary srcMarker = ALIGN(srcMarker, 4); destGMarker = ALIGN(destGMarker, 4); destFMarker = ALIGN(destFMarker, 8); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { if (outFPRs != NULL && inStruct != NULL) *(double*)&outFPRs[destFMarker] = (double)*(float*)&inStruct[srcMarker]; destFMarker += 8; fprsUsed++; } if (outGPRs != NULL && inStruct != NULL) *(double*)&outGPRs[destGMarker] = (double)*(float*)&inStruct[srcMarker]; srcMarker += 4; destGMarker += 4; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (srcMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 4)) destGMarker = ALIGN(destGMarker, 8); } break; case FFI_TYPE_DOUBLE: srcMarker = ALIGN(srcMarker, 8); destFMarker = ALIGN(destFMarker, 8); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { if (outFPRs != NULL && inStruct != NULL) *(double*)&outFPRs[destFMarker] = *(double*)&inStruct[srcMarker]; destFMarker += 8; fprsUsed++; } if (outGPRs != NULL && inStruct != NULL) *(double*)&outGPRs[destGMarker] = *(double*)&inStruct[srcMarker]; srcMarker += 8; // Skip next GPR destGMarker += 8; destGMarker = ALIGN(destGMarker, 8); break; case FFI_TYPE_LONGDOUBLE: srcMarker = ALIGN(srcMarker, 16); if (fprsUsed < NUM_FPR_ARG_REGISTERS) { destFMarker = ALIGN(destFMarker, 8); destGMarker = ALIGN(destGMarker, 8); if (outFPRs != NULL && inStruct != NULL) *(long double*)&outFPRs[destFMarker] = *(long double*)&inStruct[srcMarker]; if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[destGMarker] = *(long double*)&inStruct[srcMarker]; destFMarker += 16; fprsUsed += 2; } else { destGMarker = ALIGN(destGMarker, 16); if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[destGMarker] = *(long double*)&inStruct[srcMarker]; } srcMarker += 16; destGMarker += 16; // Skip next 2 GPRs destGMarker = ALIGN(destGMarker, 8); // was 16 break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: if (inType->alignment == 1) // bytes only { if (inType->size == 1) { if (outGPRs != NULL && inStruct != NULL) outGPRs[destGMarker] = inStruct[srcMarker]; srcMarker++; destGMarker++; } else if (inType->size == 2) { if (outGPRs != NULL && inStruct != NULL) { outGPRs[destGMarker] = inStruct[srcMarker]; outGPRs[destGMarker + 1] = inStruct[srcMarker + 1]; } srcMarker += 2; destGMarker += 2; i++; } else { if (outGPRs != NULL && inStruct != NULL) { // Avoid memcpy for small chunks. if (inType->size <= sizeof(long)) *(long*)&outGPRs[destGMarker] = *(long*)&inStruct[srcMarker]; else memcpy(&outGPRs[destGMarker], &inStruct[srcMarker], inType->size); } srcMarker += inType->size; destGMarker += inType->size; i += inType->size - 1; } } else // bytes and other stuff { if (outGPRs != NULL && inStruct != NULL) outGPRs[destGMarker] = inStruct[srcMarker]; srcMarker++; destGMarker++; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (destGMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 4)) destGMarker = ALIGN(destGMarker, inType->alignment); // was 8 } } break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: srcMarker = ALIGN(srcMarker, 2); destGMarker = ALIGN(destGMarker, 2); if (outGPRs != NULL && inStruct != NULL) *(short*)&outGPRs[destGMarker] = *(short*)&inStruct[srcMarker]; srcMarker += 2; destGMarker += 2; if (inType->elements[i + 1] == NULL) destGMarker = ALIGN(destGMarker, inType->alignment); break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: srcMarker = ALIGN(srcMarker, 4); destGMarker = ALIGN(destGMarker, 4); if (outGPRs != NULL && inStruct != NULL) *(int*)&outGPRs[destGMarker] = *(int*)&inStruct[srcMarker]; srcMarker += 4; destGMarker += 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: srcMarker = ALIGN(srcMarker, 8); destGMarker = ALIGN(destGMarker, 8); if (outGPRs != NULL && inStruct != NULL) *(long long*)&outGPRs[destGMarker] = *(long long*)&inStruct[srcMarker]; srcMarker += 8; destGMarker += 8; if (inType->elements[i + 1] == NULL) destGMarker = ALIGN(destGMarker, inType->alignment); break; case FFI_TYPE_STRUCT: recurseCount++; ffi64_struct_to_reg_form(inType->elements[i], inStruct, &srcMarker, &fprsUsed, outGPRs, &destGMarker, outFPRs, &destFMarker); recurseCount--; break; default: FFI_ASSERT(0); break; } } destGMarker = ALIGN(destGMarker, inType->alignment); // Take care of the special case for 16-byte structs, but not for // nested structs. if (recurseCount == 0 && destGMarker == 16) { if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[0] = *(long double*)&inStruct[0]; destFMarker = savedFMarker; fprsUsed = savedFPRsUsed; } if (ioStructMarker) *ioStructMarker = ALIGN(srcMarker, 8); if (ioFPRsUsed) *ioFPRsUsed = fprsUsed; if (ioGPRSize) *ioGPRSize = ALIGN(destGMarker, 8); if (ioFPRSize) *ioFPRSize = ALIGN(destFMarker, 8); } /* ffi64_stret_needs_ptr Determine whether a returned struct needs a pointer in r3 or can fit in registers. */ bool ffi64_stret_needs_ptr( const ffi_type* inType, unsigned short* ioGPRCount, unsigned short* ioFPRCount) { // Obvious case first- struct is larger than combined FPR size. if (inType->size > 14 * 8) return true; // Now the struct can physically fit in registers, determine if it // also fits logically. bool needsPtr = false; unsigned short gprsUsed = 0; unsigned short fprsUsed = 0; size_t i; if (ioGPRCount) gprsUsed = *ioGPRCount; if (ioFPRCount) fprsUsed = *ioFPRCount; for (i = 0; inType->elements[i] != NULL && !needsPtr; i++) { switch (inType->elements[i]->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: gprsUsed++; fprsUsed++; if (fprsUsed > 13) needsPtr = true; break; case FFI_TYPE_LONGDOUBLE: gprsUsed += 2; fprsUsed += 2; if (fprsUsed > 14) needsPtr = true; break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: { gprsUsed++; if (gprsUsed > 8) { needsPtr = true; break; } if (inType->elements[i + 1] == NULL) // last byte in the struct break; // Count possible contiguous bytes ahead, up to 8. unsigned short j; for (j = 1; j < 8; j++) { if (inType->elements[i + j] == NULL || !FFI_TYPE_1_BYTE(inType->elements[i + j]->type)) break; } i += j - 1; // allow for i++ before the test condition break; } case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: gprsUsed++; if (gprsUsed > 8) needsPtr = true; break; case FFI_TYPE_STRUCT: needsPtr = ffi64_stret_needs_ptr( inType->elements[i], &gprsUsed, &fprsUsed); break; default: FFI_ASSERT(0); break; } } if (ioGPRCount) *ioGPRCount = gprsUsed; if (ioFPRCount) *ioFPRCount = fprsUsed; return needsPtr; } /* ffi64_data_size Calculate the size in bytes of an ffi type. */ unsigned int ffi64_data_size( const ffi_type* inType) { unsigned int size = 0; switch (inType->type) { case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: size = 1; break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: size = 2; break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_FLOAT: size = 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: size = 8; break; case FFI_TYPE_LONGDOUBLE: size = 16; break; case FFI_TYPE_STRUCT: ffi64_struct_to_reg_form( inType, NULL, NULL, NULL, NULL, &size, NULL, NULL); break; case FFI_TYPE_VOID: break; default: FFI_ASSERT(0); break; } return size; } #endif /* defined(__ppc64__) */ #endif /* __ppc__ || __ppc64__ */
LubosD/darling
src/libffi/powerpc/ppc-ffi_darwin.c
C
gpl-3.0
43,697
/** ************************************************************************** * request.c * * Copyright 2008 Bryan Ischo <bryan@ischo.com> * * This file is part of libs3. * * libs3 is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, version 3 of the License. * * In addition, as a special exception, the copyright holders give * permission to link the code of this library and its programs with the * OpenSSL library, and distribute linked combinations including the two. * * libs3 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License version 3 * along with libs3, in a file named COPYING. If not, see * <http://www.gnu.org/licenses/>. * ************************************************************************** **/ #include <ctype.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/utsname.h> #include "request.h" #include "request_context.h" #include "response_headers_handler.h" #include "util.h" #define USER_AGENT_SIZE 256 #define REQUEST_STACK_SIZE 32 static char userAgentG[USER_AGENT_SIZE]; static pthread_mutex_t requestStackMutexG; static Request *requestStackG[REQUEST_STACK_SIZE]; static int requestStackCountG; char defaultHostNameG[S3_MAX_HOSTNAME_SIZE]; typedef struct RequestComputedValues { // All x-amz- headers, in normalized form (i.e. NAME: VALUE, no other ws) char *amzHeaders[S3_MAX_METADATA_COUNT + 2]; // + 2 for acl and date // The number of x-amz- headers int amzHeadersCount; // Storage for amzHeaders (the +256 is for x-amz-acl and x-amz-date) char amzHeadersRaw[COMPACTED_METADATA_BUFFER_SIZE + 256 + 1]; // Canonicalized x-amz- headers string_multibuffer(canonicalizedAmzHeaders, COMPACTED_METADATA_BUFFER_SIZE + 256 + 1); // URL-Encoded key char urlEncodedKey[MAX_URLENCODED_KEY_SIZE + 1]; // Canonicalized resource char canonicalizedResource[MAX_CANONICALIZED_RESOURCE_SIZE + 1]; // Cache-Control header (or empty) char cacheControlHeader[128]; // Content-Type header (or empty) char contentTypeHeader[128]; // Content-MD5 header (or empty) char md5Header[128]; // Content-Disposition header (or empty) char contentDispositionHeader[128]; // Content-Encoding header (or empty) char contentEncodingHeader[128]; // Expires header (or empty) char expiresHeader[128]; // If-Modified-Since header char ifModifiedSinceHeader[128]; // If-Unmodified-Since header char ifUnmodifiedSinceHeader[128]; // If-Match header char ifMatchHeader[128]; // If-None-Match header char ifNoneMatchHeader[128]; // Range header char rangeHeader[128]; // Authorization header char authorizationHeader[128]; } RequestComputedValues; // Called whenever we detect that the request headers have been completely // processed; which happens either when we get our first read/write callback, // or the request is finished being procesed. Returns nonzero on success, // zero on failure. static void request_headers_done(Request *request) { if (request->propertiesCallbackMade) { return; } request->propertiesCallbackMade = 1; // Get the http response code long httpResponseCode; request->httpResponseCode = 0; if (curl_easy_getinfo(request->curl, CURLINFO_RESPONSE_CODE, &httpResponseCode) != CURLE_OK) { // Not able to get the HTTP response code - error request->status = S3StatusInternalError; return; } else { request->httpResponseCode = httpResponseCode; } response_headers_handler_done(&(request->responseHeadersHandler), request->curl); // Only make the callback if it was a successful request; otherwise we're // returning information about the error response itself if (request->propertiesCallback && (request->httpResponseCode >= 200) && (request->httpResponseCode <= 299)) { request->status = (*(request->propertiesCallback)) (&(request->responseHeadersHandler.responseProperties), request->callbackData); } } static size_t curl_header_func(void *ptr, size_t size, size_t nmemb, void *data) { Request *request = (Request *) data; int len = size * nmemb; response_headers_handler_add (&(request->responseHeadersHandler), (char *) ptr, len); return len; } static size_t curl_read_func(void *ptr, size_t size, size_t nmemb, void *data) { Request *request = (Request *) data; int len = size * nmemb; // CURL may call this function before response headers are available, // so don't assume response headers are available and attempt to parse // them. Leave that to curl_write_func, which is guaranteed to be called // only after headers are available. if (request->status != S3StatusOK) { return CURL_READFUNC_ABORT; } // If there is no data callback, or the data callback has already returned // contentLength bytes, return 0; if (!request->toS3Callback || !request->toS3CallbackBytesRemaining) { return 0; } // Don't tell the callback that we are willing to accept more data than we // really are if (len > request->toS3CallbackBytesRemaining) { len = request->toS3CallbackBytesRemaining; } // Otherwise, make the data callback int ret = (*(request->toS3Callback)) (len, (char *) ptr, request->callbackData); if (ret < 0) { request->status = S3StatusAbortedByCallback; return CURL_READFUNC_ABORT; } else { if (ret > request->toS3CallbackBytesRemaining) { ret = request->toS3CallbackBytesRemaining; } request->toS3CallbackBytesRemaining -= ret; return ret; } } static size_t curl_write_func(void *ptr, size_t size, size_t nmemb, void *data) { Request *request = (Request *) data; int len = size * nmemb; request_headers_done(request); if (request->status != S3StatusOK) { return 0; } // On HTTP error, we expect to parse an HTTP error response if ((request->httpResponseCode < 200) || (request->httpResponseCode > 299)) { request->status = error_parser_add (&(request->errorParser), (char *) ptr, len); } // If there was a callback registered, make it else if (request->fromS3Callback) { request->status = (*(request->fromS3Callback)) (len, (char *) ptr, request->callbackData); } // Else, consider this an error - S3 has sent back data when it was not // expected else { request->status = S3StatusInternalError; } return ((request->status == S3StatusOK) ? len : 0); } // This function 'normalizes' all x-amz-meta headers provided in // params->requestHeaders, which means it removes all whitespace from // them such that they all look exactly like this: // x-amz-meta-${NAME}: ${VALUE} // It also adds the x-amz-acl, x-amz-copy-source, x-amz-metadata-directive, // and x-amz-server-side-encryption headers if necessary, and always adds the // x-amz-date header. It copies the raw string values into // params->amzHeadersRaw, and creates an array of string pointers representing // these headers in params->amzHeaders (and also sets params->amzHeadersCount // to be the count of the total number of x-amz- headers thus created). static S3Status compose_amz_headers(const RequestParams *params, RequestComputedValues *values) { const S3PutProperties *properties = params->putProperties; values->amzHeadersCount = 0; values->amzHeadersRaw[0] = 0; int len = 0; // Append a header to amzHeaders, trimming whitespace from the end. // Does NOT trim whitespace from the beginning. #define headers_append(isNewHeader, format, ...) \ do { \ if (isNewHeader) { \ values->amzHeaders[values->amzHeadersCount++] = \ &(values->amzHeadersRaw[len]); \ } \ len += snprintf(&(values->amzHeadersRaw[len]), \ sizeof(values->amzHeadersRaw) - len, \ format, __VA_ARGS__); \ if (len >= (int) sizeof(values->amzHeadersRaw)) { \ return S3StatusMetaDataHeadersTooLong; \ } \ while ((len > 0) && (values->amzHeadersRaw[len - 1] == ' ')) { \ len--; \ } \ values->amzHeadersRaw[len++] = 0; \ } while (0) #define header_name_tolower_copy(str, l) \ do { \ values->amzHeaders[values->amzHeadersCount++] = \ &(values->amzHeadersRaw[len]); \ if ((len + l) >= (int) sizeof(values->amzHeadersRaw)) { \ return S3StatusMetaDataHeadersTooLong; \ } \ int todo = l; \ while (todo--) { \ if ((*(str) >= 'A') && (*(str) <= 'Z')) { \ values->amzHeadersRaw[len++] = 'a' + (*(str) - 'A'); \ } \ else { \ values->amzHeadersRaw[len++] = *(str); \ } \ (str)++; \ } \ } while (0) // Check and copy in the x-amz-meta headers if (properties) { int i; for (i = 0; i < properties->metaDataCount; i++) { const S3NameValue *property = &(properties->metaData[i]); char headerName[S3_MAX_METADATA_SIZE - sizeof(": v")]; int l = snprintf(headerName, sizeof(headerName), S3_METADATA_HEADER_NAME_PREFIX "%s", property->name); char *hn = headerName; header_name_tolower_copy(hn, l); // Copy in the value headers_append(0, ": %s", property->value); } // Add the x-amz-acl header, if necessary const char *cannedAclString; switch (properties->cannedAcl) { case S3CannedAclPrivate: cannedAclString = 0; break; case S3CannedAclPublicRead: cannedAclString = "public-read"; break; case S3CannedAclPublicReadWrite: cannedAclString = "public-read-write"; break; default: // S3CannedAclAuthenticatedRead cannedAclString = "authenticated-read"; break; } if (cannedAclString) { headers_append(1, "x-amz-acl: %s", cannedAclString); } // Add the x-amz-server-side-encryption header, if necessary if (properties->useServerSideEncryption) { headers_append(1, "x-amz-server-side-encryption: %s", "AES256"); } } // Add the x-amz-date header time_t now = time(NULL); char date[64]; strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&now)); headers_append(1, "x-amz-date: %s", date); if (params->httpRequestType == HttpRequestTypeCOPY) { // Add the x-amz-copy-source header if (params->copySourceBucketName && params->copySourceBucketName[0] && params->copySourceKey && params->copySourceKey[0]) { headers_append(1, "x-amz-copy-source: /%s/%s", params->copySourceBucketName, params->copySourceKey); } // And the x-amz-metadata-directive header if (properties) { headers_append(1, "%s", "x-amz-metadata-directive: REPLACE"); } } return S3StatusOK; } // Composes the other headers static S3Status compose_standard_headers(const RequestParams *params, RequestComputedValues *values) { #define do_put_header(fmt, sourceField, destField, badError, tooLongError) \ do { \ if (params->putProperties && \ params->putProperties-> sourceField && \ params->putProperties-> sourceField[0]) { \ /* Skip whitespace at beginning of val */ \ const char *val = params->putProperties-> sourceField; \ while (*val && is_blank(*val)) { \ val++; \ } \ if (!*val) { \ return badError; \ } \ /* Compose header, make sure it all fit */ \ int len = snprintf(values-> destField, \ sizeof(values-> destField), fmt, val); \ if (len >= (int) sizeof(values-> destField)) { \ return tooLongError; \ } \ /* Now remove the whitespace at the end */ \ while (is_blank(values-> destField[len])) { \ len--; \ } \ values-> destField[len] = 0; \ } \ else { \ values-> destField[0] = 0; \ } \ } while (0) #define do_get_header(fmt, sourceField, destField, badError, tooLongError) \ do { \ if (params->getConditions && \ params->getConditions-> sourceField && \ params->getConditions-> sourceField[0]) { \ /* Skip whitespace at beginning of val */ \ const char *val = params->getConditions-> sourceField; \ while (*val && is_blank(*val)) { \ val++; \ } \ if (!*val) { \ return badError; \ } \ /* Compose header, make sure it all fit */ \ int len = snprintf(values-> destField, \ sizeof(values-> destField), fmt, val); \ if (len >= (int) sizeof(values-> destField)) { \ return tooLongError; \ } \ /* Now remove the whitespace at the end */ \ while (is_blank(values-> destField[len])) { \ len--; \ } \ values-> destField[len] = 0; \ } \ else { \ values-> destField[0] = 0; \ } \ } while (0) // Cache-Control do_put_header("Cache-Control: %s", cacheControl, cacheControlHeader, S3StatusBadCacheControl, S3StatusCacheControlTooLong); // ContentType do_put_header("Content-Type: %s", contentType, contentTypeHeader, S3StatusBadContentType, S3StatusContentTypeTooLong); // MD5 do_put_header("Content-MD5: %s", md5, md5Header, S3StatusBadMD5, S3StatusMD5TooLong); // Content-Disposition do_put_header("Content-Disposition: attachment; filename=\"%s\"", contentDispositionFilename, contentDispositionHeader, S3StatusBadContentDispositionFilename, S3StatusContentDispositionFilenameTooLong); // ContentEncoding do_put_header("Content-Encoding: %s", contentEncoding, contentEncodingHeader, S3StatusBadContentEncoding, S3StatusContentEncodingTooLong); // Expires if (params->putProperties && (params->putProperties->expires >= 0)) { time_t t = (time_t) params->putProperties->expires; strftime(values->expiresHeader, sizeof(values->expiresHeader), "Expires: %a, %d %b %Y %H:%M:%S UTC", gmtime(&t)); } else { values->expiresHeader[0] = 0; } // If-Modified-Since if (params->getConditions && (params->getConditions->ifModifiedSince >= 0)) { time_t t = (time_t) params->getConditions->ifModifiedSince; strftime(values->ifModifiedSinceHeader, sizeof(values->ifModifiedSinceHeader), "If-Modified-Since: %a, %d %b %Y %H:%M:%S UTC", gmtime(&t)); } else { values->ifModifiedSinceHeader[0] = 0; } // If-Unmodified-Since header if (params->getConditions && (params->getConditions->ifNotModifiedSince >= 0)) { time_t t = (time_t) params->getConditions->ifNotModifiedSince; strftime(values->ifUnmodifiedSinceHeader, sizeof(values->ifUnmodifiedSinceHeader), "If-Unmodified-Since: %a, %d %b %Y %H:%M:%S UTC", gmtime(&t)); } else { values->ifUnmodifiedSinceHeader[0] = 0; } // If-Match header do_get_header("If-Match: %s", ifMatchETag, ifMatchHeader, S3StatusBadIfMatchETag, S3StatusIfMatchETagTooLong); // If-None-Match header do_get_header("If-None-Match: %s", ifNotMatchETag, ifNoneMatchHeader, S3StatusBadIfNotMatchETag, S3StatusIfNotMatchETagTooLong); // Range header if (params->startByte || params->byteCount) { if (params->byteCount) { snprintf(values->rangeHeader, sizeof(values->rangeHeader), "Range: bytes=%llu-%llu", (unsigned long long) params->startByte, (unsigned long long) (params->startByte + params->byteCount - 1)); } else { snprintf(values->rangeHeader, sizeof(values->rangeHeader), "Range: bytes=%llu-", (unsigned long long) params->startByte); } } else { values->rangeHeader[0] = 0; } return S3StatusOK; } // URL encodes the params->key value into params->urlEncodedKey static S3Status encode_key(const RequestParams *params, RequestComputedValues *values) { return (urlEncode(values->urlEncodedKey, params->key, S3_MAX_KEY_SIZE) ? S3StatusOK : S3StatusUriTooLong); } // Simple comparison function for comparing two HTTP header names that are // embedded within an HTTP header line, returning true if header1 comes // before header2 alphabetically, false if not static int headerle(const char *header1, const char *header2) { while (1) { if (*header1 == ':') { return (*header2 != ':'); } else if (*header2 == ':') { return 0; } else if (*header2 < *header1) { return 0; } else if (*header2 > *header1) { return 1; } header1++, header2++; } } // Replace this with merge sort eventually, it's the best stable sort. But // since typically the number of elements being sorted is small, it doesn't // matter that much which sort is used, and gnome sort is the world's simplest // stable sort. Added a slight twist to the standard gnome_sort - don't go // forward +1, go forward to the last highest index considered. This saves // all the string comparisons that would be done "going forward", and thus // only does the necessary string comparisons to move values back into their // sorted position. static void header_gnome_sort(const char **headers, int size) { int i = 0, last_highest = 0; while (i < size) { if ((i == 0) || headerle(headers[i - 1], headers[i])) { i = ++last_highest; } else { const char *tmp = headers[i]; headers[i] = headers[i - 1]; headers[--i] = tmp; } } } // Canonicalizes the x-amz- headers into the canonicalizedAmzHeaders buffer static void canonicalize_amz_headers(RequestComputedValues *values) { // Make a copy of the headers that will be sorted const char *sortedHeaders[S3_MAX_METADATA_COUNT]; memcpy(sortedHeaders, values->amzHeaders, (values->amzHeadersCount * sizeof(sortedHeaders[0]))); // Now sort these header_gnome_sort(sortedHeaders, values->amzHeadersCount); // Now copy this sorted list into the buffer, all the while: // - folding repeated headers into single lines, and // - folding multiple lines // - removing the space after the colon int lastHeaderLen = 0, i; char *buffer = values->canonicalizedAmzHeaders; for (i = 0; i < values->amzHeadersCount; i++) { const char *header = sortedHeaders[i]; const char *c = header; // If the header names are the same, append the next value if ((i > 0) && !strncmp(header, sortedHeaders[i - 1], lastHeaderLen)) { // Replacing the previous newline with a comma *(buffer - 1) = ','; // Skip the header name and space c += (lastHeaderLen + 1); } // Else this is a new header else { // Copy in everything up to the space in the ": " while (*c != ' ') { *buffer++ = *c++; } // Save the header len since it's a new header lastHeaderLen = c - header; // Skip the space c++; } // Now copy in the value, folding the lines while (*c) { // If c points to a \r\n[whitespace] sequence, then fold // this newline out if ((*c == '\r') && (*(c + 1) == '\n') && is_blank(*(c + 2))) { c += 3; while (is_blank(*c)) { c++; } // Also, what has most recently been copied into buffer amy // have been whitespace, and since we're folding whitespace // out around this newline sequence, back buffer up over // any whitespace it contains while (is_blank(*(buffer - 1))) { buffer--; } continue; } *buffer++ = *c++; } // Finally, add the newline *buffer++ = '\n'; } // Terminate the buffer *buffer = 0; } // Canonicalizes the resource into params->canonicalizedResource static void canonicalize_resource(const char *bucketName, const char *subResource, const char *urlEncodedKey, char *buffer) { int len = 0; *buffer = 0; #define append(str) len += sprintf(&(buffer[len]), "%s", str) if (bucketName && bucketName[0]) { buffer[len++] = '/'; append(bucketName); } append("/"); if (urlEncodedKey && urlEncodedKey[0]) { append(urlEncodedKey); } if (subResource && subResource[0]) { append("?"); append(subResource); } } // Convert an HttpRequestType to an HTTP Verb string static const char *http_request_type_to_verb(HttpRequestType requestType) { switch (requestType) { case HttpRequestTypeGET: return "GET"; case HttpRequestTypeHEAD: return "HEAD"; case HttpRequestTypePUT: case HttpRequestTypeCOPY: return "PUT"; default: // HttpRequestTypeDELETE return "DELETE"; } } // Composes the Authorization header for the request static S3Status compose_auth_header(const RequestParams *params, RequestComputedValues *values) { // We allow for: // 17 bytes for HTTP-Verb + \n // 129 bytes for Content-MD5 + \n // 129 bytes for Content-Type + \n // 1 byte for empty Date + \n // CanonicalizedAmzHeaders & CanonicalizedResource char signbuf[17 + 129 + 129 + 1 + (sizeof(values->canonicalizedAmzHeaders) - 1) + (sizeof(values->canonicalizedResource) - 1) + 1]; int len = 0; #define signbuf_append(format, ...) \ len += snprintf(&(signbuf[len]), sizeof(signbuf) - len, \ format, __VA_ARGS__) signbuf_append ("%s\n", http_request_type_to_verb(params->httpRequestType)); // For MD5 and Content-Type, use the value in the actual header, because // it's already been trimmed signbuf_append("%s\n", values->md5Header[0] ? &(values->md5Header[sizeof("Content-MD5: ") - 1]) : ""); signbuf_append ("%s\n", values->contentTypeHeader[0] ? &(values->contentTypeHeader[sizeof("Content-Type: ") - 1]) : ""); signbuf_append("%s", "\n"); // Date - we always use x-amz-date signbuf_append("%s", values->canonicalizedAmzHeaders); signbuf_append("%s", values->canonicalizedResource); // Generate an HMAC-SHA-1 of the signbuf unsigned char hmac[20]; HMAC_SHA1(hmac, (unsigned char *) params->bucketContext.secretAccessKey, strlen(params->bucketContext.secretAccessKey), (unsigned char *) signbuf, len); // Now base-64 encode the results char b64[((20 + 1) * 4) / 3]; int b64Len = base64Encode(hmac, 20, b64); snprintf(values->authorizationHeader, sizeof(values->authorizationHeader), "Authorization: AWS %s:%.*s", params->bucketContext.accessKeyId, b64Len, b64); return S3StatusOK; } // Compose the URI to use for the request given the request parameters static S3Status compose_uri(char *buffer, int bufferSize, const S3BucketContext *bucketContext, const char *urlEncodedKey, const char *subResource, const char *queryParams) { int len = 0; #define uri_append(fmt, ...) \ do { \ len += snprintf(&(buffer[len]), bufferSize - len, fmt, __VA_ARGS__); \ if (len >= bufferSize) { \ return S3StatusUriTooLong; \ } \ } while (0) uri_append("http%s://", (bucketContext->protocol == S3ProtocolHTTP) ? "" : "s"); const char *hostName = bucketContext->hostName ? bucketContext->hostName : defaultHostNameG; if (bucketContext->bucketName && bucketContext->bucketName[0]) { if (bucketContext->uriStyle == S3UriStyleVirtualHost) { uri_append("%s.%s", bucketContext->bucketName, hostName); } else { uri_append("%s/%s", hostName, bucketContext->bucketName); } } else { uri_append("%s", hostName); } uri_append("%s", "/"); uri_append("%s", urlEncodedKey); if (subResource && subResource[0]) { uri_append("?%s", subResource); } if (queryParams) { uri_append("%s%s", (subResource && subResource[0]) ? "&" : "?", queryParams); } return S3StatusOK; } // Sets up the curl handle given the completely computed RequestParams static S3Status setup_curl(Request *request, const RequestParams *params, const RequestComputedValues *values) { CURLcode status; #define curl_easy_setopt_safe(opt, val) \ if ((status = curl_easy_setopt \ (request->curl, opt, val)) != CURLE_OK) { \ return S3StatusFailedToInitializeRequest; \ } // Debugging only // curl_easy_setopt_safe(CURLOPT_VERBOSE, 1); // Set private data to request for the benefit of S3RequestContext curl_easy_setopt_safe(CURLOPT_PRIVATE, request); // Set header callback and data curl_easy_setopt_safe(CURLOPT_HEADERDATA, request); curl_easy_setopt_safe(CURLOPT_HEADERFUNCTION, &curl_header_func); // Set read callback, data, and readSize curl_easy_setopt_safe(CURLOPT_READFUNCTION, &curl_read_func); curl_easy_setopt_safe(CURLOPT_READDATA, request); // Set write callback and data curl_easy_setopt_safe(CURLOPT_WRITEFUNCTION, &curl_write_func); curl_easy_setopt_safe(CURLOPT_WRITEDATA, request); // Ask curl to parse the Last-Modified header. This is easier than // parsing it ourselves. curl_easy_setopt_safe(CURLOPT_FILETIME, 1); // Curl docs suggest that this is necessary for multithreaded code. // However, it also points out that DNS timeouts will not be honored // during DNS lookup, which can be worked around by using the c-ares // library, which we do not do yet. curl_easy_setopt_safe(CURLOPT_NOSIGNAL, 1); // Turn off Curl's built-in progress meter curl_easy_setopt_safe(CURLOPT_NOPROGRESS, 1); // xxx todo - support setting the proxy for Curl to use (can't use https // for proxies though) // xxx todo - support setting the network interface for Curl to use // I think this is useful - we don't need interactive performance, we need // to complete large operations quickly curl_easy_setopt_safe(CURLOPT_TCP_NODELAY, 1); // Don't use Curl's 'netrc' feature curl_easy_setopt_safe(CURLOPT_NETRC, CURL_NETRC_IGNORED); // Don't verify S3's certificate, there are known to be issues with // them sometimes // xxx todo - support an option for verifying the S3 CA (default false) curl_easy_setopt_safe(CURLOPT_SSL_VERIFYPEER, 0); // Follow any redirection directives that S3 sends curl_easy_setopt_safe(CURLOPT_FOLLOWLOCATION, 1); // A safety valve in case S3 goes bananas with redirects curl_easy_setopt_safe(CURLOPT_MAXREDIRS, 10); // Set the User-Agent; maybe Amazon will track these? curl_easy_setopt_safe(CURLOPT_USERAGENT, userAgentG); // Set the low speed limit and time; we abort transfers that stay at // less than 1K per second for more than 15 seconds. // xxx todo - make these configurable // xxx todo - allow configurable max send and receive speed curl_easy_setopt_safe(CURLOPT_LOW_SPEED_LIMIT, 1024); curl_easy_setopt_safe(CURLOPT_LOW_SPEED_TIME, 15); // Append standard headers #define append_standard_header(fieldName) \ if (values-> fieldName [0]) { \ request->headers = curl_slist_append(request->headers, \ values-> fieldName); \ } // Would use CURLOPT_INFILESIZE_LARGE, but it is buggy in libcurl if (params->httpRequestType == HttpRequestTypePUT) { char header[256]; snprintf(header, sizeof(header), "Content-Length: %llu", (unsigned long long) params->toS3CallbackTotalSize); request->headers = curl_slist_append(request->headers, header); request->headers = curl_slist_append(request->headers, "Transfer-Encoding:"); } else if (params->httpRequestType == HttpRequestTypeCOPY) { request->headers = curl_slist_append(request->headers, "Transfer-Encoding:"); } append_standard_header(cacheControlHeader); append_standard_header(contentTypeHeader); append_standard_header(md5Header); append_standard_header(contentDispositionHeader); append_standard_header(contentEncodingHeader); append_standard_header(expiresHeader); append_standard_header(ifModifiedSinceHeader); append_standard_header(ifUnmodifiedSinceHeader); append_standard_header(ifMatchHeader); append_standard_header(ifNoneMatchHeader); append_standard_header(rangeHeader); append_standard_header(authorizationHeader); // Append x-amz- headers int i; for (i = 0; i < values->amzHeadersCount; i++) { request->headers = curl_slist_append(request->headers, values->amzHeaders[i]); } // Set the HTTP headers curl_easy_setopt_safe(CURLOPT_HTTPHEADER, request->headers); // Set URI curl_easy_setopt_safe(CURLOPT_URL, request->uri); // Set request type. switch (params->httpRequestType) { case HttpRequestTypeHEAD: curl_easy_setopt_safe(CURLOPT_NOBODY, 1); break; case HttpRequestTypePUT: case HttpRequestTypeCOPY: curl_easy_setopt_safe(CURLOPT_UPLOAD, 1); break; case HttpRequestTypeDELETE: curl_easy_setopt_safe(CURLOPT_CUSTOMREQUEST, "DELETE"); break; default: // HttpRequestTypeGET break; } return S3StatusOK; } static void request_deinitialize(Request *request) { if (request->headers) { curl_slist_free_all(request->headers); } error_parser_deinitialize(&(request->errorParser)); // curl_easy_reset prevents connections from being re-used for some // reason. This makes HTTP Keep-Alive meaningless and is very bad for // performance. But it is necessary to allow curl to work properly. // xxx todo figure out why curl_easy_reset(request->curl); } static S3Status request_get(const RequestParams *params, const RequestComputedValues *values, Request **reqReturn) { Request *request = 0; // Try to get one from the request stack. We hold the lock for the // shortest time possible here. pthread_mutex_lock(&requestStackMutexG); if (requestStackCountG) { request = requestStackG[--requestStackCountG]; } pthread_mutex_unlock(&requestStackMutexG); // If we got one, deinitialize it for re-use if (request) { request_deinitialize(request); } // Else there wasn't one available in the request stack, so create one else { if (!(request = (Request *) malloc(sizeof(Request)))) { return S3StatusOutOfMemory; } if (!(request->curl = curl_easy_init())) { free(request); return S3StatusFailedToInitializeRequest; } } // Initialize the request request->prev = 0; request->next = 0; // Request status is initialized to no error, will be updated whenever // an error occurs request->status = S3StatusOK; S3Status status; // Start out with no headers request->headers = 0; // Compute the URL if ((status = compose_uri (request->uri, sizeof(request->uri), &(params->bucketContext), values->urlEncodedKey, params->subResource, params->queryParams)) != S3StatusOK) { curl_easy_cleanup(request->curl); free(request); return status; } // Set all of the curl handle options if ((status = setup_curl(request, params, values)) != S3StatusOK) { curl_easy_cleanup(request->curl); free(request); return status; } request->propertiesCallback = params->propertiesCallback; request->toS3Callback = params->toS3Callback; request->toS3CallbackBytesRemaining = params->toS3CallbackTotalSize; request->fromS3Callback = params->fromS3Callback; request->completeCallback = params->completeCallback; request->callbackData = params->callbackData; response_headers_handler_initialize(&(request->responseHeadersHandler)); request->propertiesCallbackMade = 0; error_parser_initialize(&(request->errorParser)); *reqReturn = request; return S3StatusOK; } static void request_destroy(Request *request) { request_deinitialize(request); curl_easy_cleanup(request->curl); free(request); } static void request_release(Request *request) { pthread_mutex_lock(&requestStackMutexG); // If the request stack is full, destroy this one if (requestStackCountG == REQUEST_STACK_SIZE) { pthread_mutex_unlock(&requestStackMutexG); request_destroy(request); } // Else put this one at the front of the request stack; we do this because // we want the most-recently-used curl handle to be re-used on the next // request, to maximize our chances of re-using a TCP connection before it // times out else { requestStackG[requestStackCountG++] = request; pthread_mutex_unlock(&requestStackMutexG); } } S3Status request_api_initialize(const char *userAgentInfo, int flags, const char *defaultHostName) { if (curl_global_init(CURL_GLOBAL_ALL & ~((flags & S3_INIT_WINSOCK) ? 0 : CURL_GLOBAL_WIN32)) != CURLE_OK) { return S3StatusInternalError; } if (!defaultHostName) { defaultHostName = S3_DEFAULT_HOSTNAME; } if (snprintf(defaultHostNameG, S3_MAX_HOSTNAME_SIZE, "%s", defaultHostName) >= S3_MAX_HOSTNAME_SIZE) { return S3StatusUriTooLong; } pthread_mutex_init(&requestStackMutexG, 0); requestStackCountG = 0; if (!userAgentInfo || !*userAgentInfo) { userAgentInfo = "Unknown"; } char platform[96]; struct utsname utsn; if (uname(&utsn)) { strncpy(platform, "Unknown", sizeof(platform)); // Because strncpy doesn't always zero terminate platform[sizeof(platform) - 1] = 0; } else { snprintf(platform, sizeof(platform), "%s%s%s", utsn.sysname, utsn.machine[0] ? " " : "", utsn.machine); } snprintf(userAgentG, sizeof(userAgentG), "Mozilla/4.0 (Compatible; %s; libs3 %s.%s; %s)", userAgentInfo, LIBS3_VER_MAJOR, LIBS3_VER_MINOR, platform); return S3StatusOK; } void request_api_deinitialize() { pthread_mutex_destroy(&requestStackMutexG); while (requestStackCountG--) { request_destroy(requestStackG[requestStackCountG]); } } void request_perform(const RequestParams *params, S3RequestContext *context) { Request *request; S3Status status; #define return_status(status) \ (*(params->completeCallback))(status, 0, params->callbackData); \ return // These will hold the computed values RequestComputedValues computed; // Validate the bucket name if (params->bucketContext.bucketName && ((status = S3_validate_bucket_name (params->bucketContext.bucketName, params->bucketContext.uriStyle)) != S3StatusOK)) { return_status(status); } // Compose the amz headers if ((status = compose_amz_headers(params, &computed)) != S3StatusOK) { return_status(status); } // Compose standard headers if ((status = compose_standard_headers (params, &computed)) != S3StatusOK) { return_status(status); } // URL encode the key if ((status = encode_key(params, &computed)) != S3StatusOK) { return_status(status); } // Compute the canonicalized amz headers canonicalize_amz_headers(&computed); // Compute the canonicalized resource canonicalize_resource(params->bucketContext.bucketName, params->subResource, computed.urlEncodedKey, computed.canonicalizedResource); // Compose Authorization header if ((status = compose_auth_header(params, &computed)) != S3StatusOK) { return_status(status); } // Get an initialized Request structure now if ((status = request_get(params, &computed, &request)) != S3StatusOK) { return_status(status); } // If a RequestContext was provided, add the request to the curl multi if (context) { CURLMcode code = curl_multi_add_handle(context->curlm, request->curl); if (code == CURLM_OK) { if (context->requests) { request->prev = context->requests->prev; request->next = context->requests; context->requests->prev->next = request; context->requests->prev = request; } else { context->requests = request->next = request->prev = request; } } else { if (request->status == S3StatusOK) { request->status = (code == CURLM_OUT_OF_MEMORY) ? S3StatusOutOfMemory : S3StatusInternalError; } request_finish(request); } } // Else, perform the request immediately else { CURLcode code = curl_easy_perform(request->curl); if ((code != CURLE_OK) && (request->status == S3StatusOK)) { request->status = request_curl_code_to_status(code); } // Finish the request, ensuring that all callbacks have been made, and // also releases the request request_finish(request); } } void request_finish(Request *request) { // If we haven't detected this already, we now know that the headers are // definitely done being read in request_headers_done(request); // If there was no error processing the request, then possibly there was // an S3 error parsed, which should be converted into the request status if (request->status == S3StatusOK) { error_parser_convert_status(&(request->errorParser), &(request->status)); // If there still was no error recorded, then it is possible that // there was in fact an error but that there was no error XML // detailing the error if ((request->status == S3StatusOK) && ((request->httpResponseCode < 200) || (request->httpResponseCode > 299))) { switch (request->httpResponseCode) { case 0: // This happens if the request never got any HTTP response // headers at all, we call this a ConnectionFailed error request->status = S3StatusConnectionFailed; break; case 100: // Some versions of libcurl erroneously set HTTP // status to this break; case 301: request->status = S3StatusErrorPermanentRedirect; break; case 307: request->status = S3StatusHttpErrorMovedTemporarily; break; case 400: request->status = S3StatusHttpErrorBadRequest; break; case 403: request->status = S3StatusHttpErrorForbidden; break; case 404: request->status = S3StatusHttpErrorNotFound; break; case 405: request->status = S3StatusErrorMethodNotAllowed; break; case 409: request->status = S3StatusHttpErrorConflict; break; case 411: request->status = S3StatusErrorMissingContentLength; break; case 412: request->status = S3StatusErrorPreconditionFailed; break; case 416: request->status = S3StatusErrorInvalidRange; break; case 500: request->status = S3StatusErrorInternalError; break; case 501: request->status = S3StatusErrorNotImplemented; break; case 503: request->status = S3StatusErrorSlowDown; break; default: request->status = S3StatusHttpErrorUnknown; break; } } } (*(request->completeCallback)) (request->status, &(request->errorParser.s3ErrorDetails), request->callbackData); request_release(request); } S3Status request_curl_code_to_status(CURLcode code) { switch (code) { case CURLE_OUT_OF_MEMORY: return S3StatusOutOfMemory; case CURLE_COULDNT_RESOLVE_PROXY: case CURLE_COULDNT_RESOLVE_HOST: return S3StatusNameLookupError; case CURLE_COULDNT_CONNECT: return S3StatusFailedToConnect; case CURLE_WRITE_ERROR: case CURLE_OPERATION_TIMEDOUT: return S3StatusConnectionFailed; case CURLE_PARTIAL_FILE: return S3StatusOK; case CURLE_SSL_CACERT: return S3StatusServerFailedVerification; default: return S3StatusInternalError; } } S3Status S3_generate_authenticated_query_string (char *buffer, const S3BucketContext *bucketContext, const char *key, int64_t expires, const char *resource) { #define MAX_EXPIRES (((int64_t) 1 << 31) - 1) // S3 seems to only accept expiration dates up to the number of seconds // representably by a signed 32-bit integer if (expires < 0) { expires = MAX_EXPIRES; } else if (expires > MAX_EXPIRES) { expires = MAX_EXPIRES; } // xxx todo: rework this so that it can be incorporated into shared code // with request_perform(). It's really unfortunate that this code is not // shared with request_perform(). // URL encode the key char urlEncodedKey[S3_MAX_KEY_SIZE * 3]; if (key) { urlEncode(urlEncodedKey, key, strlen(key)); } else { urlEncodedKey[0] = 0; } // Compute canonicalized resource char canonicalizedResource[MAX_CANONICALIZED_RESOURCE_SIZE]; canonicalize_resource(bucketContext->bucketName, resource, urlEncodedKey, canonicalizedResource); // We allow for: // 17 bytes for HTTP-Verb + \n // 1 byte for empty Content-MD5 + \n // 1 byte for empty Content-Type + \n // 20 bytes for Expires + \n // 0 bytes for CanonicalizedAmzHeaders // CanonicalizedResource char signbuf[17 + 1 + 1 + 1 + 20 + sizeof(canonicalizedResource) + 1]; int len = 0; #define signbuf_append(format, ...) \ len += snprintf(&(signbuf[len]), sizeof(signbuf) - len, \ format, __VA_ARGS__) signbuf_append("%s\n", "GET"); // HTTP-Verb signbuf_append("%s\n", ""); // Content-MD5 signbuf_append("%s\n", ""); // Content-Type signbuf_append("%llu\n", (unsigned long long) expires); signbuf_append("%s", canonicalizedResource); // Generate an HMAC-SHA-1 of the signbuf unsigned char hmac[20]; HMAC_SHA1(hmac, (unsigned char *) bucketContext->secretAccessKey, strlen(bucketContext->secretAccessKey), (unsigned char *) signbuf, len); // Now base-64 encode the results char b64[((20 + 1) * 4) / 3]; int b64Len = base64Encode(hmac, 20, b64); // Now urlEncode that char signature[sizeof(b64) * 3]; urlEncode(signature, b64, b64Len); // Finally, compose the uri, with params: // ?AWSAccessKeyId=xxx[&Expires=]&Signature=xxx char queryParams[sizeof("AWSAccessKeyId=") + 20 + sizeof("&Expires=") + 20 + sizeof("&Signature=") + sizeof(signature) + 1]; sprintf(queryParams, "AWSAccessKeyId=%s&Expires=%ld&Signature=%s", bucketContext->accessKeyId, (long) expires, signature); return compose_uri(buffer, S3_MAX_AUTHENTICATED_QUERY_STRING_SIZE, bucketContext, urlEncodedKey, resource, queryParams); }
irods/libs3_original
src/request.c
C
gpl-3.0
50,518