code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Copyright 2011 Red Hat, Inc. and/or its affiliates.
*
* Licensed 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 org.drools.core.util;
import org.drools.core.factmodel.traits.IndexedTypeHierarchy;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class HierarchyTest {
@Test
public void testHierEncoderTrivial() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "B" ) );
encoder.encode( "D", Arrays.asList( "B", "C" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0" ), encoder.getCode( "A" ) );
assertEquals( parseBitSet( "1" ), encoder.getCode( "B" ) );
assertEquals( parseBitSet( "11" ), encoder.getCode( "C" ) );
assertEquals( parseBitSet( "111" ), encoder.getCode( "D" ) );
}
@Test
public void testHierManyRoots() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Collections.EMPTY_LIST );
encoder.encode( "C", Collections.EMPTY_LIST );
encoder.encode( "D", Collections.EMPTY_LIST );
encoder.encode( "E", Collections.EMPTY_LIST );
System.out.println( encoder );
assertEquals( parseBitSet( "1" ), encoder.getCode( "A" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "B" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "C" ) );
assertEquals( parseBitSet( "1000" ), encoder.getCode( "D" ) );
assertEquals( parseBitSet( "10000" ), encoder.getCode( "E" ) );
assertEquals( 5, encoder.size() );
assertEquals( 5, encoder.getSortedMembers().size() );
assertEquals( 5, encoder.getSortedMap().size() );
}
@Test
public void testHierManyRootsPropagation() {
HierarchyEncoderImpl encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "A" ) );
encoder.encode( "D", Arrays.asList( "B", "C" ) );
encoder.encode( "E", Collections.EMPTY_LIST );
System.out.println( encoder );
BitSet a = encoder.getCode( "A" );
BitSet b = encoder.getCode( "B" );
BitSet c = encoder.getCode( "C" );
BitSet d = encoder.getCode( "D" );
BitSet e = encoder.getCode( "E" );
assertTrue( encoder.superset( b, a ) > 0 );
assertTrue( encoder.superset( c, a ) > 0 );
assertTrue( encoder.superset( d, a ) > 0 );
assertTrue( encoder.superset( d, b ) > 0 );
assertTrue( encoder.superset( d, c ) > 0 );
assertTrue( encoder.superset( e, a ) < 0 );
assertTrue( encoder.superset( e, b ) < 0 );
assertTrue( encoder.superset( e, c ) < 0 );
assertTrue( encoder.superset( e, d ) < 0 );
assertTrue( encoder.superset( e, e ) == 0 );
}
@Test
public void testHierALotOfClasses() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
int N = 1194;
encoder.encode( "A", Collections.EMPTY_LIST );
for ( int j = 1; j < N; j++ ) {
encoder.encode( "X" + j, Arrays.asList( "A" ) );
}
assertEquals( N, encoder.size() );
BitSet code = encoder.getCode( "X" + ( N -1 ) );
assertEquals( 1, code.cardinality() );
assertTrue( code.get( N - 2 ) );
}
@Test
public void testHierEncoderSimpleInheritance() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "A" ) );
encoder.encode( "D", Arrays.asList( "B" ) );
encoder.encode( "E", Arrays.asList( "B" ) );
encoder.encode( "F", Arrays.asList( "C" ) );
encoder.encode( "G", Arrays.asList( "C" ) );
System.out.println( encoder );
assertEquals( parseBitSet("0"), encoder.getCode("A"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "B" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "C" ) );
assertEquals( parseBitSet( "101" ), encoder.getCode( "D" ) );
assertEquals( parseBitSet( "1001" ), encoder.getCode( "E" ) );
assertEquals( parseBitSet( "110" ), encoder.getCode( "F" ) );
assertEquals( parseBitSet( "1010" ), encoder.getCode( "G" ) );
}
@Test
public void testHierEncoderAnotherSimpleInheritance() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "R", Collections.EMPTY_LIST );
encoder.encode( "A1", Arrays.asList( "R" ) );
encoder.encode( "A2", Arrays.asList( "R" ) );
encoder.encode( "A3", Arrays.asList( "R" ) );
encoder.encode( "B1", Arrays.asList( "R" ) );
encoder.encode( "B2", Arrays.asList( "R" ) );
encoder.encode( "B3", Arrays.asList( "R" ) );
encoder.encode( "B4", Arrays.asList( "B1", "B2" ) );
encoder.encode( "B5", Arrays.asList( "B1", "B3" ) );
encoder.encode( "B6", Arrays.asList( "B2", "B3" ) );
encoder.encode( "B7", Arrays.asList( "B4", "B5", "B6" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0"), encoder.getCode("R"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "A1" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "A2" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "A3" ) );
assertEquals( parseBitSet( "1000" ), encoder.getCode( "B1" ) );
assertEquals( parseBitSet( "10000" ), encoder.getCode( "B2" ) );
assertEquals( parseBitSet( "100000" ), encoder.getCode( "B3" ) );
assertEquals( parseBitSet( "11000" ), encoder.getCode( "B4" ) );
assertEquals( parseBitSet( "101000" ), encoder.getCode( "B5" ) );
assertEquals( parseBitSet( "110000" ), encoder.getCode( "B6" ) );
assertEquals( parseBitSet( "111000" ), encoder.getCode( "B7" ) );
}
@Test
public void testHierEncoderAnotherSimpleInheritanceChangeOrder() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "R", Collections.EMPTY_LIST );
encoder.encode( "B1", Arrays.asList( "R" ) );
encoder.encode( "B2", Arrays.asList( "R" ) );
encoder.encode( "B3", Arrays.asList( "R" ) );
encoder.encode( "B4", Arrays.asList( "B1", "B2" ) );
encoder.encode( "B5", Arrays.asList( "B1", "B3" ) );
encoder.encode( "B6", Arrays.asList( "B2", "B3" ) );
encoder.encode( "B7", Arrays.asList( "B4", "B5", "B6" ) );
encoder.encode( "A1", Arrays.asList( "R" ) );
encoder.encode( "A2", Arrays.asList( "R" ) );
encoder.encode( "A3", Arrays.asList( "R" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0"), encoder.getCode("R"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "B1" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "B2" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "B3" ) );
assertEquals( parseBitSet( "11" ), encoder.getCode( "B4" ) );
assertEquals( parseBitSet( "101" ), encoder.getCode( "B5" ) );
assertEquals( parseBitSet( "110" ), encoder.getCode( "B6" ) );
assertEquals( parseBitSet( "111" ), encoder.getCode( "B7" ) );
assertEquals( parseBitSet( "1000" ), encoder.getCode( "A1" ) );
assertEquals( parseBitSet( "10000" ), encoder.getCode( "A2" ) );
assertEquals( parseBitSet( "100000" ), encoder.getCode( "A3" ) );
}
@Test
public void testHierEncoderBipartiteInheritance() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "R", Collections.EMPTY_LIST );
encoder.encode( "A1", Arrays.asList( "R" ) );
encoder.encode( "A2", Arrays.asList( "R" ) );
encoder.encode( "A3", Arrays.asList( "R" ) );
encoder.encode( "B1", Arrays.asList( "R" ) );
encoder.encode( "B2", Arrays.asList( "R" ) );
encoder.encode( "B3", Arrays.asList( "R" ) );
encoder.encode( "B4", Arrays.asList( "B1", "B2", "B3" ) );
encoder.encode( "B5", Arrays.asList( "B1", "B2", "B3" ) );
encoder.encode( "B6", Arrays.asList( "B1", "B2", "B3" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0"), encoder.getCode("R"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "A1" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "A2" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "A3" ) );
assertEquals( parseBitSet( "1000" ), encoder.getCode( "B1" ) );
assertEquals( parseBitSet( "10000" ), encoder.getCode( "B2" ) );
assertEquals( parseBitSet( "100000" ), encoder.getCode( "B3" ) );
assertEquals( parseBitSet( "10111000" ), encoder.getCode( "B4" ) );
assertEquals( parseBitSet( "1111000" ), encoder.getCode( "B5" ) );
assertEquals( parseBitSet( "100111000" ), encoder.getCode( "B6" ) );
}
@Test
public void testHierEncoderBipartiteInheritanceDiffOrder() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "R", Collections.EMPTY_LIST );
encoder.encode( "B1", Arrays.asList( "R" ) );
encoder.encode( "B2", Arrays.asList( "R" ) );
encoder.encode( "B3", Arrays.asList( "R" ) );
encoder.encode( "B4", Arrays.asList( "B1", "B2", "B3" ) );
encoder.encode( "B5", Arrays.asList( "B1", "B2", "B3" ) );
encoder.encode( "B6", Arrays.asList( "B1", "B2", "B3" ) );
encoder.encode( "A1", Arrays.asList( "R" ) );
encoder.encode( "A2", Arrays.asList( "R" ) );
encoder.encode( "A3", Arrays.asList( "R" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0"), encoder.getCode("R"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "B1" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "B2" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "B3" ) );
assertEquals( parseBitSet( "10111" ), encoder.getCode( "B4" ) );
assertEquals( parseBitSet( "1111" ), encoder.getCode( "B5" ) );
assertEquals( parseBitSet( "100111" ), encoder.getCode( "B6" ) );
assertEquals( parseBitSet( "1000000" ), encoder.getCode( "A1" ) );
assertEquals( parseBitSet( "10000000" ), encoder.getCode( "A2" ) );
assertEquals( parseBitSet( "100000000" ), encoder.getCode( "A3" ) );
}
@Test
public void testSquare() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "T", Collections.EMPTY_LIST );
encoder.encode( "A", Arrays.asList( "T" ) );
encoder.encode( "B", Arrays.asList( "T" ) );
encoder.encode( "C", Arrays.asList( "A", "B" ) );
encoder.encode( "D", Arrays.asList( "A", "B" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0" ), encoder.getCode( "T" ) );
assertEquals( parseBitSet( "1" ), encoder.getCode( "A" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "B" ) );
assertEquals( parseBitSet( "111" ), encoder.getCode( "D" ) );
assertEquals( parseBitSet( "1011" ), encoder.getCode( "C" ) );
}
@Test
public void testConflictArising() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "A" ) );
encoder.encode( "D", Arrays.asList( "B" ) );
encoder.encode( "E", Arrays.asList( "B" ) );
encoder.encode( "F", Arrays.asList( "C" ) );
encoder.encode( "G", Arrays.asList( "C" ) );
encoder.encode( "H", Arrays.asList( "E" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0" ), encoder.getCode( "A" ) );
assertEquals( parseBitSet( "1" ), encoder.getCode( "B" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "C" ) );
assertEquals( parseBitSet( "101" ), encoder.getCode( "D" ) );
assertEquals( parseBitSet( "1001" ), encoder.getCode( "E" ) );
assertEquals( parseBitSet( "110" ), encoder.getCode( "F" ) );
assertEquals( parseBitSet( "1010" ), encoder.getCode( "G" ) );
assertEquals( parseBitSet( "11001" ), encoder.getCode( "H" ) );
encoder.encode( "I", Arrays.asList( "E", "F" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0" ), encoder.getCode( "A" ) );
assertEquals( parseBitSet( "1" ), encoder.getCode( "B" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "C" ) );
assertEquals( parseBitSet( "101" ), encoder.getCode( "D" ) );
assertEquals( parseBitSet( "1000001" ), encoder.getCode( "E" ) );
assertEquals( parseBitSet( "100010" ), encoder.getCode( "F" ) );
assertEquals( parseBitSet( "1010" ), encoder.getCode( "G" ) );
assertEquals( parseBitSet( "1010001" ), encoder.getCode( "H" ) );
assertEquals( parseBitSet( "1100011" ), encoder.getCode( "I" ) );
checkHier( encoder, 'I' );
}
@Test
public void testConflictArising2() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "A" ) );
encoder.encode( "D", Arrays.asList( "B" ) );
encoder.encode( "E", Arrays.asList( "B" ) );
encoder.encode( "F", Arrays.asList( "C" ) );
encoder.encode( "G", Arrays.asList( "C" ) );
encoder.encode( "H", Arrays.asList( "E" ) );
encoder.encode( "J", Arrays.asList( "F" ) );
encoder.encode( "K", Arrays.asList( "J" ) );
System.out.println( encoder );
encoder.encode( "I", Arrays.asList( "E", "F" ) );
System.out.println( encoder );
checkHier( encoder, 'K' );
}
@Test
public void testHierEncoderBipartiteStarInheritance() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "R", Collections.EMPTY_LIST );
encoder.encode( "B1", Arrays.asList( "R" ) );
encoder.encode( "B2", Arrays.asList( "R" ) );
encoder.encode( "B3", Arrays.asList( "R" ) );
encoder.encode( "B4", Arrays.asList( "B1", "B2" ) );
encoder.encode( "B5", Arrays.asList( "B1", "B3" ) );
encoder.encode( "B6", Arrays.asList( "B2", "B3" ) );
encoder.encode( "B7", Arrays.asList( "B4", "B5", "B6" ) );
encoder.encode( "A1", Arrays.asList( "R" ) );
encoder.encode( "A2", Arrays.asList( "R" ) );
encoder.encode( "A3", Arrays.asList( "R" ) );
encoder.encode( "A4", Arrays.asList( "A1", "A2", "A3" ) );
encoder.encode( "A5", Arrays.asList( "A4" ) );
encoder.encode( "A6", Arrays.asList( "A4" ) );
encoder.encode( "A7", Arrays.asList( "A4" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0"), encoder.getCode("R"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "B1" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "B2" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "B3" ) );
assertEquals( parseBitSet( "11" ), encoder.getCode( "B4" ) );
assertEquals( parseBitSet( "101" ), encoder.getCode( "B5" ) );
assertEquals( parseBitSet( "110" ), encoder.getCode( "B6" ) );
assertEquals( parseBitSet( "111" ), encoder.getCode( "B7" ) );
assertEquals( parseBitSet( "1000" ), encoder.getCode( "A1" ) );
assertEquals( parseBitSet( "10000" ), encoder.getCode( "A2" ) );
assertEquals( parseBitSet( "100000" ), encoder.getCode( "A3" ) );
assertEquals( parseBitSet( "111000" ), encoder.getCode( "A4" ) );
assertEquals( parseBitSet( "1111000" ), encoder.getCode( "A5" ) );
assertEquals( parseBitSet( "10111000" ), encoder.getCode( "A6" ) );
assertEquals( parseBitSet( "100111000" ), encoder.getCode( "A7" ) );
}
@Test
public void testHierEncoderBipartiteStarInheritanceDiffOrder() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "R", Collections.EMPTY_LIST );
encoder.encode( "A1", Arrays.asList( "R" ) );
encoder.encode( "A2", Arrays.asList( "R" ) );
encoder.encode( "A3", Arrays.asList( "R" ) );
encoder.encode( "A4", Arrays.asList( "A1", "A2", "A3" ) );
encoder.encode( "A5", Arrays.asList( "A4" ) );
encoder.encode( "A6", Arrays.asList( "A4" ) );
encoder.encode( "A7", Arrays.asList( "A4" ) );
encoder.encode( "B1", Arrays.asList( "R" ) );
encoder.encode( "B2", Arrays.asList( "R" ) );
encoder.encode( "B3", Arrays.asList( "R" ) );
encoder.encode( "B4", Arrays.asList( "B1", "B2" ) );
encoder.encode( "B5", Arrays.asList( "B1", "B3" ) );
encoder.encode( "B6", Arrays.asList( "B2", "B3" ) );
encoder.encode( "B7", Arrays.asList( "B4", "B5", "B6" ) );
System.out.println( encoder );
assertEquals( parseBitSet( "0"), encoder.getCode("R"));
assertEquals( parseBitSet( "1" ), encoder.getCode( "A1" ) );
assertEquals( parseBitSet( "10" ), encoder.getCode( "A2" ) );
assertEquals( parseBitSet( "100" ), encoder.getCode( "A3" ) );
assertEquals( parseBitSet( "111" ), encoder.getCode( "A4" ) );
assertEquals( parseBitSet( "1111" ), encoder.getCode( "A5" ) );
assertEquals( parseBitSet( "10111" ), encoder.getCode( "A6" ) );
assertEquals( parseBitSet( "100111" ), encoder.getCode( "A7" ) );
assertEquals( parseBitSet( "1000000" ), encoder.getCode( "B1" ) );
assertEquals( parseBitSet( "10000000" ), encoder.getCode( "B2" ) );
assertEquals( parseBitSet( "100000000" ), encoder.getCode( "B3" ) );
assertEquals( parseBitSet( "011000000" ), encoder.getCode( "B4" ) );
assertEquals( parseBitSet( "101000000" ), encoder.getCode( "B5" ) );
assertEquals( parseBitSet( "110000000" ), encoder.getCode( "B6" ) );
assertEquals( parseBitSet( "111000000" ), encoder.getCode( "B7" ) );
}
private BitSet parseBitSet( String s ) {
BitSet b = new BitSet();
int n = s.length();
for( int j = 0; j < s.length(); j++ ) {
if ( s.charAt( j ) == '1' ) {
b.set( n - j - 1 );
}
}
return b;
}
@Test
public void testHierEncoderComplexInheritance() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
checkHier( encoder, 'A' );
encoder.encode( "B", Arrays.asList( "A" ) );
checkHier( encoder, 'B' );
encoder.encode( "C", Arrays.asList( "A" ) );
checkHier( encoder, 'C' );
encoder.encode( "D", Arrays.asList( "B" ) );
checkHier( encoder, 'D' );
encoder.encode( "E", Arrays.asList( "B" ) );
checkHier( encoder, 'E' );
encoder.encode( "F", Arrays.asList( "C" ) );
checkHier( encoder, 'F' );
encoder.encode( "G", Arrays.asList( "C" ) );
checkHier( encoder, 'G' );
encoder.encode( "H", Arrays.asList( "D" ) );
checkHier( encoder, 'H' );
encoder.encode( "I", Arrays.asList( "D" ) );
checkHier( encoder, 'I' );
//
encoder.encode( "J", Arrays.asList( "E", "F" ) );
checkHier( encoder, 'J' );
encoder.encode( "K", Arrays.asList( "E", "F" ) );
checkHier( encoder, 'K' );
encoder.encode( "L", Arrays.asList( "G" ) );
checkHier( encoder, 'L' );
encoder.encode( "M", Arrays.asList( "G" ) );
checkHier( encoder, 'M' );
encoder.encode( "N", Arrays.asList( "I", "L" ) );
checkHier( encoder, 'N' );
encoder.encode( "O", Arrays.asList( "H", "M" ) );
checkHier( encoder, 'O' );
System.out.println( encoder );
Collection<BitSet> codes = encoder.getSortedMap().values();
Iterator<BitSet> iter = codes.iterator();
Long last = -1L;
for ( int j = 0; j < codes.size() -1; j++ ) {
BitSet ns = iter.next();
Long next = toLong( ns );
System.out.println( next );
assertTrue( next > last );
last = next;
}
}
private Long toLong( BitSet ns ) {
Long l = 0L;
for ( int j = 0; j < ns.length(); j++ ) {
if ( ns.get( j ) ) {
l += ( 1 << j );
}
}
return l;
}
private void checkHier( HierarchyEncoder encoder, char fin ) {
List<String>[] sups = new ArrayList[ fin - 'A' + 1 ];
for ( int j = 'A'; j <= fin; j++ ) {
sups[ j - 'A' ] = ((HierarchyEncoderImpl) encoder).ancestorValues( "" + (char) j );
};
for ( int j = 'A' ; j < 'A' + sups.length ; j++ ) {
for ( int k = 'A'; k < 'A' + sups.length; k++ ) {
String x = "" + (char) j;
String y = "" + (char) k;
BitSet xcode = encoder.getCode( x );
BitSet ycode = encoder.getCode( y );
int subOf = ((HierarchyEncoderImpl) encoder).superset(xcode, ycode);
if ( x.equals( y ) ) {
assertEquals( x + " vs " + y, 0, subOf );
} else if ( sups[ j - 'A' ].contains( y ) ) {
assertEquals( x + " vs " + y, 1, subOf );
} else {
assertEquals( x + " vs " + y, -1, subOf );
}
}
}
}
@Test
public void testHierEncoderMoreInheritance() {
HierarchyEncoderImpl encoder = new HierarchyEncoderImpl();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "A" ) );
encoder.encode( "D", Arrays.asList( "A" ) );
encoder.encode( "E", Arrays.asList( "B" ) );
encoder.encode( "F", Arrays.asList( "C" ) );
encoder.encode( "G", Arrays.asList( "D" ) );
encoder.encode( "H", Arrays.asList( "D" ) );
encoder.encode( "I", Arrays.asList( "E" ) );
encoder.encode( "J", Arrays.asList( "F" ) );
encoder.encode( "K", Arrays.asList( "G" ) );
encoder.encode( "L", Arrays.asList( "I", "J" ) );
List<String>[] sups = new List[ ] {
encoder.ancestorValues( "A" ),
encoder.ancestorValues( "B" ),
encoder.ancestorValues( "C" ),
encoder.ancestorValues( "D" ),
encoder.ancestorValues( "E" ),
encoder.ancestorValues( "F" ),
encoder.ancestorValues( "G" ),
encoder.ancestorValues( "H" ),
encoder.ancestorValues( "I" ),
encoder.ancestorValues( "J" ),
encoder.ancestorValues( "K" ),
encoder.ancestorValues( "L" ),
};
for ( int j = 'A' ; j <= 'L' ; j++ ) {
for ( int k = 'A'; k <= 'L'; k++ ) {
String x = "" + (char) j;
String y = "" + (char) k;
BitSet xcode = encoder.getCode( x );
BitSet ycode = encoder.getCode( y );
int subOf = encoder.superset( xcode, ycode );
if ( x.equals( y ) ) {
assertEquals( 0, subOf );
} else if ( sups[ j - 'A' ].contains( y ) ) {
assertEquals( 1, subOf );
} else {
assertEquals( -1, subOf );
}
}
}
}
@Test
public void testSecondOrderInheritance() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "T", Collections.EMPTY_LIST );
encoder.encode( "A", Arrays.asList( "T" ) );
encoder.encode( "B", Arrays.asList( "T" ) );
encoder.encode( "C", Arrays.asList( "T" ) );
encoder.encode( "D", Arrays.asList( "C" ) );
encoder.encode( "F", Arrays.asList( "B", "C" ) );
System.out.println( encoder );
encoder.encode( "Z", Arrays.asList( "A", "B", "D" ) );
System.out.println( encoder );
assertTrue( ((HierarchyEncoderImpl) encoder).superset(encoder.getCode("Z"), encoder.getCode("F")) < 0 ) ;
assertTrue( ((HierarchyEncoderImpl) encoder).superset(encoder.getCode("F"), encoder.getCode("Z")) < 0 ) ;
}
@Test
public void testDecoderAncestors() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "Thing", Collections.EMPTY_LIST );
encoder.encode( "A", Arrays.asList( "Thing" ) );
encoder.encode( "Z", Arrays.asList( "Thing" ) );
encoder.encode( "B", Arrays.asList( "A", "Z" ) );
encoder.encode( "C", Arrays.asList( "A", "Z" ) );
encoder.encode( "N", Arrays.asList( "B", "C" ) );
encoder.encode( "P", Arrays.asList( "Thing" ) );
encoder.encode( "Q", Arrays.asList( "Thing" ) );
encoder.encode( "R", Arrays.asList( "Thing" ) );
encoder.encode( "S", Arrays.asList( "R" ) );
encoder.encode( "T", Arrays.asList( "C", "Q" ) );
encoder.encode( "M", Arrays.asList( "R", "Q" ) );
encoder.encode( "O", Arrays.asList( "M", "P" ) );
System.out.println( encoder );
BitSet b;
Collection x;
b = parseBitSet( "1100111" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "Q" ) );
assertTrue( x.contains( "T" ) );
assertTrue( x.contains( "R" ) );
assertTrue( x.contains( "S" ) );
assertTrue( x.contains( "M" ) );
assertTrue( x.contains( "Thing" ) );
assertEquals( 9, x.size() );
b = parseBitSet( "100000" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "Q" ) );
assertTrue( x.contains( "Thing" ) );
b = parseBitSet( "1111" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 6, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "B" ) );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "N" ) );
assertTrue( x.contains( "Thing" ) );
b = parseBitSet( "111" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 4, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "Thing" ) );
b = parseBitSet( "1" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Thing" ) );
b = parseBitSet( "10" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "Thing" ) );
b = parseBitSet( "0" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "Thing" ) );
b = parseBitSet( "1011" );
x = encoder.upperAncestors(b);
System.out.println( "ANC " + x );
assertEquals( 4, x.size() );
assertTrue( x.contains( "Thing" ) );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "B" ) );
assertTrue( x.contains( "Z" ) );
}
@Test
public void testDecoderDescendants() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "Thing", Collections.EMPTY_LIST );
encoder.encode( "A", Arrays.asList( "Thing" ) );
encoder.encode( "Z", Arrays.asList( "Thing" ) );
encoder.encode( "B", Arrays.asList( "A", "Z" ) );
encoder.encode( "C", Arrays.asList( "A", "Z" ) );
encoder.encode( "N", Arrays.asList( "B", "C" ) );
encoder.encode( "P", Arrays.asList( "Thing" ) );
encoder.encode( "Q", Arrays.asList( "Thing" ) );
encoder.encode( "R", Arrays.asList( "Thing" ) );
encoder.encode( "S", Arrays.asList( "R" ) );
encoder.encode( "T", Arrays.asList( "C", "Q" ) );
encoder.encode( "M", Arrays.asList( "R", "Q" ) );
encoder.encode( "O", Arrays.asList( "M", "P" ) );
System.out.println( encoder );
BitSet b;
Collection x;
b = parseBitSet( "111" );
x = encoder.lowerDescendants(b);
System.out.println( "DESC " + x );
assertEquals( 3, x.size() );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "N" ) );
assertTrue( x.contains( "T" ) );
b = parseBitSet( "10" );
x = encoder.lowerDescendants(b);
System.out.println( "DESC " + x );
assertEquals( 5, x.size() );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "N" ) );
assertTrue( x.contains( "T" ) );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "B" ) );
b = parseBitSet( "100000" );
x = encoder.lowerDescendants(b);
System.out.println( "DESC " + x );
assertEquals( 4, x.size() );
assertTrue( x.contains( "Q" ) );
assertTrue( x.contains( "T" ) );
assertTrue( x.contains( "M" ) );
assertTrue( x.contains( "O" ) );
b = parseBitSet( "100010" );
x = encoder.lowerDescendants(b);
System.out.println( "DESC " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "T" ) );
b = parseBitSet( "1111" );
x = encoder.lowerDescendants(b);
System.out.println( "DESC " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "N" ) );
b = parseBitSet( "1" );
x = encoder.lowerDescendants(b);
System.out.println( "DESC " + x );
assertEquals( 5, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "B" ) );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "N" ) );
assertTrue( x.contains( "T" ) );
System.out.println(" +*******************************+ ");
x = encoder.lowerDescendants(new BitSet());
System.out.println( "DESC " + x );
assertEquals( 13, x.size() );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "Thing" ) );
}
@Test
public void testHierEncoderDecoderLower() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "Thing", Collections.EMPTY_LIST );
encoder.encode( "A", Arrays.asList( "Thing" ) );
encoder.encode( "Z", Arrays.asList( "Thing" ) );
encoder.encode( "B", Arrays.asList( "A", "Z" ) );
encoder.encode( "C", Arrays.asList( "A", "Z" ) );
encoder.encode( "N", Arrays.asList( "B", "C" ) );
encoder.encode( "P", Arrays.asList( "Thing" ) );
encoder.encode( "Q", Arrays.asList( "Thing" ) );
encoder.encode( "R", Arrays.asList( "Thing" ) );
encoder.encode( "S", Arrays.asList( "R" ) );
encoder.encode( "T", Arrays.asList( "C", "Q" ) );
encoder.encode( "M", Arrays.asList( "R", "Q" ) );
encoder.encode( "O", Arrays.asList( "M", "P" ) );
System.out.println( encoder );
Collection x;
x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "B" ) ) );
System.out.println( "GCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "B" ) );
x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "B" ) ) );
System.out.println( "GCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "N" ) );
x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "Z", "Q" ) ) );
System.out.println( "GCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "T" ) );
x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "Z", "Q" ) ) );
System.out.println( "GCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "T" ) );
x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "A", "Z" ) ) );
System.out.println( "GCS " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "B" ) );
assertTrue( x.contains( "C" ) );
x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "A", "Z" ) ) );
System.out.println( "GCS " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "B" ) );
assertTrue( x.contains( "C" ) );
x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "Thing" ) ) );
System.out.println( "GCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "Thing" ) );
x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "Thing" ) ) );
System.out.println( "GCS " + x );
assertEquals( 5, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
assertTrue( x.contains( "P" ) );
assertTrue( x.contains( "Q" ) );
assertTrue( x.contains( "R" ) );
}
@Test
public void testHierEncoderDecoderUpper() {
HierarchyEncoder encoder = new HierarchyEncoderImpl();
encoder.encode( "Thing", Collections.EMPTY_LIST );
encoder.encode( "A", Arrays.asList( "Thing" ) );
encoder.encode( "Z", Arrays.asList( "Thing" ) );
encoder.encode( "B", Arrays.asList( "A", "Z" ) );
encoder.encode( "C", Arrays.asList( "A", "Z" ) );
encoder.encode( "N", Arrays.asList( "B", "C" ) );
encoder.encode( "P", Arrays.asList( "Thing" ) );
encoder.encode( "Q", Arrays.asList( "Thing" ) );
encoder.encode( "R", Arrays.asList( "Thing" ) );
encoder.encode( "S", Arrays.asList( "R" ) );
encoder.encode( "T", Arrays.asList( "C", "Q" ) );
encoder.encode( "M", Arrays.asList( "R", "Q" ) );
encoder.encode( "O", Arrays.asList( "M", "P" ) );
System.out.println( encoder );
Collection x;
x = encoder.upperBorder( encoder.metMembersCode( Arrays.asList( "B" ) ) );
System.out.println( "LCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "B" ) );
x = encoder.immediateParents( encoder.metMembersCode( Arrays.asList( "B" ) ) );
System.out.println( "LCS " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "Z", "Q" ) ) );
System.out.println( "LCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "Thing" ) );
x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "Z", "Q" ) ) );
System.out.println( "LCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "Thing" ) );
x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "B", "C" ) ) );
System.out.println( "LCS " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "B", "C" ) ) );
System.out.println( "LCS " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "A" ) );
assertTrue( x.contains( "Z" ) );
x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "T" ) ) );
System.out.println( "LCS " + x );
assertEquals( 1, x.size() );
assertTrue( x.contains( "T" ) );
x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "T" ) ) );
System.out.println( "LCS " + x );
assertEquals( 2, x.size() );
assertTrue( x.contains( "C" ) );
assertTrue( x.contains( "Q" ) );
}
@Test
public void testClassInstanceHierarchies() {
HierarchyEncoder<String> encoder = new HierarchyEncoderImpl<String>();
BitSet ak = encoder.encode( "A", Collections.EMPTY_LIST );
BitSet bk = encoder.encode( "B", Arrays.asList( "A" ) );
BitSet ck = encoder.encode( "C", Arrays.asList( "A" ) );
BitSet dk = encoder.encode( "D", Arrays.asList( "B" ) );
BitSet ek = encoder.encode( "E", Arrays.asList( "B" ) );
BitSet fk = encoder.encode( "F", Arrays.asList( "C" ) );
BitSet gk = encoder.encode( "G", Arrays.asList( "C" ) );
BitSet hk = encoder.encode( "H", Arrays.asList( "D" ) );
BitSet ik = encoder.encode( "I", Arrays.asList( "D" ) );
BitSet jk = encoder.encode( "J", Arrays.asList( "E", "F" ) );
BitSet kk = encoder.encode( "K", Arrays.asList( "E", "F" ) );
BitSet lk = encoder.encode( "L", Arrays.asList( "G" ) );
BitSet mk = encoder.encode( "M", Arrays.asList( "G" ) );
BitSet nk = encoder.encode( "N", Arrays.asList( "I", "L" ) );
BitSet ok = encoder.encode( "O", Arrays.asList( "H", "M" ) );
System.out.println( encoder );
CodedHierarchy<String> types = new IndexedTypeHierarchy<String>( "A", new BitSet(), "ZZZZ", encoder.getBottom() );
types.addMember( "A", ak );
types.addMember( "c", ck );
types.addMember( "f", fk );
types.addMember( "j", jk );
types.addMember( "k", kk );
types.addMember( "n", nk );
types.addMember( "o", ok );
types.addMember( "h", hk );
System.out.println( types );
assertEquals( Arrays.asList( "c", "h" ), types.children( "A" ) );
assertEquals( Arrays.asList( "f", "n", "o" ), types.children( "c" ) );
assertEquals( Arrays.asList( "j", "k" ), types.children( "f" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "j" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "k" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "n" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "o" ) );
assertEquals( Arrays.asList( "o" ), types.children( "h" ) );
assertEquals( Arrays.asList( ), types.children( "ZZZZ" ) );
assertEquals( Arrays.asList( ), types.parents( "a" ) );
assertEquals( Arrays.asList( "A" ), types.parents( "c" ) );
assertEquals( Arrays.asList( "c" ), types.parents( "f" ) );
assertEquals( Arrays.asList( "f" ), types.parents( "j" ) );
assertEquals( Arrays.asList( "f" ), types.parents( "k" ) );
assertEquals( Arrays.asList( "c" ), types.parents( "n" ) );
assertEquals( Arrays.asList( "c", "h" ), types.parents( "o" ) );
assertEquals( Arrays.asList( "A" ), types.parents( "h" ) );
assertEquals( Arrays.asList( "j", "k", "n", "o" ), types.parents( "ZZZZ" ) );
BitSet pk = encoder.encode( "P", Arrays.asList( "O" ) );
types.addMember( "p", pk );
System.out.println( types );
assertEquals( Arrays.asList( "o" ), types.parents( "p" ) );
assertEquals( Arrays.asList( "j", "k", "n", "p" ), types.parents( "ZZZZ" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "p" ) );
types.removeMember( "o" );
System.out.println( types );
assertEquals( Arrays.asList( "c", "h" ), types.parents( "p" ) );
assertEquals( Arrays.asList( "f", "n", "p" ), types.children( "c" ) );
assertEquals( Arrays.asList( "j", "k" ), types.children( "f" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "n" ) );
assertEquals( Arrays.asList( "ZZZZ" ), types.children( "p" ) );
assertEquals( Arrays.asList( "p" ), types.children( "h" ) );
}
@Test
public void testUnwantedCodeOverriding() {
HierarchyEncoder<String> encoder = new HierarchyEncoderImpl<String>();
BitSet ak = encoder.encode( "A", Collections.EMPTY_LIST );
BitSet ck = encoder.encode( "C", Arrays.asList( "A" ) );
BitSet dk = encoder.encode( "D", Arrays.asList( "A" ) );
BitSet gk = encoder.encode( "G", Arrays.asList( "C", "D" ) );
BitSet bk = encoder.encode( "B", Arrays.asList( "A" ) );
BitSet ek = encoder.encode( "E", Arrays.asList( "B" ) );
BitSet ik = encoder.encode( "I", Arrays.asList( "E", "C" ) );
BitSet fk = encoder.encode( "F", Arrays.asList( "B", "C" ) );
BitSet jk = encoder.encode( "J", Arrays.asList( "F", "D" ) );
BitSet lk = encoder.encode( "L", Arrays.asList( "J" ) );
assertNotNull( encoder.getCode( "L" ) );
BitSet ok = encoder.encode( "O", Arrays.asList( "L" ) );
assertNotNull( encoder.getCode( "L" ) );
BitSet kk = encoder.encode( "K", Arrays.asList( "F", "G" ) );
assertNotNull( encoder.getCode( "L" ) );
BitSet mk = encoder.encode( "M", Arrays.asList( "J", "K" ) );
assertNotNull( encoder.getCode( "L" ) );
BitSet nk = encoder.encode( "N", Arrays.asList( "K" ) );
assertNotNull( encoder.getCode( "L" ) );
BitSet hk = encoder.encode( "H", Arrays.asList( "F" ) );
assertNotNull( encoder.getCode( "L" ) );
BitSet pk = encoder.encode( "P", Arrays.asList( "A" ) );
assertNotNull( encoder.getCode( "L" ) );
System.out.println( encoder );
assertEquals( 16, encoder.size() );
}
@Test
public void testDeepTree() {
HierarchyEncoder<String> encoder = new HierarchyEncoderImpl<String>();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A" ) );
encoder.encode( "C", Arrays.asList( "A" ) );
encoder.encode( "D", Arrays.asList( "C" ) );
encoder.encode( "E", Arrays.asList( "D" ) );
encoder.encode( "F", Arrays.asList( "D" ) );
encoder.encode( "G", Arrays.asList( "C" ) );
encoder.encode( "H", Arrays.asList( "G" ) );
encoder.encode( "I", Arrays.asList( "G" ) );
encoder.encode( "J", Arrays.asList( "C" ) );
encoder.encode( "K", Arrays.asList( "C" ) );
encoder.encode( "L", Arrays.asList( "B" ) );
encoder.encode( "M", Arrays.asList( "B" ) );
encoder.encode( "N", Arrays.asList( "A" ) );
encoder.encode( "O", Arrays.asList( "N" ) );
System.out.println( encoder );
checkHier( encoder, 'O' );
}
@Test
public void testNestedTree() {
HierarchyEncoder<String> encoder = new HierarchyEncoderImpl<String>();
encoder.encode( "A", Collections.EMPTY_LIST );
encoder.encode( "B", Arrays.asList( "A") );
encoder.encode( "C", Arrays.asList( "B") );
encoder.encode( "D", Arrays.asList( "B") );
encoder.encode( "E", Arrays.asList( "D") );
encoder.encode( "F", Arrays.asList( "E") );
encoder.encode( "G", Arrays.asList( "E") );
encoder.encode( "H", Arrays.asList( "G") );
encoder.encode( "I", Arrays.asList( "H") );
encoder.encode( "J", Arrays.asList( "E") );
encoder.encode( "K", Arrays.asList( "J") );
encoder.encode( "L", Arrays.asList( "K") );
encoder.encode( "M", Arrays.asList( "J") );
encoder.encode( "N", Arrays.asList( "M") );
encoder.encode( "O", Arrays.asList( "J") );
encoder.encode( "P", Arrays.asList( "O") );
encoder.encode( "Q", Arrays.asList( "J") );
encoder.encode( "R", Arrays.asList( "Q") );
encoder.encode( "S", Arrays.asList( "B") );
encoder.encode( "T", Arrays.asList( "S") );
encoder.encode( "U", Arrays.asList( "T") );
encoder.encode( "V", Arrays.asList( "B") );
encoder.encode( "W", Arrays.asList( "V") );
encoder.encode( "X", Arrays.asList( "W") );
System.out.println( encoder );
encoder.encode( "Y", Arrays.asList( "F", "W") );
System.out.println( encoder );
checkHier( encoder, (char) ( 'A' + encoder.size() - 1 ) );
}
} | rokn/Count_Words_2015 | testing/drools-master/drools-core/src/test/java/org/drools/core/util/HierarchyTest.java | Java | mit | 46,096 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.max.internal.exceptions;
/**
* Will be thrown when there is an attempt to put a new message line into the message processor,
* but the processor is currently processing an other message type.
*
* @author Christian Rockrohr <[email protected]> - Initial contribution
*/
public class IncompleteMessageException extends Exception {
/**
* required variable to avoid IncorrectMultilineIndexException warning
*/
private static final long serialVersionUID = -8882867114144637120L;
}
| Snickermicker/openhab2 | bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/exceptions/IncompleteMessageException.java | Java | epl-1.0 | 915 |
<?php
/**
* $Id: vi.php,v 1.5 2005/10/03 15:07:35 mike Exp $
*/
$this->codes = array(
'aa' => 'Afar',
'ab' => 'Abkhazian',
'ae' => 'Avestan',
'af' => 'Afrikaans',
'ak' => 'Akan',
'am' => 'Amharic',
'an' => 'Aragonese',
'ar' => 'TiαΊΏng A-rαΊp',
'as' => 'Assamese',
'av' => 'Avaric',
'ay' => 'Aymara',
'az' => 'TiαΊΏng Ai-dΓ©c-bai-gian',
'ba' => 'Bashkir',
'be' => 'TiαΊΏng BΓͺ-la-rΓΊt',
'bg' => 'TiαΊΏng Bun-ga-ri',
'bh' => 'Bihari',
'bi' => 'Bislama',
'bm' => 'Bambara',
'bn' => 'Bengali',
'bo' => 'TiαΊΏng TΓ’y TαΊ‘ng',
'br' => 'Breton',
'bs' => 'Bosnian',
'ca' => 'TiαΊΏng Ca-ta-lΔng',
'ce' => 'Chechen',
'ch' => 'Chamorro',
'co' => 'Corsican',
'cr' => 'Cree',
'cs' => 'TiαΊΏng SΓ©c',
'cu' => 'Church Slavic',
'cv' => 'Chuvash',
'cy' => 'Welsh',
'da' => 'TiαΊΏng Δan MαΊ‘ch',
'de' => 'TiαΊΏng Δα»©c',
'dv' => 'Divehi',
'dz' => 'Dzongkha',
'ee' => 'Ewe',
'el' => 'TiαΊΏng Hy LαΊ‘p',
'en' => 'TiαΊΏng Anh',
'eo' => 'TiαΊΏng Quα»c TαΊΏ Ngα»―',
'es' => 'TiαΊΏng TΓ’y Ban Nha',
'et' => 'TiαΊΏng E-xtΓ΄-ni-a',
'eu' => 'Basque',
'fa' => 'TiαΊΏng Ba TΖ°',
'ff' => 'Fulah',
'fi' => 'TiαΊΏng PhαΊ§n Lan',
'fj' => 'Fijian',
'fo' => 'Faroese',
'fr' => 'TiαΊΏng PhΓ‘p',
'fy' => 'Frisian',
'ga' => 'TiαΊΏng Ai-len',
'gd' => 'Scottish Gaelic',
'gl' => 'Galician',
'gn' => 'Guarani',
'gu' => 'Gujarati',
'gv' => 'Manx',
'ha' => 'Hausa',
'he' => 'TiαΊΏng HΓͺ-brΖ‘',
'hi' => 'TiαΊΏng Hin-Δi',
'ho' => 'Hiri Motu',
'hr' => 'TiαΊΏng CrΓ΄-a-ti-a',
'ht' => 'Haitian',
'hu' => 'TiαΊΏng Hung-ga-ri',
'hy' => 'TiαΊΏng Γc-mΓͺ-ni',
'hz' => 'Herero',
'ia' => 'TiαΊΏng Khoa Hα»c Quα»c TαΊΏ',
'id' => 'TiαΊΏng In-ΔΓ΄-nΓͺ-xia',
'ie' => 'Interlingue',
'ig' => 'Igbo',
'ii' => 'Sichuan Yi',
'ik' => 'Inupiaq',
'io' => 'Ido',
'is' => 'TiαΊΏng Ai-xΖ‘-len',
'it' => 'TiαΊΏng Γ',
'iu' => 'Inuktitut',
'ja' => 'TiαΊΏng NhαΊt',
'jv' => 'TiαΊΏng Gia-va',
'ka' => 'Georgian',
'kg' => 'Kongo',
'ki' => 'Kikuyu',
'kj' => 'Kuanyama',
'kk' => 'Kazakh',
'kl' => 'Kalaallisut',
'km' => 'TiαΊΏng Campuchia',
'kn' => 'TiαΊΏng Kan-na-Δa',
'ko' => 'TiαΊΏng HΓ n Quα»c',
'kr' => 'Kanuri',
'ks' => 'Kashmiri',
'ku' => 'Kurdish',
'kv' => 'Komi',
'kw' => 'Cornish',
'ky' => 'Kirghiz',
'la' => 'TiαΊΏng La-tinh',
'lb' => 'Luxembourgish',
'lg' => 'Ganda',
'li' => 'Limburgish',
'ln' => 'Lingala',
'lo' => 'TiαΊΏng LΓ o',
'lt' => 'TiαΊΏng LΓt-va',
'lu' => 'Luba-Katanga',
'lv' => 'TiαΊΏng LΓ‘t-vi-a',
'mg' => 'Malagasy',
'mh' => 'Marshallese',
'mi' => 'Maori',
'mk' => 'TiαΊΏng Ma-xΓͺ-ΔΓ΄-ni-a',
'ml' => 'Malayalam',
'mn' => 'TiαΊΏng MΓ΄ng Cα»',
'mo' => 'Moldavian',
'mr' => 'Marathi',
'ms' => 'TiαΊΏng Ma-lay-xi-a',
'mt' => 'Maltese',
'my' => 'Burmese',
'na' => 'Nauru',
'nb' => 'Norwegian BokmΓ₯l',
'nd' => 'North Ndebele',
'ne' => 'TiαΊΏng NΓͺ-pan',
'ng' => 'Ndonga',
'nl' => 'TiαΊΏng HΓ Lan',
'nn' => 'Norwegian Nynorsk',
'no' => 'TiαΊΏng Na Uy',
'nr' => 'South Ndebele',
'nv' => 'Navajo',
'ny' => 'Nyanja; Chichewa; Chewa',
'oc' => 'Occitan (post 1500); ProvenΓ§al',
'oj' => 'Ojibwa',
'om' => 'Oromo',
'or' => 'Oriya',
'os' => 'Ossetic',
'pa' => 'Punjabi',
'pi' => 'Pali',
'pl' => 'TiαΊΏng Ba Lan',
'ps' => 'Pashto (Pushto)',
'pt' => 'TiαΊΏng Bα» ΔΓ o Nha',
'qu' => 'Quechua',
'rm' => 'Rhaeto-Romance',
'rn' => 'Rundi',
'ro' => 'TiαΊΏng Ru-ma-ni',
'ru' => 'TiαΊΏng Nga',
'rw' => 'Kinyarwanda',
'sa' => 'TiαΊΏng PhαΊ‘n',
'sc' => 'Sardinian',
'sd' => 'Sindhi',
'se' => 'Northern Sami',
'sg' => 'Sango',
'sh' => 'Serbo-Croatian',
'si' => 'Sinhalese',
'sk' => 'TiαΊΏng XlΓ΄-vΓ‘c',
'sl' => 'TiαΊΏng XlΓ΄-ven',
'sm' => 'Samoan',
'sn' => 'Shona',
'so' => 'TiαΊΏng XΓ΄-ma-li',
'sq' => 'TiαΊΏng An-ba-ni',
'sr' => 'TiαΊΏng SΓ©c-bi',
'ss' => 'Swati',
'st' => 'Southern Sotho',
'su' => 'Sundanese',
'sv' => 'TiαΊΏng Thα»₯y Δiα»n',
'sw' => 'Swahili',
'ta' => 'Tamil',
'te' => 'Telugu',
'tg' => 'Tajik',
'th' => 'TiαΊΏng ThΓ‘i',
'ti' => 'Tigrinya',
'tk' => 'Turkmen',
'tl' => 'Tagalog',
'tn' => 'Tswana',
'to' => 'Tonga (Tonga Islands)',
'tr' => 'TiαΊΏng Thα» NhΔ© Kα»³',
'ts' => 'Tsonga',
'tt' => 'Tatar',
'tw' => 'Twi',
'ty' => 'Tahitian',
'ug' => 'Uighur',
'uk' => 'TiαΊΏng U-crai-na',
'ur' => 'Urdu',
'uz' => 'TiαΊΏng U-dΖ‘-bαΊΏch',
've' => 'Venda',
'vi' => 'TiαΊΏng Viα»t',
'vo' => 'VolapΓΌk',
'wa' => 'Walloon',
'wo' => 'Wolof',
'xh' => 'Xhosa',
'yi' => 'TiαΊΏng Y-Δit',
'yo' => 'Yoruba',
'za' => 'Zhuang',
'zh' => 'TiαΊΏng Trung Quα»c',
'zu' => 'Zulu',
);
?>
| idoxlr8/HVAC | xataface/lib/I18Nv2/Language/vi.php | PHP | gpl-2.0 | 5,075 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
"""WTForm filters implementation.
Filters can be applied to incoming form data, after process_formdata() has run.
See more information on:
http://wtforms.simplecodes.com/docs/1.0.4/fields.html#wtforms.fields.Field
"""
import six
from invenio.utils.html import HTMLWasher, \
CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST
def strip_string(value):
"""Remove leading and trailing spaces from string."""
if isinstance(value, six.string_types):
return value.strip()
else:
return value
def splitlines_list(value):
"""Split string per line into a list."""
if isinstance(value, six.string_types):
newdata = []
for line in value.splitlines():
if line.strip():
newdata.append(line.strip().encode('utf8'))
return newdata
else:
return value
def splitchar_list(c):
"""Return filter function that split string per char into a list.
:param c: Character to split on.
"""
def _inner(value):
"""Split string per char into a list."""
if isinstance(value, six.string_types):
newdata = []
for item in value.split(c):
if item.strip():
newdata.append(item.strip().encode('utf8'))
return newdata
else:
return value
return _inner
def map_func(func):
"""Return filter function that map a function to each item of a list.
:param func: Function to map.
"""
# FIXME
def _mapper(data):
"""Map a function to each item of a list."""
if isinstance(data, list):
return map(func, data)
else:
return data
return _mapper
def strip_prefixes(*prefixes):
"""Return a filter function that removes leading prefixes from a string."""
def _inner(value):
"""Remove a leading prefix from string."""
if isinstance(value, six.string_types):
for prefix in prefixes:
if value.lower().startswith(prefix):
return value[len(prefix):]
return value
return _inner
def sanitize_html(allowed_tag_whitelist=CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST):
"""Sanitize HTML."""
def _inner(value):
if isinstance(value, six.string_types):
washer = HTMLWasher()
return washer.wash(value,
allowed_tag_whitelist=allowed_tag_whitelist)
else:
return value
return _inner
| zenodo/invenio | invenio/modules/deposit/filter_utils.py | Python | gpl-2.0 | 3,264 |
/*
* Copyright 2012 Freescale Semiconductor, Inc.
* Andy Fleming <[email protected]>
* Roy Zang <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0+
* Some part is taken from tsec.c
*/
#include <common.h>
#include <miiphy.h>
#include <phy.h>
#include <asm/io.h>
#include <asm/fsl_memac.h>
#include <fm_eth.h>
/*
* Write value to the PHY for this device to the register at regnum, waiting
* until the write is done before it returns. All PHY configuration has to be
* done through the TSEC1 MIIM regs
*/
int memac_mdio_write(struct mii_dev *bus, int port_addr, int dev_addr,
int regnum, u16 value)
{
u32 mdio_ctl;
struct memac_mdio_controller *regs = bus->priv;
u32 c45 = 1; /* Default to 10G interface */
if (dev_addr == MDIO_DEVAD_NONE) {
c45 = 0; /* clause 22 */
dev_addr = regnum & 0x1f;
clrbits_be32(®s->mdio_stat, MDIO_STAT_ENC);
} else
setbits_be32(®s->mdio_stat, MDIO_STAT_ENC);
/* Wait till the bus is free */
while ((in_be32(®s->mdio_stat)) & MDIO_STAT_BSY)
;
/* Set the port and dev addr */
mdio_ctl = MDIO_CTL_PORT_ADDR(port_addr) | MDIO_CTL_DEV_ADDR(dev_addr);
out_be32(®s->mdio_ctl, mdio_ctl);
/* Set the register address */
if (c45)
out_be32(®s->mdio_addr, regnum & 0xffff);
/* Wait till the bus is free */
while ((in_be32(®s->mdio_stat)) & MDIO_STAT_BSY)
;
/* Write the value to the register */
out_be32(®s->mdio_data, MDIO_DATA(value));
/* Wait till the MDIO write is complete */
while ((in_be32(®s->mdio_data)) & MDIO_DATA_BSY)
;
return 0;
}
/*
* Reads from register regnum in the PHY for device dev, returning the value.
* Clears miimcom first. All PHY configuration has to be done through the
* TSEC1 MIIM regs
*/
int memac_mdio_read(struct mii_dev *bus, int port_addr, int dev_addr,
int regnum)
{
u32 mdio_ctl;
struct memac_mdio_controller *regs = bus->priv;
u32 c45 = 1;
if (dev_addr == MDIO_DEVAD_NONE) {
c45 = 0; /* clause 22 */
dev_addr = regnum & 0x1f;
clrbits_be32(®s->mdio_stat, MDIO_STAT_ENC);
} else
setbits_be32(®s->mdio_stat, MDIO_STAT_ENC);
/* Wait till the bus is free */
while ((in_be32(®s->mdio_stat)) & MDIO_STAT_BSY)
;
/* Set the Port and Device Addrs */
mdio_ctl = MDIO_CTL_PORT_ADDR(port_addr) | MDIO_CTL_DEV_ADDR(dev_addr);
out_be32(®s->mdio_ctl, mdio_ctl);
/* Set the register address */
if (c45)
out_be32(®s->mdio_addr, regnum & 0xffff);
/* Wait till the bus is free */
while ((in_be32(®s->mdio_stat)) & MDIO_STAT_BSY)
;
/* Initiate the read */
mdio_ctl |= MDIO_CTL_READ;
out_be32(®s->mdio_ctl, mdio_ctl);
/* Wait till the MDIO write is complete */
while ((in_be32(®s->mdio_data)) & MDIO_DATA_BSY)
;
/* Return all Fs if nothing was there */
if (in_be32(®s->mdio_stat) & MDIO_STAT_RD_ER)
return 0xffff;
return in_be32(®s->mdio_data) & 0xffff;
}
int memac_mdio_reset(struct mii_dev *bus)
{
return 0;
}
int fm_memac_mdio_init(bd_t *bis, struct memac_mdio_info *info)
{
struct mii_dev *bus = mdio_alloc();
if (!bus) {
printf("Failed to allocate FM TGEC MDIO bus\n");
return -1;
}
bus->read = memac_mdio_read;
bus->write = memac_mdio_write;
bus->reset = memac_mdio_reset;
sprintf(bus->name, info->name);
bus->priv = info->regs;
/*
* On some platforms like B4860, default value of MDIO_CLK_DIV bits
* in mdio_stat(mdio_cfg) register generates MDIO clock too high
* (much higher than 2.5MHz), violating the IEEE specs.
* On other platforms like T1040, default value of MDIO_CLK_DIV bits
* is zero, so MDIO clock is disabled.
* So, for proper functioning of MDIO, MDIO_CLK_DIV bits needs to
* be properly initialized.
*/
setbits_be32(&((struct memac_mdio_controller *)info->regs)->mdio_stat,
MDIO_STAT_CLKDIV(258));
return mdio_register(bus);
}
| hephaex/bbb | u-boot/drivers/net/fm/memac_phy.c | C | gpl-2.0 | 3,815 |
#ifndef MY_GPIO_ARCH_H
#define MY_GPIO_ARCH_H
#define GPIO_ARCH_SET_SPI_CS_HIGH() \
{ \
}
#endif /* MY_GPIO_ARCH_H */
| roubo/openPPZ | sw/airborne/arch/lpc21/mcu_periph/gpio_arch.h | C | gpl-2.0 | 134 |
class CfgMagazines {
class HandGrenade;
class ACE_HandFlare_Base: HandGrenade {
scope = 1;
value = 2;
nameSoundWeapon = "smokeshell";
nameSound = "smokeshell";
mass = 4;
initSpeed = 22;
};
class ACE_HandFlare_White: ACE_HandFlare_Base {
author = ECSTRING(common,ACETeam);
scope = 2;
displayname = CSTRING(M127A1_White_Name);
descriptionShort = CSTRING(M127A1_White_Description);
displayNameShort = CSTRING(M127A1_White_NameShort);
model = "\A3\weapons_f\ammo\flare_white";
picture = "\A3\Weapons_F\Data\UI\gear_flare_white_ca.paa";
ammo = "ACE_G_Handflare_White";
};
class ACE_HandFlare_Red: ACE_HandFlare_Base {
author = ECSTRING(common,ACETeam);
scope = 2;
displayname = CSTRING(M127A1_Red_Name);
descriptionShort = CSTRING(M127A1_Red_Description);
displayNameShort = CSTRING(M127A1_Red_NameShort);
model = "\A3\weapons_f\ammo\flare_red";
picture = "\A3\Weapons_F\Data\UI\gear_flare_red_ca.paa";
ammo = "ACE_G_Handflare_Red";
};
class ACE_HandFlare_Green: ACE_HandFlare_Base {
author = ECSTRING(common,ACETeam);
scope = 2;
displayname = CSTRING(M127A1_Green_Name);
descriptionShort = CSTRING(M127A1_Green_Description);
displayNameShort = CSTRING(M127A1_Green_NameShort);
model = "\A3\weapons_f\ammo\flare_green";
picture = "\A3\Weapons_F\Data\UI\gear_flare_green_ca.paa";
ammo = "ACE_G_Handflare_Green";
};
class ACE_HandFlare_Yellow: ACE_HandFlare_Base {
author = ECSTRING(common,ACETeam);
scope = 2;
displayname = CSTRING(M127A1_Yellow_Name);
descriptionShort = CSTRING(M127A1_Yellow_Description);
displayNameShort = CSTRING(M127A1_Yellow_NameShort);
model = "\A3\weapons_f\ammo\flare_yellow";
picture = "\A3\Weapons_F\Data\UI\gear_flare_yellow_ca.paa";
ammo = "ACE_G_Handflare_Yellow";
};
class ACE_M84: HandGrenade {
author = ECSTRING(common,ACETeam);
displayname = CSTRING(M84_Name);
descriptionShort = CSTRING(M84_Description);
displayNameShort = CSTRING(M84_NameShort);
model = QPATHTOF(models\ACE_m84.p3d);
picture = QPATHTOF(UI\ACE_m84_x_ca.paa);
ammo = "ACE_G_M84";
mass = 4;
};
class SmokeShell;
class ACE_M14: SmokeShell {
author = ECSTRING(common,ACETeam);
displayname = CSTRING(Incendiary_Name);
descriptionShort = CSTRING(Incendiary_Description);
displayNameShort = CSTRING(Incendiary_NameShort);
model = QPATHTOF(models\ace_anm14th3.p3d);
picture = QPATHTOF(UI\ace_anm14th3_x_ca.paa);
ammo = "ACE_G_M14";
mass = 4;
};
class 3Rnd_UGL_FlareGreen_F;
class 6Rnd_GreenSignal_F: 3Rnd_UGL_FlareGreen_F {
author = ECSTRING(common,ACETeam);
ammo = "F_40mm_Green";
initSpeed = 120;
};
class 6Rnd_RedSignal_F: 6Rnd_GreenSignal_F {
author = ECSTRING(common,ACETeam);
ammo = "F_40mm_Red";
initSpeed = 120;
};
};
| NorXAengell/ACE3 | addons/grenades/CfgMagazines.hpp | C++ | gpl-2.0 | 3,190 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Connect
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
$commands = array(
'config-show' => array(
'summary' => 'Show All Settings',
'function' => 'doConfigShow',
'shortcut' => 'csh',
'options' => array(
'channel' => array(
'shortopt' => 'c',
'doc' => 'show configuration variables for another channel',
'arg' => 'CHAN',
),
),
'doc' => '[layer]
Displays all configuration values. An optional argument
may be used to tell which configuration layer to display. Valid
configuration layers are "user", "system" and "default". To display
configurations for different channels, set the default_channel
configuration variable and run config-show again.
',
),
'config-get' => array(
'summary' => 'Show One Setting',
'function' => 'doConfigGet',
'shortcut' => 'cg',
'options' => array(
'channel' => array(
'shortopt' => 'c',
'doc' => 'show configuration variables for another channel',
'arg' => 'CHAN',
),
),
'doc' => '<parameter> [layer]
Displays the value of one configuration parameter. The
first argument is the name of the parameter, an optional second argument
may be used to tell which configuration layer to look in. Valid configuration
layers are "user", "system" and "default". If no layer is specified, a value
will be picked from the first layer that defines the parameter, in the order
just specified. The configuration value will be retrieved for the channel
specified by the default_channel configuration variable.
',
),
'config-set' => array(
'summary' => 'Change Setting',
'function' => 'doConfigSet',
'shortcut' => 'cs',
'options' => array(
'channel' => array(
'shortopt' => 'c',
'doc' => 'show configuration variables for another channel',
'arg' => 'CHAN',
),
),
'doc' => '<parameter> <value> [layer]
Sets the value of one configuration parameter. The first argument is
the name of the parameter, the second argument is the new value. Some
parameters are subject to validation, and the command will fail with
an error message if the new value does not make sense. An optional
third argument may be used to specify in which layer to set the
configuration parameter. The default layer is "user". The
configuration value will be set for the current channel, which
is controlled by the default_channel configuration variable.
',
),
'config-help' => array(
'summary' => 'Show Information About Setting',
'function' => 'doConfigHelp',
'shortcut' => 'ch',
'options' => array(),
'doc' => '[parameter]
Displays help for a configuration parameter. Without arguments it
displays help for all configuration parameters.
',
),
);
| chemissi/P2 | src/public/downloader/lib/Mage/Connect/Command/Config_Header.php | PHP | gpl-2.0 | 3,946 |
/*
* BCMSDH Function Driver for the native SDIO/MMC driver in the Linux Kernel
*
* Copyright (C) 1999-2014, 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: bcmsdh_sdmmc_linux.c 425711 2013-09-25 06:40:41Z $
*/
#include <typedefs.h>
#include <bcmutils.h>
#include <sdio.h> /* SDIO Device and Protocol Specs */
#include <bcmsdbus.h> /* bcmsdh to/from specific controller APIs */
#include <sdiovar.h> /* to get msglevel bit values */
#include <linux/sched.h> /* request_irq() */
#include <linux/mmc/core.h>
#include <linux/mmc/card.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#if !defined(SDIO_VENDOR_ID_BROADCOM)
#define SDIO_VENDOR_ID_BROADCOM 0x02d0
#endif /* !defined(SDIO_VENDOR_ID_BROADCOM) */
#define SDIO_DEVICE_ID_BROADCOM_DEFAULT 0x0000
#if !defined(SDIO_DEVICE_ID_BROADCOM_4325_SDGWB)
#define SDIO_DEVICE_ID_BROADCOM_4325_SDGWB 0x0492 /* BCM94325SDGWB */
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4325_SDGWB) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_4325)
#define SDIO_DEVICE_ID_BROADCOM_4325 0x0493
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4325) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_4329)
#define SDIO_DEVICE_ID_BROADCOM_4329 0x4329
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4329) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_4319)
#define SDIO_DEVICE_ID_BROADCOM_4319 0x4319
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4319) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_4330)
#define SDIO_DEVICE_ID_BROADCOM_4330 0x4330
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4330) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_4334)
#define SDIO_DEVICE_ID_BROADCOM_4334 0x4334
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4334) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_4324)
#define SDIO_DEVICE_ID_BROADCOM_4324 0x4324
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_4324) */
#if !defined(SDIO_DEVICE_ID_BROADCOM_43239)
#define SDIO_DEVICE_ID_BROADCOM_43239 43239
#endif /* !defined(SDIO_DEVICE_ID_BROADCOM_43239) */
#include <bcmsdh_sdmmc.h>
#include <dhd_dbg.h>
#ifdef WL_CFG80211
extern void wl_cfg80211_set_parent_dev(void *dev);
#endif
extern void sdioh_sdmmc_devintr_off(sdioh_info_t *sd);
extern void sdioh_sdmmc_devintr_on(sdioh_info_t *sd);
extern int dhd_os_check_wakelock(void *dhdp);
extern int dhd_os_check_if_up(void *dhdp);
extern void *bcmsdh_get_drvdata(void);
int sdio_function_init(void);
void sdio_function_cleanup(void);
#define DESCRIPTION "bcmsdh_sdmmc Driver"
#define AUTHOR "Broadcom Corporation"
/* module param defaults */
static int clockoverride = 0;
module_param(clockoverride, int, 0644);
MODULE_PARM_DESC(clockoverride, "SDIO card clock override");
PBCMSDH_SDMMC_INSTANCE gInstance;
/* Maximum number of bcmsdh_sdmmc devices supported by driver */
#define BCMSDH_SDMMC_MAX_DEVICES 1
extern int bcmsdh_probe(struct device *dev);
extern int bcmsdh_remove(struct device *dev);
extern volatile bool dhd_mmc_suspend;
static int bcmsdh_sdmmc_probe(struct sdio_func *func,
const struct sdio_device_id *id)
{
int ret = 0;
static struct sdio_func sdio_func_0;
if (!gInstance)
return -EINVAL;
if (func) {
sd_trace(("bcmsdh_sdmmc: %s Enter\n", __FUNCTION__));
sd_trace(("sdio_bcmsdh: func->class=%x\n", func->class));
sd_trace(("sdio_vendor: 0x%04x\n", func->vendor));
sd_trace(("sdio_device: 0x%04x\n", func->device));
sd_trace(("Function#: 0x%04x\n", func->num));
if (func->num == 1) {
sdio_func_0.num = 0;
sdio_func_0.card = func->card;
gInstance->func[0] = &sdio_func_0;
if(func->device == 0x4) { /* 4318 */
gInstance->func[2] = NULL;
sd_trace(("NIC found, calling bcmsdh_probe...\n"));
ret = bcmsdh_probe(&func->dev);
}
}
gInstance->func[func->num] = func;
if (func->num == 2) {
#ifdef WL_CFG80211
wl_cfg80211_set_parent_dev(&func->dev);
#endif
sd_trace(("F2 found, calling bcmsdh_probe...\n"));
ret = bcmsdh_probe(&func->dev);
if (ret < 0)
gInstance->func[2] = NULL;
}
} else {
ret = -ENODEV;
}
return ret;
}
static void bcmsdh_sdmmc_remove(struct sdio_func *func)
{
if (func) {
sd_trace(("bcmsdh_sdmmc: %s Enter\n", __FUNCTION__));
sd_info(("sdio_bcmsdh: func->class=%x\n", func->class));
sd_info(("sdio_vendor: 0x%04x\n", func->vendor));
sd_info(("sdio_device: 0x%04x\n", func->device));
sd_info(("Function#: 0x%04x\n", func->num));
if (gInstance->func[2]) {
sd_trace(("F2 found, calling bcmsdh_remove...\n"));
bcmsdh_remove(&func->dev);
gInstance->func[2] = NULL;
}
if (func->num == 1) {
sdio_claim_host(func);
sdio_disable_func(func);
sdio_release_host(func);
gInstance->func[1] = NULL;
}
}
}
/* devices we support, null terminated */
static const struct sdio_device_id bcmsdh_sdmmc_ids[] = {
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_DEFAULT) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4325_SDGWB) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4325) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4329) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4319) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4330) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4334) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_4324) },
{ SDIO_DEVICE(SDIO_VENDOR_ID_BROADCOM, SDIO_DEVICE_ID_BROADCOM_43239) },
{ SDIO_DEVICE_CLASS(SDIO_CLASS_NONE) },
{ /* end: all zeroes */ },
};
MODULE_DEVICE_TABLE(sdio, bcmsdh_sdmmc_ids);
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 39)) && defined(CONFIG_PM)
static int bcmsdh_sdmmc_suspend(struct device *pdev)
{
struct sdio_func *func = dev_to_sdio_func(pdev);
mmc_pm_flag_t sdio_flags;
int ret;
if (func->num != 2)
return 0;
sd_trace(("%s Enter\n", __FUNCTION__));
if (dhd_os_check_wakelock(bcmsdh_get_drvdata()))
return -EBUSY;
sdio_flags = sdio_get_host_pm_caps(func);
if (!(sdio_flags & MMC_PM_KEEP_POWER)) {
sd_err(("%s: can't keep power while host is suspended\n", __FUNCTION__));
return -EINVAL;
}
/* keep power while host suspended */
ret = sdio_set_host_pm_flags(func, MMC_PM_KEEP_POWER);
if (ret) {
sd_err(("%s: error while trying to keep power\n", __FUNCTION__));
return ret;
}
#if defined(OOB_INTR_ONLY)
bcmsdh_oob_intr_set(0);
#endif
dhd_mmc_suspend = TRUE;
smp_mb();
return 0;
}
static int bcmsdh_sdmmc_resume(struct device *pdev)
{
#if defined(OOB_INTR_ONLY)
struct sdio_func *func = dev_to_sdio_func(pdev);
#endif
sd_trace(("%s Enter\n", __FUNCTION__));
dhd_mmc_suspend = FALSE;
#if defined(OOB_INTR_ONLY)
if ((func->num == 2) && dhd_os_check_if_up(bcmsdh_get_drvdata()))
bcmsdh_oob_intr_set(1);
#endif
smp_mb();
return 0;
}
static const struct dev_pm_ops bcmsdh_sdmmc_pm_ops = {
.suspend = bcmsdh_sdmmc_suspend,
.resume = bcmsdh_sdmmc_resume,
};
#endif /* (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 39)) && defined(CONFIG_PM) */
#if defined(BCMLXSDMMC)
static struct semaphore *notify_semaphore = NULL;
static int dummy_probe(struct sdio_func *func,
const struct sdio_device_id *id)
{
if (func && (func->num != 2)) {
return 0;
}
if (notify_semaphore)
up(notify_semaphore);
return 0;
}
static void dummy_remove(struct sdio_func *func)
{
}
static struct sdio_driver dummy_sdmmc_driver = {
.probe = dummy_probe,
.remove = dummy_remove,
.name = "dummy_sdmmc",
.id_table = bcmsdh_sdmmc_ids,
};
int sdio_func_reg_notify(void* semaphore)
{
notify_semaphore = semaphore;
return sdio_register_driver(&dummy_sdmmc_driver);
}
void sdio_func_unreg_notify(void)
{
OSL_SLEEP(15);
sdio_unregister_driver(&dummy_sdmmc_driver);
}
#endif /* defined(BCMLXSDMMC) */
static struct sdio_driver bcmsdh_sdmmc_driver = {
.probe = bcmsdh_sdmmc_probe,
.remove = bcmsdh_sdmmc_remove,
.name = "bcmsdh_sdmmc",
.id_table = bcmsdh_sdmmc_ids,
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 39)) && defined(CONFIG_PM)
.drv = {
.pm = &bcmsdh_sdmmc_pm_ops,
},
#endif /* (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 39)) && defined(CONFIG_PM) */
};
struct sdos_info {
sdioh_info_t *sd;
spinlock_t lock;
};
int
sdioh_sdmmc_osinit(sdioh_info_t *sd)
{
struct sdos_info *sdos;
if (!sd)
return BCME_BADARG;
sdos = (struct sdos_info*)MALLOC(sd->osh, sizeof(struct sdos_info));
sd->sdos_info = (void*)sdos;
if (sdos == NULL)
return BCME_NOMEM;
sdos->sd = sd;
spin_lock_init(&sdos->lock);
return BCME_OK;
}
void
sdioh_sdmmc_osfree(sdioh_info_t *sd)
{
struct sdos_info *sdos;
ASSERT(sd && sd->sdos_info);
sdos = (struct sdos_info *)sd->sdos_info;
MFREE(sd->osh, sdos, sizeof(struct sdos_info));
}
/* Interrupt enable/disable */
SDIOH_API_RC
sdioh_interrupt_set(sdioh_info_t *sd, bool enable)
{
ulong flags;
struct sdos_info *sdos;
if (!sd)
return BCME_BADARG;
sd_trace(("%s: %s\n", __FUNCTION__, enable ? "Enabling" : "Disabling"));
sdos = (struct sdos_info *)sd->sdos_info;
ASSERT(sdos);
#if !defined(OOB_INTR_ONLY)
if (enable && !(sd->intr_handler && sd->intr_handler_arg)) {
sd_err(("%s: no handler registered, will not enable\n", __FUNCTION__));
return SDIOH_API_RC_FAIL;
}
#endif /* !defined(OOB_INTR_ONLY) */
/* Ensure atomicity for enable/disable calls */
spin_lock_irqsave(&sdos->lock, flags);
sd->client_intr_enabled = enable;
if (enable) {
sdioh_sdmmc_devintr_on(sd);
} else {
sdioh_sdmmc_devintr_off(sd);
}
spin_unlock_irqrestore(&sdos->lock, flags);
return SDIOH_API_RC_SUCCESS;
}
#ifdef BCMSDH_MODULE
static int __init
bcmsdh_module_init(void)
{
int error = 0;
error = sdio_function_init();
return error;
}
static void __exit
bcmsdh_module_cleanup(void)
{
sdio_function_cleanup();
}
module_init(bcmsdh_module_init);
module_exit(bcmsdh_module_cleanup);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION(DESCRIPTION);
MODULE_AUTHOR(AUTHOR);
#endif /* BCMSDH_MODULE */
/*
* module init
*/
int sdio_function_init(void)
{
int error = 0;
sd_trace(("bcmsdh_sdmmc: %s Enter\n", __FUNCTION__));
gInstance = kzalloc(sizeof(BCMSDH_SDMMC_INSTANCE), GFP_KERNEL);
if (!gInstance)
return -ENOMEM;
error = sdio_register_driver(&bcmsdh_sdmmc_driver);
if (error) {
kfree(gInstance);
gInstance = NULL;
}
return error;
}
/*
* module cleanup
*/
extern int bcmsdh_remove(struct device *dev);
void sdio_function_cleanup(void)
{
sd_trace(("%s Enter\n", __FUNCTION__));
sdio_unregister_driver(&bcmsdh_sdmmc_driver);
if (gInstance) {
kfree(gInstance);
gInstance = NULL;
}
}
| SlimRoms/kernel_sony_msm8974pro | drivers/net/wireless/bcmdhd/bcmsdh_sdmmc_linux.c | C | gpl-2.0 | 11,547 |
/*
===========================================================================
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 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/>.
===========================================================================
*/
/*
=======================================================================
FORCE INTERFACE
=======================================================================
*/
// use this to get a demo build without an explicit demo build, i.e. to get the demo ui files to build
#include "ui_local.h"
#include "qcommon/qfiles.h"
#include "ui_force.h"
int uiForceSide = FORCE_LIGHTSIDE;
int uiJediNonJedi = -1;
int uiForceRank = FORCE_MASTERY_JEDI_KNIGHT;
int uiMaxRank = MAX_FORCE_RANK;
int uiMaxPoints = 20;
int uiForceUsed = 0;
int uiForceAvailable=0;
extern const char *UI_TeamName(int team);
qboolean gTouchedForce = qfalse;
void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow);
qboolean uiForcePowersDisabled[NUM_FORCE_POWERS] = {
qfalse,//FP_HEAL,//instant
qfalse,//FP_LEVITATION,//hold/duration
qfalse,//FP_SPEED,//duration
qfalse,//FP_PUSH,//hold/duration
qfalse,//FP_PULL,//hold/duration
qfalse,//FP_TELEPATHY,//instant
qfalse,//FP_GRIP,//hold/duration
qfalse,//FP_LIGHTNING,//hold/duration
qfalse,//FP_RAGE,//duration
qfalse,//FP_PROTECT,
qfalse,//FP_ABSORB,
qfalse,//FP_TEAM_HEAL,
qfalse,//FP_TEAM_FORCE,
qfalse,//FP_DRAIN,
qfalse,//FP_SEE,
qfalse,//FP_SABER_OFFENSE,
qfalse,//FP_SABER_DEFENSE,
qfalse//FP_SABERTHROW,
};
int uiForcePowersRank[NUM_FORCE_POWERS] = {
0,//FP_HEAL = 0,//instant
1,//FP_LEVITATION,//hold/duration, this one defaults to 1 (gives a free point)
0,//FP_SPEED,//duration
0,//FP_PUSH,//hold/duration
0,//FP_PULL,//hold/duration
0,//FP_TELEPATHY,//instant
0,//FP_GRIP,//hold/duration
0,//FP_LIGHTNING,//hold/duration
0,//FP_RAGE,//duration
0,//FP_PROTECT,
0,//FP_ABSORB,
0,//FP_TEAM_HEAL,
0,//FP_TEAM_FORCE,
0,//FP_DRAIN,
0,//FP_SEE,
1,//FP_SABER_OFFENSE, //default to 1 point in attack
1,//FP_SABER_DEFENSE, //defualt to 1 point in defense
0//FP_SABERTHROW,
};
int uiForcePowerDarkLight[NUM_FORCE_POWERS] = //0 == neutral
{ //nothing should be usable at rank 0..
FORCE_LIGHTSIDE,//FP_HEAL,//instant
0,//FP_LEVITATION,//hold/duration
0,//FP_SPEED,//duration
0,//FP_PUSH,//hold/duration
0,//FP_PULL,//hold/duration
FORCE_LIGHTSIDE,//FP_TELEPATHY,//instant
FORCE_DARKSIDE,//FP_GRIP,//hold/duration
FORCE_DARKSIDE,//FP_LIGHTNING,//hold/duration
FORCE_DARKSIDE,//FP_RAGE,//duration
FORCE_LIGHTSIDE,//FP_PROTECT,//duration
FORCE_LIGHTSIDE,//FP_ABSORB,//duration
FORCE_LIGHTSIDE,//FP_TEAM_HEAL,//instant
FORCE_DARKSIDE,//FP_TEAM_FORCE,//instant
FORCE_DARKSIDE,//FP_DRAIN,//hold/duration
0,//FP_SEE,//duration
0,//FP_SABER_OFFENSE,
0,//FP_SABER_DEFENSE,
0//FP_SABERTHROW,
//NUM_FORCE_POWERS
};
int uiForceStarShaders[NUM_FORCE_STAR_IMAGES][2];
int uiSaberColorShaders[NUM_SABER_COLORS];
void UI_InitForceShaders(void)
{
uiForceStarShaders[0][0] = trap->R_RegisterShaderNoMip("forcestar0");
uiForceStarShaders[0][1] = trap->R_RegisterShaderNoMip("forcestar0");
uiForceStarShaders[1][0] = trap->R_RegisterShaderNoMip("forcecircle1");
uiForceStarShaders[1][1] = trap->R_RegisterShaderNoMip("forcestar1");
uiForceStarShaders[2][0] = trap->R_RegisterShaderNoMip("forcecircle2");
uiForceStarShaders[2][1] = trap->R_RegisterShaderNoMip("forcestar2");
uiForceStarShaders[3][0] = trap->R_RegisterShaderNoMip("forcecircle3");
uiForceStarShaders[3][1] = trap->R_RegisterShaderNoMip("forcestar3");
uiForceStarShaders[4][0] = trap->R_RegisterShaderNoMip("forcecircle4");
uiForceStarShaders[4][1] = trap->R_RegisterShaderNoMip("forcestar4");
uiForceStarShaders[5][0] = trap->R_RegisterShaderNoMip("forcecircle5");
uiForceStarShaders[5][1] = trap->R_RegisterShaderNoMip("forcestar5");
uiForceStarShaders[6][0] = trap->R_RegisterShaderNoMip("forcecircle6");
uiForceStarShaders[6][1] = trap->R_RegisterShaderNoMip("forcestar6");
uiForceStarShaders[7][0] = trap->R_RegisterShaderNoMip("forcecircle7");
uiForceStarShaders[7][1] = trap->R_RegisterShaderNoMip("forcestar7");
uiForceStarShaders[8][0] = trap->R_RegisterShaderNoMip("forcecircle8");
uiForceStarShaders[8][1] = trap->R_RegisterShaderNoMip("forcestar8");
uiSaberColorShaders[SABER_RED] = trap->R_RegisterShaderNoMip("menu/art/saber_red");
uiSaberColorShaders[SABER_ORANGE] = trap->R_RegisterShaderNoMip("menu/art/saber_orange");
uiSaberColorShaders[SABER_YELLOW] = trap->R_RegisterShaderNoMip("menu/art/saber_yellow");
uiSaberColorShaders[SABER_GREEN] = trap->R_RegisterShaderNoMip("menu/art/saber_green");
uiSaberColorShaders[SABER_BLUE] = trap->R_RegisterShaderNoMip("menu/art/saber_blue");
uiSaberColorShaders[SABER_PURPLE] = trap->R_RegisterShaderNoMip("menu/art/saber_purple");
}
// Draw the stars spent on the current force power
void UI_DrawForceStars(rectDef_t *rect, float scale, vec4_t color, int textStyle, int forceindex, int val, int min, int max)
{
int i,pad = 4;
int xPos,width = 16;
int starcolor;
if (val < min || val > max)
{
val = min;
}
if (1) // if (val)
{
xPos = rect->x;
for (i=FORCE_LEVEL_1;i<=max;i++)
{
starcolor = bgForcePowerCost[forceindex][i];
if (uiForcePowersDisabled[forceindex])
{
vec4_t grColor = {0.2f, 0.2f, 0.2f, 1.0f};
trap->R_SetColor(grColor);
}
if (val >= i)
{ // Draw a star.
UI_DrawHandlePic( xPos, rect->y+6, width, width, uiForceStarShaders[starcolor][1] );
}
else
{ // Draw a circle.
UI_DrawHandlePic( xPos, rect->y+6, width, width, uiForceStarShaders[starcolor][0] );
}
if (uiForcePowersDisabled[forceindex])
{
trap->R_SetColor(NULL);
}
xPos += width + pad;
}
}
}
// Set the client's force power layout.
void UI_UpdateClientForcePowers(const char *teamArg)
{
trap->Cvar_Set( "forcepowers", va("%i-%i-%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i",
uiForceRank, uiForceSide, uiForcePowersRank[0], uiForcePowersRank[1],
uiForcePowersRank[2], uiForcePowersRank[3], uiForcePowersRank[4],
uiForcePowersRank[5], uiForcePowersRank[6], uiForcePowersRank[7],
uiForcePowersRank[8], uiForcePowersRank[9], uiForcePowersRank[10],
uiForcePowersRank[11], uiForcePowersRank[12], uiForcePowersRank[13],
uiForcePowersRank[14], uiForcePowersRank[15], uiForcePowersRank[16],
uiForcePowersRank[17]) );
if (gTouchedForce)
{
if (teamArg && teamArg[0])
{
trap->Cmd_ExecuteText( EXEC_APPEND, va("forcechanged \"%s\"\n", teamArg) );
}
else
{
trap->Cmd_ExecuteText( EXEC_APPEND, "forcechanged\n" );
}
}
gTouchedForce = qfalse;
}
int UI_TranslateFCFIndex(int index)
{
if (uiForceSide == FORCE_LIGHTSIDE)
{
return index-uiInfo.forceConfigLightIndexBegin;
}
return index-uiInfo.forceConfigDarkIndexBegin;
}
void UI_SaveForceTemplate()
{
char *selectedName = UI_Cvar_VariableString("ui_SaveFCF");
char fcfString[512];
char forceStringValue[4];
fileHandle_t f;
int strPlace = 0;
int forcePlace = 0;
int i = 0;
qboolean foundFeederItem = qfalse;
if (!selectedName || !selectedName[0])
{
Com_Printf("You did not provide a name for the template.\n");
return;
}
if (uiForceSide == FORCE_LIGHTSIDE)
{ //write it into the light side folder
trap->FS_Open(va("forcecfg/light/%s.fcf", selectedName), &f, FS_WRITE);
}
else
{ //if it isn't light it must be dark
trap->FS_Open(va("forcecfg/dark/%s.fcf", selectedName), &f, FS_WRITE);
}
if (!f)
{
Com_Printf("There was an error writing the template file (read-only?).\n");
return;
}
Com_sprintf(fcfString, sizeof(fcfString), "%i-%i-", uiForceRank, uiForceSide);
strPlace = strlen(fcfString);
while (forcePlace < NUM_FORCE_POWERS)
{
Com_sprintf(forceStringValue, sizeof(forceStringValue), "%i", uiForcePowersRank[forcePlace]);
//Just use the force digit even if multiple digits. Shouldn't be longer than 1.
fcfString[strPlace] = forceStringValue[0];
strPlace++;
forcePlace++;
}
fcfString[strPlace] = '\n';
fcfString[strPlace+1] = 0;
trap->FS_Write(fcfString, strlen(fcfString), f);
trap->FS_Close(f);
Com_Printf("Template saved as \"%s\".\n", selectedName);
//Now, update the FCF list
UI_LoadForceConfig_List();
//Then, scroll through and select the template for the file we just saved
while (i < uiInfo.forceConfigCount)
{
if (!Q_stricmp(uiInfo.forceConfigNames[i], selectedName))
{
if ((uiForceSide == FORCE_LIGHTSIDE && uiInfo.forceConfigSide[i]) ||
(uiForceSide == FORCE_DARKSIDE && !uiInfo.forceConfigSide[i]))
{
Menu_SetFeederSelection(NULL, FEEDER_FORCECFG, UI_TranslateFCFIndex(i), NULL);
foundFeederItem = qtrue;
}
}
i++;
}
//Else, go back to 0
if (!foundFeederItem)
{
Menu_SetFeederSelection(NULL, FEEDER_FORCECFG, 0, NULL);
}
}
//
extern qboolean UI_TrueJediEnabled( void );
void UpdateForceUsed()
{
int curpower, currank;
menuDef_t *menu;
// Currently we don't make a distinction between those that wish to play Jedi of lower than maximum skill.
uiForceRank = uiMaxRank;
uiForceUsed = 0;
uiForceAvailable = forceMasteryPoints[uiForceRank];
// Make sure that we have one freebie in jump.
if (uiForcePowersRank[FP_LEVITATION]<1)
{
uiForcePowersRank[FP_LEVITATION]=1;
}
if ( UI_TrueJediEnabled() )
{//true jedi mode is set
if ( uiJediNonJedi == -1 )
{
int x = 0;
qboolean clear = qfalse, update = qfalse;
uiJediNonJedi = FORCE_NONJEDI;
while ( x < NUM_FORCE_POWERS )
{//if any force power is set, we must be a jedi
if ( x == FP_LEVITATION || x == FP_SABER_OFFENSE )
{
if ( uiForcePowersRank[x] > 1 )
{
uiJediNonJedi = FORCE_JEDI;
break;
}
else if ( uiForcePowersRank[x] > 0 )
{
clear = qtrue;
}
}
else if ( uiForcePowersRank[x] > 0 )
{
uiJediNonJedi = FORCE_JEDI;
break;
}
x++;
}
if ( uiJediNonJedi == FORCE_JEDI )
{
if ( uiForcePowersRank[FP_SABER_OFFENSE] < 1 )
{
uiForcePowersRank[FP_SABER_OFFENSE]=1;
update = qtrue;
}
}
else if ( clear )
{
x = 0;
while ( x < NUM_FORCE_POWERS )
{//clear all force
uiForcePowersRank[x] = 0;
x++;
}
update = qtrue;
}
if ( update )
{
int myTeam;
myTeam = (int)(trap->Cvar_VariableValue("ui_myteam"));
if ( myTeam != TEAM_SPECTATOR )
{
UI_UpdateClientForcePowers(UI_TeamName(myTeam));//will cause him to respawn, if it's been 5 seconds since last one
}
else
{
UI_UpdateClientForcePowers(NULL);//just update powers
}
}
}
}
menu = Menus_FindByName("ingame_playerforce");
// Set the cost of the saberattack according to whether its free.
if (ui_freeSaber.integer)
{ // Make saber free
bgForcePowerCost[FP_SABER_OFFENSE][FORCE_LEVEL_1] = 0;
bgForcePowerCost[FP_SABER_DEFENSE][FORCE_LEVEL_1] = 0;
// Make sure that we have one freebie in saber if applicable.
if (uiForcePowersRank[FP_SABER_OFFENSE]<1)
{
uiForcePowersRank[FP_SABER_OFFENSE]=1;
}
if (uiForcePowersRank[FP_SABER_DEFENSE]<1)
{
uiForcePowersRank[FP_SABER_DEFENSE]=1;
}
if (menu)
{
Menu_ShowItemByName(menu, "setFP_SABER_DEFENSE", qtrue);
Menu_ShowItemByName(menu, "setfp_saberthrow", qtrue);
Menu_ShowItemByName(menu, "effectentry", qtrue);
Menu_ShowItemByName(menu, "effectfield", qtrue);
Menu_ShowItemByName(menu, "nosaber", qfalse);
}
}
else
{ // Make saber normal cost
bgForcePowerCost[FP_SABER_OFFENSE][FORCE_LEVEL_1] = 1;
bgForcePowerCost[FP_SABER_DEFENSE][FORCE_LEVEL_1] = 1;
// Also, check if there is no saberattack. If there isn't, there had better not be any defense or throw!
if (uiForcePowersRank[FP_SABER_OFFENSE]<1)
{
uiForcePowersRank[FP_SABER_DEFENSE]=0;
uiForcePowersRank[FP_SABERTHROW]=0;
if (menu)
{
Menu_ShowItemByName(menu, "setfp_saberdefend", qfalse);
Menu_ShowItemByName(menu, "setfp_saberthrow", qfalse);
Menu_ShowItemByName(menu, "effectentry", qfalse);
Menu_ShowItemByName(menu, "effectfield", qfalse);
Menu_ShowItemByName(menu, "nosaber", qtrue);
}
}
else
{
if (menu)
{
Menu_ShowItemByName(menu, "setfp_saberdefend", qtrue);
Menu_ShowItemByName(menu, "setfp_saberthrow", qtrue);
Menu_ShowItemByName(menu, "effectentry", qtrue);
Menu_ShowItemByName(menu, "effectfield", qtrue);
Menu_ShowItemByName(menu, "nosaber", qfalse);
}
}
}
// Make sure that we're still legal.
for (curpower=0;curpower<NUM_FORCE_POWERS;curpower++)
{ // Make sure that our ranks are within legal limits.
if (uiForcePowersRank[curpower]<0)
uiForcePowersRank[curpower]=0;
else if (uiForcePowersRank[curpower]>=NUM_FORCE_POWER_LEVELS)
uiForcePowersRank[curpower]=(NUM_FORCE_POWER_LEVELS-1);
for (currank=FORCE_LEVEL_1;currank<=uiForcePowersRank[curpower];currank++)
{ // Check on this force power
if (uiForcePowersRank[curpower]>0)
{ // Do not charge the player for the one freebie in jump, or if there is one in saber.
if ( (curpower == FP_LEVITATION && currank == FORCE_LEVEL_1) ||
(curpower == FP_SABER_OFFENSE && currank == FORCE_LEVEL_1 && ui_freeSaber.integer) ||
(curpower == FP_SABER_DEFENSE && currank == FORCE_LEVEL_1 && ui_freeSaber.integer) )
{
// Do nothing (written this way for clarity)
}
else
{ // Check if we can accrue the cost of this power.
if (bgForcePowerCost[curpower][currank] > uiForceAvailable)
{ // We can't afford this power. Break to the next one.
// Remove this power from the player's roster.
uiForcePowersRank[curpower] = currank-1;
break;
}
else
{ // Sure we can afford it.
uiForceUsed += bgForcePowerCost[curpower][currank];
uiForceAvailable -= bgForcePowerCost[curpower][currank];
}
}
}
}
}
}
//Mostly parts of other functions merged into one another.
//Puts the current UI stuff into a string, legalizes it, and then reads it back out.
void UI_ReadLegalForce(void)
{
char fcfString[512];
char forceStringValue[4];
int strPlace = 0;
int forcePlace = 0;
int i = 0;
char singleBuf[64];
char info[MAX_INFO_VALUE];
int c = 0;
int iBuf = 0;
int forcePowerRank = 0;
int currank = 0;
int forceTeam = 0;
qboolean updateForceLater = qfalse;
//First, stick them into a string.
Com_sprintf(fcfString, sizeof(fcfString), "%i-%i-", uiForceRank, uiForceSide);
strPlace = strlen(fcfString);
while (forcePlace < NUM_FORCE_POWERS)
{
Com_sprintf(forceStringValue, sizeof(forceStringValue), "%i", uiForcePowersRank[forcePlace]);
//Just use the force digit even if multiple digits. Shouldn't be longer than 1.
fcfString[strPlace] = forceStringValue[0];
strPlace++;
forcePlace++;
}
fcfString[strPlace] = '\n';
fcfString[strPlace+1] = 0;
info[0] = '\0';
trap->GetConfigString(CS_SERVERINFO, info, sizeof(info));
if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) ))
{
switch((int)(trap->Cvar_VariableValue("ui_myteam")))
{
case TEAM_RED:
forceTeam = FORCE_DARKSIDE;
break;
case TEAM_BLUE:
forceTeam = FORCE_LIGHTSIDE;
break;
default:
break;
}
}
//Second, legalize them.
if (!BG_LegalizedForcePowers(fcfString, sizeof (fcfString), uiMaxRank, ui_freeSaber.integer, forceTeam, atoi( Info_ValueForKey( info, "g_gametype" )), 0))
{ //if they were illegal, we should refresh them.
updateForceLater = qtrue;
}
//Lastly, put them back into the UI storage from the legalized string
i = 0;
while (fcfString[i] && fcfString[i] != '-')
{
singleBuf[c] = fcfString[i];
c++;
i++;
}
singleBuf[c] = 0;
c = 0;
i++;
iBuf = atoi(singleBuf);
if (iBuf > uiMaxRank || iBuf < 0)
{ //this force config uses a rank level higher than our currently restricted level.. so we can't use it
//FIXME: Print a message indicating this to the user
// return;
}
uiForceRank = iBuf;
while (fcfString[i] && fcfString[i] != '-')
{
singleBuf[c] = fcfString[i];
c++;
i++;
}
singleBuf[c] = 0;
c = 0;
i++;
uiForceSide = atoi(singleBuf);
if (uiForceSide != FORCE_LIGHTSIDE &&
uiForceSide != FORCE_DARKSIDE)
{
uiForceSide = FORCE_LIGHTSIDE;
return;
}
//clear out the existing powers
while (c < NUM_FORCE_POWERS)
{
uiForcePowersRank[c] = 0;
c++;
}
uiForceUsed = 0;
uiForceAvailable = forceMasteryPoints[uiForceRank];
gTouchedForce = qtrue;
for (c=0;fcfString[i]&&c<NUM_FORCE_POWERS;c++,i++)
{
singleBuf[0] = fcfString[i];
singleBuf[1] = 0;
iBuf = atoi(singleBuf); // So, that means that Force Power "c" wants to be set to rank "iBuf".
if (iBuf < 0)
{
iBuf = 0;
}
forcePowerRank = iBuf;
if (forcePowerRank > FORCE_LEVEL_3 || forcePowerRank < 0)
{ //err.. not correct
continue; // skip this power
}
if (uiForcePowerDarkLight[c] && uiForcePowerDarkLight[c] != uiForceSide)
{ //Apparently the user has crafted a force config that has powers that don't fit with the config's side.
continue; // skip this power
}
// Accrue cost for each assigned rank for this power.
for (currank=FORCE_LEVEL_1;currank<=forcePowerRank;currank++)
{
if (bgForcePowerCost[c][currank] > uiForceAvailable)
{ // Break out, we can't afford any more power.
break;
}
// Pay for this rank of this power.
uiForceUsed += bgForcePowerCost[c][currank];
uiForceAvailable -= bgForcePowerCost[c][currank];
uiForcePowersRank[c]++;
}
}
if (uiForcePowersRank[FP_LEVITATION] < 1)
{
uiForcePowersRank[FP_LEVITATION]=1;
}
if (uiForcePowersRank[FP_SABER_OFFENSE] < 1 && ui_freeSaber.integer)
{
uiForcePowersRank[FP_SABER_OFFENSE]=1;
}
if (uiForcePowersRank[FP_SABER_DEFENSE] < 1 && ui_freeSaber.integer)
{
uiForcePowersRank[FP_SABER_DEFENSE]=1;
}
UpdateForceUsed();
if (updateForceLater)
{
gTouchedForce = qtrue;
UI_UpdateClientForcePowers(NULL);
}
}
void UI_UpdateForcePowers()
{
char *forcePowers = UI_Cvar_VariableString("forcepowers");
char readBuf[256];
int i = 0, i_f = 0, i_r = 0;
uiForceSide = 0;
if (forcePowers && forcePowers[0])
{
while (forcePowers[i])
{
i_r = 0;
while (forcePowers[i] && forcePowers[i] != '-' && i_r < 255)
{
readBuf[i_r] = forcePowers[i];
i_r++;
i++;
}
readBuf[i_r] = '\0';
if (i_r >= 255 || !forcePowers[i] || forcePowers[i] != '-')
{
uiForceSide = 0;
goto validitycheck;
}
uiForceRank = atoi(readBuf);
i_r = 0;
if (uiForceRank > uiMaxRank)
{
uiForceRank = uiMaxRank;
}
i++;
while (forcePowers[i] && forcePowers[i] != '-' && i_r < 255)
{
readBuf[i_r] = forcePowers[i];
i_r++;
i++;
}
readBuf[i_r] = '\0';
if (i_r >= 255 || !forcePowers[i] || forcePowers[i] != '-')
{
uiForceSide = 0;
goto validitycheck;
}
uiForceSide = atoi(readBuf);
i_r = 0;
i++;
i_f = FP_HEAL;
while (forcePowers[i] && i_f < NUM_FORCE_POWERS)
{
readBuf[0] = forcePowers[i];
readBuf[1] = '\0';
uiForcePowersRank[i_f] = atoi(readBuf);
if (i_f == FP_LEVITATION &&
uiForcePowersRank[i_f] < 1)
{
uiForcePowersRank[i_f] = 1;
}
if (i_f == FP_SABER_OFFENSE &&
uiForcePowersRank[i_f] < 1 &&
ui_freeSaber.integer)
{
uiForcePowersRank[i_f] = 1;
}
if (i_f == FP_SABER_DEFENSE &&
uiForcePowersRank[i_f] < 1 &&
ui_freeSaber.integer)
{
uiForcePowersRank[i_f] = 1;
}
i_f++;
i++;
}
if (i_f < NUM_FORCE_POWERS)
{ //info for all the powers wasn't there..
uiForceSide = 0;
goto validitycheck;
}
i++;
}
}
validitycheck:
if (!uiForceSide)
{
uiForceSide = 1;
uiForceRank = 1;
i = 0;
while (i < NUM_FORCE_POWERS)
{
if (i == FP_LEVITATION)
{
uiForcePowersRank[i] = 1;
}
else if (i == FP_SABER_OFFENSE && ui_freeSaber.integer)
{
uiForcePowersRank[i] = 1;
}
else if (i == FP_SABER_DEFENSE && ui_freeSaber.integer)
{
uiForcePowersRank[i] = 1;
}
else
{
uiForcePowersRank[i] = 0;
}
i++;
}
UI_UpdateClientForcePowers(NULL);
}
UpdateForceUsed();
}
extern int uiSkinColor;
extern int uiHoldSkinColor;
qboolean UI_SkinColor_HandleKey(int flags, float *special, int key, int num, int min, int max, int type)
{
if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER)
{
int i = num;
if (key == A_MOUSE2)
{
i--;
}
else
{
i++;
}
if (i < min)
{
i = max;
}
else if (i > max)
{
i = min;
}
num = i;
uiSkinColor = num;
uiHoldSkinColor = uiSkinColor;
UI_FeederSelection(FEEDER_Q3HEADS, uiInfo.q3SelectedHead, NULL);
return qtrue;
}
return qfalse;
}
qboolean UI_ForceSide_HandleKey(int flags, float *special, int key, int num, int min, int max, int type)
{
char info[MAX_INFO_VALUE];
info[0] = '\0';
trap->GetConfigString(CS_SERVERINFO, info, sizeof(info));
if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) ))
{
switch((int)(trap->Cvar_VariableValue("ui_myteam")))
{
case TEAM_RED:
return qfalse;
case TEAM_BLUE:
return qfalse;
default:
break;
}
}
if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER)
{
int i = num;
int x = 0;
//update the feeder item selection, it might be different depending on side
Menu_SetFeederSelection(NULL, FEEDER_FORCECFG, 0, NULL);
if (key == A_MOUSE2)
{
i--;
}
else
{
i++;
}
if (i < min)
{
i = max;
}
else if (i > max)
{
i = min;
}
num = i;
uiForceSide = num;
// Resetting power ranks based on if light or dark side is chosen
while (x < NUM_FORCE_POWERS)
{
if (uiForcePowerDarkLight[x] && uiForceSide != uiForcePowerDarkLight[x])
{
uiForcePowersRank[x] = 0;
}
x++;
}
UpdateForceUsed();
gTouchedForce = qtrue;
return qtrue;
}
return qfalse;
}
qboolean UI_JediNonJedi_HandleKey(int flags, float *special, int key, int num, int min, int max, int type)
{
char info[MAX_INFO_VALUE];
info[0] = '\0';
trap->GetConfigString(CS_SERVERINFO, info, sizeof(info));
if ( !UI_TrueJediEnabled() )
{//true jedi mode is not set
return qfalse;
}
if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER)
{
int i = num;
int x = 0;
if (key == A_MOUSE2)
{
i--;
}
else
{
i++;
}
if (i < min)
{
i = max;
}
else if (i > max)
{
i = min;
}
num = i;
uiJediNonJedi = num;
// Resetting power ranks based on if light or dark side is chosen
if ( !num )
{//not a jedi?
int myTeam = (int)(trap->Cvar_VariableValue("ui_myteam"));
while ( x < NUM_FORCE_POWERS )
{//clear all force powers
uiForcePowersRank[x] = 0;
x++;
}
if ( myTeam != TEAM_SPECTATOR )
{
UI_UpdateClientForcePowers(UI_TeamName(myTeam));//will cause him to respawn, if it's been 5 seconds since last one
}
else
{
UI_UpdateClientForcePowers(NULL);//just update powers
}
}
else if ( num )
{//a jedi, set the minimums, hopefuly they know to set the rest!
if ( uiForcePowersRank[FP_LEVITATION] < FORCE_LEVEL_1 )
{//force jump 1 minimum
uiForcePowersRank[FP_LEVITATION] = FORCE_LEVEL_1;
}
if ( uiForcePowersRank[FP_SABER_OFFENSE] < FORCE_LEVEL_1 )
{//saber attack 1, minimum
uiForcePowersRank[FP_SABER_OFFENSE] = FORCE_LEVEL_1;
}
}
UpdateForceUsed();
gTouchedForce = qtrue;
return qtrue;
}
return qfalse;
}
qboolean UI_ForceMaxRank_HandleKey(int flags, float *special, int key, int num, int min, int max, int type)
{
if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER)
{
int i = num;
if (key == A_MOUSE2)
{
i--;
}
else
{
i++;
}
if (i < min)
{
i = max;
}
else if (i > max)
{
i = min;
}
num = i;
uiMaxRank = num;
trap->Cvar_Set( "g_maxForceRank", va("%i", num));
// The update force used will remove overallocated powers automatically.
UpdateForceUsed();
gTouchedForce = qtrue;
return qtrue;
}
return qfalse;
}
// This function will either raise or lower a power by one rank.
qboolean UI_ForcePowerRank_HandleKey(int flags, float *special, int key, int num, int min, int max, int type)
{
qboolean raising;
if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER || key == A_BACKSPACE)
{
int forcepower, rank;
//this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index
forcepower = (type-UI_FORCE_RANK)-1;
//the power is disabled on the server
if (uiForcePowersDisabled[forcepower])
{
return qtrue;
}
// If we are not on the same side as a power, or if we are not of any rank at all.
if (uiForcePowerDarkLight[forcepower] && uiForceSide != uiForcePowerDarkLight[forcepower])
{
return qtrue;
}
else if (forcepower == FP_SABER_DEFENSE || forcepower == FP_SABERTHROW)
{ // Saberdefend and saberthrow can't be bought if there is no saberattack
if (uiForcePowersRank[FP_SABER_OFFENSE] < 1)
{
return qtrue;
}
}
if (type == UI_FORCE_RANK_LEVITATION)
{
min += 1;
}
if (type == UI_FORCE_RANK_SABERATTACK && ui_freeSaber.integer)
{
min += 1;
}
if (type == UI_FORCE_RANK_SABERDEFEND && ui_freeSaber.integer)
{
min += 1;
}
if (key == A_MOUSE2 || key == A_BACKSPACE)
{ // Lower a point.
if (uiForcePowersRank[forcepower]<=min)
{
return qtrue;
}
raising = qfalse;
}
else
{ // Raise a point.
if (uiForcePowersRank[forcepower]>=max)
{
return qtrue;
}
raising = qtrue;
}
if (raising)
{ // Check if we can accrue the cost of this power.
rank = uiForcePowersRank[forcepower]+1;
if (bgForcePowerCost[forcepower][rank] > uiForceAvailable)
{ // We can't afford this power. Abandon ship.
return qtrue;
}
else
{ // Sure we can afford it.
uiForceUsed += bgForcePowerCost[forcepower][rank];
uiForceAvailable -= bgForcePowerCost[forcepower][rank];
uiForcePowersRank[forcepower]=rank;
}
}
else
{ // Lower the point.
rank = uiForcePowersRank[forcepower];
uiForceUsed -= bgForcePowerCost[forcepower][rank];
uiForceAvailable += bgForcePowerCost[forcepower][rank];
uiForcePowersRank[forcepower]--;
}
UpdateForceUsed();
gTouchedForce = qtrue;
return qtrue;
}
return qfalse;
}
int gCustRank = 0;
int gCustSide = 0;
int gCustPowersRank[NUM_FORCE_POWERS] = {
0,//FP_HEAL = 0,//instant
1,//FP_LEVITATION,//hold/duration, this one defaults to 1 (gives a free point)
0,//FP_SPEED,//duration
0,//FP_PUSH,//hold/duration
0,//FP_PULL,//hold/duration
0,//FP_TELEPATHY,//instant
0,//FP_GRIP,//hold/duration
0,//FP_LIGHTNING,//hold/duration
0,//FP_RAGE,//duration
0,//FP_PROTECT,
0,//FP_ABSORB,
0,//FP_TEAM_HEAL,
0,//FP_TEAM_FORCE,
0,//FP_DRAIN,
0,//FP_SEE,
0,//FP_SABER_OFFENSE,
0,//FP_SABER_DEFENSE,
0//FP_SABERTHROW,
};
/*
=================
UI_ForceConfigHandle
=================
*/
void UI_ForceConfigHandle( int oldindex, int newindex )
{
fileHandle_t f;
int len = 0;
int i = 0;
int c = 0;
int iBuf = 0, forcePowerRank, currank;
char fcfBuffer[8192];
char singleBuf[64];
char info[MAX_INFO_VALUE];
int forceTeam = 0;
if (oldindex == 0)
{ //switching out from custom config, so first shove the current values into the custom storage
i = 0;
while (i < NUM_FORCE_POWERS)
{
gCustPowersRank[i] = uiForcePowersRank[i];
i++;
}
gCustRank = uiForceRank;
gCustSide = uiForceSide;
}
if (newindex == 0)
{ //switching back to custom, shove the values back in from the custom storage
i = 0;
uiForceUsed = 0;
gTouchedForce = qtrue;
while (i < NUM_FORCE_POWERS)
{
uiForcePowersRank[i] = gCustPowersRank[i];
uiForceUsed += uiForcePowersRank[i];
i++;
}
uiForceRank = gCustRank;
uiForceSide = gCustSide;
UpdateForceUsed();
return;
}
//If we made it here, we want to load in a new config
if (uiForceSide == FORCE_LIGHTSIDE)
{ //we should only be displaying lightside configs, so.. look in the light folder
newindex += uiInfo.forceConfigLightIndexBegin;
if (newindex >= uiInfo.forceConfigCount)
return;
len = trap->FS_Open(va("forcecfg/light/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ);
}
else
{ //else dark
newindex += uiInfo.forceConfigDarkIndexBegin;
if (newindex >= uiInfo.forceConfigCount || newindex > uiInfo.forceConfigLightIndexBegin)
{ //dark gets read in before light
return;
}
len = trap->FS_Open(va("forcecfg/dark/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ);
}
if (len <= 0)
{ //This should not have happened. But, before we quit out, attempt searching the other light/dark folder for the file.
if (uiForceSide == FORCE_LIGHTSIDE)
len = trap->FS_Open(va("forcecfg/dark/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ);
else
len = trap->FS_Open(va("forcecfg/light/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ);
if (len <= 0)
{ //still failure? Oh well.
return;
}
}
if (len >= 8192)
{
return;
}
trap->FS_Read(fcfBuffer, len, f);
fcfBuffer[len] = 0;
trap->FS_Close(f);
i = 0;
info[0] = '\0';
trap->GetConfigString(CS_SERVERINFO, info, sizeof(info));
if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) ))
{
switch((int)(trap->Cvar_VariableValue("ui_myteam")))
{
case TEAM_RED:
forceTeam = FORCE_DARKSIDE;
break;
case TEAM_BLUE:
forceTeam = FORCE_LIGHTSIDE;
break;
default:
break;
}
}
BG_LegalizedForcePowers(fcfBuffer, sizeof (fcfBuffer), uiMaxRank, ui_freeSaber.integer, forceTeam, atoi( Info_ValueForKey( info, "g_gametype" )), 0);
//legalize the config based on the max rank
//now that we're done with the handle, it's time to parse our force data out of the string
//we store strings in rank-side-xxxxxxxxx format (where the x's are individual force power levels)
while (fcfBuffer[i] && fcfBuffer[i] != '-')
{
singleBuf[c] = fcfBuffer[i];
c++;
i++;
}
singleBuf[c] = 0;
c = 0;
i++;
iBuf = atoi(singleBuf);
if (iBuf > uiMaxRank || iBuf < 0)
{ //this force config uses a rank level higher than our currently restricted level.. so we can't use it
//FIXME: Print a message indicating this to the user
return;
}
uiForceRank = iBuf;
while (fcfBuffer[i] && fcfBuffer[i] != '-')
{
singleBuf[c] = fcfBuffer[i];
c++;
i++;
}
singleBuf[c] = 0;
c = 0;
i++;
uiForceSide = atoi(singleBuf);
if (uiForceSide != FORCE_LIGHTSIDE &&
uiForceSide != FORCE_DARKSIDE)
{
uiForceSide = FORCE_LIGHTSIDE;
return;
}
//clear out the existing powers
while (c < NUM_FORCE_POWERS)
{
/*
if (c==FP_LEVITATION)
{
uiForcePowersRank[c]=1;
}
else if (c==FP_SABER_OFFENSE && ui_freeSaber.integer)
{
uiForcePowersRank[c]=1;
}
else if (c==FP_SABER_DEFENSE && ui_freeSaber.integer)
{
uiForcePowersRank[c]=1;
}
else
{
uiForcePowersRank[c] = 0;
}
*/
//rww - don't need to do these checks. Just trust whatever the saber config says.
uiForcePowersRank[c] = 0;
c++;
}
uiForceUsed = 0;
uiForceAvailable = forceMasteryPoints[uiForceRank];
gTouchedForce = qtrue;
for (c=0;fcfBuffer[i]&&c<NUM_FORCE_POWERS;c++,i++)
{
singleBuf[0] = fcfBuffer[i];
singleBuf[1] = 0;
iBuf = atoi(singleBuf); // So, that means that Force Power "c" wants to be set to rank "iBuf".
if (iBuf < 0)
{
iBuf = 0;
}
forcePowerRank = iBuf;
if (forcePowerRank > FORCE_LEVEL_3 || forcePowerRank < 0)
{ //err.. not correct
continue; // skip this power
}
if (uiForcePowerDarkLight[c] && uiForcePowerDarkLight[c] != uiForceSide)
{ //Apparently the user has crafted a force config that has powers that don't fit with the config's side.
continue; // skip this power
}
// Accrue cost for each assigned rank for this power.
for (currank=FORCE_LEVEL_1;currank<=forcePowerRank;currank++)
{
if (bgForcePowerCost[c][currank] > uiForceAvailable)
{ // Break out, we can't afford any more power.
break;
}
// Pay for this rank of this power.
uiForceUsed += bgForcePowerCost[c][currank];
uiForceAvailable -= bgForcePowerCost[c][currank];
uiForcePowersRank[c]++;
}
}
if (uiForcePowersRank[FP_LEVITATION] < 1)
{
uiForcePowersRank[FP_LEVITATION]=1;
}
if (uiForcePowersRank[FP_SABER_OFFENSE] < 1 && ui_freeSaber.integer)
{
uiForcePowersRank[FP_SABER_OFFENSE]=1;
}
if (uiForcePowersRank[FP_SABER_DEFENSE] < 1 && ui_freeSaber.integer)
{
uiForcePowersRank[FP_SABER_DEFENSE]=1;
}
UpdateForceUsed();
}
| TheSil/WhoracleMod | codemp/ui/ui_force.c | C | gpl-2.0 | 32,975 |
/* wchar_t type related definitions.
Copyright (C) 2000-2013 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#ifndef _BITS_WCHAR_H
#define _BITS_WCHAR_H 1
/* The fallback definitions, for when __WCHAR_MAX__ or __WCHAR_MIN__
are not defined, give the right value and type as long as both int
and wchar_t are 32-bit types. Adding L'\0' to a constant value
ensures that the type is correct; it is necessary to use (L'\0' +
0) rather than just L'\0' so that the type in C++ is the promoted
version of wchar_t rather than the distinct wchar_t type itself.
Because wchar_t in preprocessor #if expressions is treated as
intmax_t or uintmax_t, the expression (L'\0' - 1) would have the
wrong value for WCHAR_MAX in such expressions and so cannot be used
to define __WCHAR_MAX in the unsigned case. */
#ifdef __WCHAR_MAX__
# define __WCHAR_MAX __WCHAR_MAX__
#elif L'\0' - 1 > 0
# define __WCHAR_MAX (0xffffffffu + L'\0')
#else
# define __WCHAR_MAX (0x7fffffff + L'\0')
#endif
#ifdef __WCHAR_MIN__
# define __WCHAR_MIN __WCHAR_MIN__
#elif L'\0' - 1 > 0
# define __WCHAR_MIN (L'\0' + 0)
#else
# define __WCHAR_MIN (-__WCHAR_MAX - 1)
#endif
#endif /* bits/wchar.h */
| SanDisk-Open-Source/SSD_Dashboard | uefi/userspace/glibc/bits/wchar.h | C | gpl-2.0 | 1,905 |
/*
* Copyright (c) 2013-2014 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* 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.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
/* Host Debug log implementation */
#include "athdefs.h"
#include "a_types.h"
#include "dbglog_host.h"
#include "wmi.h"
#include "wmi_unified_api.h"
#include "wma.h"
#include "ol_defines.h"
#include <wlan_nlink_srv.h>
#include "vos_diag_core_event.h"
#include "qwlan_version.h"
#include <wlan_hdd_main.h>
#include <wlan_hdd_wext.h>
#include <net/sock.h>
#include <linux/netlink.h>
#ifdef WLAN_OPEN_SOURCE
#include <linux/debugfs.h>
#endif /* WLAN_OPEN_SOURCE */
#include "wmi_unified_priv.h"
#define CLD_DEBUGFS_DIR "cld"
#define DEBUGFS_BLOCK_NAME "dbglog_block"
#define ATH_MODULE_NAME fwlog
#include <a_debug.h>
#define FWLOG_DEBUG ATH_DEBUG_MAKE_MODULE_MASK(0)
#if defined(DEBUG)
static bool appstarted = FALSE;
static bool senddriverstatus = FALSE;
static bool kd_nl_init = FALSE;
static int cnss_diag_pid = INVALID_PID;
static int get_version = 0;
static int gprint_limiter = 0;
static ATH_DEBUG_MASK_DESCRIPTION g_fwlogDebugDescription[] = {
{FWLOG_DEBUG,"fwlog"},
};
ATH_DEBUG_INSTANTIATE_MODULE_VAR(fwlog,
"fwlog",
"Firmware Debug Log",
ATH_DEBUG_MASK_DEFAULTS | ATH_DEBUG_INFO | ATH_DEBUG_ERR,
ATH_DEBUG_DESCRIPTION_COUNT(g_fwlogDebugDescription),
g_fwlogDebugDescription);
#endif
module_dbg_print mod_print[WLAN_MODULE_ID_MAX];
A_UINT32 dbglog_process_type = DBGLOG_PROCESS_NET_RAW;
A_STATUS
wmi_config_debug_module_cmd(wmi_unified_t wmi_handle, A_UINT32 param, A_UINT32 val,
A_UINT32 *module_id_bitmap, A_UINT32 bitmap_len);
const char *dbglog_get_module_str(A_UINT32 module_id)
{
switch (module_id) {
case WLAN_MODULE_INF:
return "INF";
case WLAN_MODULE_WMI:
return "WMI";
case WLAN_MODULE_STA_PWRSAVE:
return "STA PS";
case WLAN_MODULE_WHAL:
return "WHAL";
case WLAN_MODULE_COEX:
return "COEX";
case WLAN_MODULE_ROAM:
return "ROAM";
case WLAN_MODULE_RESMGR_CHAN_MANAGER:
return "CHANMGR";
case WLAN_MODULE_RESMGR:
return "RESMGR";
case WLAN_MODULE_VDEV_MGR:
return "VDEV";
case WLAN_MODULE_SCAN:
return "SCAN";
case WLAN_MODULE_RATECTRL:
return "RC";
case WLAN_MODULE_AP_PWRSAVE:
return "AP PS";
case WLAN_MODULE_BLOCKACK:
return "BA";
case WLAN_MODULE_MGMT_TXRX:
return "MGMT";
case WLAN_MODULE_DATA_TXRX:
return "DATA";
case WLAN_MODULE_HTT:
return "HTT";
case WLAN_MODULE_HOST:
return "HOST";
case WLAN_MODULE_BEACON:
return "BEACON";
case WLAN_MODULE_OFFLOAD:
return "OFFLOAD";
case WLAN_MODULE_WAL:
return "WAL";
case WAL_MODULE_DE:
return "DE";
case WLAN_MODULE_PCIELP:
return "PCIELP";
case WLAN_MODULE_RTT:
return "RTT";
case WLAN_MODULE_DCS:
return "DCS";
case WLAN_MODULE_CACHEMGR:
return "CACHEMGR";
case WLAN_MODULE_ANI:
return "ANI";
case WLAN_MODULE_TEST:
return "TESTPOINT";
case WLAN_MODULE_STA_SMPS:
return "STA_SMPS";
case WLAN_MODULE_TDLS:
return "TDLS";
case WLAN_MODULE_P2P:
return "P2P";
case WLAN_MODULE_WOW:
return "WoW";
case WLAN_MODULE_IBSS_PWRSAVE:
return "IBSS PS";
case WLAN_MODULE_EXTSCAN:
return "ExtScan";
case WLAN_MODULE_UNIT_TEST:
return "UNIT_TEST";
case WLAN_MODULE_MLME:
return "MLME";
case WLAN_MODULE_SUPPL:
return "SUPPLICANT";
default:
return "UNKNOWN";
}
}
char * DBG_MSG_ARR[WLAN_MODULE_ID_MAX][MAX_DBG_MSGS] =
{
{
"INF_MSG_START",
"INF_ASSERTION_FAILED",
"INF_TARGET_ID",
"INF_MSG_END"
},
{
"WMI_DBGID_DEFINITION_START",
"WMI_CMD_RX_XTND_PKT_TOO_SHORT",
"WMI_EXTENDED_CMD_NOT_HANDLED",
"WMI_CMD_RX_PKT_TOO_SHORT",
"WMI_CALLING_WMI_EXTENSION_FN",
"WMI_CMD_NOT_HANDLED",
"WMI_IN_SYNC",
"WMI_TARGET_WMI_SYNC_CMD",
"WMI_SET_SNR_THRESHOLD_PARAMS",
"WMI_SET_RSSI_THRESHOLD_PARAMS",
"WMI_SET_LQ_TRESHOLD_PARAMS",
"WMI_TARGET_CREATE_PSTREAM_CMD",
"WMI_WI_DTM_INUSE",
"WMI_TARGET_DELETE_PSTREAM_CMD",
"WMI_TARGET_IMPLICIT_DELETE_PSTREAM_CMD",
"WMI_TARGET_GET_BIT_RATE_CMD",
"WMI_GET_RATE_MASK_CMD_FIX_RATE_MASK_IS",
"WMI_TARGET_GET_AVAILABLE_CHANNELS_CMD",
"WMI_TARGET_GET_TX_PWR_CMD",
"WMI_FREE_EVBUF_WMIBUF",
"WMI_FREE_EVBUF_DATABUF",
"WMI_FREE_EVBUF_BADFLAG",
"WMI_HTC_RX_ERROR_DATA_PACKET",
"WMI_HTC_RX_SYNC_PAUSING_FOR_MBOX",
"WMI_INCORRECT_WMI_DATA_HDR_DROPPING_PKT",
"WMI_SENDING_READY_EVENT",
"WMI_SETPOWER_MDOE_TO_MAXPERF",
"WMI_SETPOWER_MDOE_TO_REC",
"WMI_BSSINFO_EVENT_FROM",
"WMI_TARGET_GET_STATS_CMD",
"WMI_SENDING_SCAN_COMPLETE_EVENT",
"WMI_SENDING_RSSI_INDB_THRESHOLD_EVENT ",
"WMI_SENDING_RSSI_INDBM_THRESHOLD_EVENT",
"WMI_SENDING_LINK_QUALITY_THRESHOLD_EVENT",
"WMI_SENDING_ERROR_REPORT_EVENT",
"WMI_SENDING_CAC_EVENT",
"WMI_TARGET_GET_ROAM_TABLE_CMD",
"WMI_TARGET_GET_ROAM_DATA_CMD",
"WMI_SENDING_GPIO_INTR_EVENT",
"WMI_SENDING_GPIO_ACK_EVENT",
"WMI_SENDING_GPIO_DATA_EVENT",
"WMI_CMD_RX",
"WMI_CMD_RX_XTND",
"WMI_EVENT_SEND",
"WMI_EVENT_SEND_XTND",
"WMI_CMD_PARAMS_DUMP_START",
"WMI_CMD_PARAMS_DUMP_END",
"WMI_CMD_PARAMS",
"WMI_EVENT_ALLOC_FAILURE",
"WMI_DBGID_DCS_PARAM_CMD",
"WMI_SEND_EVENT_WRONG_TLV",
"WMI_SEND_EVENT_NO_TLV_DEF",
"WMI_DBGID_DEFNITION_END",
},
{
"PS_STA_DEFINITION_START",
"PS_STA_PM_ARB_REQUEST",
"PS_STA_DELIVER_EVENT",
"PS_STA_PSPOLL_SEQ_DONE",
"PS_STA_COEX_MODE",
"PS_STA_PSPOLL_ALLOW",
"PS_STA_SET_PARAM",
"PS_STA_SPECPOLL_TIMER_STARTED",
"PS_STA_SPECPOLL_TIMER_STOPPED",
},
{
"WHAL_DBGID_DEFINITION_START",
"WHAL_ERROR_ANI_CONTROL",
"WHAL_ERROR_CHIP_TEST1",
"WHAL_ERROR_CHIP_TEST2",
"WHAL_ERROR_EEPROM_CHECKSUM",
"WHAL_ERROR_EEPROM_MACADDR",
"WHAL_ERROR_INTERRUPT_HIU",
"WHAL_ERROR_KEYCACHE_RESET",
"WHAL_ERROR_KEYCACHE_SET",
"WHAL_ERROR_KEYCACHE_TYPE",
"WHAL_ERROR_KEYCACHE_TKIPENTRY",
"WHAL_ERROR_KEYCACHE_WEPLENGTH",
"WHAL_ERROR_PHY_INVALID_CHANNEL",
"WHAL_ERROR_POWER_AWAKE",
"WHAL_ERROR_POWER_SET",
"WHAL_ERROR_RECV_STOPDMA",
"WHAL_ERROR_RECV_STOPPCU",
"WHAL_ERROR_RESET_CHANNF1",
"WHAL_ERROR_RESET_CHANNF2",
"WHAL_ERROR_RESET_PM",
"WHAL_ERROR_RESET_OFFSETCAL",
"WHAL_ERROR_RESET_RFGRANT",
"WHAL_ERROR_RESET_RXFRAME",
"WHAL_ERROR_RESET_STOPDMA",
"WHAL_ERROR_RESET_ERRID",
"WHAL_ERROR_RESET_ADCDCCAL1",
"WHAL_ERROR_RESET_ADCDCCAL2",
"WHAL_ERROR_RESET_TXIQCAL",
"WHAL_ERROR_RESET_RXIQCAL",
"WHAL_ERROR_RESET_CARRIERLEAK",
"WHAL_ERROR_XMIT_COMPUTE",
"WHAL_ERROR_XMIT_NOQUEUE",
"WHAL_ERROR_XMIT_ACTIVEQUEUE",
"WHAL_ERROR_XMIT_BADTYPE",
"WHAL_ERROR_XMIT_STOPDMA",
"WHAL_ERROR_INTERRUPT_BB_PANIC",
"WHAL_ERROR_PAPRD_MAXGAIN_ABOVE_WINDOW",
"WHAL_ERROR_QCU_HW_PAUSE_MISMATCH",
"WHAL_DBGID_DEFINITION_END",
},
{
"COEX_DEBUGID_START",
"BTCOEX_DBG_MCI_1",
"BTCOEX_DBG_MCI_2",
"BTCOEX_DBG_MCI_3",
"BTCOEX_DBG_MCI_4",
"BTCOEX_DBG_MCI_5",
"BTCOEX_DBG_MCI_6",
"BTCOEX_DBG_MCI_7",
"BTCOEX_DBG_MCI_8",
"BTCOEX_DBG_MCI_9",
"BTCOEX_DBG_MCI_10",
"COEX_WAL_BTCOEX_INIT",
"COEX_WAL_PAUSE",
"COEX_WAL_RESUME",
"COEX_UPDATE_AFH",
"COEX_HWQ_EMPTY_CB",
"COEX_MCI_TIMER_HANDLER",
"COEX_MCI_RECOVER",
"ERROR_COEX_MCI_ISR",
"ERROR_COEX_MCI_GPM",
"COEX_ProfileType",
"COEX_LinkID",
"COEX_LinkState",
"COEX_LinkRole",
"COEX_LinkRate",
"COEX_VoiceType",
"COEX_TInterval",
"COEX_WRetrx",
"COEX_Attempts",
"COEX_PerformanceState",
"COEX_LinkType",
"COEX_RX_MCI_GPM_VERSION_QUERY",
"COEX_RX_MCI_GPM_VERSION_RESPONSE",
"COEX_RX_MCI_GPM_STATUS_QUERY",
"COEX_STATE_WLAN_VDEV_DOWN",
"COEX_STATE_WLAN_VDEV_START",
"COEX_STATE_WLAN_VDEV_CONNECTED",
"COEX_STATE_WLAN_VDEV_SCAN_STARTED",
"COEX_STATE_WLAN_VDEV_SCAN_END",
"COEX_STATE_WLAN_DEFAULT",
"COEX_CHANNEL_CHANGE",
"COEX_POWER_CHANGE",
"COEX_CONFIG_MGR",
"COEX_TX_MCI_GPM_BT_CAL_REQ",
"COEX_TX_MCI_GPM_BT_CAL_GRANT",
"COEX_TX_MCI_GPM_BT_CAL_DONE",
"COEX_TX_MCI_GPM_WLAN_CAL_REQ",
"COEX_TX_MCI_GPM_WLAN_CAL_GRANT",
"COEX_TX_MCI_GPM_WLAN_CAL_DONE",
"COEX_TX_MCI_GPM_BT_DEBUG",
"COEX_TX_MCI_GPM_VERSION_QUERY",
"COEX_TX_MCI_GPM_VERSION_RESPONSE",
"COEX_TX_MCI_GPM_STATUS_QUERY",
"COEX_TX_MCI_GPM_HALT_BT_GPM",
"COEX_TX_MCI_GPM_WLAN_CHANNELS",
"COEX_TX_MCI_GPM_BT_PROFILE_INFO",
"COEX_TX_MCI_GPM_BT_STATUS_UPDATE",
"COEX_TX_MCI_GPM_BT_UPDATE_FLAGS",
"COEX_TX_MCI_GPM_UNKNOWN",
"COEX_TX_MCI_SYS_WAKING",
"COEX_TX_MCI_LNA_TAKE",
"COEX_TX_MCI_LNA_TRANS",
"COEX_TX_MCI_SYS_SLEEPING",
"COEX_TX_MCI_REQ_WAKE",
"COEX_TX_MCI_REMOTE_RESET",
"COEX_TX_MCI_TYPE_UNKNOWN",
"COEX_WHAL_MCI_RESET",
"COEX_POLL_BT_CAL_DONE_TIMEOUT",
"COEX_WHAL_PAUSE",
"COEX_RX_MCI_GPM_BT_CAL_REQ",
"COEX_RX_MCI_GPM_BT_CAL_DONE",
"COEX_RX_MCI_GPM_BT_CAL_GRANT",
"COEX_WLAN_CAL_START",
"COEX_WLAN_CAL_RESULT",
"COEX_BtMciState",
"COEX_BtCalState",
"COEX_WlanCalState",
"COEX_RxReqWakeCount",
"COEX_RxRemoteResetCount",
"COEX_RESTART_CAL",
"COEX_SENDMSG_QUEUE",
"COEX_RESETSEQ_LNAINFO_TIMEOUT",
"COEX_MCI_ISR_IntRaw",
"COEX_MCI_ISR_Int1Raw",
"COEX_MCI_ISR_RxMsgRaw",
"COEX_WHAL_COEX_RESET",
"COEX_WAL_COEX_INIT",
"COEX_TXRX_CNT_LIMIT_ISR",
"COEX_CH_BUSY",
"COEX_REASSESS_WLAN_STATE",
"COEX_BTCOEX_WLAN_STATE_UPDATE",
"COEX_BT_NUM_OF_PROFILES",
"COEX_BT_NUM_OF_HID_PROFILES",
"COEX_BT_NUM_OF_ACL_PROFILES",
"COEX_BT_NUM_OF_HI_ACL_PROFILES",
"COEX_BT_NUM_OF_VOICE_PROFILES",
"COEX_WLAN_AGGR_LIMIT",
"COEX_BT_LOW_PRIO_BUDGET",
"COEX_BT_HI_PRIO_BUDGET",
"COEX_BT_IDLE_TIME",
"COEX_SET_COEX_WEIGHT",
"COEX_WLAN_WEIGHT_GROUP",
"COEX_BT_WEIGHT_GROUP",
"COEX_BT_INTERVAL_ALLOC",
"COEX_BT_SCHEME",
"COEX_BT_MGR",
"COEX_BT_SM_ERROR",
"COEX_SYSTEM_UPDATE",
"COEX_LOW_PRIO_LIMIT",
"COEX_HI_PRIO_LIMIT",
"COEX_BT_INTERVAL_START",
"COEX_WLAN_INTERVAL_START",
"COEX_NON_LINK_BUDGET",
"COEX_CONTENTION_MSG",
"COEX_SET_NSS",
"COEX_SELF_GEN_MASK",
"COEX_PROFILE_ERROR",
"COEX_WLAN_INIT",
"COEX_BEACON_MISS",
"COEX_BEACON_OK",
"COEX_BTCOEX_SCAN_ACTIVITY",
"COEX_SCAN_ACTIVITY",
"COEX_FORCE_QUIETTIME",
"COEX_BT_MGR_QUIETTIME",
"COEX_BT_INACTIVITY_TRIGGER",
"COEX_BT_INACTIVITY_REPORTED",
"COEX_TX_MCI_GPM_WLAN_PRIO",
"COEX_TX_MCI_GPM_BT_PAUSE_PROFILE",
"COEX_TX_MCI_GPM_WLAN_SET_ACL_INACTIVITY",
"COEX_RX_MCI_GPM_BT_ACL_INACTIVITY_REPORT",
"COEX_GENERIC_ERROR",
"COEX_RX_RATE_THRESHOLD",
"COEX_RSSI",
"COEX_WLAN_VDEV_NOTIF_START", // 133
"COEX_WLAN_VDEV_NOTIF_UP", // 134
"COEX_WLAN_VDEV_NOTIF_DOWN", // 135
"COEX_WLAN_VDEV_NOTIF_STOP", // 136
"COEX_WLAN_VDEV_NOTIF_ADD_PEER", // 137
"COEX_WLAN_VDEV_NOTIF_DELETE_PEER", // 138
"COEX_WLAN_VDEV_NOTIF_CONNECTED_PEER", // 139
"COEX_WLAN_VDEV_NOTIF_PAUSE", // 140
"COEX_WLAN_VDEV_NOTIF_UNPAUSED", // 141
"COEX_STATE_WLAN_VDEV_PEER_ADD", // 142
"COEX_STATE_WLAN_VDEV_CONNECTED_PEER", // 143
"COEX_STATE_WLAN_VDEV_DELETE_PEER", // 144
"COEX_STATE_WLAN_VDEV_PAUSE", // 145
"COEX_STATE_WLAN_VDEV_UNPAUSED", // 146
"COEX_SCAN_CALLBACK", // 147
"COEX_RC_SET_CHAINMASK", // 148
"COEX_TX_MCI_GPM_WLAN_SET_BT_RXSS_THRES", // 149
"COEX_TX_MCI_GPM_BT_RXSS_THRES_QUERY", // 150
"COEX_BT_RXSS_THRES", // 151
"COEX_BT_PROFILE_ADD_RMV", // 152
"COEX_BT_SCHED_INFO", // 153
"COEX_TRF_MGMT", // 154
"COEX_SCHED_START", // 155
"COEX_SCHED_RESULT", // 156
"COEX_SCHED_ERROR", // 157
"COEX_SCHED_PRE_OP", // 158
"COEX_SCHED_POST_OP", // 159
"COEX_RX_RATE", // 160
"COEX_ACK_PRIORITY", // 161
"COEX_STATE_WLAN_VDEV_UP", // 162
"COEX_STATE_WLAN_VDEV_PEER_UPDATE", // 163
"COEX_STATE_WLAN_VDEV_STOP", // 164
"COEX_WLAN_PAUSE_PEER", // 165
"COEX_WLAN_UNPAUSE_PEER", // 166
"COEX_WLAN_PAUSE_INTERVAL_START", // 167
"COEX_WLAN_POSTPAUSE_INTERVAL_START", // 168
"COEX_TRF_FREERUN", // 169
"COEX_TRF_SHAPE_PM", // 170
"COEX_TRF_SHAPE_PSP", // 171
"COEX_TRF_SHAPE_S_CTS", // 172
"COEX_CHAIN_CONFIG", // 173
"COEX_SYSTEM_MONITOR", // 174
"COEX_SINGLECHAIN_INIT", // 175
"COEX_MULTICHAIN_INIT", // 176
"COEX_SINGLECHAIN_DBG_1", // 177
"COEX_SINGLECHAIN_DBG_2", // 178
"COEX_SINGLECHAIN_DBG_3", // 179
"COEX_MULTICHAIN_DBG_1", // 180
"COEX_MULTICHAIN_DBG_2", // 181
"COEX_MULTICHAIN_DBG_3", // 182
"COEX_PSP_TX_CB", // 183
"COEX_PSP_RX_CB", // 184
"COEX_PSP_STAT_1", // 185
"COEX_PSP_SPEC_POLL", // 186
"COEX_PSP_READY_STATE", // 187
"COEX_PSP_TX_STATUS_STATE", // 188
"COEX_PSP_RX_STATUS_STATE_1", // 189
"COEX_PSP_NOT_READY_STATE", // 190
"COEX_PSP_DISABLED_STATE", // 191
"COEX_PSP_ENABLED_STATE", // 192
"COEX_PSP_SEND_PSPOLL", // 193
"COEX_PSP_MGR_ENTER", // 194
"COEX_PSP_MGR_RESULT", // 195
"COEX_PSP_NONWLAN_INTERVAL", // 196
"COEX_PSP_STAT_2", // 197
"COEX_PSP_RX_STATUS_STATE_2", // 198
"COEX_PSP_ERROR", // 199
"COEX_T2BT", // 200
"COEX_BT_DURATION", // 201
"COEX_TX_MCI_GPM_WLAN_SCHED_INFO_TRIG", // 202
"COEX_TX_MCI_GPM_WLAN_SCHED_INFO_TRIG_RSP", // 203
"COEX_TX_MCI_GPM_SCAN_OP", // 204
"COEX_TX_MCI_GPM_BT_PAUSE_GPM_TX", // 205
"COEX_CTS2S_SEND", // 206
"COEX_CTS2S_RESULT", // 207
"COEX_ENTER_OCS", // 208
"COEX_EXIT_OCS", // 209
"COEX_UPDATE_OCS", // 210
"COEX_STATUS_OCS", // 211
"COEX_STATS_BT", // 212
"COEX_MWS_WLAN_INIT",
"COEX_MWS_WBTMR_SYNC",
"COEX_MWS_TYPE2_RX",
"COEX_MWS_TYPE2_TX",
"COEX_MWS_WLAN_CHAVD",
"COEX_MWS_WLAN_CHAVD_INSERT",
"COEX_MWS_WLAN_CHAVD_MERGE",
"COEX_MWS_WLAN_CHAVD_RPT",
"COEX_MWS_CP_MSG_SEND",
"COEX_MWS_CP_ESCAPE",
"COEX_MWS_CP_UNFRAME",
"COEX_MWS_CP_SYNC_UPDATE",
"COEX_MWS_CP_SYNC",
"COEX_MWS_CP_WLAN_STATE_IND",
"COEX_MWS_CP_SYNCRESP_TIMEOUT",
"COEX_MWS_SCHEME_UPDATE",
"COEX_MWS_WLAN_EVENT",
"COEX_MWS_UART_UNESCAPE",
"COEX_MWS_UART_ENCODE_SEND",
"COEX_MWS_UART_RECV_DECODE",
"COEX_MWS_UL_HDL",
"COEX_MWS_REMOTE_EVENT",
"COEX_MWS_OTHER",
"COEX_MWS_ERROR",
"COEX_MWS_ANT_DIVERSITY", //237
"COEX_P2P_GO",
"COEX_P2P_CLIENT",
"COEX_SCC_1",
"COEX_SCC_2",
"COEX_MCC_1",
"COEX_MCC_2",
"COEX_TRF_SHAPE_NOA",
"COEX_NOA_ONESHOT",
"COEX_NOA_PERIODIC",
"COEX_LE_1",
"COEX_LE_2",
"COEX_ANT_1",
"COEX_ANT_2",
"COEX_ENTER_NOA",
"COEX_EXIT_NOA",
"COEX_BT_SCAN_PROTECT", // 253
"COEX_DEBUG_ID_END" // 254
},
{
"ROAM_DBGID_DEFINITION_START",
"ROAM_MODULE_INIT",
"ROAM_DEV_START",
"ROAM_CONFIG_RSSI_THRESH",
"ROAM_CONFIG_SCAN_PERIOD",
"ROAM_CONFIG_AP_PROFILE",
"ROAM_CONFIG_CHAN_LIST",
"ROAM_CONFIG_SCAN_PARAMS",
"ROAM_CONFIG_RSSI_CHANGE",
"ROAM_SCAN_TIMER_START",
"ROAM_SCAN_TIMER_EXPIRE",
"ROAM_SCAN_TIMER_STOP",
"ROAM_SCAN_STARTED",
"ROAM_SCAN_COMPLETE",
"ROAM_SCAN_CANCELLED",
"ROAM_CANDIDATE_FOUND",
"ROAM_RSSI_ACTIVE_SCAN",
"ROAM_RSSI_ACTIVE_ROAM",
"ROAM_RSSI_GOOD",
"ROAM_BMISS_FIRST_RECV",
"ROAM_DEV_STOP",
"ROAM_FW_OFFLOAD_ENABLE",
"ROAM_CANDIDATE_SSID_MATCH",
"ROAM_CANDIDATE_SECURITY_MATCH",
"ROAM_LOW_RSSI_INTERRUPT",
"ROAM_HIGH_RSSI_INTERRUPT",
"ROAM_SCAN_REQUESTED",
"ROAM_BETTER_CANDIDATE_FOUND",
"ROAM_BETTER_AP_EVENT",
"ROAM_CANCEL_LOW_PRIO_SCAN",
"ROAM_FINAL_BMISS_RECVD",
"ROAM_CONFIG_SCAN_MODE",
"ROAM_BMISS_FINAL_SCAN_ENABLE",
"ROAM_SUITABLE_AP_EVENT",
"ROAM_RSN_IE_PARSE_ERROR",
"ROAM_WPA_IE_PARSE_ERROR",
"ROAM_SCAN_CMD_FROM_HOST",
"ROAM_HO_SORT_CANDIDATE",
"ROAM_HO_SAVE_CANDIDATE",
"ROAM_HO_GET_CANDIDATE",
"ROAM_HO_OFFLOAD_SET_PARAM",
"ROAM_HO_SM",
"ROAM_HO_HTT_SAVED",
"ROAM_HO_SYNC_START",
"ROAM_HO_START",
"ROAM_HO_COMPLETE",
"ROAM_HO_STOP",
"ROAM_HO_HTT_FORWARD",
"ROAM_DBGID_DEFINITION_END"
},
{
"RESMGR_CHMGR_DEFINITION_START",
"RESMGR_CHMGR_PAUSE_COMPLETE",
"RESMGR_CHMGR_CHANNEL_CHANGE",
"RESMGR_CHMGR_RESUME_COMPLETE",
"RESMGR_CHMGR_VDEV_PAUSE",
"RESMGR_CHMGR_VDEV_UNPAUSE",
"RESMGR_CHMGR_CTS2S_TX_COMP",
"RESMGR_CHMGR_CFEND_TX_COMP",
"RESMGR_CHMGR_DEFINITION_END"
},
{
"RESMGR_DEFINITION_START",
"RESMGR_OCS_ALLOCRAM_SIZE",
"RESMGR_OCS_RESOURCES",
"RESMGR_LINK_CREATE",
"RESMGR_LINK_DELETE",
"RESMGR_OCS_CHREQ_CREATE",
"RESMGR_OCS_CHREQ_DELETE",
"RESMGR_OCS_CHREQ_START",
"RESMGR_OCS_CHREQ_STOP",
"RESMGR_OCS_SCHEDULER_INVOKED",
"RESMGR_OCS_CHREQ_GRANT",
"RESMGR_OCS_CHREQ_COMPLETE",
"RESMGR_OCS_NEXT_TSFTIME",
"RESMGR_OCS_TSF_TIMEOUT_US",
"RESMGR_OCS_CURR_CAT_WINDOW",
"RESMGR_OCS_CURR_CAT_WINDOW_REQ",
"RESMGR_OCS_CURR_CAT_WINDOW_TIMESLOT",
"RESMGR_OCS_CHREQ_RESTART",
"RESMGR_OCS_CLEANUP_CH_ALLOCATORS",
"RESMGR_OCS_PURGE_CHREQ",
"RESMGR_OCS_CH_ALLOCATOR_FREE",
"RESMGR_OCS_RECOMPUTE_SCHEDULE",
"RESMGR_OCS_NEW_CAT_WINDOW_REQ",
"RESMGR_OCS_NEW_CAT_WINDOW_TIMESLOT",
"RESMGR_OCS_CUR_CH_ALLOC",
"RESMGR_OCS_WIN_CH_ALLOC",
"RESMGR_OCS_SCHED_CH_CHANGE",
"RESMGR_OCS_CONSTRUCT_CAT_WIN",
"RESMGR_OCS_CHREQ_PREEMPTED",
"RESMGR_OCS_CH_SWITCH_REQ",
"RESMGR_OCS_CHANNEL_SWITCHED",
"RESMGR_OCS_CLEANUP_STALE_REQS",
"RESMGR_OCS_CHREQ_UPDATE",
"RESMGR_OCS_REG_NOA_NOTIF",
"RESMGR_OCS_DEREG_NOA_NOTIF",
"RESMGR_OCS_GEN_PERIODIC_NOA",
"RESMGR_OCS_RECAL_QUOTAS",
"RESMGR_OCS_GRANTED_QUOTA_STATS",
"RESMGR_OCS_ALLOCATED_QUOTA_STATS",
"RESMGR_OCS_REQ_QUOTA_STATS",
"RESMGR_OCS_TRACKING_TIME_FIRED",
"RESMGR_VC_ARBITRATE_ATTRIBUTES",
"RESMGR_OCS_LATENCY_STRICT_TIME_SLOT",
"RESMGR_OCS_CURR_TSF",
"RESMGR_OCS_QUOTA_REM",
"RESMGR_OCS_LATENCY_CASE_NO",
"RESMGR_OCS_WIN_CAT_DUR",
"RESMGR_VC_UPDATE_CUR_VC",
"RESMGR_VC_REG_UNREG_LINK",
"RESMGR_VC_PRINT_LINK",
"RESMGR_OCS_MISS_TOLERANCE",
"RESMGR_DYN_SCH_ALLOCRAM_SIZE",
"RESMGR_DYN_SCH_ENABLE",
"RESMGR_DYN_SCH_ACTIVE",
"RESMGR_DYN_SCH_CH_STATS_START",
"RESMGR_DYN_SCH_CH_SX_STATS",
"RESMGR_DYN_SCH_TOT_UTIL_PER",
"RESMGR_DYN_SCH_HOME_CH_QUOTA",
"RESMGR_OCS_REG_RECAL_QUOTA_NOTIF",
"RESMGR_OCS_DEREG_RECAL_QUOTA_NOTIF",
"RESMGR_DEFINITION_END"
},
{
"VDEV_MGR_DEBID_DEFINITION_START", /* vdev Mgr */
"VDEV_MGR_FIRST_BEACON_MISS_DETECTED",
"VDEV_MGR_FINAL_BEACON_MISS_DETECTED",
"VDEV_MGR_BEACON_IN_SYNC",
"VDEV_MGR_AP_KEEPALIVE_IDLE",
"VDEV_MGR_AP_KEEPALIVE_INACTIVE",
"VDEV_MGR_AP_KEEPALIVE_UNRESPONSIVE",
"VDEV_MGR_AP_TBTT_CONFIG",
"VDEV_MGR_FIRST_BCN_RECEIVED",
"VDEV_MGR_VDEV_START",
"VDEV_MGR_VDEV_UP",
"VDEV_MGR_PEER_AUTHORIZED",
"VDEV_MGR_OCS_HP_LP_REQ_POSTED",
"VDEV_MGR_VDEV_START_OCS_HP_REQ_COMPLETE",
"VDEV_MGR_VDEV_START_OCS_HP_REQ_STOP",
"VDEV_MGR_HP_START_TIME",
"VDEV_MGR_VDEV_PAUSE_DELAY_UPDATE",
"VDEV_MGR_VDEV_PAUSE_FAIL",
"VDEV_MGR_GEN_PERIODIC_NOA",
"VDEV_MGR_OFF_CHAN_GO_CH_REQ_SETUP",
"VDEV_MGR_DEFINITION_END",
},
{
"SCAN_START_COMMAND_FAILED", /* scan */
"SCAN_STOP_COMMAND_FAILED",
"SCAN_EVENT_SEND_FAILED",
"SCAN_ENGINE_START",
"SCAN_ENGINE_CANCEL_COMMAND",
"SCAN_ENGINE_STOP_DUE_TO_TIMEOUT",
"SCAN_EVENT_SEND_TO_HOST",
"SCAN_FWLOG_EVENT_ADD",
"SCAN_FWLOG_EVENT_REM",
"SCAN_FWLOG_EVENT_PREEMPTED",
"SCAN_FWLOG_EVENT_RESTARTED",
"SCAN_FWLOG_EVENT_COMPLETED",
},
{
"RATECTRL_DBGID_DEFINITION_START", /* Rate ctrl*/
"RATECTRL_DBGID_ASSOC",
"RATECTRL_DBGID_NSS_CHANGE",
"RATECTRL_DBGID_CHAINMASK_ERR",
"RATECTRL_DBGID_UNEXPECTED_FRAME",
"RATECTRL_DBGID_WAL_RCQUERY",
"RATECTRL_DBGID_WAL_RCUPDATE",
"RATECTRL_DBGID_GTX_UPDATE",
"RATECTRL_DBGID_DEFINITION_END"
},
{
"AP_PS_DBGID_DEFINITION_START",
"AP_PS_DBGID_UPDATE_TIM",
"AP_PS_DBGID_PEER_STATE_CHANGE",
"AP_PS_DBGID_PSPOLL",
"AP_PS_DBGID_PEER_CREATE",
"AP_PS_DBGID_PEER_DELETE",
"AP_PS_DBGID_VDEV_CREATE",
"AP_PS_DBGID_VDEV_DELETE",
"AP_PS_DBGID_SYNC_TIM",
"AP_PS_DBGID_NEXT_RESPONSE",
"AP_PS_DBGID_START_SP",
"AP_PS_DBGID_COMPLETED_EOSP",
"AP_PS_DBGID_TRIGGER",
"AP_PS_DBGID_DUPLICATE_TRIGGER",
"AP_PS_DBGID_UAPSD_RESPONSE",
"AP_PS_DBGID_SEND_COMPLETE",
"AP_PS_DBGID_SEND_N_COMPLETE",
"AP_PS_DBGID_DETECT_OUT_OF_SYNC_STA",
"AP_PS_DBGID_DELIVER_CAB",
},
{
"" /* Block Ack */
},
/* Mgmt TxRx */
{
"MGMT_TXRX_DBGID_DEFINITION_START",
"MGMT_TXRX_FORWARD_TO_HOST",
"MGMT_TXRX_DBGID_DEFINITION_END",
},
{ /* Data TxRx */
"DATA_TXRX_DBGID_DEFINITION_START",
"DATA_TXRX_DBGID_RX_DATA_SEQ_LEN_INFO",
"DATA_TXRX_DBGID_DEFINITION_END",
},
{ "" /* HTT */
},
{ "" /* HOST */
},
{ "" /* BEACON */
"BEACON_EVENT_SWBA_SEND_FAILED",
"BEACON_EVENT_EARLY_RX_BMISS_STATUS",
"BEACON_EVENT_EARLY_RX_SLEEP_SLOP",
"BEACON_EVENT_EARLY_RX_CONT_BMISS_TIMEOUT",
"BEACON_EVENT_EARLY_RX_PAUSE_SKIP_BCN_NUM",
"BEACON_EVENT_EARLY_RX_CLK_DRIFT",
"BEACON_EVENT_EARLY_RX_AP_DRIFT",
"BEACON_EVENT_EARLY_RX_BCN_TYPE",
},
{ /* Offload Mgr */
"OFFLOAD_MGR_DBGID_DEFINITION_START",
"OFFLOADMGR_REGISTER_OFFLOAD",
"OFFLOADMGR_DEREGISTER_OFFLOAD",
"OFFLOADMGR_NO_REG_DATA_HANDLERS",
"OFFLOADMGR_NO_REG_EVENT_HANDLERS",
"OFFLOADMGR_REG_OFFLOAD_FAILED",
"OFFLOADMGR_DBGID_DEFINITION_END",
},
{
"WAL_DBGID_DEFINITION_START",
"WAL_DBGID_FAST_WAKE_REQUEST",
"WAL_DBGID_FAST_WAKE_RELEASE",
"WAL_DBGID_SET_POWER_STATE",
"WAL_DBGID_MISSING",
"WAL_DBGID_CHANNEL_CHANGE_FORCE_RESET",
"WAL_DBGID_CHANNEL_CHANGE",
"WAL_DBGID_VDEV_START",
"WAL_DBGID_VDEV_STOP",
"WAL_DBGID_VDEV_UP",
"WAL_DBGID_VDEV_DOWN",
"WAL_DBGID_SW_WDOG_RESET",
"WAL_DBGID_TX_SCH_REGISTER_TIDQ",
"WAL_DBGID_TX_SCH_UNREGISTER_TIDQ",
"WAL_DBGID_TX_SCH_TICKLE_TIDQ",
"WAL_DBGID_XCESS_FAILURES",
"WAL_DBGID_AST_ADD_WDS_ENTRY",
"WAL_DBGID_AST_DEL_WDS_ENTRY",
"WAL_DBGID_AST_WDS_ENTRY_PEER_CHG",
"WAL_DBGID_AST_WDS_SRC_LEARN_FAIL",
"WAL_DBGID_STA_KICKOUT",
"WAL_DBGID_BAR_TX_FAIL",
"WAL_DBGID_BAR_ALLOC_FAIL",
"WAL_DBGID_LOCAL_DATA_TX_FAIL",
"WAL_DBGID_SECURITY_PM4_QUEUED",
"WAL_DBGID_SECURITY_GM1_QUEUED",
"WAL_DBGID_SECURITY_PM4_SENT",
"WAL_DBGID_SECURITY_ALLOW_DATA",
"WAL_DBGID_SECURITY_UCAST_KEY_SET",
"WAL_DBGID_SECURITY_MCAST_KEY_SET",
"WAL_DBGID_SECURITY_ENCR_EN",
"WAL_DBGID_BB_WDOG_TRIGGERED",
"WAL_DBGID_RX_LOCAL_BUFS_LWM",
"WAL_DBGID_RX_LOCAL_DROP_LARGE_MGMT",
"WAL_DBGID_VHT_ILLEGAL_RATE_PHY_ERR_DETECTED",
"WAL_DBGID_DEV_RESET",
"WAL_DBGID_TX_BA_SETUP",
"WAL_DBGID_RX_BA_SETUP",
"WAL_DBGID_DEV_TX_TIMEOUT",
"WAL_DBGID_DEV_RX_TIMEOUT",
"WAL_DBGID_STA_VDEV_XRETRY",
"WAL_DBGID_DCS",
"WAL_DBGID_MGMT_TX_FAIL",
"WAL_DBGID_SET_M4_SENT_MANUALLY",
"WAL_DBGID_PROCESS_4_WAY_HANDSHAKE",
"WAL_DBGID_WAL_CHANNEL_CHANGE_START",
"WAL_DBGID_WAL_CHANNEL_CHANGE_COMPLETE",
"WAL_DBGID_WHAL_CHANNEL_CHANGE_START",
"WAL_DBGID_WHAL_CHANNEL_CHANGE_COMPLETE",
"WAL_DBGID_TX_MGMT_DESCID_SEQ_TYPE_LEN",
"WAL_DBGID_TX_DATA_MSDUID_SEQ_TYPE_LEN",
"WAL_DBGID_TX_DISCARD",
"WAL_DBGID_TX_MGMT_COMP_DESCID_STATUS",
"WAL_DBGID_TX_DATA_COMP_MSDUID_STATUS",
"WAL_DBGID_RESET_PCU_CYCLE_CNT",
"WAL_DBGID_SETUP_RSSI_INTERRUPTS",
"WAL_DBGID_BRSSI_CONFIG",
"WAL_DBGID_CURRENT_BRSSI_AVE",
"WAL_DBGID_BCN_TX_COMP",
"WAL_DBGID_SET_HW_CHAINMASK",
"WAL_DBGID_SET_HW_CHAINMASK_TXRX_STOP_FAIL",
"WAL_DBGID_GET_HW_CHAINMASK",
"WAL_DBGID_SMPS_DISABLE",
"WAL_DBGID_SMPS_ENABLE_HW_CNTRL",
"WAL_DBGID_SMPS_SWSEL_CHAINMASK",
"WAL_DBGID_DEFINITION_END",
},
{
"" /* DE */
},
{
"" /* pcie lp */
},
{
/* RTT */
"RTT_CALL_FLOW",
"RTT_REQ_SUB_TYPE",
"RTT_MEAS_REQ_HEAD",
"RTT_MEAS_REQ_BODY",
"",
"",
"RTT_INIT_GLOBAL_STATE",
"",
"RTT_REPORT",
"",
"RTT_ERROR_REPORT",
"RTT_TIMER_STOP",
"RTT_SEND_TM_FRAME",
"RTT_V3_RESP_CNT",
"RTT_V3_RESP_FINISH",
"RTT_CHANNEL_SWITCH_REQ",
"RTT_CHANNEL_SWITCH_GRANT",
"RTT_CHANNEL_SWITCH_COMPLETE",
"RTT_CHANNEL_SWITCH_PREEMPT",
"RTT_CHANNEL_SWITCH_STOP",
"RTT_TIMER_START",
},
{ /* RESOURCE */
"RESOURCE_DBGID_DEFINITION_START",
"RESOURCE_PEER_ALLOC",
"RESOURCE_PEER_FREE",
"RESOURCE_PEER_ALLOC_WAL_PEER",
"RESOURCE_PEER_NBRHOOD_MGMT_ALLOC",
"RESOURCE_PEER_NBRHOOD_MGMT_INFO,"
"RESOURCE_DBGID_DEFINITION_END",
},
{ /* DCS */
"WLAN_DCS_DBGID_INIT",
"WLAN_DCS_DBGID_WMI_CWINT",
"WLAN_DCS_DBGID_TIMER",
"WLAN_DCS_DBGID_CMDG",
"WLAN_DCS_DBGID_CMDS",
"WLAN_DCS_DBGID_DINIT"
},
{ /* CACHEMGR */
""
},
{ /* ANI */
"ANI_DBGID_POLL",
"ANI_DBGID_CONTROL",
"ANI_DBGID_OFDM_PARAMS",
"ANI_DBGID_CCK_PARAMS",
"ANI_DBGID_RESET",
"ANI_DBGID_RESTART",
"ANI_DBGID_OFDM_LEVEL",
"ANI_DBGID_CCK_LEVEL",
"ANI_DBGID_FIRSTEP",
"ANI_DBGID_CYCPWR",
"ANI_DBGID_MRC_CCK",
"ANI_DBGID_SELF_CORR_LOW",
"ANI_DBGID_ENABLE",
"ANI_DBGID_CURRENT_LEVEL",
"ANI_DBGID_POLL_PERIOD",
"ANI_DBGID_LISTEN_PERIOD",
"ANI_DBGID_OFDM_LEVEL_CFG",
"ANI_DBGID_CCK_LEVEL_CFG"
},
{
"P2P_DBGID_DEFINITION_START",
"P2P_DEV_REGISTER",
"P2P_HANDLE_NOA",
"P2P_UPDATE_SCHEDULE_OPPS",
"P2P_UPDATE_SCHEDULE",
"P2P_UPDATE_START_TIME",
"P2P_UPDATE_START_TIME_DIFF_TSF32",
"P2P_UPDATE_START_TIME_FINAL",
"P2P_SETUP_SCHEDULE_TIMER",
"P2P_PROCESS_SCHEDULE_AFTER_CALC",
"P2P_PROCESS_SCHEDULE_STARTED_TIMER",
"P2P_CALC_SCHEDULES_FIRST_CALL_ALL_NEXT_EVENT",
"P2P_CALC_SCHEDULES_FIRST_VALUE",
"P2P_CALC_SCHEDULES_EARLIEST_NEXT_EVENT",
"P2P_CALC_SCHEDULES_SANITY_COUNT",
"P2P_CALC_SCHEDULES_CALL_ALL_NEXT_EVENT_FROM_WHILE_LOOP",
"P2P_CALC_SCHEDULES_TIMEOUT_1",
"P2P_CALC_SCHEDULES_TIMEOUT_2",
"P2P_FIND_ALL_NEXT_EVENTS_REQ_EXPIRED",
"P2P_FIND_ALL_NEXT_EVENTS_REQ_ACTIVE",
"P2P_FIND_NEXT_EVENT_REQ_NOT_STARTED",
"P2P_FIND_NEXT_EVENT_REQ_COMPLETE_NON_PERIODIC",
"P2P_FIND_NEXT_EVENT_IN_MID_OF_NOA",
"P2P_FIND_NEXT_EVENT_REQ_COMPLETE",
"P2P_SCHEDULE_TIMEOUT",
"P2P_CALC_SCHEDULES_ENTER",
"P2P_PROCESS_SCHEDULE_ENTER",
"P2P_FIND_ALL_NEXT_EVENTS_INDIVIDUAL_REQ_AFTER_CHANGE",
"P2P_FIND_ALL_NEXT_EVENTS_INDIVIDUAL_REQ_BEFORE_CHANGE",
"P2P_FIND_ALL_NEXT_EVENTS_ENTER",
"P2P_FIND_NEXT_EVENT_ENTER",
"P2P_NOA_GO_PRESENT",
"P2P_NOA_GO_ABSENT",
"P2P_GO_NOA_NOTIF",
"P2P_GO_TBTT_OFFSET",
"P2P_GO_GET_NOA_INFO",
"P2P_GO_ADD_ONE_SHOT_NOA",
"P2P_GO_GET_NOA_IE",
"P2P_GO_BCN_TX_COMP",
"P2P_DBGID_DEFINITION_END",
},
{
"CSA_DBGID_DEFINITION_START",
"CSA_OFFLOAD_POOL_INIT",
"CSA_OFFLOAD_REGISTER_VDEV",
"CSA_OFFLOAD_DEREGISTER_VDEV",
"CSA_DEREGISTER_VDEV_ERROR",
"CSA_OFFLOAD_BEACON_RECEIVED",
"CSA_OFFLOAD_BEACON_CSA_RECV",
"CSA_OFFLOAD_CSA_RECV_ERROR_IE",
"CSA_OFFLOAD_CSA_TIMER_ERROR",
"CSA_OFFLOAD_CSA_TIMER_EXP",
"CSA_OFFLOAD_WMI_EVENT_ERROR",
"CSA_OFFLOAD_WMI_EVENT_SENT",
"CSA_OFFLOAD_WMI_CHANSWITCH_RECV",
"CSA_DBGID_DEFINITION_END",
},
{ /* NLO offload */
""
},
{
"WLAN_CHATTER_DBGID_DEFINITION_START",
"WLAN_CHATTER_ENTER",
"WLAN_CHATTER_EXIT",
"WLAN_CHATTER_FILTER_HIT",
"WLAN_CHATTER_FILTER_MISS",
"WLAN_CHATTER_FILTER_FULL",
"WLAN_CHATTER_FILTER_TM_ADJ",
"WLAN_CHATTER_BUFFER_FULL",
"WLAN_CHATTER_TIMEOUT",
"WLAN_CHATTER_DBGID_DEFINITION_END",
},
{
"WOW_DBGID_DEFINITION_START",
"WOW_ENABLE_CMDID",
"WOW_RECV_DATA_PKT",
"WOW_WAKE_HOST_DATA",
"WOW_RECV_MGMT",
"WOW_WAKE_HOST_MGMT",
"WOW_RECV_EVENT",
"WOW_WAKE_HOST_EVENT",
"WOW_INIT",
"WOW_RECV_MAGIC_PKT",
"WOW_RECV_BITMAP_PATTERN",
"WOW_AP_VDEV_DISALLOW",
"WOW_STA_VDEV_DISALLOW",
"WOW_P2PGO_VDEV_DISALLOW",
"WOW_NS_OFLD_ENABLE",
"WOW_ARP_OFLD_ENABLE",
"WOW_NS_ARP_OFLD_DISABLE",
"WOW_NS_RECEIVED",
"WOW_NS_REPLIED",
"WOW_ARP_RECEIVED",
"WOW_ARP_REPLIED",
"WOW_DBGID_DEFINITION_END",
},
{ /* WAL VDEV */
""
},
{ /* WAL PDEV */
""
},
{ /* TEST */
"TP_CHANGE_CHANNEL",
"TP_LOCAL_SEND",
},
{ /* STA SMPS */
"STA_SMPS_DBGID_DEFINITION_START",
"STA_SMPS_DBGID_CREATE_PDEV_INSTANCE",
"STA_SMPS_DBGID_CREATE_VIRTUAL_CHAN_INSTANCE",
"STA_SMPS_DBGID_DELETE_VIRTUAL_CHAN_INSTANCE",
"STA_SMPS_DBGID_CREATE_STA_INSTANCE",
"STA_SMPS_DBGID_DELETE_STA_INSTANCE",
"STA_SMPS_DBGID_VIRTUAL_CHAN_SMPS_START",
"STA_SMPS_DBGID_VIRTUAL_CHAN_SMPS_STOP",
"STA_SMPS_DBGID_SEND_SMPS_ACTION_FRAME",
"STA_SMPS_DBGID_HOST_FORCED_MODE",
"STA_SMPS_DBGID_FW_FORCED_MODE",
"STA_SMPS_DBGID_RSSI_THRESHOLD_CROSSED",
"STA_SMPS_DBGID_SMPS_ACTION_FRAME_COMPLETION",
"STA_SMPS_DBGID_DTIM_EBT_EVENT_CHMASK_UPDATE",
"STA_SMPS_DBGID_DTIM_CHMASK_UPDATE",
"STA_SMPS_DBGID_DTIM_BEACON_EVENT_CHMASK_UPDATE",
"STA_SMPS_DBGID_DTIM_POWER_STATE_CHANGE",
"STA_SMPS_DBGID_DTIM_CHMASK_UPDATE_SLEEP",
"STA_SMPS_DBGID_DTIM_CHMASK_UPDATE_AWAKE",
"SMPS_DBGID_DEFINITION_END",
},
{ /* SWBMISS */
"SWBMISS_DBGID_DEFINITION_START",
"SWBMISS_ENABLED",
"SWBMISS_DISABLED",
"SWBMISS_DBGID_DEFINITION_END",
},
{ /* WMMAC */
""
},
{ /* TDLS */
"TDLS_DBGID_DEFINITION_START",
"TDLS_DBGID_VDEV_CREATE",
"TDLS_DBGID_VDEV_DELETE",
"TDLS_DBGID_ENABLED_PASSIVE",
"TDLS_DBGID_ENABLED_ACTIVE",
"TDLS_DBGID_DISABLED",
"TDLS_DBGID_CONNTRACK_TIMER",
"TDLS_DBGID_WAL_SET",
"TDLS_DBGID_WAL_GET",
"TDLS_DBGID_WAL_PEER_UPDATE_SET",
"TDLS_DBGID_WAL_PEER_UPDATE_EVT",
"TDLS_DBGID_WAL_VDEV_CREATE",
"TDLS_DBGID_WAL_VDEV_DELETE",
"TDLS_DBGID_WLAN_EVENT",
"TDLS_DBGID_WLAN_PEER_UPDATE_SET",
"TDLS_DBGID_PEER_EVT_DRP_THRESH",
"TDLS_DBGID_PEER_EVT_DRP_RATE",
"TDLS_DBGID_PEER_EVT_DRP_RSSI",
"TDLS_DBGID_PEER_EVT_DISCOVER",
"TDLS_DBGID_PEER_EVT_DELETE",
"TDLS_DBGID_PEER_CAP_UPDATE",
"TDLS_DBGID_UAPSD_SEND_PTI_FRAME",
"TDLS_DBGID_UAPSD_SEND_PTI_FRAME2PEER",
"TDLS_DBGID_UAPSD_START_PTR_TIMER",
"TDLS_DBGID_UAPSD_CANCEL_PTR_TIMER",
"TDLS_DBGID_UAPSD_PTR_TIMER_TIMEOUT",
"TDLS_DBGID_UAPSD_STA_PS_EVENT_HANDLER",
"TDLS_DBGID_UAPSD_PEER_EVENT_HANDLER",
"TDLS_DBGID_UAPSD_PS_DEFAULT_SETTINGS",
"TDLS_DBGID_UAPSD_GENERIC",
},
{ /* HB */
"WLAN_HB_DBGID_DEFINITION_START",
"WLAN_HB_DBGID_INIT",
"WLAN_HB_DBGID_TCP_GET_TXBUF_FAIL",
"WLAN_HB_DBGID_TCP_SEND_FAIL",
"WLAN_HB_DBGID_BSS_PEER_NULL",
"WLAN_HB_DBGID_UDP_GET_TXBUF_FAIL",
"WLAN_HB_DBGID_UDP_SEND_FAIL",
"WLAN_HB_DBGID_WMI_CMD_INVALID_PARAM",
"WLAN_HB_DBGID_WMI_CMD_INVALID_OP",
"WLAN_HB_DBGID_WOW_NOT_ENTERED",
"WLAN_HB_DBGID_ALLOC_SESS_FAIL",
"WLAN_HB_DBGID_CTX_NULL",
"WLAN_HB_DBGID_CHKSUM_ERR",
"WLAN_HB_DBGID_UDP_TX",
"WLAN_HB_DBGID_TCP_TX",
"WLAN_HB_DBGID_DEFINITION_END",
},
{ /* TXBF */
"TXBFEE_DBGID_START",
"TXBFEE_DBGID_NDPA_RECEIVED",
"TXBFEE_DBGID_HOST_CONFIG_TXBFEE_TYPE",
"TXBFER_DBGID_SEND_NDPA",
"TXBFER_DBGID_GET_NDPA_BUF_FAIL",
"TXBFER_DBGID_SEND_NDPA_FAIL",
"TXBFER_DBGID_GET_NDP_BUF_FAIL",
"TXBFER_DBGID_SEND_NDP_FAIL",
"TXBFER_DBGID_GET_BRPOLL_BUF_FAIL",
"TXBFER_DBGID_SEND_BRPOLL_FAIL",
"TXBFER_DBGID_HOST_CONFIG_CMDID",
"TXBFEE_DBGID_HOST_CONFIG_CMDID",
"TXBFEE_DBGID_ENABLED_ENABLED_UPLOAD_H",
"TXBFEE_DBGID_UPLOADH_CV_TAG",
"TXBFEE_DBGID_UPLOADH_H_TAG",
"TXBFEE_DBGID_CAPTUREH_RECEIVED",
"TXBFEE_DBGID_PACKET_IS_STEERED",
"TXBFEE_UPLOADH_EVENT_ALLOC_MEM_FAIL",
"TXBFEE_DBGID_END",
},
{ /*BATCH SCAN*/
},
{ /*THERMAL MGR*/
"THERMAL_MGR_DBGID_DEFINITION_START",
"THERMAL_MGR_NEW_THRESH",
"THERMAL_MGR_THRESH_CROSSED",
"THERMAL_MGR_DBGID_DEFINITION END",
},
{ /* WLAN_MODULE_PHYERR_DFS */
""
},
{
/* WLAN_MODULE_RMC */
"RMC_DBGID_DEFINITION_START",
"RMC_CREATE_INSTANCE",
"RMC_DELETE_INSTANCE",
"RMC_LDR_SEL",
"RMC_NO_LDR",
"RMC_LDR_NOT_SEL",
"RMC_LDR_INF_SENT",
"RMC_PEER_ADD",
"RMC_PEER_DELETE",
"RMC_PEER_UNKNOWN",
"RMC_SET_MODE",
"RMC_SET_ACTION_PERIOD",
"RMC_ACRION_FRAME_RX",
"RMC_DBGID_DEFINITION_END",
},
{
/* WLAN_MODULE_STATS */
"WLAN_STATS_DBGID_DEFINITION_START",
"WLAN_STATS_DBGID_EST_LINKSPEED_VDEV_EN_DIS",
"WLAN_STATS_DBGID_EST_LINKSPEED_CHAN_TIME_START",
"WLAN_STATS_DBGID_EST_LINKSPEED_CHAN_TIME_END",
"WLAN_STATS_DBGID_EST_LINKSPEED_CALC",
"WLAN_STATS_DBGID_EST_LINKSPEED_UPDATE_HOME_CHAN",
"WLAN_STATS_DBGID_DEFINITION_END",
},
{
/* WLAN_MODULE_NAN */
},
{
/* WLAN_MODULE_IBSS_PWRSAVE */
"IBSS_PS_DBGID_DEFINITION_START",
"IBSS_PS_DBGID_PEER_CREATE",
"IBSS_PS_DBGID_PEER_DELETE",
"IBSS_PS_DBGID_VDEV_CREATE",
"IBSS_PS_DBGID_VDEV_DELETE",
"IBSS_PS_DBGID_VDEV_EVENT",
"IBSS_PS_DBGID_PEER_EVENT",
"IBSS_PS_DBGID_DELIVER_CAB",
"IBSS_PS_DBGID_DELIVER_UC_DATA",
"IBSS_PS_DBGID_DELIVER_UC_DATA_ERROR",
"IBSS_PS_DBGID_UC_INACTIVITY_TMR_RESTART",
"IBSS_PS_DBGID_MC_INACTIVITY_TMR_RESTART",
"IBSS_PS_DBGID_NULL_TX_COMPLETION",
"IBSS_PS_DBGID_ATIM_TIMER_START",
"IBSS_PS_DBGID_UC_ATIM_SEND",
"IBSS_PS_DBGID_BC_ATIM_SEND",
"IBSS_PS_DBGID_UC_TIMEOUT",
"IBSS_PS_DBGID_PWR_COLLAPSE_ALLOWED",
"IBSS_PS_DBGID_PWR_COLLAPSE_NOT_ALLOWED",
"IBSS_PS_DBGID_SET_PARAM",
"IBSS_PS_DBGID_HOST_TX_PAUSE",
"IBSS_PS_DBGID_HOST_TX_UNPAUSE",
"IBSS_PS_DBGID_PS_DESC_BIN_HWM",
"IBSS_PS_DBGID_PS_DESC_BIN_LWM",
"IBSS_PS_DBGID_PS_KICKOUT_PEER",
"IBSS_PS_DBGID_SET_PEER_PARAM",
"IBSS_PS_DBGID_BCN_ATIM_WIN_MISMATCH",
"IBSS_PS_DBGID_RX_CHAINMASK_CHANGE",
},
{
/* HIF UART Interface DBGIDs */
"HIF_UART_DBGID_START",
"HIF_UART_DBGID_POWER_STATE",
"HIF_UART_DBGID_TXRX_FLOW",
"HIF_UART_DBGID_TXRX_CTRL_CHAR",
"HIF_UART_DBGID_TXRX_BUF_DUMP",
},
{
/* LPI */
""
},
{
/* EXTSCAN DBGIDs */
"EXTSCAN_START",
"EXTSCAN_STOP",
"EXTSCAN_CLEAR_ENTRY_CONTENT",
"EXTSCAN_GET_FREE_ENTRY_SUCCESS",
"EXTSCAN_GET_FREE_ENTRY_INCONSISTENT",
"EXTSCAN_GET_FREE_ENTRY_NO_MORE_ENTRIES",
"EXTSCAN_CREATE_ENTRY_SUCCESS",
"EXTSCAN_CREATE_ENTRY_ERROR",
"EXTSCAN_SEARCH_SCAN_ENTRY_QUEUE",
"EXTSCAN_SEARCH_SCAN_ENTRY_KEY_FOUND",
"EXTSCAN_SEARCH_SCAN_ENTRY_KEY_NOT_FOUND",
"EXTSCAN_ADD_ENTRY",
"EXTSCAN_BUCKET_SEND_OPERATION_EVENT",
"EXTSCAN_BUCKET_SEND_OPERATION_EVENT_FAILED",
"EXTSCAN_BUCKET_START_SCAN_CYCLE",
"EXTSCAN_BUCKET_PERIODIC_TIMER",
"EXTSCAN_SEND_START_STOP_EVENT",
"EXTSCAN_NOTIFY_WLAN_CHANGE",
"EXTSCAN_NOTIFY_WLAN_HOTLIST_MATCH",
"EXTSCAN_MAIN_RECEIVED_FRAME",
"EXTSCAN_MAIN_NO_SSID_IE",
"EXTSCAN_MAIN_MALFORMED_FRAME",
"EXTSCAN_FIND_BSSID_BY_REFERENCE",
"EXTSCAN_FIND_BSSID_BY_REFERENCE_ERROR",
"EXTSCAN_NOTIFY_TABLE_USAGE",
"EXTSCAN_FOUND_RSSI_ENTRY",
"EXTSCAN_BSSID_FOUND_RSSI_SAMPLE",
"EXTSCAN_BSSID_ADDED_RSSI_SAMPLE",
"EXTSCAN_BSSID_REPLACED_RSSI_SAMPLE",
"EXTSCAN_BSSID_TRANSFER_CURRENT_SAMPLES",
"EXTSCAN_BUCKET_PROCESS_SCAN_EVENT",
"EXTSCAN_BUCKET_CANNOT_FIND_BUCKET",
"EXTSCAN_START_SCAN_REQUEST_FAILED",
"EXTSCAN_BUCKET_STOP_CURRENT_SCANS",
"EXTSCAN_BUCKET_SCAN_STOP_REQUEST",
"EXTSCAN_BUCKET_PERIODIC_TIMER_ERROR",
"EXTSCAN_BUCKET_START_OPERATION",
"EXTSCAN_START_INTERNAL_ERROR",
"EXTSCAN_NOTIFY_HOTLIST_MATCH",
"EXTSCAN_CONFIG_HOTLIST_TABLE",
"EXTSCAN_CONFIG_WLAN_CHANGE_TABLE",
},
{ /* UNIT_TEST */
"UNIT_TEST_GEN",
},
{ /* MLME */
"MLME_DEBUG_CMN",
"MLME_IF",
"MLME_AUTH",
"MLME_REASSOC",
"MLME_DEAUTH",
"MLME_DISASSOC",
"MLME_ROAM",
"MLME_RETRY",
"MLME_TIMER",
"MLME_FRMPARSE",
},
{ /*SUPPLICANT */
"SUPPL_INIT",
"SUPPL_RECV_EAPOL",
"SUPPL_RECV_EAPOL_TIMEOUT",
"SUPPL_SEND_EAPOL",
"SUPPL_MIC_MISMATCH",
"SUPPL_FINISH",
},
};
int dbglog_module_log_enable(wmi_unified_t wmi_handle, A_UINT32 mod_id,
bool isenable)
{
A_UINT32 val = 0;
if (mod_id > WLAN_MODULE_ID_MAX) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("dbglog_module_log_enable: Invalid module id %d\n",
mod_id));
return -EINVAL;
}
WMI_DBGLOG_SET_MODULE_ID(val,mod_id);
if (isenable) {
/* set it to global module level */
WMI_DBGLOG_SET_LOG_LEVEL(val,DBGLOG_INFO);
} else {
/* set it to ERROR level */
WMI_DBGLOG_SET_LOG_LEVEL(val,DBGLOG_ERR);
}
wmi_config_debug_module_cmd(wmi_handle, WMI_DEBUG_LOG_PARAM_LOG_LEVEL, val, NULL,0);
return 0;
}
int dbglog_vap_log_enable(wmi_unified_t wmi_handle, A_UINT16 vap_id,
bool isenable)
{
if (vap_id > DBGLOG_MAX_VDEVID) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("dbglog_vap_log_enable:Invalid vap_id %d\n",
vap_id));
return -EINVAL;
}
wmi_config_debug_module_cmd(wmi_handle,
isenable ? WMI_DEBUG_LOG_PARAM_VDEV_ENABLE:WMI_DEBUG_LOG_PARAM_VDEV_DISABLE, vap_id, NULL,0 );
return 0;
}
int dbglog_set_log_lvl(wmi_unified_t wmi_handle, DBGLOG_LOG_LVL log_lvl)
{
A_UINT32 val = 0;
if (log_lvl > DBGLOG_LVL_MAX) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("dbglog_set_log_lvl:Invalid log level %d\n",
log_lvl));
return -EINVAL;
}
WMI_DBGLOG_SET_MODULE_ID(val,WMI_DEBUG_LOG_MODULE_ALL);
WMI_DBGLOG_SET_LOG_LEVEL(val,log_lvl);
wmi_config_debug_module_cmd(wmi_handle, WMI_DEBUG_LOG_PARAM_LOG_LEVEL, val, NULL,0);
return 0;
}
int dbglog_set_mod_log_lvl(wmi_unified_t wmi_handle, A_UINT32 mod_log_lvl)
{
A_UINT32 val = 0;
/* set the global module level to log_lvl */
WMI_DBGLOG_SET_MODULE_ID(val,(mod_log_lvl/10));
WMI_DBGLOG_SET_LOG_LEVEL(val,(mod_log_lvl%10));
wmi_config_debug_module_cmd(wmi_handle, WMI_DEBUG_LOG_PARAM_LOG_LEVEL, val, NULL,0);
return 0;
}
A_STATUS
wmi_config_debug_module_cmd(wmi_unified_t wmi_handle, A_UINT32 param, A_UINT32 val,
A_UINT32 *module_id_bitmap, A_UINT32 bitmap_len)
{
wmi_buf_t buf;
wmi_debug_log_config_cmd_fixed_param *configmsg;
A_STATUS status = A_OK;
int i;
int len;
int8_t *buf_ptr;
int32_t *module_id_bitmap_array; /* Used to fomr the second tlv*/
ASSERT(bitmap_len < MAX_MODULE_ID_BITMAP_WORDS);
/* Allocate size for 2 tlvs - including tlv hdr space for second tlv*/
len = sizeof(wmi_debug_log_config_cmd_fixed_param) + WMI_TLV_HDR_SIZE +
(sizeof(int32_t) * MAX_MODULE_ID_BITMAP_WORDS);
buf = wmi_buf_alloc(wmi_handle, len);
if (buf == NULL)
return A_NO_MEMORY;
configmsg = (wmi_debug_log_config_cmd_fixed_param *)(wmi_buf_data(buf));
buf_ptr = (int8_t *)configmsg;
WMITLV_SET_HDR(&configmsg->tlv_header,
WMITLV_TAG_STRUC_wmi_debug_log_config_cmd_fixed_param,
WMITLV_GET_STRUCT_TLVLEN(wmi_debug_log_config_cmd_fixed_param));
configmsg->dbg_log_param = param;
configmsg->value = val;
/* Filling in the data part of second tlv -- should follow first tlv _ WMI_TLV_HDR_SIZE*/
module_id_bitmap_array = (A_UINT32*)(buf_ptr +
sizeof(wmi_debug_log_config_cmd_fixed_param) +
WMI_TLV_HDR_SIZE);
WMITLV_SET_HDR(buf_ptr + sizeof(wmi_debug_log_config_cmd_fixed_param),
WMITLV_TAG_ARRAY_UINT32,
sizeof(A_UINT32) * MAX_MODULE_ID_BITMAP_WORDS);
if (module_id_bitmap) {
for(i=0;i<bitmap_len;++i) {
module_id_bitmap_array[i] = module_id_bitmap[i];
}
}
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("wmi_dbg_cfg_send: param 0x%x val 0x%x \n ", param, val));
status = wmi_unified_cmd_send(wmi_handle, buf,
len, WMI_DBGLOG_CFG_CMDID);
if (status != A_OK)
adf_nbuf_free(buf);
return status;
}
void
dbglog_set_vap_enable_bitmap(wmi_unified_t wmi_handle, A_UINT32 vap_enable_bitmap)
{
wmi_config_debug_module_cmd(wmi_handle,
WMI_DEBUG_LOG_PARAM_VDEV_ENABLE_BITMAP,
vap_enable_bitmap, NULL,0 );
}
void
dbglog_set_mod_enable_bitmap(wmi_unified_t wmi_handle,A_UINT32 log_level, A_UINT32 *mod_enable_bitmap, A_UINT32 bitmap_len )
{
wmi_config_debug_module_cmd(wmi_handle,
WMI_DEBUG_LOG_PARAM_MOD_ENABLE_BITMAP,
log_level,
mod_enable_bitmap,bitmap_len);
}
int dbglog_report_enable(wmi_unified_t wmi_handle, bool isenable)
{
int bitmap[2] = {0};
if (isenable > TRUE) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("dbglog_report_enable:Invalid value %d\n",
isenable));
return -EINVAL;
}
if(isenable){
/* set the vap enable bitmap */
dbglog_set_vap_enable_bitmap(wmi_handle, 0xFFFF);
bitmap[0] = 0xFFFFFFFF;
bitmap[1] = 0x1F;
/* set the module level bitmap */
dbglog_set_mod_enable_bitmap(wmi_handle, 0x0, bitmap, 2);
} else {
dbglog_set_vap_enable_bitmap(wmi_handle, bitmap[0]);
dbglog_set_mod_enable_bitmap(wmi_handle, DBGLOG_LVL_MAX, bitmap, 2);
}
return 0;
}
static char *
dbglog_get_msg(A_UINT32 moduleid, A_UINT32 debugid)
{
static char unknown_str[64];
if (moduleid < WLAN_MODULE_ID_MAX && debugid < MAX_DBG_MSGS) {
char *str = DBG_MSG_ARR[moduleid][debugid];
if (str && str[0] != '\0') {
return str;
}
}
snprintf(unknown_str, sizeof(unknown_str),
"UNKNOWN %u:%u",
moduleid, debugid);
return unknown_str;
}
void
dbglog_printf(
A_UINT32 timestamp,
A_UINT16 vap_id,
const char *fmt, ...)
{
char buf[128];
va_list ap;
if (vap_id < DBGLOG_MAX_VDEVID) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (DBGLOG_PRINT_PREFIX "[%u] vap-%u ", timestamp, vap_id));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (DBGLOG_PRINT_PREFIX "[%u] ", timestamp));
}
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("%s\n", buf));
}
void
dbglog_printf_no_line_break(
A_UINT32 timestamp,
A_UINT16 vap_id,
const char *fmt, ...)
{
char buf[128];
va_list ap;
if (vap_id < DBGLOG_MAX_VDEVID) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (DBGLOG_PRINT_PREFIX "[%u] vap-%u ", timestamp, vap_id));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (DBGLOG_PRINT_PREFIX "[%u] ", timestamp));
}
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("%s", buf));
}
#define USE_NUMERIC 0
A_BOOL
dbglog_default_print_handler(A_UINT32 mod_id, A_UINT16 vap_id, A_UINT32 dbg_id,
A_UINT32 timestamp, A_UINT16 numargs, A_UINT32 *args)
{
int i;
if (vap_id < DBGLOG_MAX_VDEVID) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (DBGLOG_PRINT_PREFIX "[%u] vap-%u %s ( ", timestamp, vap_id, dbglog_get_msg(mod_id, dbg_id)));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (DBGLOG_PRINT_PREFIX "[%u] %s ( ", timestamp, dbglog_get_msg(mod_id, dbg_id)));
}
for (i = 0; i < numargs; i++) {
#if USE_NUMERIC
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("%u", args[i]));
#else
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("%#x", args[i]));
#endif
if ((i + 1) < numargs) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (", "));
}
}
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (" )\n"));
return TRUE;
}
#define DBGLOG_PARSE_ARGS_STRING_LENGTH (DBGLOG_NUM_ARGS_MAX * 11 + 10)
static int
dbglog_print_raw_data(A_UINT32 *buffer, A_UINT32 length)
{
A_UINT32 timestamp;
A_UINT32 debugid;
A_UINT32 moduleid;
A_UINT16 numargs, curArgs;
A_UINT32 count = 0, totalWriteLen, writeLen;
char parseArgsString[DBGLOG_PARSE_ARGS_STRING_LENGTH];
char *dbgidString;
while (count < length) {
debugid = DBGLOG_GET_DBGID(buffer[count + 1]);
moduleid = DBGLOG_GET_MODULEID(buffer[count + 1]);
numargs = DBGLOG_GET_NUMARGS(buffer[count + 1]);
timestamp = DBGLOG_GET_TIME_STAMP(buffer[count]);
if (moduleid < WLAN_MODULE_ID_MAX && debugid < MAX_DBG_MSGS && numargs <= DBGLOG_NUM_ARGS_MAX) {
OS_MEMZERO(parseArgsString, sizeof(parseArgsString));
totalWriteLen = 0;
for (curArgs = 0; curArgs < numargs; curArgs++){
// Using sprintf_s instead of sprintf, to avoid length overflow
writeLen = snprintf(parseArgsString + totalWriteLen, DBGLOG_PARSE_ARGS_STRING_LENGTH - totalWriteLen, "%x ", buffer[count + 2 + curArgs]);
totalWriteLen += writeLen;
}
if (debugid < MAX_DBG_MSGS){
dbgidString = DBG_MSG_ARR[moduleid][debugid];
if (dbgidString != NULL) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("fw:%s(%x %x):%s\n",
dbgidString,
timestamp, buffer[count+1],
parseArgsString));
} else {
/* host need sync with FW id */
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("fw:%s:m:%x,id:%x(%x %x):%s\n",
"UNKNOWN", moduleid, debugid,
timestamp, buffer[count+1],
parseArgsString));
}
} else if (debugid == DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG) {
/* specific debugid */
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("fw:%s:m:%x,id:%x(%x %x):%s\n",
"DBGLOG_SM_MSG", moduleid, debugid,
timestamp, buffer[count+1],
parseArgsString));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("fw:%s:m:%x,id:%x(%x %x):%s\n",
"UNKNOWN", moduleid, debugid,
timestamp, buffer[count+1],
parseArgsString));
}
}
count += numargs + 2; /* 32 bit Time stamp + 32 bit Dbg header*/
}
return 0;
}
#ifdef WLAN_OPEN_SOURCE
static int
dbglog_debugfs_raw_data(wmi_unified_t wmi_handle, const u_int8_t *buf, A_UINT32 length, A_UINT32 dropped)
{
struct fwdebug *fwlog = (struct fwdebug *)&wmi_handle->dbglog;
struct dbglog_slot *slot;
struct sk_buff *skb;
size_t slot_len;
if (WARN_ON(length > ATH6KL_FWLOG_PAYLOAD_SIZE))
return -ENODEV;
slot_len = sizeof(*slot) + ATH6KL_FWLOG_PAYLOAD_SIZE;
skb = alloc_skb(slot_len, GFP_KERNEL);
if (!skb)
return -ENOMEM;
slot = (struct dbglog_slot *) skb_put(skb, slot_len);
slot->diag_type = (A_UINT32)DIAG_TYPE_FW_DEBUG_MSG;
slot->timestamp = cpu_to_le32(jiffies);
slot->length = cpu_to_le32(length);
slot->dropped = cpu_to_le32(dropped);
memcpy(slot->payload, buf, length);
/* Need to pad each record to fixed length ATH6KL_FWLOG_PAYLOAD_SIZE */
memset(slot->payload + length, 0, ATH6KL_FWLOG_PAYLOAD_SIZE - length);
spin_lock(&fwlog->fwlog_queue.lock);
__skb_queue_tail(&fwlog->fwlog_queue, skb);
complete(&fwlog->fwlog_completion);
/* drop oldest entries */
while (skb_queue_len(&fwlog->fwlog_queue) >
ATH6KL_FWLOG_MAX_ENTRIES) {
skb = __skb_dequeue(&fwlog->fwlog_queue);
kfree_skb(skb);
}
spin_unlock(&fwlog->fwlog_queue.lock);
return TRUE;
}
#endif /* WLAN_OPEN_SOURCE */
/*
* Package the data from the fw diag WMI event handler.
* Pass this data to cnss-diag service
*/
int
send_fw_diag_nl_data(wmi_unified_t wmi_handle, const u_int8_t *buffer,
A_UINT32 len, A_UINT32 event_type)
{
struct sk_buff *skb_out;
struct nlmsghdr *nlh;
int res = 0;
if (WARN_ON(len > ATH6KL_FWLOG_PAYLOAD_SIZE))
return -ENODEV;
if (cnss_diag_pid != INVALID_PID)
{
skb_out = nlmsg_new(len, 0);
if (!skb_out)
{
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Failed to allocate new skb\n"));
return -1;
}
nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, len, 0);
memcpy(nlmsg_data(nlh), buffer, len);
NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
res = nl_srv_ucast(skb_out, cnss_diag_pid, MSG_DONTWAIT);
if (res < 0)
{
AR_DEBUG_PRINTF(ATH_DEBUG_RSVD1,
("nl_srv_ucast failed 0x%x \n", res));
cnss_diag_pid = INVALID_PID;
return res;
}
}
return res;
}
static int
send_diag_netlink_data(const u_int8_t *buffer,
A_UINT32 len, A_UINT32 cmd)
{
struct sk_buff *skb_out;
struct nlmsghdr *nlh;
int res = 0;
struct dbglog_slot *slot;
size_t slot_len;
if (WARN_ON(len > ATH6KL_FWLOG_PAYLOAD_SIZE))
return -ENODEV;
if (cnss_diag_pid != INVALID_PID) {
slot_len = sizeof(*slot) + ATH6KL_FWLOG_PAYLOAD_SIZE;
skb_out = nlmsg_new(slot_len, 0);
if (!skb_out) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,
("Failed to allocate new skb\n"));
return -1;
}
nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, slot_len, 0);
slot = (struct dbglog_slot *) nlmsg_data(nlh);
slot->diag_type = cmd;
slot->timestamp = cpu_to_le32(jiffies);
slot->length = cpu_to_le32(len);
/* Version mapped to get_version here */
slot->dropped = get_version;
memcpy(slot->payload, buffer, len);
NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
res = nl_srv_ucast(skb_out, cnss_diag_pid, MSG_DONTWAIT);
if (res < 0) {
AR_DEBUG_PRINTF(ATH_DEBUG_RSVD1,
("nl_srv_ucast failed 0x%x \n", res));
cnss_diag_pid = INVALID_PID;
return res;
}
}
return res;
}
int
dbglog_process_netlink_data(wmi_unified_t wmi_handle, const u_int8_t *buffer,
A_UINT32 len, A_UINT32 dropped)
{
struct sk_buff *skb_out;
struct nlmsghdr *nlh;
int res = 0;
struct dbglog_slot *slot;
size_t slot_len;
if (WARN_ON(len > ATH6KL_FWLOG_PAYLOAD_SIZE))
return -ENODEV;
if (cnss_diag_pid != INVALID_PID)
{
slot_len = sizeof(*slot) + ATH6KL_FWLOG_PAYLOAD_SIZE;
skb_out = nlmsg_new(slot_len, 0);
if (!skb_out)
{
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Failed to allocate new skb\n"));
return -1;
}
nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, slot_len, 0);
slot = (struct dbglog_slot *) nlmsg_data(nlh);
slot->diag_type = (A_UINT32)DIAG_TYPE_FW_DEBUG_MSG;
slot->timestamp = cpu_to_le32(jiffies);
slot->length = cpu_to_le32(len);
slot->dropped = cpu_to_le32(dropped);
memcpy(slot->payload, buffer, len);
NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
res = nl_srv_ucast(skb_out, cnss_diag_pid, MSG_DONTWAIT);
if (res < 0)
{
AR_DEBUG_PRINTF(ATH_DEBUG_RSVD1,
("nl_srv_ucast failed 0x%x \n", res));
cnss_diag_pid = INVALID_PID;
return res;
}
}
return res;
}
/*
* WMI diag data event handler, this function invoked as a CB
* when there DIAG_EVENT, DIAG_MSG, DIAG_DBG to be
* forwarded from the FW. This is the new implementation for
* replacement of fw_dbg and dbg messages
*/
static int
diag_fw_handler(ol_scn_t scn, u_int8_t *data, u_int32_t datalen)
{
tp_wma_handle wma = (tp_wma_handle)scn;
wmitlv_cmd_param_info *param_buf;
u_int8_t *datap;
u_int32_t len = 0;
u_int32_t *buffer;
if (!wma) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("NULL Pointer assigned\n"));
return -1;
}
/* when fw asser occurs,host can't use TLV format. */
if (wma->is_fw_assert) {
datap = data;
len = datalen;
wma->is_fw_assert = 0;
} else {
param_buf = (wmitlv_cmd_param_info *) data;
if (!param_buf) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,
("Get NULL point message from FW\n"));
return -1;
}
param_buf = (wmitlv_cmd_param_info *) data;
datap = param_buf->tlv_ptr;
len = param_buf->num_elements;
if (!get_version) {
buffer = (u_int32_t *)datap ;
buffer++; /* skip offset */
if (WLAN_DIAG_TYPE_CONFIG == DIAG_GET_TYPE(*buffer)) {
buffer++; /* skip */
if (DIAG_VERSION_INFO == DIAG_GET_ID(*buffer)) {
buffer++; /* skip */
/* get payload */
get_version = *buffer;
}
}
}
}
if (dbglog_process_type == DBGLOG_PROCESS_PRINT_RAW) {
if (!gprint_limiter) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("NOT Supported"
" only supports net link socket\n"));
gprint_limiter = TRUE;
}
return 0;
}
if ( (dbglog_process_type == DBGLOG_PROCESS_NET_RAW) &&
(cnss_diag_pid != 0)) {
return send_diag_netlink_data((A_UINT8 *)datap,
len, DIAG_TYPE_FW_MSG);
}
#ifdef WLAN_OPEN_SOURCE
if (dbglog_process_type == DBGLOG_PROCESS_POOL_RAW) {
if (!gprint_limiter) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("NOT Supported"
" only supports net link socket\n"));
gprint_limiter = TRUE;
}
return 0;
}
#endif /* WLAN_OPEN_SOURCE */
if (!gprint_limiter) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("NOT Supported"
" only supports net link socket\n"));
gprint_limiter = TRUE;
}
/* Always returns zero */
return (0);
}
/*
* WMI diag data event handler, this function invoked as a CB
* when there DIAG_DATA to be forwarded from the FW.
*/
int
fw_diag_data_event_handler(ol_scn_t scn, u_int8_t *data, u_int32_t datalen)
{
tp_wma_handle wma = (tp_wma_handle)scn;
struct wlan_diag_data *diag_data;
WMI_DIAG_DATA_CONTAINER_EVENTID_param_tlvs *param_buf;
wmi_diag_data_container_event_fixed_param *fixed_param;
u_int8_t *datap;
u_int32_t num_data=0; /* Total events */
u_int32_t diag_data_len=0; /* each fw diag payload */
u_int32_t diag_type=0;
u_int32_t i=0;
u_int32_t nl_data_len=0; /* diag hdr + payload */
param_buf = (WMI_DIAG_DATA_CONTAINER_EVENTID_param_tlvs *) data;
if (!param_buf) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Got NULL point message from FW\n"));
return -1;
}
if (!wma) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("NULL Pointer assigned\n"));
return -1;
}
fixed_param = param_buf->fixed_param;
num_data = param_buf->num_bufp;
datap = (u_int8_t *)param_buf->bufp;
/* If cnss-diag service started triggered during the init of services */
if (appstarted) {
for (i = 0; i < num_data; i++) {
diag_data = (struct wlan_diag_data *)datap;
diag_type = WLAN_DIAG_0_TYPE_GET(diag_data->word0);
diag_data_len = WLAN_DIAG_0_LEN_GET(diag_data->word0);
/* Length of diag struct and len of payload */
nl_data_len = sizeof(struct wlan_diag_data) + diag_data_len;
#if 0
print_hex_dump_bytes("payload: ", DUMP_PREFIX_ADDRESS,
diag_data->payload, diag_data_len);
#endif
switch (diag_type) {
case DIAG_TYPE_FW_EVENT:
return send_fw_diag_nl_data((wmi_unified_t)wma->wmi_handle,
datap, nl_data_len, diag_type);
break;
case DIAG_TYPE_FW_LOG:
return send_fw_diag_nl_data((wmi_unified_t)wma->wmi_handle,
datap, nl_data_len, diag_type);
break;
}
/* Move to the next event and send to cnss-diag */
datap += nl_data_len;
}
}
return 0;
}
int
dbglog_parse_debug_logs(ol_scn_t scn, u_int8_t *data, u_int32_t datalen)
{
tp_wma_handle wma = (tp_wma_handle)scn;
A_UINT32 count;
A_UINT32 *buffer;
A_UINT32 timestamp;
A_UINT32 debugid;
A_UINT32 moduleid;
A_UINT16 vapid;
A_UINT16 numargs;
adf_os_size_t length;
A_UINT32 dropped;
WMI_DEBUG_MESG_EVENTID_param_tlvs *param_buf;
u_int8_t *datap;
u_int32_t len;
if (!wma) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("NULL Pointer assigned\n"));
return -1;
}
/*when fw asser occurs,host can't use TLV format.*/
if (wma->is_fw_assert) {
datap = data;
len = datalen;
wma->is_fw_assert = 0;
} else {
param_buf = (WMI_DEBUG_MESG_EVENTID_param_tlvs *) data;
if (!param_buf) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Get NULL point message from FW\n"));
return -1;
}
datap = param_buf->bufp;
len = param_buf->num_bufp;
}
dropped = *((A_UINT32 *)datap);
if (dropped > 0) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("%d log buffers are dropped \n", dropped));
}
datap += sizeof(dropped);
len -= sizeof(dropped);
count = 0;
buffer = (A_UINT32 *)datap;
length = (len >> 2);
if ( dbglog_process_type == DBGLOG_PROCESS_PRINT_RAW) {
return dbglog_print_raw_data(buffer, length);
}
if ( dbglog_process_type == DBGLOG_PROCESS_NET_RAW) {
if(appstarted){
return dbglog_process_netlink_data((wmi_unified_t)wma->wmi_handle,
(A_UINT8 *)buffer,
len, dropped);
} else {
return 0;
}
}
#ifdef WLAN_OPEN_SOURCE
if (dbglog_process_type == DBGLOG_PROCESS_POOL_RAW) {
return dbglog_debugfs_raw_data((wmi_unified_t)wma->wmi_handle,
(A_UINT8 *)buffer, len, dropped);
}
#endif /* WLAN_OPEN_SOURCE */
while ((count + 2) < length) {
timestamp = DBGLOG_GET_TIME_STAMP(buffer[count]);
debugid = DBGLOG_GET_DBGID(buffer[count + 1]);
moduleid = DBGLOG_GET_MODULEID(buffer[count + 1]);
vapid = DBGLOG_GET_VDEVID(buffer[count + 1]);
numargs = DBGLOG_GET_NUMARGS(buffer[count + 1]);
if ((count + 2 + numargs) > length)
return 0;
if (moduleid >= WLAN_MODULE_ID_MAX)
return 0;
if (mod_print[moduleid] == NULL) {
/* No module specific log registered use the default handler*/
dbglog_default_print_handler(moduleid, vapid, debugid, timestamp,
numargs,
(((A_UINT32 *)buffer) + 2 + count));
} else {
if(!(mod_print[moduleid](moduleid, vapid, debugid, timestamp,
numargs,
(((A_UINT32 *)buffer) + 2 + count)))) {
/* The message is not handled by the module specific handler*/
dbglog_default_print_handler(moduleid, vapid, debugid, timestamp,
numargs,
(((A_UINT32 *)buffer) + 2 + count));
}
}
count += numargs + 2; /* 32 bit Time stamp + 32 bit Dbg header*/
}
/* Always returns zero */
return (0);
}
void
dbglog_reg_modprint(A_UINT32 mod_id, module_dbg_print printfn)
{
if (!mod_print[mod_id]) {
mod_print[mod_id] = printfn;
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("module print is already registered for this module %d\n",
mod_id));
}
}
void
dbglog_sm_print(
A_UINT32 timestamp,
A_UINT16 vap_id,
A_UINT16 numargs,
A_UINT32 *args,
const char *module_prefix,
const char *states[], A_UINT32 num_states,
const char *events[], A_UINT32 num_events)
{
A_UINT8 type, arg1, arg2, arg3;
A_UINT32 extra, extra2, extra3;
if (numargs != 4) {
return;
}
type = (args[0] >> 24) & 0xff;
arg1 = (args[0] >> 16) & 0xff;
arg2 = (args[0] >> 8) & 0xff;
arg3 = (args[0] >> 0) & 0xff;
extra = args[1];
extra2 = args[2];
extra3 = args[3];
switch (type) {
case 0: /* state transition */
if (arg1 < num_states && arg2 < num_states) {
dbglog_printf(timestamp, vap_id, "%s: %s => %s (%#x, %#x, %#x)",
module_prefix, states[arg1], states[arg2], extra, extra2, extra3);
} else {
dbglog_printf(timestamp, vap_id, "%s: %u => %u (%#x, %#x, %#x)",
module_prefix, arg1, arg2, extra, extra2, extra3);
}
break;
case 1: /* dispatch event */
if (arg1 < num_states && arg2 < num_events) {
dbglog_printf(timestamp, vap_id, "%s: %s < %s (%#x, %#x, %#x)",
module_prefix, states[arg1], events[arg2], extra, extra2, extra3);
} else {
dbglog_printf(timestamp, vap_id, "%s: %u < %u (%#x, %#x, %#x)",
module_prefix, arg1, arg2, extra, extra2, extra3);
}
break;
case 2: /* warning */
switch (arg1) {
case 0: /* unhandled event */
if (arg2 < num_states && arg3 < num_events) {
dbglog_printf(timestamp, vap_id, "%s: unhandled event %s in state %s (%#x, %#x, %#x)",
module_prefix, events[arg3], states[arg2], extra, extra2, extra3);
} else {
dbglog_printf(timestamp, vap_id, "%s: unhandled event %u in state %u (%#x, %#x, %#x)",
module_prefix, arg3, arg2, extra, extra2, extra3);
}
break;
default:
break;
}
break;
}
}
A_BOOL
dbglog_sta_powersave_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"IDLE",
"ACTIVE",
"SLEEP_TXQ_FLUSH",
"SLEEP_TX_SENT",
"PAUSE",
"SLEEP_DOZE",
"SLEEP_AWAKE",
"ACTIVE_TXQ_FLUSH",
"ACTIVE_TX_SENT",
"PAUSE_TXQ_FLUSH",
"PAUSE_TX_SENT",
"IDLE_TXQ_FLUSH",
"IDLE_TX_SENT",
};
static const char *events[] = {
"START",
"STOP",
"PAUSE",
"UNPAUSE",
"TIM",
"DTIM",
"SEND_COMPLETE",
"PRE_SEND",
"RX",
"HWQ_EMPTY",
"PAUSE_TIMEOUT",
"TXRX_INACTIVITY_TIMEOUT",
"PSPOLL_TIMEOUT",
"UAPSD_TIMEOUT",
"DELAYED_SLEEP_TIMEOUT",
"SEND_N_COMPLETE",
"TIDQ_PAUSE_COMPLETE",
"SEND_PSPOLL",
"SEND_SPEC_PSPOLL",
};
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "STA PS",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
case PS_STA_PM_ARB_REQUEST:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id, "PM ARB request flags=%x, last_time=%x %s: %s",
args[1], args[2], dbglog_get_module_str(args[0]), args[3] ? "SLEEP" : "WAKE");
}
break;
case PS_STA_DELIVER_EVENT:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id, "STA PS: %s %s",
(args[0] == 0 ? "PAUSE_COMPLETE" :
(args[0] == 1 ? "UNPAUSE_COMPLETE" :
(args[0] == 2 ? "SLEEP" :
(args[0] == 3 ? "AWAKE" : "UNKNOWN")))),
(args[1] == 0 ? "SUCCESS" :
(args[1] == 1 ? "TXQ_FLUSH_TIMEOUT" :
(args[1] == 2 ? "NO_ACK" :
(args[1] == 3 ? "RX_LEAK_TIMEOUT" :
(args[1] == 4 ? "PSPOLL_UAPSD_BUSY_TIMEOUT" : "UNKNOWN"))))));
}
break;
case PS_STA_PSPOLL_SEQ_DONE:
if (numargs == 5) {
dbglog_printf(timestamp, vap_id, "STA PS poll: queue=%u comp=%u rsp=%u rsp_dur=%u fc=%x qos=%x %s",
args[0], args[1], args[2], args[3],
(args[4] >> 16) & 0xffff,
(args[4] >> 8) & 0xff,
(args[4] & 0xff) == 0 ? "SUCCESS" :
(args[4] & 0xff) == 1 ? "NO_ACK" :
(args[4] & 0xff) == 2 ? "DROPPED" :
(args[4] & 0xff) == 3 ? "FILTERED" :
(args[4] & 0xff) == 4 ? "RSP_TIMEOUT" : "UNKNOWN");
}
break;
case PS_STA_COEX_MODE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id, "STA PS COEX MODE %s",
args[0] ? "ENABLED" : "DISABLED");
}
break;
case PS_STA_PSPOLL_ALLOW:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id, "STA PS-Poll %s flags=%x time=%u",
args[0] ? "ALLOW" : "DISALLOW", args[1], args[2]);
}
break;
case PS_STA_SET_PARAM:
if (numargs == 2) {
struct {
char *name;
int is_time_param;
} params[] = {
{ "MAX_SLEEP_ATTEMPTS", 0 },
{ "DELAYED_SLEEP", 1 },
{ "TXRX_INACTIVITY", 1 },
{ "MAX_TX_BEFORE_WAKE", 0 },
{ "UAPSD_TIMEOUT", 1 },
{ "UAPSD_CONFIG", 0 },
{ "PSPOLL_RESPONSE_TIMEOUT", 1 },
{ "MAX_PSPOLL_BEFORE_WAKE", 0 },
{ "RX_WAKE_POLICY", 0 },
{ "DELAYED_PAUSE_RX_LEAK", 1 },
{ "TXRX_INACTIVITY_BLOCKED_RETRY", 1 },
{ "SPEC_WAKE_INTERVAL", 1 },
{ "MAX_SPEC_NODATA_PSPOLL", 0 },
{ "ESTIMATED_PSPOLL_RESP_TIME", 1 },
{ "QPOWER_MAX_PSPOLL_BEFORE_WAKE", 0 },
{ "QPOWER_ENABLE", 0 },
};
A_UINT32 param = args[0];
A_UINT32 value = args[1];
if (param < ARRAY_LENGTH(params)) {
if (params[param].is_time_param) {
dbglog_printf(timestamp, vap_id, "STA PS SET_PARAM %s => %u (us)",
params[param].name, value);
} else {
dbglog_printf(timestamp, vap_id, "STA PS SET_PARAM %s => %#x",
params[param].name, value);
}
} else {
dbglog_printf(timestamp, vap_id, "STA PS SET_PARAM %x => %#x",
param, value);
}
}
break;
case PS_STA_SPECPOLL_TIMER_STARTED:
dbglog_printf(timestamp, vap_id, "SPEC Poll Timer Started: Beacon time Remaining:%d wakeup interval:%d", args[0], args[1]);
break;
case PS_STA_SPECPOLL_TIMER_STOPPED:
dbglog_printf(timestamp, vap_id,
"SPEC Poll Timer Stopped");
break;
default:
return FALSE;
}
return TRUE;
}
/* IBSS PS sub modules */
enum wlan_ibss_ps_sub_module {
WLAN_IBSS_PS_SUB_MODULE_IBSS_NW_SM = 0,
WLAN_IBSS_PS_SUB_MODULE_IBSS_SELF_PS = 1,
WLAN_IBSS_PS_SUB_MODULE_IBSS_PEER_PS = 2,
WLAN_IBSS_PS_SUB_MODULE_MAX = 3,
};
#define WLAN_IBSS_PS_SUB_MODULE_OFFSET 0x1E
A_BOOL
dbglog_ibss_powersave_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *nw_states[] = {
"WAIT_FOR_TBTT",
"ATIM_WINDOW_PRE_BCN",
"ATIM_WINDOW_POST_BCN",
"OUT_OF_ATIM_WINDOW",
"PAUSE_PENDING",
"PAUSED",
};
static const char *ps_states[] = {
"ACTIVE",
"SLEEP_TX_SEND",
"SLEEP_DOZE_PAUSE_PENDING",
"SLEEP_DOZE",
"SLEEP_AWAKE",
"ACTIVE_TX_SEND",
"PAUSE_TX_SEND",
"PAUSED",
};
static const char *peer_ps_states[] = {
"ACTIVE",
"SLEEP_AWAKE",
"SLEEP_DOZE",
"PS_UNKNOWN",
};
static const char *events[] = {
"START",
"STOP",
"SWBA",
"TBTT",
"TX_BCN_CMP",
"SEND_COMPLETE",
"SEND_N_COMPLETE",
"PRE_SEND",
"RX",
"UC_INACTIVITY_TIMEOUT",
"BC_INACTIVITY_TIMEOUT",
"ATIM_WINDOW_BEGIN",
"ATIM_WINDOW_END",
"HWQ_EMPTY",
"UC_ATIM_RCVD",
"TRAFFIC_EXCHANGE_DONE",
"POWER_SAVE_STATE_CHANGE",
"NEW_PEER_JOIN",
"IBSS_VDEV_PAUSE_REQUEST",
"IBSS_VDEV_PAUSE_RESPONSE",
"IBSS_VDEV_PAUSE_TIMEOUT",
"IBSS_VDEV_UNPAUSE_REQUEST",
"PS_STATE_CHANGE",
};
enum wlan_ibss_ps_sub_module sub_module;
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
sub_module = (args[1] >> WLAN_IBSS_PS_SUB_MODULE_OFFSET) & 0x3;
switch(sub_module)
{
case WLAN_IBSS_PS_SUB_MODULE_IBSS_NW_SM:
dbglog_sm_print(timestamp, vap_id, numargs, args, "IBSS PS NW",
nw_states, ARRAY_LENGTH(nw_states), events,
ARRAY_LENGTH(events));
break;
case WLAN_IBSS_PS_SUB_MODULE_IBSS_SELF_PS:
dbglog_sm_print(timestamp, vap_id, numargs, args,
"IBSS PS Self", ps_states, ARRAY_LENGTH(ps_states),
events, ARRAY_LENGTH(events));
break;
case WLAN_IBSS_PS_SUB_MODULE_IBSS_PEER_PS:
dbglog_sm_print(timestamp, vap_id, numargs, args,
"IBSS PS Peer", peer_ps_states,
ARRAY_LENGTH(peer_ps_states), events,
ARRAY_LENGTH(events));
break;
default:
break;
}
break;
case IBSS_PS_DBGID_PEER_CREATE:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: peer alloc failed for peer ID:%u", args[0]);
} else if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: create peer ID=%u", args[0]);
}
break;
case IBSS_PS_DBGID_PEER_DELETE:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: delete peer ID=%u num_peers:%d num_sleeping_peers:%d ps_enabled_for_this_peer:%d",
args[0], args[1], args[2], args[3]);
}
break;
case IBSS_PS_DBGID_VDEV_CREATE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: vdev alloc failed",
args[0]);
} else if (numargs == 0) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: vdev created");
}
break;
case IBSS_PS_DBGID_VDEV_DELETE:
dbglog_printf(timestamp, vap_id, "IBSS PS: vdev deleted");
break;
case IBSS_PS_DBGID_VDEV_EVENT:
if (numargs == 1) {
if (args[0] == 5) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: vdev event for peer add");
} else if (args[0] == 7) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: vdev event for peer delete");
}
else {
dbglog_printf(timestamp, vap_id,
"IBSS PS: vdev event %u", args[0]);
}
}
break;
case IBSS_PS_DBGID_PEER_EVENT:
if (numargs == 4) {
if (args[0] == 0xFFFF) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: pre_send for peer:%u peer_type:%u sm_event_mask:%0x",
args[1], args[3], args[2]);
} else if (args[0] == 0x20000) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: send_complete for peer:%u peer_type:%u sm_event_mask:%0x",
args[1], args[3], args[2]);
} else if (args[0] == 0x10) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: send_n_complete for peer:%u peer_type:%u sm_event_mask:%0x",
args[1], args[3], args[2]);
} else if (args[0] == 0x40) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: rx event for peer:%u peer_type:%u sm_event_mask:%0x",
args[1], args[3], args[2]);
} else if (args[0] == 0x4) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: hw_q_empty for peer:%u peer_type:%u sm_event_mask:%0x",
args[1], args[3], args[2]);
}
}
break;
case IBSS_PS_DBGID_DELIVER_CAB:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Deliver CAB n_mpdu:%d send_flags:%0x tid_cur:%d q_depth_for_other_tid:%d",
args[0], args[1], args[2], args[3]);
}
break;
case IBSS_PS_DBGID_DELIVER_UC_DATA:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Deliver UC data peer:%d tid:%d n_mpdu:%d send_flags:%0x",
args[0], args[1], args[2], args[3]);
}
break;
case IBSS_PS_DBGID_DELIVER_UC_DATA_ERROR:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Deliver UC data error peer:%d tid:%d allowed_tidmask:%0x, pending_tidmap:%0x",
args[0], args[1], args[2], args[3]);
}
break;
case IBSS_PS_DBGID_UC_INACTIVITY_TMR_RESTART:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: UC timer restart peer:%d timer_val:%0x",
args[0], args[1]);
}
break;
case IBSS_PS_DBGID_MC_INACTIVITY_TMR_RESTART:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: MC timer restart timer_val:%0x",
args[0]);
}
break;
case IBSS_PS_DBGID_NULL_TX_COMPLETION:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: null tx completion peer:%d tx_completion_status:%d flags:%0x",
args[0], args[1], args[2]);
}
break;
case IBSS_PS_DBGID_ATIM_TIMER_START:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: ATIM timer start tsf:%0x %0x tbtt:%0x %0x",
args[0], args[1], args[2], args[3]);
}
break;
case IBSS_PS_DBGID_UC_ATIM_SEND:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Send ATIM to peer:%d",
args[1]);
} else if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: no peers to send UC ATIM",
args[1]);
}
break;
case IBSS_PS_DBGID_BC_ATIM_SEND:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: MC Data, num_of_peers:%d bc_atim_sent:%d",
args[1], args[0]);
}
break;
case IBSS_PS_DBGID_UC_TIMEOUT:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: UC timeout for peer:%d send_null:%d",
args[0], args[1]);
}
break;
case IBSS_PS_DBGID_PWR_COLLAPSE_ALLOWED:
dbglog_printf(timestamp, vap_id, "IBSS PS: allow power collapse");
break;
case IBSS_PS_DBGID_PWR_COLLAPSE_NOT_ALLOWED:
if (numargs == 0) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: power collapse not allowed by INI");
} else if(numargs == 1) {
dbglog_printf(timestamp, vap_id, "IBSS PS: power collapse not allowed since peer id:%d is not PS capable",
args[0]);
} else if(numargs == 2) {
dbglog_printf(timestamp, vap_id, "IBSS PS: power collapse not allowed - no peers in NW");
} else if (numargs == 3) {
if (args[0] == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: power collapse not allowed, non-zero qdepth %d %d",
args[1], args[2]);
} else if (args[0] == 3) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: power collapse not allowed by peer:%d peer_flags:%0x",
args[1], args[2]);
}
} else if (numargs == 5) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: power collapse not allowed by state m/c nw_cur_state:%d nw_next_state:%d ps_cur_state:%d flags:%0x",
args[1], args[2], args[3], args[4]);
}
break;
case IBSS_PS_DBGID_SET_PARAM:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Set Param ID:%0x Value:%0x",
args[0], args[1]);
}
break;
case IBSS_PS_DBGID_HOST_TX_PAUSE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Pausing host, vdev_map:%0x",
args[0]);
}
break;
case IBSS_PS_DBGID_HOST_TX_UNPAUSE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Unpausing host, vdev_map:%0x",
args[0]);
}
break;
case IBSS_PS_DBGID_PS_DESC_BIN_LWM:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: LWM, vdev_map:%0x",
args[0]);
}
break;
case IBSS_PS_DBGID_PS_DESC_BIN_HWM:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: HWM, vdev_map:%0x",
args[0]);
}
break;
case IBSS_PS_DBGID_PS_KICKOUT_PEER:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"IBSS PS: Kickout peer id:%d atim_fail_cnt:%d status:%d",
args[0], args[1], args[2]);
}
break;
case IBSS_PS_DBGID_SET_PEER_PARAM:
if(numargs == 3) {
dbglog_printf(timestamp, vap_id, "IBSS PS: Set Peer Id:%d Param ID:%0x Value:%0x",
args[0], args[1], args[2]);
}
break;
case IBSS_PS_DBGID_BCN_ATIM_WIN_MISMATCH:
if(numargs == 4) {
if(args[0] == 0xDEAD) {
dbglog_printf(timestamp, vap_id, "IBSS PS: ATIM window length mismatch, our's:%d, peer id:%d, peer's:%d",
args[1], args[2], args[3]);
} else if(args[0] == 0xBEEF) {
dbglog_printf(timestamp, vap_id, "IBSS PS: Peer ATIM window length changed, peer id:%d, peer recorded atim window:%d new atim window:%d",
args[1], args[2], args[3]);
}
}
break;
case IBSS_PS_DBGID_RX_CHAINMASK_CHANGE:
if(numargs == 2) {
if(args[1] == 0x1) {
dbglog_printf(timestamp, vap_id, "IBSS PS: Voting for low power chainmask from :%d", args[0]);
} else {
dbglog_printf(timestamp, vap_id, "IBSS PS: Voting for high power chainmask from :%d", args[0]);
}
}
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL dbglog_ratectrl_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
switch (dbg_id) {
case RATECTRL_DBGID_ASSOC:
dbglog_printf(timestamp, vap_id, "RATE: ChainMask %d, phymode %d, ni_flags 0x%08x, vht_mcs_set 0x%04x, ht_mcs_set 0x%04x",
args[0], args[1], args[2], args[3], args[4]);
break;
case RATECTRL_DBGID_NSS_CHANGE:
dbglog_printf(timestamp, vap_id, "RATE: NEW NSS %d\n", args[0]);
break;
case RATECTRL_DBGID_CHAINMASK_ERR:
dbglog_printf(timestamp, vap_id, "RATE: Chainmask ERR %d %d %d\n",
args[0], args[1], args[2]);
break;
case RATECTRL_DBGID_UNEXPECTED_FRAME:
dbglog_printf(timestamp, vap_id, "RATE: WARN1: rate %d flags 0x%08x\n", args[0], args[1]);
break;
case RATECTRL_DBGID_WAL_RCQUERY:
dbglog_printf(timestamp, vap_id, "ratectrl_dbgid_wal_rcquery [rix1 %d rix2 %d rix3 %d proberix %d ppduflag 0x%x] ",
args[0], args[1], args[2], args[3], args[4]);
break;
case RATECTRL_DBGID_WAL_RCUPDATE:
dbglog_printf(timestamp, vap_id, "ratectrl_dbgid_wal_rcupdate [numelems %d ppduflag 0x%x] ",
args[0], args[1]);
break;
case RATECTRL_DBGID_GTX_UPDATE:
{
switch (args[0]) {
case 255:
dbglog_printf(timestamp, vap_id, "GtxInitPwrCfg [bw[last %d|cur %d] rtcode 0x%x tpc %d tpc_init_pwr_cfg %d] ",
args[1] >> 8, args[1] & 0xff, args[2], args[3], args[4]);
break;
case 254:
dbglog_printf(timestamp, vap_id, "gtx_cfg_addr [RTMask0@0x%x PERThreshold@0x%x gtxTPCMin@0x%x userGtxMask@0x%x] ",
args[1], args[2], args[3], args[4]);
break;
default:
dbglog_printf(timestamp, vap_id, "gtx_update [act %d bw %d rix 0x%x tpc %d per %d lastrssi %d] ",
args[0], args[1], args[2], args[3], args[4], args[5]);
}
}
break;
}
return TRUE;
}
A_BOOL dbglog_ani_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
switch (dbg_id) {
case ANI_DBGID_ENABLE:
dbglog_printf(timestamp, vap_id,
"ANI Enable: %d", args[0]);
break;
case ANI_DBGID_POLL:
dbglog_printf(timestamp, vap_id,
"ANI POLLING: AccumListenTime %d ListenTime %d ofdmphyerr %d cckphyerr %d",
args[0], args[1], args[2],args[3]);
break;
case ANI_DBGID_RESTART:
dbglog_printf(timestamp, vap_id,"ANI Restart");
break;
case ANI_DBGID_CURRENT_LEVEL:
dbglog_printf(timestamp, vap_id,
"ANI CURRENT LEVEL ofdm level %d cck level %d",args[0],args[1]);
break;
case ANI_DBGID_OFDM_LEVEL:
dbglog_printf(timestamp, vap_id,
"ANI UPDATE ofdm level %d firstep %d firstep_low %d cycpwr_thr %d self_corr_low %d",
args[0], args[1],args[2],args[3],args[4]);
break;
case ANI_DBGID_CCK_LEVEL:
dbglog_printf(timestamp, vap_id,
"ANI UPDATE cck level %d firstep %d firstep_low %d mrc_cck %d",
args[0],args[1],args[2],args[3]);
break;
case ANI_DBGID_CONTROL:
dbglog_printf(timestamp, vap_id,
"ANI CONTROL ofdmlevel %d ccklevel %d\n",
args[0]);
break;
case ANI_DBGID_OFDM_PARAMS:
dbglog_printf(timestamp, vap_id,
"ANI ofdm_control firstep %d cycpwr %d\n",
args[0],args[1]);
break;
case ANI_DBGID_CCK_PARAMS:
dbglog_printf(timestamp, vap_id,
"ANI cck_control mrc_cck %d barker_threshold %d\n",
args[0],args[1]);
break;
case ANI_DBGID_RESET:
dbglog_printf(timestamp, vap_id,
"ANI resetting resetflag %d resetCause %8x channel index %d",
args[0],args[1],args[2]);
break;
case ANI_DBGID_SELF_CORR_LOW:
dbglog_printf(timestamp, vap_id,"ANI self_corr_low %d",args[0]);
break;
case ANI_DBGID_FIRSTEP:
dbglog_printf(timestamp, vap_id,"ANI firstep %d firstep_low %d",
args[0],args[1]);
break;
case ANI_DBGID_MRC_CCK:
dbglog_printf(timestamp, vap_id,"ANI mrc_cck %d",args[0]);
break;
case ANI_DBGID_CYCPWR:
dbglog_printf(timestamp, vap_id,"ANI cypwr_thresh %d",args[0]);
break;
case ANI_DBGID_POLL_PERIOD:
dbglog_printf(timestamp, vap_id,"ANI Configure poll period to %d",args[0]);
break;
case ANI_DBGID_LISTEN_PERIOD:
dbglog_printf(timestamp, vap_id,"ANI Configure listen period to %d",args[0]);
break;
case ANI_DBGID_OFDM_LEVEL_CFG:
dbglog_printf(timestamp, vap_id,"ANI Configure ofdm level to %d",args[0]);
break;
case ANI_DBGID_CCK_LEVEL_CFG:
dbglog_printf(timestamp, vap_id,"ANI Configure cck level to %d",args[0]);
break;
default:
dbglog_printf(timestamp, vap_id,"ANI arg1 %d arg2 %d arg3 %d",
args[0],args[1],args[2]);
break;
}
return TRUE;
}
A_BOOL
dbglog_ap_powersave_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
switch (dbg_id) {
case AP_PS_DBGID_UPDATE_TIM:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"AP PS: TIM update AID=%u %s",
args[0], args[1] ? "set" : "clear");
}
break;
case AP_PS_DBGID_PEER_STATE_CHANGE:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u power save %s",
args[0], args[1] ? "enabled" : "disabled");
}
break;
case AP_PS_DBGID_PSPOLL:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u pspoll response tid=%u flags=%x",
args[0], args[1], args[2]);
}
break;
case AP_PS_DBGID_PEER_CREATE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"AP PS: create peer AID=%u", args[0]);
}
break;
case AP_PS_DBGID_PEER_DELETE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"AP PS: delete peer AID=%u", args[0]);
}
break;
case AP_PS_DBGID_VDEV_CREATE:
dbglog_printf(timestamp, vap_id, "AP PS: vdev create");
break;
case AP_PS_DBGID_VDEV_DELETE:
dbglog_printf(timestamp, vap_id, "AP PS: vdev delete");
break;
case AP_PS_DBGID_SYNC_TIM:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u advertised=%#x buffered=%#x", args[0], args[1], args[2]);
}
break;
case AP_PS_DBGID_NEXT_RESPONSE:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u select next response %s%s%s", args[0],
args[1] ? "(usp active) " : "",
args[2] ? "(pending usp) " : "",
args[3] ? "(pending poll response)" : "");
}
break;
case AP_PS_DBGID_START_SP:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u START SP tsf=%#x (%u)",
args[0], args[1], args[2]);
}
break;
case AP_PS_DBGID_COMPLETED_EOSP:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u EOSP eosp_tsf=%#x trigger_tsf=%#x",
args[0], args[1], args[2]);
}
break;
case AP_PS_DBGID_TRIGGER:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u TRIGGER tsf=%#x %s%s", args[0], args[1],
args[2] ? "(usp active) " : "",
args[3] ? "(send_n in progress)" : "");
}
break;
case AP_PS_DBGID_DUPLICATE_TRIGGER:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u DUP TRIGGER tsf=%#x seq=%u ac=%u",
args[0], args[1], args[2], args[3]);
}
break;
case AP_PS_DBGID_UAPSD_RESPONSE:
if (numargs == 5) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u UAPSD response tid=%u, n_mpdu=%u flags=%#x max_sp=%u current_sp=%u",
args[0], args[1], args[2], args[3], (args[4] >> 16) & 0xffff, args[4] & 0xffff);
}
break;
case AP_PS_DBGID_SEND_COMPLETE:
if (numargs == 5) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u SEND_COMPLETE fc=%#x qos=%#x %s%s",
args[0], args[1], args[2],
args[3] ? "(usp active) " : "",
args[4] ? "(pending poll response)" : "");
}
break;
case AP_PS_DBGID_SEND_N_COMPLETE:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u SEND_N_COMPLETE %s%s",
args[0],
args[1] ? "(usp active) " : "",
args[2] ? "(pending poll response)" : "");
}
break;
case AP_PS_DBGID_DETECT_OUT_OF_SYNC_STA:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"AP PS: AID=%u detected out-of-sync now=%u tx_waiting=%u txq_depth=%u",
args[0], args[1], args[2], args[3]);
}
break;
case AP_PS_DBGID_DELIVER_CAB:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"AP PS: CAB %s n_mpdus=%u, flags=%x, extra=%u",
(args[0] == 17) ? "MGMT" : "DATA", args[1], args[2], args[3]);
}
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL
dbglog_wal_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"ACTIVE",
"WAIT",
"WAIT_FILTER",
"PAUSE",
"PAUSE_SEND_N",
"BLOCK",
};
static const char *events[] = {
"PAUSE",
"PAUSE_FILTER",
"UNPAUSE",
"BLOCK",
"BLOCK_FILTER",
"UNBLOCK",
"HWQ_EMPTY",
"ALLOW_N",
};
#define WAL_VDEV_TYPE(type) \
(type == 0 ? "AP" : \
(type == 1 ? "STA" : \
(type == 2 ? "IBSS" : \
(type == 2 ? "MONITOR" : \
"UNKNOWN"))))
#define WAL_SLEEP_STATE(state) \
(state == 1 ? "NETWORK SLEEP" : \
(state == 2 ? "AWAKE" : \
(state == 3 ? "SYSTEM SLEEP" : \
"UNKNOWN")))
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "TID PAUSE",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
case WAL_DBGID_SET_POWER_STATE:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"WAL %s => %s, req_count=%u",
WAL_SLEEP_STATE(args[0]), WAL_SLEEP_STATE(args[1]),
args[2]);
}
break;
case WAL_DBGID_CHANNEL_CHANGE_FORCE_RESET:
if (numargs == 4) {
dbglog_printf(timestamp, vap_id,
"WAL channel change (force reset) freq=%u, flags=%u mode=%u rx_ok=%u tx_ok=%u",
args[0] & 0x0000ffff, (args[0] & 0xffff0000) >> 16, args[1],
args[2], args[3]);
}
break;
case WAL_DBGID_CHANNEL_CHANGE:
if (numargs == 2) {
dbglog_printf(timestamp, vap_id,
"WAL channel change freq=%u, mode=%u flags=%u rx_ok=1 tx_ok=1",
args[0] & 0x0000ffff, (args[0] & 0xffff0000) >> 16, args[1]);
}
break;
case WAL_DBGID_VDEV_START:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id, "WAL %s vdev started",
WAL_VDEV_TYPE(args[0]));
}
break;
case WAL_DBGID_VDEV_STOP:
dbglog_printf(timestamp, vap_id, "WAL %s vdev stopped",
WAL_VDEV_TYPE(args[0]));
break;
case WAL_DBGID_VDEV_UP:
dbglog_printf(timestamp, vap_id, "WAL %s vdev up, count=%u",
WAL_VDEV_TYPE(args[0]), args[1]);
break;
case WAL_DBGID_VDEV_DOWN:
dbglog_printf(timestamp, vap_id, "WAL %s vdev down, count=%u",
WAL_VDEV_TYPE(args[0]), args[1]);
break;
case WAL_DBGID_TX_MGMT_DESCID_SEQ_TYPE_LEN:
dbglog_printf(timestamp, vap_id, "WAL Tx Mgmt frame desc_id=0x%x, seq=0x%x, type=0x%x, len=0x%x islocal=0x%x",
args[0], args[1], args[2], (args[3] & 0xffff0000) >> 16, args[3] & 0x0000ffff);
break;
case WAL_DBGID_TX_MGMT_COMP_DESCID_STATUS:
dbglog_printf(timestamp, vap_id, "WAL Tx Mgmt frame completion desc_id=0x%x, status=0x%x, islocal=0x%x",
args[0], args[1], args[2]);
break;
case WAL_DBGID_TX_DATA_MSDUID_SEQ_TYPE_LEN:
dbglog_printf(timestamp, vap_id, "WAL Tx Data frame msdu_id=0x%x, seq=0x%x, type=0x%x, len=0x%x",
args[0], args[1], args[2], args[3]);
break;
case WAL_DBGID_TX_DATA_COMP_MSDUID_STATUS:
dbglog_printf(timestamp, vap_id, "WAL Tx Data frame completion desc_id=0x%x, status=0x%x, seq=0x%x",
args[0], args[1], args[2]);
break;
case WAL_DBGID_RESET_PCU_CYCLE_CNT:
dbglog_printf(timestamp, vap_id, "WAL PCU cycle counter value at reset:%x", args[0]);
break;
case WAL_DBGID_TX_DISCARD:
dbglog_printf(timestamp, vap_id, "WAL Tx enqueue discard msdu_id=0x%x", args[0]);
break;
case WAL_DBGID_SET_HW_CHAINMASK:
dbglog_printf(timestamp, vap_id, "WAL_DBGID_SET_HW_CHAINMASK "
"pdev=%d, txchain=0x%x, rxchain=0x%x",
args[0], args[1], args[2]);
break;
case WAL_DBGID_SET_HW_CHAINMASK_TXRX_STOP_FAIL:
dbglog_printf(timestamp, vap_id, "WAL_DBGID_SET_HW_CHAINMASK_TXRX_STOP_FAIL rxstop=%d, txstop=%d",
args[0], args[1]);
break;
case WAL_DBGID_GET_HW_CHAINMASK:
dbglog_printf(timestamp, vap_id, "WAL_DBGID_GET_HW_CHAINMASK "
"txchain=0x%x, rxchain=0x%x",
args[0], args[1]);
break;
case WAL_DBGID_SMPS_DISABLE:
dbglog_printf(timestamp, vap_id, "WAL_DBGID_SMPS_DISABLE");
break;
case WAL_DBGID_SMPS_ENABLE_HW_CNTRL:
dbglog_printf(timestamp, vap_id, "WAL_DBGID_SMPS_ENABLE_HW_CNTRL low_pwr_mask=0x%x, high_pwr_mask=0x%x",
args[0], args[1]);
break;
case WAL_DBGID_SMPS_SWSEL_CHAINMASK:
dbglog_printf(timestamp, vap_id, "WAL_DBGID_SMPS_SWSEL_CHAINMASK low_pwr=0x%x, chain_mask=0x%x",
args[0], args[1]);
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL
dbglog_scan_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"IDLE",
"BSSCHAN",
"WAIT_FOREIGN_CHAN",
"FOREIGN_CHANNEL",
"TERMINATING"
};
static const char *events[] = {
"REQ",
"STOP",
"BSSCHAN",
"FOREIGN_CHAN",
"CHECK_ACTIVITY",
"REST_TIME_EXPIRE",
"DWELL_TIME_EXPIRE",
"PROBE_TIME_EXPIRE",
};
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "SCAN",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL dbglog_coex_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 * args)
{
A_UINT8 i;
char * dbg_id_str;
static const char * wlan_rx_xput_status[] = {
"WLAN_XPUT_NORMAL",
"WLAN_XPUT_UNDER_THRESH",
"WLAN_XPUT_CRITICAL",
"WLAN_XPUT_RECOVERY_TIMEOUT",
};
static const char * coex_sched_req[] = {
"SCHED_REQ_NEXT",
"SCHED_REQ_BT",
"SCHED_REQ_WLAN",
"SCHED_REQ_POSTPAUSE",
"SCHED_REQ_UNPAUSE",
};
static const char * coex_sched_type[] = {
"SCHED_NONE",
"SCHED_WLAN",
"SCHED_BT",
"SCHED_WLAN_PAUSE",
"SCHED_WLAN_POSTPAUSE",
"SCHED_WLAN_UNPAUSE",
"COEX_SCHED_MWS",
};
static const char * coex_trf_mgmt_type[] = {
"TRF_MGMT_FREERUN",
"TRF_MGMT_SHAPE_PM",
"TRF_MGMT_SHAPE_PSP",
"TRF_MGMT_SHAPE_S_CTS",
"TRF_MGMT_SHAPE_OCS",
"TRF_MGMT_SHAPE_FIXED_TIME",
"TRF_MGMT_SHAPE_NOA",
"TRF_MGMT_SHAPE_OCS_CRITICAL",
"TRF_MGMT_NONE",
};
static const char * coex_system_status[] = {
"ALL_OFF",
"BTCOEX_NOT_REQD",
"WLAN_IS_IDLE",
"EXECUTE_SCHEME",
"BT_FULL_CONCURRENCY",
"WLAN_SLEEPING",
"WLAN_IS_PAUSED",
"WAIT_FOR_NEXT_ACTION",
"SOC_WAKE",
};
static const char * wlan_rssi_type[] = {
"LOW_RSSI",
"MID_RSSI",
"HI_RSSI",
"INVALID_RSSI",
};
static const char * coex_bt_scheme[] = {
"IDLE_CTRL",
"ACTIVE_ASYNC_CTRL",
"PASSIVE_SYNC_CTRL",
"ACTIVE_SYNC_CTRL",
"DEFAULT_CTRL",
"CONCURRENCY_CTRL",
};
static const char * wal_peer_rx_rate_stats_event_sent[] = {
"PR_RX_EVT_SENT_NONE",
"PR_RX_EVT_SENT_LOWER",
"PR_RX_EVT_SENT_UPPER",
};
static const char * wlan_psp_stimulus[] = {
"ENTRY",
"EXIT",
"PS_READY",
"PS_NOT_READY",
"RX_MORE_DATA_RCVD",
"RX_NO_MORE_DATA_RCVD",
"TX_DATA_COMPLT",
"TX_COMPLT",
"TIM_SET",
"REQ",
"DONE_SUCCESS",
"DONE_NO_PS_POLL_ACK",
"DONE_RESPONSE_TMO",
"DONE_DROPPED",
"DONE_FILTERED",
"WLAN_START",
"NONWLAN_START",
"NONWLAN_INTVL_UPDATE",
"NULL_TX",
"NULL_TX_COMPLT",
"BMISS_FIRST",
"NULL_TX_FAIL",
"RX_NO_MORE_DATA_DATAFRM",
};
static const char * coex_pspoll_state[] = {
"STATE_DISABLED",
"STATE_NOT_READY",
"STATE_ENABLED",
"STATE_READY",
"STATE_TX_STATUS",
"STATE_RX_STATUS",
};
static const char * coex_scheduler_interval[] = {
"COEX_SCHED_NONWLAN_INT",
"COEX_SCHED_WLAN_INT",
};
static const char * wlan_weight[] = {
"BT_COEX_BASE",
"BT_COEX_LOW",
"BT_COEX_MID",
"BT_COEX_MID_NONSYNC",
"BT_COEX_HI_NONVOICE",
"BT_COEX_HI",
"BT_COEX_CRITICAL",
};
static const char * wlan_power_state[] = {
"SLEEP",
"AWAKE",
"FULL_SLEEP",
};
static const char * coex_psp_error_type[] = {
"DISABLED_STATE",
"VDEV_NULL",
"COEX_PSP_ENTRY",
"ZERO_INTERVAL",
"COEX_PSP_EXIT",
"READY_DISABLED",
"READY_NOT_DISABLED",
"POLL_PKT_DROPPED",
"SET_TIMER_PARAM",
};
static const char * wlan_phymode[] = {
"A",
"G",
"B",
"G_ONLY",
"NA_HT20",
"NG_HT20",
"NA_HT40",
"NG_HT40",
"AC_VHT20",
"AC_VHT40",
"AC_VHT80",
"AC_VHT20_2G",
"AC_VHT40_2G",
"AC_VHT80_2G",
"UNKNOWN",
};
static const char * wlan_curr_band[] = {
"2G",
"5G",
};
dbg_id_str = dbglog_get_msg(mod_id, dbg_id);
switch (dbg_id) {
case COEX_SYSTEM_UPDATE:
if (numargs == 1 && args[0] < 9) {
dbglog_printf(timestamp, vap_id, "%s: %s", dbg_id_str, coex_system_status[args[0]]);
} else if (numargs >= 5 && args[0] < 9 && args[2] < 9) {
dbglog_printf(timestamp, vap_id, "%s: %s, WlanSysState(0x%x), %s, NumChains(%u), AggrLimit(%u)",
dbg_id_str, coex_system_status[args[0]], args[1], coex_trf_mgmt_type[args[2]], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_SCHED_START:
if (numargs >= 5 && args[0] < 5 && args[2] < 9 && args[3] < 4 && args[4] < 4) {
if (args[1] == 0xffffffff) {
dbglog_printf(timestamp, vap_id, "%s: %s, DETERMINE_DURATION, %s, %s, %s",
dbg_id_str, coex_sched_req[args[0]], coex_trf_mgmt_type[args[2]], wlan_rx_xput_status[args[3]], wlan_rssi_type[args[4]]);
} else {
dbglog_printf(timestamp, vap_id, "%s: %s, IntvlDur(%u), %s, %s, %s",
dbg_id_str, coex_sched_req[args[0]], args[1], coex_trf_mgmt_type[args[2]], wlan_rx_xput_status[args[3]], wlan_rssi_type[args[4]]);
}
} else {
return FALSE;
}
break;
case COEX_SCHED_RESULT:
if (numargs >= 5 && args[0] < 5 && args[1] < 9 && args[2] < 9) {
dbglog_printf(timestamp, vap_id, "%s: %s, %s, %s, CoexMgrPolicy(%u), IdleOverride(%u)",
dbg_id_str, coex_sched_req[args[0]], coex_trf_mgmt_type[args[1]], coex_trf_mgmt_type[args[2]], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_BT_SCHEME:
if (numargs >= 1 && args[0] < 6) {
dbglog_printf(timestamp, vap_id, "%s: %s", dbg_id_str, coex_bt_scheme[args[0]]);
} else {
return FALSE;
}
break;
case COEX_TRF_FREERUN:
if (numargs >= 5 && args[0] < 7) {
dbglog_printf(timestamp, vap_id, "%s: %s, AllocatedBtIntvls(%u), BtIntvlCnt(%u), AllocatedWlanIntvls(%u), WlanIntvlCnt(%u)",
dbg_id_str, coex_sched_type[args[0]], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_TRF_SHAPE_PM: // used by ocs now
if (numargs >= 3) {
dbglog_printf(timestamp, vap_id, "%s: IntvlLength(%u), BtDuration(%u), WlanDuration(%u)",
dbg_id_str, args[0], args[1], args[2]);
} else {
return FALSE;
}
break;
case COEX_SYSTEM_MONITOR:
if (numargs >= 5 && args[1] < 4 && args[4] < 4) {
dbglog_printf(timestamp, vap_id, "%s: WlanRxCritical(%u), %s, MinDirectRxRate(%u), MonitorActiveNum(%u), %s",
dbg_id_str, args[0], wlan_rx_xput_status[args[1]], args[2], args[3], wlan_rssi_type[args[4]]);
} else {
return FALSE;
}
break;
case COEX_RX_RATE:
if (numargs >= 5 && args[4] < 3) {
dbglog_printf(timestamp, vap_id, "%s: NumUnderThreshPeers(%u), MinDirectRate(%u), LastRateSample(%u), DeltaT(%u), %s",
dbg_id_str, args[0], args[1], args[2], args[3], wal_peer_rx_rate_stats_event_sent[args[4]]);
} else {
return FALSE;
}
break;
case COEX_WLAN_INTERVAL_START:
if (numargs >= 5) {
dbglog_printf(timestamp, vap_id, "%s: WlanIntvlCnt(%u), Duration(%u), Weight(%u), BaseIdleOverride(%u), WeightMat[0](0x%x)",
dbg_id_str, args[0], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_WLAN_POSTPAUSE_INTERVAL_START:
if (numargs >= 4) {
dbglog_printf(timestamp, vap_id, "%s: WlanPostPauseIntvlCnt(%u), XputMonitorActiveNum(%u), Duration(%u), Weight(%u)",
dbg_id_str, args[0], args[1], args[2], args[3]);
} else {
return FALSE;
}
break;
case COEX_BT_INTERVAL_START:
if (numargs >= 5) {
dbglog_printf(timestamp, vap_id, "%s: BtIntvlCnt(%u), Duration(%u), Weight(%u), BaseIdleOverride(%u), WeightMat[0](0x%x), ",
dbg_id_str, args[0], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_POWER_CHANGE:
if (numargs >= 3 && args[1] < 3 && args[2] < 3) {
dbglog_printf(timestamp, vap_id, "%s: Event(0x%x) %s->%s",
dbg_id_str, args[0], wlan_power_state[args[1]], wlan_power_state[args[2]]);
} else {
return FALSE;
}
break;
case COEX_CHANNEL_CHANGE:
if (numargs >= 5 && args[3] < 2 && args[4] < 15) {
dbglog_printf(timestamp, vap_id, "%s: %uMhz->%uMhz, WlanSysState(0x%x), CurrBand(%s), PhyMode(%s)",
dbg_id_str, args[0], args[1], args[2], wlan_curr_band[args[3]], wlan_phymode[args[4]]);
} else {
return FALSE;
}
break;
case COEX_PSP_MGR_ENTER:
if (numargs >= 5 && args[0] < 23 && args[1] < 6 && args[3] < 2) {
dbglog_printf(timestamp, vap_id, "%s: %s, %s, PsPollAvg(%u), %s, CurrT(%u)",
dbg_id_str, wlan_psp_stimulus[args[0]], coex_pspoll_state[args[1]], args[2], coex_scheduler_interval[args[3]], args[4]);
} else {
return FALSE;
}
break;
//Translate following into decimal
case COEX_SINGLECHAIN_DBG_1:
case COEX_SINGLECHAIN_DBG_2:
case COEX_SINGLECHAIN_DBG_3:
case COEX_MULTICHAIN_DBG_1:
case COEX_MULTICHAIN_DBG_2:
case COEX_MULTICHAIN_DBG_3:
case BTCOEX_DBG_MCI_1:
case BTCOEX_DBG_MCI_2:
case BTCOEX_DBG_MCI_3:
case BTCOEX_DBG_MCI_4:
case BTCOEX_DBG_MCI_5:
case BTCOEX_DBG_MCI_6:
case BTCOEX_DBG_MCI_7:
case BTCOEX_DBG_MCI_8:
case BTCOEX_DBG_MCI_9:
case BTCOEX_DBG_MCI_10:
if (numargs > 0) {
dbglog_printf_no_line_break(timestamp, vap_id, "%s: %u",
dbg_id_str, args[0]);
for (i = 1; i < numargs; i++) {
printk(", %u", args[i]);
}
printk("\n");
} else {
return FALSE;
}
break;
case COEX_LinkID:
if (numargs >= 4) {
if (args[0]) { //Add profile
dbglog_printf(timestamp, vap_id, "%s Alloc: LocalID(%u), RemoteID(%u), MinFreeLocalID(%u)",
dbg_id_str, args[1], args[2], args[3]);
} else { //Remove profile
dbglog_printf(timestamp, vap_id, "%s Dealloc: LocalID(%u), RemoteID(%u), MinFreeLocalID(%u)",
dbg_id_str, args[1], args[2], args[3]);
}
} else {
return FALSE;
}
break;
case COEX_PSP_MGR_RESULT:
if (numargs >= 5 && args[0] < 6) {
dbglog_printf(timestamp, vap_id, "%s: %s, PsPollAvg(%u), EstimationOverrun(%u), EstimationUnderun(%u), NotReadyErr(%u)",
dbg_id_str, coex_pspoll_state[args[0]], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_TRF_SHAPE_PSP:
if (numargs >= 5 && args[0] < 7 && args[1] < 7) {
dbglog_printf(timestamp, vap_id, "%s: %s, %s, Dur(%u), BtTriggerRecvd(%u), PspWlanCritical(%u)",
dbg_id_str, coex_sched_type[args[0]], wlan_weight[args[1]], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_PSP_SPEC_POLL:
if (numargs >= 5) {
dbglog_printf(timestamp, vap_id, "%s: PsPollSpecEna(%u), Count(%u), NextTS(%u), AllowSpecPsPollTx(%u), Intvl(%u)",
dbg_id_str, args[0], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_PSP_READY_STATE:
if (numargs >= 5) {
dbglog_printf(timestamp, vap_id, "%s: T2NonWlan(%u), CoexSchedulerEndTS(%u), MoreData(%u), PSPRespExpectedTS(%u), NonWlanIdleT(%u)",
dbg_id_str, args[0], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_PSP_NONWLAN_INTERVAL:
if (numargs >= 4) {
dbglog_printf(timestamp, vap_id, "%s: NonWlanBaseIntvl(%u), NonWlanIdleT(%u), PSPSpecIntvl(%u), ApRespTimeout(%u)",
dbg_id_str, args[0], args[1], args[2], args[3]);
} else {
return FALSE;
}
break;
case COEX_PSP_ERROR:
if (numargs >= 1 && args[0] < 9) {
dbglog_printf_no_line_break(timestamp, vap_id, "%s: %s",
dbg_id_str, coex_psp_error_type[args[0]]);
for (i = 1; i < numargs; i++) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (", %u", args[i]));
}
AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("\n"));
} else {
return FALSE;
}
break;
case COEX_PSP_STAT_1:
if (numargs >= 5) {
dbglog_printf(timestamp, vap_id, "%s: ApResp0(%u), ApResp1(%u), ApResp2(%u), ApResp3(%u), ApResp4(%u)",
dbg_id_str, args[0], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_PSP_STAT_2:
if (numargs >= 5) {
dbglog_printf(timestamp, vap_id, "%s: DataPt(%u), Max(%u), NextApRespIndex(%u), NumOfValidDataPts(%u), PsPollAvg(%u)",
dbg_id_str, args[0], args[1], args[2], args[3], args[4]);
} else {
return FALSE;
}
break;
case COEX_PSP_RX_STATUS_STATE_1:
if (numargs >= 5) {
if (args[2]) {
dbglog_printf(timestamp, vap_id, "%s: RsExpectedTS(%u), RespActualTS(%u), Overrun, RsOverrunT(%u), RsRxDur(%u)",
dbg_id_str, args[0], args[1], args[3], args[4]);
} else {
dbglog_printf(timestamp, vap_id, "%s: RsExpectedTS(%u), RespActualTS(%u), Underrun, RsUnderrunT(%u), RsRxDur(%u)",
dbg_id_str, args[0], args[1], args[3], args[4]);
}
} else {
return FALSE;
}
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL
dbglog_beacon_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"INIT",
"ADJUST_START",
"ADJUSTING",
"ADJUST_HOLD",
};
static const char *events[] = {
"ADJUST_START",
"ADJUST_RESTART",
"ADJUST_STOP",
"ADJUST_PAUSE",
"ADJUST_UNPAUSE",
"ADJUST_INC_SLOP_STEP",
"ADJUST_HOLD",
"ADJUST_HOLD_TIME_OUT",
};
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "EARLY_RX",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
case BEACON_EVENT_EARLY_RX_BMISS_STATUS:
if (numargs == 3) {
dbglog_printf(timestamp, vap_id,
"early_rx bmiss status:rcv=%d total=%d miss=%d",
args[0], args[1], args[2]);
}
break;
case BEACON_EVENT_EARLY_RX_SLEEP_SLOP:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"early_rx update sleep_slop:%d",
args[0]);
}
break;
case BEACON_EVENT_EARLY_RX_CONT_BMISS_TIMEOUT:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"early_rx cont bmiss timeout,update sleep_slop:%d",
args[0]);
}
break;
case BEACON_EVENT_EARLY_RX_PAUSE_SKIP_BCN_NUM:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"early_rx skip bcn num:%d",
args[0]);
}
break;
case BEACON_EVENT_EARLY_RX_CLK_DRIFT:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"early_rx clk drift:%d",
args[0]);
}
break;
case BEACON_EVENT_EARLY_RX_AP_DRIFT:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"early_rx ap drift:%d",
args[0]);
}
break;
case BEACON_EVENT_EARLY_RX_BCN_TYPE:
if (numargs == 1) {
dbglog_printf(timestamp, vap_id,
"early_rx bcn type:%d",
args[0]);
}
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL
dbglog_data_txrx_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
switch (dbg_id) {
case DATA_TXRX_DBGID_RX_DATA_SEQ_LEN_INFO:
dbglog_printf(timestamp, vap_id, "DATA RX seq=0x%x, len=0x%x, stored=0x%x, duperr=0x%x",
args[0], args[1], (args[2] & 0xffff0000) >> 16, args[2] & 0x0000ffff);
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL dbglog_smps_print_handler(A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"S_INACTIVE",
"S_STATIC",
"S_DYNAMIC",
"S_STALLED",
"S_INACTIVE_WAIT",
"S_STATIC_WAIT",
"S_DYNAMIC_WAIT",
};
static const char *events[] = {
"E_STOP",
"E_STOP_COMPL",
"E_START",
"E_STATIC",
"E_STATIC_COMPL",
"E_DYNAMIC",
"E_DYNAMIC_COMPL",
"E_STALL",
"E_RSSI_ABOVE_THRESH",
"E_RSSI_BELOW_THRESH",
"E_FORCED_NONE",
};
switch(dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "STA_SMPS SM",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
case STA_SMPS_DBGID_CREATE_PDEV_INSTANCE:
dbglog_printf(timestamp, vap_id, "STA_SMPS Create PDEV ctx %#x",
args[0]);
break;
case STA_SMPS_DBGID_CREATE_VIRTUAL_CHAN_INSTANCE:
dbglog_printf(timestamp, vap_id, "STA_SMPS Create Virtual Chan ctx %#x",
args[0]);
break;
case STA_SMPS_DBGID_DELETE_VIRTUAL_CHAN_INSTANCE:
dbglog_printf(timestamp, vap_id, "STA_SMPS Delete Virtual Chan ctx %#x",
args[0]);
break;
case STA_SMPS_DBGID_CREATE_STA_INSTANCE:
dbglog_printf(timestamp, vap_id, "STA_SMPS Create STA ctx %#x",
args[0]);
break;
case STA_SMPS_DBGID_DELETE_STA_INSTANCE:
dbglog_printf(timestamp, vap_id, "STA_SMPS Delete STA ctx %#x",
args[0]);
break;
case STA_SMPS_DBGID_VIRTUAL_CHAN_SMPS_START:
break;
case STA_SMPS_DBGID_VIRTUAL_CHAN_SMPS_STOP:
break;
case STA_SMPS_DBGID_SEND_SMPS_ACTION_FRAME:
dbglog_printf(timestamp, vap_id, "STA_SMPS STA %#x Signal SMPS mode as %s; cb_flags %#x",
args[0],
(args[1] == 0 ? "DISABLED":
(args[1] == 0x1 ? "STATIC" :
(args[1] == 0x3 ? "DYNAMIC" : "UNKNOWN"))),
args[2]);
break;
case STA_SMPS_DBGID_DTIM_EBT_EVENT_CHMASK_UPDATE:
dbglog_printf(timestamp, vap_id, "STA_SMPS_DBGID_DTIM_EBT_EVENT_CHMASK_UPDATE");
break;
case STA_SMPS_DBGID_DTIM_CHMASK_UPDATE:
dbglog_printf(timestamp, vap_id, "STA_SMPS_DBGID_DTIM_CHMASK_UPDATE "
"tx_mask %#x rx_mask %#x arb_dtim_mask %#x",
args[0], args[1], args[2]);
break;
case STA_SMPS_DBGID_DTIM_BEACON_EVENT_CHMASK_UPDATE:
dbglog_printf(timestamp, vap_id, "STA_SMPS_DBGID_DTIM_BEACON_EVENT_CHMASK_UPDATE");
break;
case STA_SMPS_DBGID_DTIM_POWER_STATE_CHANGE:
dbglog_printf(timestamp, vap_id, "STA_SMPS_DBGID_DTIM_POWER_STATE_CHANGE cur_pwr_state %s new_pwr_state %s",
(args[0] == 0x1 ? "SLEEP":
(args[0] == 0x2 ? "AWAKE":
(args[0] == 0x3 ? "FULL_SLEEP" : "UNKNOWN"))),
(args[1] == 0x1 ? "SLEEP":
(args[1] == 0x2 ? "AWAKE":
(args[1] == 0x3 ? "FULL_SLEEP" : "UNKNOWN"))));
break;
case STA_SMPS_DBGID_DTIM_CHMASK_UPDATE_SLEEP:
dbglog_printf(timestamp, vap_id, "STA_SMPS_DBGID_DTIM_CHMASK_UPDATE_SLEEP "
"tx_mask %#x rx_mask %#x orig_rx %#x dtim_rx %#x",
args[0], args[1], args[2], args[3]);
break;
case STA_SMPS_DBGID_DTIM_CHMASK_UPDATE_AWAKE:
dbglog_printf(timestamp, vap_id, "STA_SMPS_DBGID_DTIM_CHMASK_UPDATE_AWAKE "
"tx_mask %#x rx_mask %#x orig_rx %#x",
args[0], args[1], args[2]);
break;
default:
dbglog_printf(
timestamp,
vap_id,
"STA_SMPS: UNKNOWN DBGID!");
return FALSE;
}
return TRUE;
}
A_BOOL
dbglog_p2p_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"ACTIVE",
"DOZE",
"TX_BCN",
"CTWIN",
"OPPPS",
};
static const char *events[] = {
"ONESHOT_NOA",
"CTWINDOW",
"PERIODIC_NOA",
"IDLE",
"NOA_CHANGED",
"TBTT",
"TX_BCN_CMP",
"OPPPS_OK",
"OPPPS_CHANGED",
};
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "P2P GO PS",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
default:
return FALSE;
}
return TRUE;
}
A_BOOL
dbglog_pcielp_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
static const char *states[] = {
"STOP",
"TX",
"RX",
"SLEEP",
"SUSPEND",
};
static const char *events[] = {
"VDEV_UP",
"ALL_VDEV_DOWN",
"AWAKE",
"SLEEP",
"TX_ACTIVITY",
"TX_INACTIVITY",
"TX_AC_CHANGE",
"SUSPEND",
"RESUME",
};
switch (dbg_id) {
case DBGLOG_DBGID_SM_FRAMEWORK_PROXY_DBGLOG_MSG:
dbglog_sm_print(timestamp, vap_id, numargs, args, "PCIELP",
states, ARRAY_LENGTH(states), events, ARRAY_LENGTH(events));
break;
default:
return FALSE;
}
return TRUE;
}
#ifdef WLAN_OPEN_SOURCE
static int dbglog_block_open(struct inode *inode, struct file *file)
{
struct fwdebug *fwlog = inode->i_private;
if (fwlog->fwlog_open)
return -EBUSY;
fwlog->fwlog_open = TRUE;
file->private_data = inode->i_private;
return 0;
}
static int dbglog_block_release(struct inode *inode, struct file *file)
{
struct fwdebug *fwlog = inode->i_private;
fwlog->fwlog_open = FALSE;
return 0;
}
static ssize_t dbglog_block_read(struct file *file,
char __user *user_buf,
size_t count,
loff_t *ppos)
{
struct fwdebug *fwlog = file->private_data;
struct sk_buff *skb;
ssize_t ret_cnt;
size_t len = 0, not_copied;
char *buf;
int ret;
buf = vmalloc(count);
if (!buf)
return -ENOMEM;
spin_lock_bh(&fwlog->fwlog_queue.lock);
if (skb_queue_len(&fwlog->fwlog_queue) == 0) {
/* we must init under queue lock */
init_completion(&fwlog->fwlog_completion);
spin_unlock_bh(&fwlog->fwlog_queue.lock);
ret = wait_for_completion_interruptible(
&fwlog->fwlog_completion);
if (ret == -ERESTARTSYS) {
vfree(buf);
return ret;
}
spin_lock_bh(&fwlog->fwlog_queue.lock);
}
while ((skb = __skb_dequeue(&fwlog->fwlog_queue))) {
if (skb->len > count - len) {
/* not enough space, put skb back and leave */
__skb_queue_head(&fwlog->fwlog_queue, skb);
break;
}
memcpy(buf + len, skb->data, skb->len);
len += skb->len;
kfree_skb(skb);
}
spin_unlock_bh(&fwlog->fwlog_queue.lock);
/* FIXME: what to do if len == 0? */
not_copied = copy_to_user(user_buf, buf, len);
if (not_copied != 0) {
ret_cnt = -EFAULT;
goto out;
}
*ppos = *ppos + len;
ret_cnt = len;
out:
vfree(buf);
return ret_cnt;
}
static const struct file_operations fops_dbglog_block = {
.open = dbglog_block_open,
.release = dbglog_block_release,
.read = dbglog_block_read,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
int dbglog_debugfs_init(wmi_unified_t wmi_handle)
{
wmi_handle->debugfs_phy = debugfs_create_dir(CLD_DEBUGFS_DIR, NULL);
if (!wmi_handle->debugfs_phy)
return -ENOMEM;
debugfs_create_file(DEBUGFS_BLOCK_NAME, S_IRUSR, wmi_handle->debugfs_phy, &wmi_handle->dbglog,
&fops_dbglog_block);
return TRUE;
}
int dbglog_debugfs_remove(wmi_unified_t wmi_handle)
{
debugfs_remove_recursive(wmi_handle->debugfs_phy);
return TRUE;
}
#endif /* WLAN_OPEN_SOURCE */
static void
cnss_diag_event_report(A_UINT16 event_Id, A_UINT16 length, void *pPayload)
{
A_UINT8 *pBuf, *pBuf1;
event_report_t *pEvent_report;
A_UINT16 total_len;
total_len = sizeof(event_report_t) + length;
pBuf = vos_mem_malloc(total_len);
if (!pBuf){
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,
("%s: vos_mem_malloc failed \n", __func__));
return;
}
pBuf1 = pBuf;
pEvent_report = (event_report_t*)pBuf;
pEvent_report->diag_type = DIAG_TYPE_EVENTS;
pEvent_report->event_id = event_Id;
pEvent_report->length = length;
pBuf += sizeof(event_report_t);
memcpy(pBuf, pPayload, length);
send_diag_netlink_data((A_UINT8 *) pBuf1, total_len, DIAG_TYPE_HOST_MSG);
vos_mem_free((v_VOID_t*)pBuf1);
return;
}
static void cnss_diag_send_driver_loaded(void)
{
if (appstarted) {
vos_event_wlan_bringup_status_payload_type wlan_bringup_status;
/* Send Driver up command */
strlcpy(&wlan_bringup_status.driverVersion[0], QWLAN_VERSIONSTR,
sizeof(wlan_bringup_status.driverVersion));
wlan_bringup_status.wlanStatus = DIAG_WLAN_DRIVER_LOADED;
cnss_diag_event_report(EVENT_WLAN_BRINGUP_STATUS,
sizeof(wlan_bringup_status), &wlan_bringup_status);
senddriverstatus = FALSE;
}
else
senddriverstatus = TRUE;
}
static void cnss_diag_send_driver_unloaded(void)
{
vos_event_wlan_bringup_status_payload_type wlan_bringup_status;
/* Send Driver down command */
memset(&wlan_bringup_status, 0,
sizeof(vos_event_wlan_bringup_status_payload_type));
wlan_bringup_status.wlanStatus = DIAG_WLAN_DRIVER_UNLOADED;
cnss_diag_event_report(EVENT_WLAN_BRINGUP_STATUS,
sizeof(wlan_bringup_status), &wlan_bringup_status);
}
/**---------------------------------------------------------------------------
\brief cnss_diag_msg_callback() - Call back invoked by netlink service
This function gets invoked by netlink service when a message is recevied
from the cnss-diag application in user-space.
\param -
- skb - skb with netlink message
\return - 0 for success, non zero for failure
--------------------------------------------------------------------------*/
int cnss_diag_msg_callback(struct sk_buff *skb)
{
struct nlmsghdr *nlh;
struct dbglog_slot *slot;
A_UINT8 *msg;
nlh = (struct nlmsghdr *)skb->data;
if (!nlh)
{
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: Netlink header null \n", __func__));
return -1;
}
msg = NLMSG_DATA(nlh);
/* This check added for backward compatability */
if (!memcmp(msg, "Hello", 5)) {
appstarted = TRUE;
cnss_diag_pid = nlh->nlmsg_pid;
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,
("%s: registered pid %d \n", __func__, cnss_diag_pid));
if (senddriverstatus)
cnss_diag_send_driver_loaded();
return 0;
}
else
slot = (struct dbglog_slot *)msg;
switch (slot->diag_type) {
case DIAG_TYPE_CRASH_INJECT:
if (slot->length == 2) {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,
("%s : DIAG_TYPE_CRASH_INJECT: %d %d\n", __func__,
slot->payload[0], slot->payload[1]));
process_wma_set_command_twoargs(0,
(int)GEN_PARAM_CRASH_INJECT,
slot->payload[0],
slot->payload[1], GEN_CMD);
}
else
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("crash_inject cmd error\n"));
break;
default:
break;
}
return 0;
}
/**---------------------------------------------------------------------------
\brief cnss_diag_notify_wlan_close() - Notify APP driver closed
This function notifies the user cnss-diag app that wlan driver is closed.
\param -
- None
\return - 0 for success, non zero for failure
--------------------------------------------------------------------------*/
int cnss_diag_notify_wlan_close()
{
/* Send nl msg about the wlan close */
if (0 != cnss_diag_pid)
{
cnss_diag_send_driver_unloaded();
cnss_diag_pid = 0;
}
return 0;
}
/**---------------------------------------------------------------------------
\brief cnss_diag_activate_service() - Activate cnss_diag message handler
This function registers a handler to receive netlink message from
an cnss-diag application process.
\param -
- None
\return - 0 for success, non zero for failure
--------------------------------------------------------------------------*/
int cnss_diag_activate_service()
{
int ret = 0;
/* Register the msg handler for msgs addressed to WLAN_NL_MSG_OEM */
ret = nl_srv_register(WLAN_NL_MSG_CNSS_DIAG, cnss_diag_msg_callback);
if (ret == -EINVAL)
{
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("CNSS-DIAG Registeration failed \n"));
return ret;
}
kd_nl_init = TRUE;
return 0;
}
A_BOOL
dbglog_wow_print_handler(
A_UINT32 mod_id,
A_UINT16 vap_id,
A_UINT32 dbg_id,
A_UINT32 timestamp,
A_UINT16 numargs,
A_UINT32 *args)
{
switch (dbg_id) {
case WOW_NS_OFLD_ENABLE:
if (4 == numargs) {
dbglog_printf(timestamp, vap_id,
"Enable NS offload, for sender %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\
:%02x%02x:%02x%02x:%02x%02x",
*(A_UINT8*)&args[0], *((A_UINT8*)&args[0]+1), *((A_UINT8*)&args[0]+2), *((A_UINT8*)&args[0]+3),
*(A_UINT8*)&args[1], *((A_UINT8*)&args[1]+1), *((A_UINT8*)&args[1]+2), *((A_UINT8*)&args[1]+3),
*(A_UINT8*)&args[2], *((A_UINT8*)&args[2]+1), *((A_UINT8*)&args[2]+2), *((A_UINT8*)&args[2]+3),
*(A_UINT8*)&args[3], *((A_UINT8*)&args[3]+1), *((A_UINT8*)&args[3]+2), *((A_UINT8*)&args[3]+3));
} else {
return FALSE;
}
break;
case WOW_ARP_OFLD_ENABLE:
if (1 == numargs) {
dbglog_printf(timestamp, vap_id,
"Enable ARP offload, for sender %d.%d.%d.%d",
*(A_UINT8*)args, *((A_UINT8*)args+1), *((A_UINT8*)args+2), *((A_UINT8*)args+3));
} else {
return FALSE;
}
break;
case WOW_NS_ARP_OFLD_DISABLE:
if (0 == numargs) {
dbglog_printf(timestamp, vap_id, "disable NS/ARP offload");
} else {
return FALSE;
}
break;
case WOW_NS_RECEIVED:
if (4 == numargs) {
dbglog_printf(timestamp, vap_id,
"NS requested from %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\
:%02x%02x:%02x%02x:%02x%02x",
*(A_UINT8*)&args[0], *((A_UINT8*)&args[0]+1), *((A_UINT8*)&args[0]+2), *((A_UINT8*)&args[0]+3),
*(A_UINT8*)&args[1], *((A_UINT8*)&args[1]+1), *((A_UINT8*)&args[1]+2), *((A_UINT8*)&args[1]+3),
*(A_UINT8*)&args[2], *((A_UINT8*)&args[2]+1), *((A_UINT8*)&args[2]+2), *((A_UINT8*)&args[2]+3),
*(A_UINT8*)&args[3], *((A_UINT8*)&args[3]+1), *((A_UINT8*)&args[3]+2), *((A_UINT8*)&args[3]+3));
} else {
return FALSE;
}
break;
case WOW_NS_REPLIED:
if (4 == numargs) {
dbglog_printf(timestamp, vap_id,
"NS replied to %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\
:%02x%02x:%02x%02x:%02x%02x",
*(A_UINT8*)&args[0], *((A_UINT8*)&args[0]+1), *((A_UINT8*)&args[0]+2), *((A_UINT8*)&args[0]+3),
*(A_UINT8*)&args[1], *((A_UINT8*)&args[1]+1), *((A_UINT8*)&args[1]+2), *((A_UINT8*)&args[1]+3),
*(A_UINT8*)&args[2], *((A_UINT8*)&args[2]+1), *((A_UINT8*)&args[2]+2), *((A_UINT8*)&args[2]+3),
*(A_UINT8*)&args[3], *((A_UINT8*)&args[3]+1), *((A_UINT8*)&args[3]+2), *((A_UINT8*)&args[3]+3));
} else {
return FALSE;
}
break;
case WOW_ARP_RECEIVED:
if (1 == numargs) {
dbglog_printf(timestamp, vap_id,
"ARP requested from %d.%d.%d.%d",
*(A_UINT8*)args, *((A_UINT8*)args+1), *((A_UINT8*)args+2), *((A_UINT8*)args+3));
} else {
return FALSE;
}
break;
break;
case WOW_ARP_REPLIED:
if (1 == numargs) {
dbglog_printf(timestamp, vap_id,
"ARP replied to %d.%d.%d.%d",
*(A_UINT8*)args, *((A_UINT8*)args+1), *((A_UINT8*)args+2), *((A_UINT8*)args+3));
} else {
return FALSE;
}
break;
default:
return FALSE;
}
return TRUE;
}
int dbglog_parser_type_init(wmi_unified_t wmi_handle, int type)
{
if(type >= DBGLOG_PROCESS_MAX){
return A_ERROR;
}
dbglog_process_type = type;
gprint_limiter = FALSE;
return A_OK;
}
int
dbglog_init(wmi_unified_t wmi_handle)
{
int res = 0;
OS_MEMSET(mod_print, 0, sizeof(mod_print));
dbglog_reg_modprint(WLAN_MODULE_STA_PWRSAVE, dbglog_sta_powersave_print_handler);
dbglog_reg_modprint(WLAN_MODULE_AP_PWRSAVE, dbglog_ap_powersave_print_handler);
dbglog_reg_modprint(WLAN_MODULE_WAL, dbglog_wal_print_handler);
dbglog_reg_modprint(WLAN_MODULE_SCAN, dbglog_scan_print_handler);
dbglog_reg_modprint(WLAN_MODULE_RATECTRL, dbglog_ratectrl_print_handler);
dbglog_reg_modprint(WLAN_MODULE_ANI, dbglog_ani_print_handler);
dbglog_reg_modprint(WLAN_MODULE_COEX, dbglog_coex_print_handler);
dbglog_reg_modprint(WLAN_MODULE_BEACON,dbglog_beacon_print_handler);
dbglog_reg_modprint(WLAN_MODULE_WOW, dbglog_wow_print_handler);
dbglog_reg_modprint(WLAN_MODULE_DATA_TXRX,dbglog_data_txrx_print_handler);
dbglog_reg_modprint(WLAN_MODULE_STA_SMPS, dbglog_smps_print_handler);
dbglog_reg_modprint(WLAN_MODULE_P2P, dbglog_p2p_print_handler);
dbglog_reg_modprint(WLAN_MODULE_PCIELP, dbglog_pcielp_print_handler);
dbglog_reg_modprint(WLAN_MODULE_IBSS_PWRSAVE,
dbglog_ibss_powersave_print_handler);
/* Register handler for F3 or debug messages */
res = wmi_unified_register_event_handler(wmi_handle, WMI_DEBUG_MESG_EVENTID,
dbglog_parse_debug_logs);
if (res != 0)
return res;
/* Register handler for FW diag events */
res = wmi_unified_register_event_handler(wmi_handle,
WMI_DIAG_DATA_CONTAINER_EVENTID,
fw_diag_data_event_handler);
if (res != 0)
return res;
/* Register handler for new FW diag Event, LOG, MSG combined */
res = wmi_unified_register_event_handler(wmi_handle, WMI_DIAG_EVENTID,
diag_fw_handler);
if (res != 0)
return res;
cnss_diag_send_driver_loaded();
#ifdef WLAN_OPEN_SOURCE
/* Initialize the fw debug log queue */
skb_queue_head_init(&wmi_handle->dbglog.fwlog_queue);
init_completion(&wmi_handle->dbglog.fwlog_completion);
/* Initialize debugfs */
dbglog_debugfs_init(wmi_handle);
#endif /* WLAN_OPEN_SOURCE */
return res;
}
int
dbglog_deinit(wmi_unified_t wmi_handle)
{
int res = 0;
#ifdef WLAN_OPEN_SOURCE
/* DeInitialize the fw debug log queue */
skb_queue_purge(&wmi_handle->dbglog.fwlog_queue);
complete(&wmi_handle->dbglog.fwlog_completion);
/* Deinitialize the debugfs */
dbglog_debugfs_remove(wmi_handle);
#endif /* WLAN_OPEN_SOURCE */
res = wmi_unified_unregister_event_handler(wmi_handle, WMI_DEBUG_MESG_EVENTID);
if(res != 0)
return res;
kd_nl_init = FALSE;
return res;
}
| Diaob/z_bac_150827_android_kernel_oneplus_msm8994 | drivers/staging/qcacld-2.0/CORE/UTILS/FWLOG/dbglog_host.c | C | gpl-2.0 | 142,663 |
/* binder.c
*
* Android IPC Subsystem
*
* Copyright (C) 2007-2008 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <asm/cacheflush.h>
#include <linux/fdtable.h>
#include <linux/file.h>
#include <linux/freezer.h>
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/miscdevice.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/nsproxy.h>
#include <linux/poll.h>
#include <linux/debugfs.h>
#include <linux/rbtree.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/pid_namespace.h>
#include <linux/security.h>
#include <linux/ratelimit.h>
#include "binder.h"
#include "binder_trace.h"
static DEFINE_MUTEX(binder_main_lock);
static DEFINE_MUTEX(binder_deferred_lock);
static DEFINE_MUTEX(binder_mmap_lock);
static HLIST_HEAD(binder_procs);
static HLIST_HEAD(binder_deferred_list);
static HLIST_HEAD(binder_dead_nodes);
static struct dentry *binder_debugfs_dir_entry_root;
static struct dentry *binder_debugfs_dir_entry_proc;
static struct binder_node *binder_context_mgr_node;
static kuid_t binder_context_mgr_uid = INVALID_UID;
static int binder_last_id;
static struct workqueue_struct *binder_deferred_workqueue;
#define BINDER_DEBUG_ENTRY(name) \
static int binder_##name##_open(struct inode *inode, struct file *file) \
{ \
return single_open(file, binder_##name##_show, inode->i_private); \
} \
\
static const struct file_operations binder_##name##_fops = { \
.owner = THIS_MODULE, \
.open = binder_##name##_open, \
.read = seq_read, \
.llseek = seq_lseek, \
.release = single_release, \
}
static int binder_proc_show(struct seq_file *m, void *unused);
BINDER_DEBUG_ENTRY(proc);
/* This is only defined in include/asm-arm/sizes.h */
#ifndef SZ_1K
#define SZ_1K 0x400
#endif
#ifndef SZ_4M
#define SZ_4M 0x400000
#endif
#define FORBIDDEN_MMAP_FLAGS (VM_WRITE)
#define BINDER_SMALL_BUF_SIZE (PAGE_SIZE * 64)
enum {
BINDER_DEBUG_USER_ERROR = 1U << 0,
BINDER_DEBUG_FAILED_TRANSACTION = 1U << 1,
BINDER_DEBUG_DEAD_TRANSACTION = 1U << 2,
BINDER_DEBUG_OPEN_CLOSE = 1U << 3,
BINDER_DEBUG_DEAD_BINDER = 1U << 4,
BINDER_DEBUG_DEATH_NOTIFICATION = 1U << 5,
BINDER_DEBUG_READ_WRITE = 1U << 6,
BINDER_DEBUG_USER_REFS = 1U << 7,
BINDER_DEBUG_THREADS = 1U << 8,
BINDER_DEBUG_TRANSACTION = 1U << 9,
BINDER_DEBUG_TRANSACTION_COMPLETE = 1U << 10,
BINDER_DEBUG_FREE_BUFFER = 1U << 11,
BINDER_DEBUG_INTERNAL_REFS = 1U << 12,
BINDER_DEBUG_BUFFER_ALLOC = 1U << 13,
BINDER_DEBUG_PRIORITY_CAP = 1U << 14,
BINDER_DEBUG_BUFFER_ALLOC_ASYNC = 1U << 15,
};
static uint32_t binder_debug_mask;
module_param_named(debug_mask, binder_debug_mask, uint, S_IWUSR | S_IRUGO);
static bool binder_debug_no_lock;
module_param_named(proc_no_lock, binder_debug_no_lock, bool, S_IWUSR | S_IRUGO);
static DECLARE_WAIT_QUEUE_HEAD(binder_user_error_wait);
static int binder_stop_on_user_error;
static int binder_set_stop_on_user_error(const char *val,
struct kernel_param *kp)
{
int ret;
ret = param_set_int(val, kp);
if (binder_stop_on_user_error < 2)
wake_up(&binder_user_error_wait);
return ret;
}
module_param_call(stop_on_user_error, binder_set_stop_on_user_error,
param_get_int, &binder_stop_on_user_error, S_IWUSR | S_IRUGO);
#define binder_debug(mask, x...) \
do { \
if (binder_debug_mask & mask) \
pr_info_ratelimited(x); \
} while (0)
#define binder_user_error(x...) \
do { \
if (binder_debug_mask & BINDER_DEBUG_USER_ERROR) \
pr_info(x); \
if (binder_stop_on_user_error) \
binder_stop_on_user_error = 2; \
} while (0)
enum binder_stat_types {
BINDER_STAT_PROC,
BINDER_STAT_THREAD,
BINDER_STAT_NODE,
BINDER_STAT_REF,
BINDER_STAT_DEATH,
BINDER_STAT_TRANSACTION,
BINDER_STAT_TRANSACTION_COMPLETE,
BINDER_STAT_COUNT
};
struct binder_stats {
int br[_IOC_NR(BR_FAILED_REPLY) + 1];
int bc[_IOC_NR(BC_DEAD_BINDER_DONE) + 1];
int obj_created[BINDER_STAT_COUNT];
int obj_deleted[BINDER_STAT_COUNT];
};
static struct binder_stats binder_stats;
static inline void binder_stats_deleted(enum binder_stat_types type)
{
binder_stats.obj_deleted[type]++;
}
static inline void binder_stats_created(enum binder_stat_types type)
{
binder_stats.obj_created[type]++;
}
struct binder_transaction_log_entry {
int debug_id;
int call_type;
int from_proc;
int from_thread;
int target_handle;
int to_proc;
int to_thread;
int to_node;
int data_size;
int offsets_size;
};
struct binder_transaction_log {
int next;
int full;
struct binder_transaction_log_entry entry[32];
};
static struct binder_transaction_log binder_transaction_log;
static struct binder_transaction_log binder_transaction_log_failed;
static struct binder_transaction_log_entry *binder_transaction_log_add(
struct binder_transaction_log *log)
{
struct binder_transaction_log_entry *e;
e = &log->entry[log->next];
memset(e, 0, sizeof(*e));
log->next++;
if (log->next == ARRAY_SIZE(log->entry)) {
log->next = 0;
log->full = 1;
}
return e;
}
struct binder_work {
struct list_head entry;
enum {
BINDER_WORK_TRANSACTION = 1,
BINDER_WORK_TRANSACTION_COMPLETE,
BINDER_WORK_NODE,
BINDER_WORK_DEAD_BINDER,
BINDER_WORK_DEAD_BINDER_AND_CLEAR,
BINDER_WORK_CLEAR_DEATH_NOTIFICATION,
} type;
};
struct binder_node {
int debug_id;
struct binder_work work;
union {
struct rb_node rb_node;
struct hlist_node dead_node;
};
struct binder_proc *proc;
struct hlist_head refs;
int internal_strong_refs;
int local_weak_refs;
int local_strong_refs;
binder_uintptr_t ptr;
binder_uintptr_t cookie;
unsigned has_strong_ref:1;
unsigned pending_strong_ref:1;
unsigned has_weak_ref:1;
unsigned pending_weak_ref:1;
unsigned has_async_transaction:1;
unsigned accept_fds:1;
unsigned min_priority:8;
struct list_head async_todo;
};
struct binder_ref_death {
struct binder_work work;
binder_uintptr_t cookie;
};
struct binder_ref {
/* Lookups needed: */
/* node + proc => ref (transaction) */
/* desc + proc => ref (transaction, inc/dec ref) */
/* node => refs + procs (proc exit) */
int debug_id;
struct rb_node rb_node_desc;
struct rb_node rb_node_node;
struct hlist_node node_entry;
struct binder_proc *proc;
struct binder_node *node;
uint32_t desc;
int strong;
int weak;
struct binder_ref_death *death;
};
struct binder_buffer {
struct list_head entry; /* free and allocated entries by address */
struct rb_node rb_node; /* free entry by size or allocated entry */
/* by address */
unsigned free:1;
unsigned allow_user_free:1;
unsigned async_transaction:1;
unsigned debug_id:29;
struct binder_transaction *transaction;
struct binder_node *target_node;
size_t data_size;
size_t offsets_size;
uint8_t data[0];
};
enum binder_deferred_state {
BINDER_DEFERRED_PUT_FILES = 0x01,
BINDER_DEFERRED_FLUSH = 0x02,
BINDER_DEFERRED_RELEASE = 0x04,
};
struct binder_proc {
struct hlist_node proc_node;
struct rb_root threads;
struct rb_root nodes;
struct rb_root refs_by_desc;
struct rb_root refs_by_node;
int pid;
struct vm_area_struct *vma;
struct mm_struct *vma_vm_mm;
struct task_struct *tsk;
struct files_struct *files;
struct hlist_node deferred_work_node;
int deferred_work;
void *buffer;
ptrdiff_t user_buffer_offset;
struct list_head buffers;
struct rb_root free_buffers;
struct rb_root allocated_buffers;
size_t free_async_space;
struct page **pages;
size_t buffer_size;
uint32_t buffer_free;
struct list_head todo;
wait_queue_head_t wait;
struct binder_stats stats;
struct list_head delivered_death;
int max_threads;
int requested_threads;
int requested_threads_started;
int ready_threads;
long default_priority;
struct dentry *debugfs_entry;
};
enum {
BINDER_LOOPER_STATE_REGISTERED = 0x01,
BINDER_LOOPER_STATE_ENTERED = 0x02,
BINDER_LOOPER_STATE_EXITED = 0x04,
BINDER_LOOPER_STATE_INVALID = 0x08,
BINDER_LOOPER_STATE_WAITING = 0x10,
BINDER_LOOPER_STATE_NEED_RETURN = 0x20
};
struct binder_thread {
struct binder_proc *proc;
struct rb_node rb_node;
int pid;
int looper;
struct binder_transaction *transaction_stack;
struct list_head todo;
uint32_t return_error; /* Write failed, return error code in read buf */
uint32_t return_error2; /* Write failed, return error code in read */
/* buffer. Used when sending a reply to a dead process that */
/* we are also waiting on */
wait_queue_head_t wait;
struct binder_stats stats;
};
struct binder_transaction {
int debug_id;
struct binder_work work;
struct binder_thread *from;
struct binder_transaction *from_parent;
struct binder_proc *to_proc;
struct binder_thread *to_thread;
struct binder_transaction *to_parent;
unsigned need_reply:1;
/* unsigned is_dead:1; */ /* not used at the moment */
struct binder_buffer *buffer;
unsigned int code;
unsigned int flags;
long priority;
long saved_priority;
kuid_t sender_euid;
};
static void
binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer);
static int task_get_unused_fd_flags(struct binder_proc *proc, int flags)
{
struct files_struct *files = proc->files;
unsigned long rlim_cur;
unsigned long irqs;
if (files == NULL)
return -ESRCH;
if (!lock_task_sighand(proc->tsk, &irqs))
return -EMFILE;
rlim_cur = task_rlimit(proc->tsk, RLIMIT_NOFILE);
unlock_task_sighand(proc->tsk, &irqs);
return __alloc_fd(files, 0, rlim_cur, flags);
}
/*
* copied from fd_install
*/
static void task_fd_install(
struct binder_proc *proc, unsigned int fd, struct file *file)
{
if (proc->files)
__fd_install(proc->files, fd, file);
}
/*
* copied from sys_close
*/
static long task_close_fd(struct binder_proc *proc, unsigned int fd)
{
int retval;
if (proc->files == NULL)
return -ESRCH;
retval = __close_fd(proc->files, fd);
/* can't restart close syscall because file table entry was cleared */
if (unlikely(retval == -ERESTARTSYS ||
retval == -ERESTARTNOINTR ||
retval == -ERESTARTNOHAND ||
retval == -ERESTART_RESTARTBLOCK))
retval = -EINTR;
return retval;
}
static inline void binder_lock(const char *tag)
{
trace_binder_lock(tag);
mutex_lock(&binder_main_lock);
trace_binder_locked(tag);
}
static inline void binder_unlock(const char *tag)
{
trace_binder_unlock(tag);
mutex_unlock(&binder_main_lock);
}
static void binder_set_nice(long nice)
{
long min_nice;
if (can_nice(current, nice)) {
set_user_nice(current, nice);
return;
}
min_nice = 20 - current->signal->rlim[RLIMIT_NICE].rlim_cur;
binder_debug(BINDER_DEBUG_PRIORITY_CAP,
"%d: nice value %ld not allowed use %ld instead\n",
current->pid, nice, min_nice);
set_user_nice(current, min_nice);
if (min_nice < 20)
return;
binder_user_error("%d RLIMIT_NICE not set\n", current->pid);
}
static size_t binder_buffer_size(struct binder_proc *proc,
struct binder_buffer *buffer)
{
if (list_is_last(&buffer->entry, &proc->buffers))
return proc->buffer + proc->buffer_size - (void *)buffer->data;
else
return (size_t)list_entry(buffer->entry.next,
struct binder_buffer, entry) - (size_t)buffer->data;
}
static void binder_insert_free_buffer(struct binder_proc *proc,
struct binder_buffer *new_buffer)
{
struct rb_node **p = &proc->free_buffers.rb_node;
struct rb_node *parent = NULL;
struct binder_buffer *buffer;
size_t buffer_size;
size_t new_buffer_size;
BUG_ON(!new_buffer->free);
new_buffer_size = binder_buffer_size(proc, new_buffer);
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: add free buffer, size %zd, at %p\n",
proc->pid, new_buffer_size, new_buffer);
while (*p) {
parent = *p;
buffer = rb_entry(parent, struct binder_buffer, rb_node);
BUG_ON(!buffer->free);
buffer_size = binder_buffer_size(proc, buffer);
if (new_buffer_size < buffer_size)
p = &parent->rb_left;
else
p = &parent->rb_right;
}
rb_link_node(&new_buffer->rb_node, parent, p);
rb_insert_color(&new_buffer->rb_node, &proc->free_buffers);
}
static void binder_insert_allocated_buffer(struct binder_proc *proc,
struct binder_buffer *new_buffer)
{
struct rb_node **p = &proc->allocated_buffers.rb_node;
struct rb_node *parent = NULL;
struct binder_buffer *buffer;
BUG_ON(new_buffer->free);
while (*p) {
parent = *p;
buffer = rb_entry(parent, struct binder_buffer, rb_node);
BUG_ON(buffer->free);
if (new_buffer < buffer)
p = &parent->rb_left;
else if (new_buffer > buffer)
p = &parent->rb_right;
else
BUG();
}
rb_link_node(&new_buffer->rb_node, parent, p);
rb_insert_color(&new_buffer->rb_node, &proc->allocated_buffers);
}
static struct binder_buffer *binder_buffer_lookup(struct binder_proc *proc,
uintptr_t user_ptr)
{
struct rb_node *n = proc->allocated_buffers.rb_node;
struct binder_buffer *buffer;
struct binder_buffer *kern_ptr;
kern_ptr = (struct binder_buffer *)(user_ptr - proc->user_buffer_offset
- offsetof(struct binder_buffer, data));
while (n) {
buffer = rb_entry(n, struct binder_buffer, rb_node);
BUG_ON(buffer->free);
if (kern_ptr < buffer)
n = n->rb_left;
else if (kern_ptr > buffer)
n = n->rb_right;
else
return buffer;
}
return NULL;
}
static int binder_update_page_range(struct binder_proc *proc, int allocate,
void *start, void *end,
struct vm_area_struct *vma)
{
void *page_addr;
unsigned long user_page_addr;
struct vm_struct tmp_area;
struct page **page;
struct mm_struct *mm;
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: %s pages %p-%p\n", proc->pid,
allocate ? "allocate" : "free", start, end);
if (end <= start)
return 0;
trace_binder_update_page_range(proc, allocate, start, end);
if (vma)
mm = NULL;
else
mm = get_task_mm(proc->tsk);
if (mm) {
down_write(&mm->mmap_sem);
vma = proc->vma;
if (vma && mm != proc->vma_vm_mm) {
pr_err("%d: vma mm and task mm mismatch\n",
proc->pid);
vma = NULL;
}
}
if (allocate == 0)
goto free_range;
if (vma == NULL) {
pr_err("%d: binder_alloc_buf failed to map pages in userspace, no vma\n",
proc->pid);
goto err_no_vma;
}
for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) {
int ret;
struct page **page_array_ptr;
page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];
BUG_ON(*page);
*page = alloc_page(GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO);
if (*page == NULL) {
pr_err("%d: binder_alloc_buf failed for page at %p\n",
proc->pid, page_addr);
goto err_alloc_page_failed;
}
tmp_area.addr = page_addr;
tmp_area.size = PAGE_SIZE + PAGE_SIZE /* guard page? */;
page_array_ptr = page;
ret = map_vm_area(&tmp_area, PAGE_KERNEL, &page_array_ptr);
if (ret) {
pr_err("%d: binder_alloc_buf failed to map page at %p in kernel\n",
proc->pid, page_addr);
goto err_map_kernel_failed;
}
user_page_addr =
(uintptr_t)page_addr + proc->user_buffer_offset;
ret = vm_insert_page(vma, user_page_addr, page[0]);
if (ret) {
pr_err("%d: binder_alloc_buf failed to map page at %lx in userspace\n",
proc->pid, user_page_addr);
goto err_vm_insert_page_failed;
}
/* vm_insert_page does not seem to increment the refcount */
}
if (mm) {
up_write(&mm->mmap_sem);
mmput(mm);
}
return 0;
free_range:
for (page_addr = end - PAGE_SIZE; page_addr >= start;
page_addr -= PAGE_SIZE) {
page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];
if (vma)
zap_page_range(vma, (uintptr_t)page_addr +
proc->user_buffer_offset, PAGE_SIZE, NULL);
err_vm_insert_page_failed:
unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE);
err_map_kernel_failed:
__free_page(*page);
*page = NULL;
err_alloc_page_failed:
;
}
err_no_vma:
if (mm) {
up_write(&mm->mmap_sem);
mmput(mm);
}
return -ENOMEM;
}
static struct binder_buffer *binder_alloc_buf(struct binder_proc *proc,
size_t data_size,
size_t offsets_size, int is_async)
{
struct rb_node *n = proc->free_buffers.rb_node;
struct binder_buffer *buffer;
size_t buffer_size;
struct rb_node *best_fit = NULL;
void *has_page_addr;
void *end_page_addr;
size_t size;
if (proc->vma == NULL) {
pr_err("%d: binder_alloc_buf, no vma\n",
proc->pid);
return NULL;
}
size = ALIGN(data_size, sizeof(void *)) +
ALIGN(offsets_size, sizeof(void *));
if (size < data_size || size < offsets_size) {
binder_user_error("%d: got transaction with invalid size %zd-%zd\n",
proc->pid, data_size, offsets_size);
return NULL;
}
if (is_async &&
proc->free_async_space < size + sizeof(struct binder_buffer)) {
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: binder_alloc_buf size %zd failed, no async space left\n",
proc->pid, size);
return NULL;
}
while (n) {
buffer = rb_entry(n, struct binder_buffer, rb_node);
BUG_ON(!buffer->free);
buffer_size = binder_buffer_size(proc, buffer);
if (size < buffer_size) {
best_fit = n;
n = n->rb_left;
} else if (size > buffer_size)
n = n->rb_right;
else {
best_fit = n;
break;
}
}
if (best_fit == NULL) {
pr_err("%d: binder_alloc_buf size %zd failed, no address space\n",
proc->pid, size);
return NULL;
}
if (n == NULL) {
buffer = rb_entry(best_fit, struct binder_buffer, rb_node);
buffer_size = binder_buffer_size(proc, buffer);
}
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: binder_alloc_buf size %zd got buffer %p size %zd\n",
proc->pid, size, buffer, buffer_size);
has_page_addr =
(void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK);
if (n == NULL) {
if (size + sizeof(struct binder_buffer) + 4 >= buffer_size)
buffer_size = size; /* no room for other buffers */
else
buffer_size = size + sizeof(struct binder_buffer);
}
end_page_addr =
(void *)PAGE_ALIGN((uintptr_t)buffer->data + buffer_size);
if (end_page_addr > has_page_addr)
end_page_addr = has_page_addr;
if (binder_update_page_range(proc, 1,
(void *)PAGE_ALIGN((uintptr_t)buffer->data), end_page_addr, NULL))
return NULL;
rb_erase(best_fit, &proc->free_buffers);
buffer->free = 0;
binder_insert_allocated_buffer(proc, buffer);
if (buffer_size != size) {
struct binder_buffer *new_buffer = (void *)buffer->data + size;
list_add(&new_buffer->entry, &buffer->entry);
new_buffer->free = 1;
binder_insert_free_buffer(proc, new_buffer);
}
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: binder_alloc_buf size %zd got %p\n",
proc->pid, size, buffer);
buffer->data_size = data_size;
buffer->offsets_size = offsets_size;
buffer->async_transaction = is_async;
if (is_async) {
proc->free_async_space -= size + sizeof(struct binder_buffer);
binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC,
"%d: binder_alloc_buf size %zd async free %zd\n",
proc->pid, size, proc->free_async_space);
}
return buffer;
}
static void *buffer_start_page(struct binder_buffer *buffer)
{
return (void *)((uintptr_t)buffer & PAGE_MASK);
}
static void *buffer_end_page(struct binder_buffer *buffer)
{
return (void *)(((uintptr_t)(buffer + 1) - 1) & PAGE_MASK);
}
static void binder_delete_free_buffer(struct binder_proc *proc,
struct binder_buffer *buffer)
{
struct binder_buffer *prev, *next = NULL;
int free_page_end = 1;
int free_page_start = 1;
BUG_ON(proc->buffers.next == &buffer->entry);
prev = list_entry(buffer->entry.prev, struct binder_buffer, entry);
BUG_ON(!prev->free);
if (buffer_end_page(prev) == buffer_start_page(buffer)) {
free_page_start = 0;
if (buffer_end_page(prev) == buffer_end_page(buffer))
free_page_end = 0;
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: merge free, buffer %p share page with %p\n",
proc->pid, buffer, prev);
}
if (!list_is_last(&buffer->entry, &proc->buffers)) {
next = list_entry(buffer->entry.next,
struct binder_buffer, entry);
if (buffer_start_page(next) == buffer_end_page(buffer)) {
free_page_end = 0;
if (buffer_start_page(next) ==
buffer_start_page(buffer))
free_page_start = 0;
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: merge free, buffer %p share page with %p\n",
proc->pid, buffer, prev);
}
}
list_del(&buffer->entry);
if (free_page_start || free_page_end) {
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: merge free, buffer %p do not share page%s%s with %p or %p\n",
proc->pid, buffer, free_page_start ? "" : " end",
free_page_end ? "" : " start", prev, next);
binder_update_page_range(proc, 0, free_page_start ?
buffer_start_page(buffer) : buffer_end_page(buffer),
(free_page_end ? buffer_end_page(buffer) :
buffer_start_page(buffer)) + PAGE_SIZE, NULL);
}
}
static void binder_free_buf(struct binder_proc *proc,
struct binder_buffer *buffer)
{
size_t size, buffer_size;
buffer_size = binder_buffer_size(proc, buffer);
size = ALIGN(buffer->data_size, sizeof(void *)) +
ALIGN(buffer->offsets_size, sizeof(void *));
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%d: binder_free_buf %p size %zd buffer_size %zd\n",
proc->pid, buffer, size, buffer_size);
BUG_ON(buffer->free);
BUG_ON(size > buffer_size);
BUG_ON(buffer->transaction != NULL);
BUG_ON((void *)buffer < proc->buffer);
BUG_ON((void *)buffer > proc->buffer + proc->buffer_size);
if (buffer->async_transaction) {
proc->free_async_space += size + sizeof(struct binder_buffer);
binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC,
"%d: binder_free_buf size %zd async free %zd\n",
proc->pid, size, proc->free_async_space);
}
binder_update_page_range(proc, 0,
(void *)PAGE_ALIGN((uintptr_t)buffer->data),
(void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK),
NULL);
rb_erase(&buffer->rb_node, &proc->allocated_buffers);
buffer->free = 1;
if (!list_is_last(&buffer->entry, &proc->buffers)) {
struct binder_buffer *next = list_entry(buffer->entry.next,
struct binder_buffer, entry);
if (next->free) {
rb_erase(&next->rb_node, &proc->free_buffers);
binder_delete_free_buffer(proc, next);
}
}
if (proc->buffers.next != &buffer->entry) {
struct binder_buffer *prev = list_entry(buffer->entry.prev,
struct binder_buffer, entry);
if (prev->free) {
binder_delete_free_buffer(proc, buffer);
rb_erase(&prev->rb_node, &proc->free_buffers);
buffer = prev;
}
}
binder_insert_free_buffer(proc, buffer);
}
static struct binder_node *binder_get_node(struct binder_proc *proc,
binder_uintptr_t ptr)
{
struct rb_node *n = proc->nodes.rb_node;
struct binder_node *node;
while (n) {
node = rb_entry(n, struct binder_node, rb_node);
if (ptr < node->ptr)
n = n->rb_left;
else if (ptr > node->ptr)
n = n->rb_right;
else
return node;
}
return NULL;
}
static struct binder_node *binder_new_node(struct binder_proc *proc,
binder_uintptr_t ptr,
binder_uintptr_t cookie)
{
struct rb_node **p = &proc->nodes.rb_node;
struct rb_node *parent = NULL;
struct binder_node *node;
while (*p) {
parent = *p;
node = rb_entry(parent, struct binder_node, rb_node);
if (ptr < node->ptr)
p = &(*p)->rb_left;
else if (ptr > node->ptr)
p = &(*p)->rb_right;
else
return NULL;
}
node = kzalloc(sizeof(*node), GFP_KERNEL);
if (node == NULL)
return NULL;
binder_stats_created(BINDER_STAT_NODE);
rb_link_node(&node->rb_node, parent, p);
rb_insert_color(&node->rb_node, &proc->nodes);
node->debug_id = ++binder_last_id;
node->proc = proc;
node->ptr = ptr;
node->cookie = cookie;
node->work.type = BINDER_WORK_NODE;
INIT_LIST_HEAD(&node->work.entry);
INIT_LIST_HEAD(&node->async_todo);
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"%d:%d node %d u%016llx c%016llx created\n",
proc->pid, current->pid, node->debug_id,
(u64)node->ptr, (u64)node->cookie);
return node;
}
static int binder_inc_node(struct binder_node *node, int strong, int internal,
struct list_head *target_list)
{
if (strong) {
if (internal) {
if (target_list == NULL &&
node->internal_strong_refs == 0 &&
!(node == binder_context_mgr_node &&
node->has_strong_ref)) {
pr_err("invalid inc strong node for %d\n",
node->debug_id);
return -EINVAL;
}
node->internal_strong_refs++;
} else
node->local_strong_refs++;
if (!node->has_strong_ref && target_list) {
list_del_init(&node->work.entry);
list_add_tail(&node->work.entry, target_list);
}
} else {
if (!internal)
node->local_weak_refs++;
if (!node->has_weak_ref && list_empty(&node->work.entry)) {
if (target_list == NULL) {
pr_err("invalid inc weak node for %d\n",
node->debug_id);
return -EINVAL;
}
list_add_tail(&node->work.entry, target_list);
}
}
return 0;
}
static int binder_dec_node(struct binder_node *node, int strong, int internal)
{
if (strong) {
if (internal)
node->internal_strong_refs--;
else
node->local_strong_refs--;
if (node->local_strong_refs || node->internal_strong_refs)
return 0;
} else {
if (!internal)
node->local_weak_refs--;
if (node->local_weak_refs || !hlist_empty(&node->refs))
return 0;
}
if (node->proc && (node->has_strong_ref || node->has_weak_ref)) {
if (list_empty(&node->work.entry)) {
list_add_tail(&node->work.entry, &node->proc->todo);
wake_up_interruptible(&node->proc->wait);
}
} else {
if (hlist_empty(&node->refs) && !node->local_strong_refs &&
!node->local_weak_refs) {
list_del_init(&node->work.entry);
if (node->proc) {
rb_erase(&node->rb_node, &node->proc->nodes);
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"refless node %d deleted\n",
node->debug_id);
} else {
hlist_del(&node->dead_node);
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"dead node %d deleted\n",
node->debug_id);
}
kfree(node);
binder_stats_deleted(BINDER_STAT_NODE);
}
}
return 0;
}
static struct binder_ref *binder_get_ref(struct binder_proc *proc,
uint32_t desc)
{
struct rb_node *n = proc->refs_by_desc.rb_node;
struct binder_ref *ref;
while (n) {
ref = rb_entry(n, struct binder_ref, rb_node_desc);
if (desc < ref->desc)
n = n->rb_left;
else if (desc > ref->desc)
n = n->rb_right;
else
return ref;
}
return NULL;
}
static struct binder_ref *binder_get_ref_for_node(struct binder_proc *proc,
struct binder_node *node)
{
struct rb_node *n;
struct rb_node **p = &proc->refs_by_node.rb_node;
struct rb_node *parent = NULL;
struct binder_ref *ref, *new_ref;
while (*p) {
parent = *p;
ref = rb_entry(parent, struct binder_ref, rb_node_node);
if (node < ref->node)
p = &(*p)->rb_left;
else if (node > ref->node)
p = &(*p)->rb_right;
else
return ref;
}
new_ref = kzalloc(sizeof(*ref), GFP_KERNEL);
if (new_ref == NULL)
return NULL;
binder_stats_created(BINDER_STAT_REF);
new_ref->debug_id = ++binder_last_id;
new_ref->proc = proc;
new_ref->node = node;
rb_link_node(&new_ref->rb_node_node, parent, p);
rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node);
new_ref->desc = (node == binder_context_mgr_node) ? 0 : 1;
for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
ref = rb_entry(n, struct binder_ref, rb_node_desc);
if (ref->desc > new_ref->desc)
break;
new_ref->desc = ref->desc + 1;
}
p = &proc->refs_by_desc.rb_node;
while (*p) {
parent = *p;
ref = rb_entry(parent, struct binder_ref, rb_node_desc);
if (new_ref->desc < ref->desc)
p = &(*p)->rb_left;
else if (new_ref->desc > ref->desc)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new_ref->rb_node_desc, parent, p);
rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc);
if (node) {
hlist_add_head(&new_ref->node_entry, &node->refs);
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"%d new ref %d desc %d for node %d\n",
proc->pid, new_ref->debug_id, new_ref->desc,
node->debug_id);
} else {
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"%d new ref %d desc %d for dead node\n",
proc->pid, new_ref->debug_id, new_ref->desc);
}
return new_ref;
}
static void binder_delete_ref(struct binder_ref *ref)
{
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"%d delete ref %d desc %d for node %d\n",
ref->proc->pid, ref->debug_id, ref->desc,
ref->node->debug_id);
rb_erase(&ref->rb_node_desc, &ref->proc->refs_by_desc);
rb_erase(&ref->rb_node_node, &ref->proc->refs_by_node);
if (ref->strong)
binder_dec_node(ref->node, 1, 1);
hlist_del(&ref->node_entry);
binder_dec_node(ref->node, 0, 1);
if (ref->death) {
binder_debug(BINDER_DEBUG_DEAD_BINDER,
"%d delete ref %d desc %d has death notification\n",
ref->proc->pid, ref->debug_id, ref->desc);
list_del(&ref->death->work.entry);
kfree(ref->death);
binder_stats_deleted(BINDER_STAT_DEATH);
}
kfree(ref);
binder_stats_deleted(BINDER_STAT_REF);
}
static int binder_inc_ref(struct binder_ref *ref, int strong,
struct list_head *target_list)
{
int ret;
if (strong) {
if (ref->strong == 0) {
ret = binder_inc_node(ref->node, 1, 1, target_list);
if (ret)
return ret;
}
ref->strong++;
} else {
if (ref->weak == 0) {
ret = binder_inc_node(ref->node, 0, 1, target_list);
if (ret)
return ret;
}
ref->weak++;
}
return 0;
}
static int binder_dec_ref(struct binder_ref **ptr_to_ref, int strong)
{
struct binder_ref *ref = *ptr_to_ref;
if (strong) {
if (ref->strong == 0) {
binder_user_error("%d invalid dec strong, ref %d desc %d s %d w %d\n",
ref->proc->pid, ref->debug_id,
ref->desc, ref->strong, ref->weak);
return -EINVAL;
}
ref->strong--;
if (ref->strong == 0) {
int ret;
ret = binder_dec_node(ref->node, strong, 1);
if (ret)
return ret;
}
} else {
if (ref->weak == 0) {
binder_user_error("%d invalid dec weak, ref %d desc %d s %d w %d\n",
ref->proc->pid, ref->debug_id,
ref->desc, ref->strong, ref->weak);
return -EINVAL;
}
ref->weak--;
}
if (ref->strong == 0 && ref->weak == 0) {
binder_delete_ref(ref);
*ptr_to_ref = NULL;
}
return 0;
}
static void binder_pop_transaction(struct binder_thread *target_thread,
struct binder_transaction *t)
{
if (target_thread) {
BUG_ON(target_thread->transaction_stack != t);
BUG_ON(target_thread->transaction_stack->from != target_thread);
target_thread->transaction_stack =
target_thread->transaction_stack->from_parent;
t->from = NULL;
}
t->need_reply = 0;
if (t->buffer)
t->buffer->transaction = NULL;
kfree(t);
binder_stats_deleted(BINDER_STAT_TRANSACTION);
}
static void binder_send_failed_reply(struct binder_transaction *t,
uint32_t error_code)
{
struct binder_thread *target_thread;
BUG_ON(t->flags & TF_ONE_WAY);
while (1) {
target_thread = t->from;
if (target_thread) {
if (target_thread->return_error != BR_OK &&
target_thread->return_error2 == BR_OK) {
target_thread->return_error2 =
target_thread->return_error;
target_thread->return_error = BR_OK;
}
if (target_thread->return_error == BR_OK) {
binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
"send failed reply for transaction %d to %d:%d\n",
t->debug_id, target_thread->proc->pid,
target_thread->pid);
binder_pop_transaction(target_thread, t);
target_thread->return_error = error_code;
wake_up_interruptible(&target_thread->wait);
} else {
pr_err("reply failed, target thread, %d:%d, has error code %d already\n",
target_thread->proc->pid,
target_thread->pid,
target_thread->return_error);
}
return;
} else {
struct binder_transaction *next = t->from_parent;
binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
"send failed reply for transaction %d, target dead\n",
t->debug_id);
binder_pop_transaction(target_thread, t);
if (next == NULL) {
binder_debug(BINDER_DEBUG_DEAD_BINDER,
"reply failed, no target thread at root\n");
return;
}
t = next;
binder_debug(BINDER_DEBUG_DEAD_BINDER,
"reply failed, no target thread -- retry %d\n",
t->debug_id);
}
}
}
static void binder_transaction_buffer_release(struct binder_proc *proc,
struct binder_buffer *buffer,
binder_size_t *failed_at)
{
binder_size_t *offp, *off_end;
int debug_id = buffer->debug_id;
binder_debug(BINDER_DEBUG_TRANSACTION,
"%d buffer release %d, size %zd-%zd, failed at %p\n",
proc->pid, buffer->debug_id,
buffer->data_size, buffer->offsets_size, failed_at);
if (buffer->target_node)
binder_dec_node(buffer->target_node, 1, 0);
offp = (binder_size_t *)(buffer->data +
ALIGN(buffer->data_size, sizeof(void *)));
if (failed_at)
off_end = failed_at;
else
off_end = (void *)offp + buffer->offsets_size;
for (; offp < off_end; offp++) {
struct flat_binder_object *fp;
if (*offp > buffer->data_size - sizeof(*fp) ||
buffer->data_size < sizeof(*fp) ||
!IS_ALIGNED(*offp, sizeof(u32))) {
pr_err("transaction release %d bad offset %lld, size %zd\n",
debug_id, (u64)*offp, buffer->data_size);
continue;
}
fp = (struct flat_binder_object *)(buffer->data + *offp);
switch (fp->type) {
case BINDER_TYPE_BINDER:
case BINDER_TYPE_WEAK_BINDER: {
struct binder_node *node = binder_get_node(proc, fp->binder);
if (node == NULL) {
pr_err("transaction release %d bad node %016llx\n",
debug_id, (u64)fp->binder);
break;
}
binder_debug(BINDER_DEBUG_TRANSACTION,
" node %d u%016llx\n",
node->debug_id, (u64)node->ptr);
binder_dec_node(node, fp->type == BINDER_TYPE_BINDER, 0);
} break;
case BINDER_TYPE_HANDLE:
case BINDER_TYPE_WEAK_HANDLE: {
struct binder_ref *ref = binder_get_ref(proc, fp->handle);
if (ref == NULL) {
pr_err("transaction release %d bad handle %d\n",
debug_id, fp->handle);
break;
}
binder_debug(BINDER_DEBUG_TRANSACTION,
" ref %d desc %d (node %d)\n",
ref->debug_id, ref->desc, ref->node->debug_id);
binder_dec_ref(&ref, fp->type == BINDER_TYPE_HANDLE);
} break;
case BINDER_TYPE_FD:
binder_debug(BINDER_DEBUG_TRANSACTION,
" fd %d\n", fp->handle);
if (failed_at)
task_close_fd(proc, fp->handle);
break;
default:
pr_err("transaction release %d bad object type %x\n",
debug_id, fp->type);
break;
}
}
}
static void binder_transaction(struct binder_proc *proc,
struct binder_thread *thread,
struct binder_transaction_data *tr, int reply)
{
struct binder_transaction *t;
struct binder_work *tcomplete;
binder_size_t *offp, *off_end;
binder_size_t off_min;
struct binder_proc *target_proc;
struct binder_thread *target_thread = NULL;
struct binder_node *target_node = NULL;
struct list_head *target_list;
wait_queue_head_t *target_wait;
struct binder_transaction *in_reply_to = NULL;
struct binder_transaction_log_entry *e;
uint32_t return_error;
e = binder_transaction_log_add(&binder_transaction_log);
e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
e->from_proc = proc->pid;
e->from_thread = thread->pid;
e->target_handle = tr->target.handle;
e->data_size = tr->data_size;
e->offsets_size = tr->offsets_size;
if (reply) {
in_reply_to = thread->transaction_stack;
if (in_reply_to == NULL) {
binder_user_error("%d:%d got reply transaction with no transaction stack\n",
proc->pid, thread->pid);
return_error = BR_FAILED_REPLY;
goto err_empty_call_stack;
}
binder_set_nice(in_reply_to->saved_priority);
if (in_reply_to->to_thread != thread) {
binder_user_error("%d:%d got reply transaction with bad transaction stack, transaction %d has target %d:%d\n",
proc->pid, thread->pid, in_reply_to->debug_id,
in_reply_to->to_proc ?
in_reply_to->to_proc->pid : 0,
in_reply_to->to_thread ?
in_reply_to->to_thread->pid : 0);
return_error = BR_FAILED_REPLY;
in_reply_to = NULL;
goto err_bad_call_stack;
}
thread->transaction_stack = in_reply_to->to_parent;
target_thread = in_reply_to->from;
if (target_thread == NULL) {
return_error = BR_DEAD_REPLY;
goto err_dead_binder;
}
if (target_thread->transaction_stack != in_reply_to) {
binder_user_error("%d:%d got reply transaction with bad target transaction stack %d, expected %d\n",
proc->pid, thread->pid,
target_thread->transaction_stack ?
target_thread->transaction_stack->debug_id : 0,
in_reply_to->debug_id);
return_error = BR_FAILED_REPLY;
in_reply_to = NULL;
target_thread = NULL;
goto err_dead_binder;
}
target_proc = target_thread->proc;
} else {
if (tr->target.handle) {
struct binder_ref *ref;
ref = binder_get_ref(proc, tr->target.handle);
if (ref == NULL) {
binder_user_error("%d:%d got transaction to invalid handle\n",
proc->pid, thread->pid);
return_error = BR_FAILED_REPLY;
goto err_invalid_target_handle;
}
target_node = ref->node;
} else {
target_node = binder_context_mgr_node;
if (target_node == NULL) {
return_error = BR_DEAD_REPLY;
goto err_no_context_mgr_node;
}
}
e->to_node = target_node->debug_id;
target_proc = target_node->proc;
if (target_proc == NULL) {
return_error = BR_DEAD_REPLY;
goto err_dead_binder;
}
if (security_binder_transaction(proc->tsk, target_proc->tsk) < 0) {
return_error = BR_FAILED_REPLY;
goto err_invalid_target_handle;
}
if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) {
struct binder_transaction *tmp;
tmp = thread->transaction_stack;
if (tmp->to_thread != thread) {
binder_user_error("%d:%d got new transaction with bad transaction stack, transaction %d has target %d:%d\n",
proc->pid, thread->pid, tmp->debug_id,
tmp->to_proc ? tmp->to_proc->pid : 0,
tmp->to_thread ?
tmp->to_thread->pid : 0);
return_error = BR_FAILED_REPLY;
goto err_bad_call_stack;
}
while (tmp) {
if (tmp->from && tmp->from->proc == target_proc)
target_thread = tmp->from;
tmp = tmp->from_parent;
}
}
}
if (target_thread) {
e->to_thread = target_thread->pid;
target_list = &target_thread->todo;
target_wait = &target_thread->wait;
} else {
target_list = &target_proc->todo;
target_wait = &target_proc->wait;
}
e->to_proc = target_proc->pid;
/* TODO: reuse incoming transaction for reply */
t = kzalloc(sizeof(*t), GFP_KERNEL);
if (t == NULL) {
return_error = BR_FAILED_REPLY;
goto err_alloc_t_failed;
}
binder_stats_created(BINDER_STAT_TRANSACTION);
tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);
if (tcomplete == NULL) {
return_error = BR_FAILED_REPLY;
goto err_alloc_tcomplete_failed;
}
binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE);
t->debug_id = ++binder_last_id;
e->debug_id = t->debug_id;
if (reply)
binder_debug(BINDER_DEBUG_TRANSACTION,
"%d:%d BC_REPLY %d -> %d:%d, data %016llx-%016llx size %lld-%lld\n",
proc->pid, thread->pid, t->debug_id,
target_proc->pid, target_thread->pid,
(u64)tr->data.ptr.buffer,
(u64)tr->data.ptr.offsets,
(u64)tr->data_size, (u64)tr->offsets_size);
else
binder_debug(BINDER_DEBUG_TRANSACTION,
"%d:%d BC_TRANSACTION %d -> %d - node %d, data %016llx-%016llx size %lld-%lld\n",
proc->pid, thread->pid, t->debug_id,
target_proc->pid, target_node->debug_id,
(u64)tr->data.ptr.buffer,
(u64)tr->data.ptr.offsets,
(u64)tr->data_size, (u64)tr->offsets_size);
if (!reply && !(tr->flags & TF_ONE_WAY))
t->from = thread;
else
t->from = NULL;
t->sender_euid = proc->tsk->cred->euid;
t->to_proc = target_proc;
t->to_thread = target_thread;
t->code = tr->code;
t->flags = tr->flags;
t->priority = task_nice(current);
trace_binder_transaction(reply, t, target_node);
t->buffer = binder_alloc_buf(target_proc, tr->data_size,
tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));
if (t->buffer == NULL) {
return_error = BR_FAILED_REPLY;
goto err_binder_alloc_buf_failed;
}
t->buffer->allow_user_free = 0;
t->buffer->debug_id = t->debug_id;
t->buffer->transaction = t;
t->buffer->target_node = target_node;
trace_binder_transaction_alloc_buf(t->buffer);
if (target_node)
binder_inc_node(target_node, 1, 0, NULL);
offp = (binder_size_t *)(t->buffer->data +
ALIGN(tr->data_size, sizeof(void *)));
if (copy_from_user(t->buffer->data, (const void __user *)(uintptr_t)
tr->data.ptr.buffer, tr->data_size)) {
binder_user_error("%d:%d got transaction with invalid data ptr\n",
proc->pid, thread->pid);
return_error = BR_FAILED_REPLY;
goto err_copy_data_failed;
}
if (copy_from_user(offp, (const void __user *)(uintptr_t)
tr->data.ptr.offsets, tr->offsets_size)) {
binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
proc->pid, thread->pid);
return_error = BR_FAILED_REPLY;
goto err_copy_data_failed;
}
if (!IS_ALIGNED(tr->offsets_size, sizeof(binder_size_t))) {
binder_user_error("%d:%d got transaction with invalid offsets size, %lld\n",
proc->pid, thread->pid, (u64)tr->offsets_size);
return_error = BR_FAILED_REPLY;
goto err_bad_offset;
}
off_end = (void *)offp + tr->offsets_size;
off_min = 0;
for (; offp < off_end; offp++) {
struct flat_binder_object *fp;
if (*offp > t->buffer->data_size - sizeof(*fp) ||
*offp < off_min ||
t->buffer->data_size < sizeof(*fp) ||
!IS_ALIGNED(*offp, sizeof(u32))) {
binder_user_error("%d:%d got transaction with invalid offset, %lld (min %lld, max %lld)\n",
proc->pid, thread->pid, (u64)*offp,
(u64)off_min,
(u64)(t->buffer->data_size -
sizeof(*fp)));
return_error = BR_FAILED_REPLY;
goto err_bad_offset;
}
fp = (struct flat_binder_object *)(t->buffer->data + *offp);
off_min = *offp + sizeof(struct flat_binder_object);
switch (fp->type) {
case BINDER_TYPE_BINDER:
case BINDER_TYPE_WEAK_BINDER: {
struct binder_ref *ref;
struct binder_node *node = binder_get_node(proc, fp->binder);
if (node == NULL) {
node = binder_new_node(proc, fp->binder, fp->cookie);
if (node == NULL) {
return_error = BR_FAILED_REPLY;
goto err_binder_new_node_failed;
}
node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;
node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);
}
if (fp->cookie != node->cookie) {
binder_user_error("%d:%d sending u%016llx node %d, cookie mismatch %016llx != %016llx\n",
proc->pid, thread->pid,
(u64)fp->binder, node->debug_id,
(u64)fp->cookie, (u64)node->cookie);
goto err_binder_get_ref_for_node_failed;
}
if (security_binder_transfer_binder(proc->tsk, target_proc->tsk)) {
return_error = BR_FAILED_REPLY;
goto err_binder_get_ref_for_node_failed;
}
ref = binder_get_ref_for_node(target_proc, node);
if (ref == NULL) {
return_error = BR_FAILED_REPLY;
goto err_binder_get_ref_for_node_failed;
}
if (fp->type == BINDER_TYPE_BINDER)
fp->type = BINDER_TYPE_HANDLE;
else
fp->type = BINDER_TYPE_WEAK_HANDLE;
fp->handle = ref->desc;
binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE,
&thread->todo);
trace_binder_transaction_node_to_ref(t, node, ref);
binder_debug(BINDER_DEBUG_TRANSACTION,
" node %d u%016llx -> ref %d desc %d\n",
node->debug_id, (u64)node->ptr,
ref->debug_id, ref->desc);
} break;
case BINDER_TYPE_HANDLE:
case BINDER_TYPE_WEAK_HANDLE: {
struct binder_ref *ref = binder_get_ref(proc, fp->handle);
if (ref == NULL) {
binder_user_error("%d:%d got transaction with invalid handle, %d\n",
proc->pid,
thread->pid, fp->handle);
return_error = BR_FAILED_REPLY;
goto err_binder_get_ref_failed;
}
if (security_binder_transfer_binder(proc->tsk, target_proc->tsk)) {
return_error = BR_FAILED_REPLY;
goto err_binder_get_ref_failed;
}
if (ref->node->proc == target_proc) {
if (fp->type == BINDER_TYPE_HANDLE)
fp->type = BINDER_TYPE_BINDER;
else
fp->type = BINDER_TYPE_WEAK_BINDER;
fp->binder = ref->node->ptr;
fp->cookie = ref->node->cookie;
binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);
trace_binder_transaction_ref_to_node(t, ref);
binder_debug(BINDER_DEBUG_TRANSACTION,
" ref %d desc %d -> node %d u%016llx\n",
ref->debug_id, ref->desc, ref->node->debug_id,
(u64)ref->node->ptr);
} else {
struct binder_ref *new_ref;
new_ref = binder_get_ref_for_node(target_proc, ref->node);
if (new_ref == NULL) {
return_error = BR_FAILED_REPLY;
goto err_binder_get_ref_for_node_failed;
}
fp->handle = new_ref->desc;
binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);
trace_binder_transaction_ref_to_ref(t, ref,
new_ref);
binder_debug(BINDER_DEBUG_TRANSACTION,
" ref %d desc %d -> ref %d desc %d (node %d)\n",
ref->debug_id, ref->desc, new_ref->debug_id,
new_ref->desc, ref->node->debug_id);
}
} break;
case BINDER_TYPE_FD: {
int target_fd;
struct file *file;
if (reply) {
if (!(in_reply_to->flags & TF_ACCEPT_FDS)) {
binder_user_error("%d:%d got reply with fd, %d, but target does not allow fds\n",
proc->pid, thread->pid, fp->handle);
return_error = BR_FAILED_REPLY;
goto err_fd_not_allowed;
}
} else if (!target_node->accept_fds) {
binder_user_error("%d:%d got transaction with fd, %d, but target does not allow fds\n",
proc->pid, thread->pid, fp->handle);
return_error = BR_FAILED_REPLY;
goto err_fd_not_allowed;
}
file = fget(fp->handle);
if (file == NULL) {
binder_user_error("%d:%d got transaction with invalid fd, %d\n",
proc->pid, thread->pid, fp->handle);
return_error = BR_FAILED_REPLY;
goto err_fget_failed;
}
if (security_binder_transfer_file(proc->tsk, target_proc->tsk, file) < 0) {
fput(file);
return_error = BR_FAILED_REPLY;
goto err_get_unused_fd_failed;
}
target_fd = task_get_unused_fd_flags(target_proc, O_CLOEXEC);
if (target_fd < 0) {
fput(file);
return_error = BR_FAILED_REPLY;
goto err_get_unused_fd_failed;
}
task_fd_install(target_proc, target_fd, file);
trace_binder_transaction_fd(t, fp->handle, target_fd);
binder_debug(BINDER_DEBUG_TRANSACTION,
" fd %d -> %d\n", fp->handle, target_fd);
/* TODO: fput? */
fp->handle = target_fd;
} break;
default:
binder_user_error("%d:%d got transaction with invalid object type, %x\n",
proc->pid, thread->pid, fp->type);
return_error = BR_FAILED_REPLY;
goto err_bad_object_type;
}
}
if (reply) {
BUG_ON(t->buffer->async_transaction != 0);
binder_pop_transaction(target_thread, in_reply_to);
} else if (!(t->flags & TF_ONE_WAY)) {
BUG_ON(t->buffer->async_transaction != 0);
t->need_reply = 1;
t->from_parent = thread->transaction_stack;
thread->transaction_stack = t;
} else {
BUG_ON(target_node == NULL);
BUG_ON(t->buffer->async_transaction != 1);
if (target_node->has_async_transaction) {
target_list = &target_node->async_todo;
target_wait = NULL;
} else
target_node->has_async_transaction = 1;
}
t->work.type = BINDER_WORK_TRANSACTION;
list_add_tail(&t->work.entry, target_list);
tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;
list_add_tail(&tcomplete->entry, &thread->todo);
if (target_wait)
wake_up_interruptible(target_wait);
return;
err_get_unused_fd_failed:
err_fget_failed:
err_fd_not_allowed:
err_binder_get_ref_for_node_failed:
err_binder_get_ref_failed:
err_binder_new_node_failed:
err_bad_object_type:
err_bad_offset:
err_copy_data_failed:
trace_binder_transaction_failed_buffer_release(t->buffer);
binder_transaction_buffer_release(target_proc, t->buffer, offp);
t->buffer->transaction = NULL;
binder_free_buf(target_proc, t->buffer);
err_binder_alloc_buf_failed:
kfree(tcomplete);
binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
err_alloc_tcomplete_failed:
kfree(t);
binder_stats_deleted(BINDER_STAT_TRANSACTION);
err_alloc_t_failed:
err_bad_call_stack:
err_empty_call_stack:
err_dead_binder:
err_invalid_target_handle:
err_no_context_mgr_node:
binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
"%d:%d transaction failed %d, size %lld-%lld\n",
proc->pid, thread->pid, return_error,
(u64)tr->data_size, (u64)tr->offsets_size);
{
struct binder_transaction_log_entry *fe;
fe = binder_transaction_log_add(&binder_transaction_log_failed);
*fe = *e;
}
BUG_ON(thread->return_error != BR_OK);
if (in_reply_to) {
thread->return_error = BR_TRANSACTION_COMPLETE;
binder_send_failed_reply(in_reply_to, return_error);
} else
thread->return_error = return_error;
}
static int binder_thread_write(struct binder_proc *proc,
struct binder_thread *thread,
binder_uintptr_t binder_buffer, size_t size,
binder_size_t *consumed)
{
uint32_t cmd;
void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
void __user *ptr = buffer + *consumed;
void __user *end = buffer + size;
while (ptr < end && thread->return_error == BR_OK) {
if (get_user(cmd, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
trace_binder_command(cmd);
if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
binder_stats.bc[_IOC_NR(cmd)]++;
proc->stats.bc[_IOC_NR(cmd)]++;
thread->stats.bc[_IOC_NR(cmd)]++;
}
switch (cmd) {
case BC_INCREFS:
case BC_ACQUIRE:
case BC_RELEASE:
case BC_DECREFS: {
uint32_t target;
struct binder_ref *ref;
const char *debug_string;
if (get_user(target, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
if (target == 0 && binder_context_mgr_node &&
(cmd == BC_INCREFS || cmd == BC_ACQUIRE)) {
ref = binder_get_ref_for_node(proc,
binder_context_mgr_node);
if (ref->desc != target) {
binder_user_error("%d:%d tried to acquire reference to desc 0, got %d instead\n",
proc->pid, thread->pid,
ref->desc);
}
} else
ref = binder_get_ref(proc, target);
if (ref == NULL) {
binder_user_error("%d:%d refcount change on invalid ref %d\n",
proc->pid, thread->pid, target);
break;
}
switch (cmd) {
case BC_INCREFS:
debug_string = "IncRefs";
binder_inc_ref(ref, 0, NULL);
break;
case BC_ACQUIRE:
debug_string = "Acquire";
binder_inc_ref(ref, 1, NULL);
break;
case BC_RELEASE:
debug_string = "Release";
binder_dec_ref(&ref, 1);
break;
case BC_DECREFS:
default:
debug_string = "DecRefs";
binder_dec_ref(&ref, 0);
break;
}
if (ref == NULL) {
binder_debug(BINDER_DEBUG_USER_REFS,
"binder: %d:%d %s ref deleted",
proc->pid, thread->pid, debug_string);
} else {
binder_debug(BINDER_DEBUG_USER_REFS,
"binder: %d:%d %s ref %d desc %d s %d w %d for node %d\n",
proc->pid, thread->pid, debug_string,
ref->debug_id, ref->desc, ref->strong,
ref->weak, ref->node->debug_id);
}
break;
}
case BC_INCREFS_DONE:
case BC_ACQUIRE_DONE: {
binder_uintptr_t node_ptr;
binder_uintptr_t cookie;
struct binder_node *node;
if (get_user(node_ptr, (binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
if (get_user(cookie, (binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
node = binder_get_node(proc, node_ptr);
if (node == NULL) {
binder_user_error("%d:%d %s u%016llx no match\n",
proc->pid, thread->pid,
cmd == BC_INCREFS_DONE ?
"BC_INCREFS_DONE" :
"BC_ACQUIRE_DONE",
(u64)node_ptr);
break;
}
if (cookie != node->cookie) {
binder_user_error("%d:%d %s u%016llx node %d cookie mismatch %016llx != %016llx\n",
proc->pid, thread->pid,
cmd == BC_INCREFS_DONE ?
"BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
(u64)node_ptr, node->debug_id,
(u64)cookie, (u64)node->cookie);
break;
}
if (cmd == BC_ACQUIRE_DONE) {
if (node->pending_strong_ref == 0) {
binder_user_error("%d:%d BC_ACQUIRE_DONE node %d has no pending acquire request\n",
proc->pid, thread->pid,
node->debug_id);
break;
}
node->pending_strong_ref = 0;
} else {
if (node->pending_weak_ref == 0) {
binder_user_error("%d:%d BC_INCREFS_DONE node %d has no pending increfs request\n",
proc->pid, thread->pid,
node->debug_id);
break;
}
node->pending_weak_ref = 0;
}
binder_dec_node(node, cmd == BC_ACQUIRE_DONE, 0);
binder_debug(BINDER_DEBUG_USER_REFS,
"%d:%d %s node %d ls %d lw %d\n",
proc->pid, thread->pid,
cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
node->debug_id, node->local_strong_refs, node->local_weak_refs);
break;
}
case BC_ATTEMPT_ACQUIRE:
pr_err("BC_ATTEMPT_ACQUIRE not supported\n");
return -EINVAL;
case BC_ACQUIRE_RESULT:
pr_err("BC_ACQUIRE_RESULT not supported\n");
return -EINVAL;
case BC_FREE_BUFFER: {
binder_uintptr_t data_ptr;
struct binder_buffer *buffer;
if (get_user(data_ptr, (binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
buffer = binder_buffer_lookup(proc, data_ptr);
if (buffer == NULL) {
binder_user_error("%d:%d BC_FREE_BUFFER u%016llx no match\n",
proc->pid, thread->pid, (u64)data_ptr);
break;
}
if (!buffer->allow_user_free) {
binder_user_error("%d:%d BC_FREE_BUFFER u%016llx matched unreturned buffer\n",
proc->pid, thread->pid, (u64)data_ptr);
break;
}
binder_debug(BINDER_DEBUG_FREE_BUFFER,
"%d:%d BC_FREE_BUFFER u%016llx found buffer %d for %s transaction\n",
proc->pid, thread->pid, (u64)data_ptr, buffer->debug_id,
buffer->transaction ? "active" : "finished");
if (buffer->transaction) {
buffer->transaction->buffer = NULL;
buffer->transaction = NULL;
}
if (buffer->async_transaction && buffer->target_node) {
BUG_ON(!buffer->target_node->has_async_transaction);
if (list_empty(&buffer->target_node->async_todo))
buffer->target_node->has_async_transaction = 0;
else
list_move_tail(buffer->target_node->async_todo.next, &thread->todo);
}
trace_binder_transaction_buffer_release(buffer);
binder_transaction_buffer_release(proc, buffer, NULL);
binder_free_buf(proc, buffer);
break;
}
case BC_TRANSACTION:
case BC_REPLY: {
struct binder_transaction_data tr;
if (copy_from_user(&tr, ptr, sizeof(tr)))
return -EFAULT;
ptr += sizeof(tr);
binder_transaction(proc, thread, &tr, cmd == BC_REPLY);
break;
}
case BC_REGISTER_LOOPER:
binder_debug(BINDER_DEBUG_THREADS,
"%d:%d BC_REGISTER_LOOPER\n",
proc->pid, thread->pid);
if (thread->looper & BINDER_LOOPER_STATE_ENTERED) {
thread->looper |= BINDER_LOOPER_STATE_INVALID;
binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called after BC_ENTER_LOOPER\n",
proc->pid, thread->pid);
} else if (proc->requested_threads == 0) {
thread->looper |= BINDER_LOOPER_STATE_INVALID;
binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called without request\n",
proc->pid, thread->pid);
} else {
proc->requested_threads--;
proc->requested_threads_started++;
}
thread->looper |= BINDER_LOOPER_STATE_REGISTERED;
break;
case BC_ENTER_LOOPER:
binder_debug(BINDER_DEBUG_THREADS,
"%d:%d BC_ENTER_LOOPER\n",
proc->pid, thread->pid);
if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) {
thread->looper |= BINDER_LOOPER_STATE_INVALID;
binder_user_error("%d:%d ERROR: BC_ENTER_LOOPER called after BC_REGISTER_LOOPER\n",
proc->pid, thread->pid);
}
thread->looper |= BINDER_LOOPER_STATE_ENTERED;
break;
case BC_EXIT_LOOPER:
binder_debug(BINDER_DEBUG_THREADS,
"%d:%d BC_EXIT_LOOPER\n",
proc->pid, thread->pid);
thread->looper |= BINDER_LOOPER_STATE_EXITED;
break;
case BC_REQUEST_DEATH_NOTIFICATION:
case BC_CLEAR_DEATH_NOTIFICATION: {
uint32_t target;
binder_uintptr_t cookie;
struct binder_ref *ref;
struct binder_ref_death *death;
if (get_user(target, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
if (get_user(cookie, (binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
ref = binder_get_ref(proc, target);
if (ref == NULL) {
binder_user_error("%d:%d %s invalid ref %d\n",
proc->pid, thread->pid,
cmd == BC_REQUEST_DEATH_NOTIFICATION ?
"BC_REQUEST_DEATH_NOTIFICATION" :
"BC_CLEAR_DEATH_NOTIFICATION",
target);
break;
}
binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
"%d:%d %s %016llx ref %d desc %d s %d w %d for node %d\n",
proc->pid, thread->pid,
cmd == BC_REQUEST_DEATH_NOTIFICATION ?
"BC_REQUEST_DEATH_NOTIFICATION" :
"BC_CLEAR_DEATH_NOTIFICATION",
(u64)cookie, ref->debug_id, ref->desc,
ref->strong, ref->weak, ref->node->debug_id);
if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
if (ref->death) {
binder_user_error("%d:%d BC_REQUEST_DEATH_NOTIFICATION death notification already set\n",
proc->pid, thread->pid);
break;
}
death = kzalloc(sizeof(*death), GFP_KERNEL);
if (death == NULL) {
thread->return_error = BR_ERROR;
binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
"%d:%d BC_REQUEST_DEATH_NOTIFICATION failed\n",
proc->pid, thread->pid);
break;
}
binder_stats_created(BINDER_STAT_DEATH);
INIT_LIST_HEAD(&death->work.entry);
death->cookie = cookie;
ref->death = death;
if (ref->node->proc == NULL) {
ref->death->work.type = BINDER_WORK_DEAD_BINDER;
if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
list_add_tail(&ref->death->work.entry, &thread->todo);
} else {
list_add_tail(&ref->death->work.entry, &proc->todo);
wake_up_interruptible(&proc->wait);
}
}
} else {
if (ref->death == NULL) {
binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification not active\n",
proc->pid, thread->pid);
break;
}
death = ref->death;
if (death->cookie != cookie) {
binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch %016llx != %016llx\n",
proc->pid, thread->pid,
(u64)death->cookie, (u64)cookie);
break;
}
ref->death = NULL;
if (list_empty(&death->work.entry)) {
death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
list_add_tail(&death->work.entry, &thread->todo);
} else {
list_add_tail(&death->work.entry, &proc->todo);
wake_up_interruptible(&proc->wait);
}
} else {
BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER);
death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR;
}
}
} break;
case BC_DEAD_BINDER_DONE: {
struct binder_work *w;
binder_uintptr_t cookie;
struct binder_ref_death *death = NULL;
if (get_user(cookie, (binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(void *);
list_for_each_entry(w, &proc->delivered_death, entry) {
struct binder_ref_death *tmp_death = container_of(w, struct binder_ref_death, work);
if (tmp_death->cookie == cookie) {
death = tmp_death;
break;
}
}
binder_debug(BINDER_DEBUG_DEAD_BINDER,
"%d:%d BC_DEAD_BINDER_DONE %016llx found %p\n",
proc->pid, thread->pid, (u64)cookie, death);
if (death == NULL) {
binder_user_error("%d:%d BC_DEAD_BINDER_DONE %016llx not found\n",
proc->pid, thread->pid, (u64)cookie);
break;
}
list_del_init(&death->work.entry);
if (death->work.type == BINDER_WORK_DEAD_BINDER_AND_CLEAR) {
death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
list_add_tail(&death->work.entry, &thread->todo);
} else {
list_add_tail(&death->work.entry, &proc->todo);
wake_up_interruptible(&proc->wait);
}
}
} break;
default:
pr_err("%d:%d unknown command %d\n",
proc->pid, thread->pid, cmd);
return -EINVAL;
}
*consumed = ptr - buffer;
}
return 0;
}
static void binder_stat_br(struct binder_proc *proc,
struct binder_thread *thread, uint32_t cmd)
{
trace_binder_return(cmd);
if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.br)) {
binder_stats.br[_IOC_NR(cmd)]++;
proc->stats.br[_IOC_NR(cmd)]++;
thread->stats.br[_IOC_NR(cmd)]++;
}
}
static int binder_has_proc_work(struct binder_proc *proc,
struct binder_thread *thread)
{
return !list_empty(&proc->todo) ||
(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
}
static int binder_has_thread_work(struct binder_thread *thread)
{
return !list_empty(&thread->todo) || thread->return_error != BR_OK ||
(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
}
static int binder_thread_read(struct binder_proc *proc,
struct binder_thread *thread,
binder_uintptr_t binder_buffer, size_t size,
binder_size_t *consumed, int non_block)
{
void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
void __user *ptr = buffer + *consumed;
void __user *end = buffer + size;
int ret = 0;
int wait_for_proc_work;
if (*consumed == 0) {
if (put_user(BR_NOOP, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
}
retry:
wait_for_proc_work = thread->transaction_stack == NULL &&
list_empty(&thread->todo);
if (thread->return_error != BR_OK && ptr < end) {
if (thread->return_error2 != BR_OK) {
if (put_user(thread->return_error2, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
binder_stat_br(proc, thread, thread->return_error2);
if (ptr == end)
goto done;
thread->return_error2 = BR_OK;
}
if (put_user(thread->return_error, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
binder_stat_br(proc, thread, thread->return_error);
thread->return_error = BR_OK;
goto done;
}
thread->looper |= BINDER_LOOPER_STATE_WAITING;
if (wait_for_proc_work)
proc->ready_threads++;
binder_unlock(__func__);
trace_binder_wait_for_work(wait_for_proc_work,
!!thread->transaction_stack,
!list_empty(&thread->todo));
if (wait_for_proc_work) {
if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
BINDER_LOOPER_STATE_ENTERED))) {
binder_user_error("%d:%d ERROR: Thread waiting for process work before calling BC_REGISTER_LOOPER or BC_ENTER_LOOPER (state %x)\n",
proc->pid, thread->pid, thread->looper);
wait_event_interruptible(binder_user_error_wait,
binder_stop_on_user_error < 2);
}
binder_set_nice(proc->default_priority);
if (non_block) {
if (!binder_has_proc_work(proc, thread))
ret = -EAGAIN;
} else
ret = wait_event_freezable_exclusive(proc->wait, binder_has_proc_work(proc, thread));
} else {
if (non_block) {
if (!binder_has_thread_work(thread))
ret = -EAGAIN;
} else
ret = wait_event_freezable(thread->wait, binder_has_thread_work(thread));
}
binder_lock(__func__);
if (wait_for_proc_work)
proc->ready_threads--;
thread->looper &= ~BINDER_LOOPER_STATE_WAITING;
if (ret)
return ret;
while (1) {
uint32_t cmd;
struct binder_transaction_data tr;
struct binder_work *w;
struct binder_transaction *t = NULL;
if (!list_empty(&thread->todo))
w = list_first_entry(&thread->todo, struct binder_work, entry);
else if (!list_empty(&proc->todo) && wait_for_proc_work)
w = list_first_entry(&proc->todo, struct binder_work, entry);
else {
if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */
goto retry;
break;
}
if (end - ptr < sizeof(tr) + 4)
break;
switch (w->type) {
case BINDER_WORK_TRANSACTION: {
t = container_of(w, struct binder_transaction, work);
} break;
case BINDER_WORK_TRANSACTION_COMPLETE: {
cmd = BR_TRANSACTION_COMPLETE;
if (put_user(cmd, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
binder_stat_br(proc, thread, cmd);
binder_debug(BINDER_DEBUG_TRANSACTION_COMPLETE,
"%d:%d BR_TRANSACTION_COMPLETE\n",
proc->pid, thread->pid);
list_del(&w->entry);
kfree(w);
binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
} break;
case BINDER_WORK_NODE: {
struct binder_node *node = container_of(w, struct binder_node, work);
uint32_t cmd = BR_NOOP;
const char *cmd_name;
int strong = node->internal_strong_refs || node->local_strong_refs;
int weak = !hlist_empty(&node->refs) || node->local_weak_refs || strong;
if (weak && !node->has_weak_ref) {
cmd = BR_INCREFS;
cmd_name = "BR_INCREFS";
node->has_weak_ref = 1;
node->pending_weak_ref = 1;
node->local_weak_refs++;
} else if (strong && !node->has_strong_ref) {
cmd = BR_ACQUIRE;
cmd_name = "BR_ACQUIRE";
node->has_strong_ref = 1;
node->pending_strong_ref = 1;
node->local_strong_refs++;
} else if (!strong && node->has_strong_ref) {
cmd = BR_RELEASE;
cmd_name = "BR_RELEASE";
node->has_strong_ref = 0;
} else if (!weak && node->has_weak_ref) {
cmd = BR_DECREFS;
cmd_name = "BR_DECREFS";
node->has_weak_ref = 0;
}
if (cmd != BR_NOOP) {
if (put_user(cmd, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
if (put_user(node->ptr,
(binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
if (put_user(node->cookie,
(binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
binder_stat_br(proc, thread, cmd);
binder_debug(BINDER_DEBUG_USER_REFS,
"%d:%d %s %d u%016llx c%016llx\n",
proc->pid, thread->pid, cmd_name,
node->debug_id,
(u64)node->ptr, (u64)node->cookie);
} else {
list_del_init(&w->entry);
if (!weak && !strong) {
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"%d:%d node %d u%016llx c%016llx deleted\n",
proc->pid, thread->pid, node->debug_id,
(u64)node->ptr, (u64)node->cookie);
rb_erase(&node->rb_node, &proc->nodes);
kfree(node);
binder_stats_deleted(BINDER_STAT_NODE);
} else {
binder_debug(BINDER_DEBUG_INTERNAL_REFS,
"%d:%d node %d u%016llx c%016llx state unchanged\n",
proc->pid, thread->pid, node->debug_id,
(u64)node->ptr, (u64)node->cookie);
}
}
} break;
case BINDER_WORK_DEAD_BINDER:
case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
struct binder_ref_death *death;
uint32_t cmd;
death = container_of(w, struct binder_ref_death, work);
if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION)
cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE;
else
cmd = BR_DEAD_BINDER;
if (put_user(cmd, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
if (put_user(death->cookie,
(binder_uintptr_t __user *)ptr))
return -EFAULT;
ptr += sizeof(binder_uintptr_t);
binder_stat_br(proc, thread, cmd);
binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
"%d:%d %s %016llx\n",
proc->pid, thread->pid,
cmd == BR_DEAD_BINDER ?
"BR_DEAD_BINDER" :
"BR_CLEAR_DEATH_NOTIFICATION_DONE",
(u64)death->cookie);
if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) {
list_del(&w->entry);
kfree(death);
binder_stats_deleted(BINDER_STAT_DEATH);
} else
list_move(&w->entry, &proc->delivered_death);
if (cmd == BR_DEAD_BINDER)
goto done; /* DEAD_BINDER notifications can cause transactions */
} break;
}
if (!t)
continue;
BUG_ON(t->buffer == NULL);
if (t->buffer->target_node) {
struct binder_node *target_node = t->buffer->target_node;
tr.target.ptr = target_node->ptr;
tr.cookie = target_node->cookie;
t->saved_priority = task_nice(current);
if (t->priority < target_node->min_priority &&
!(t->flags & TF_ONE_WAY))
binder_set_nice(t->priority);
else if (!(t->flags & TF_ONE_WAY) ||
t->saved_priority > target_node->min_priority)
binder_set_nice(target_node->min_priority);
cmd = BR_TRANSACTION;
} else {
tr.target.ptr = 0;
tr.cookie = 0;
cmd = BR_REPLY;
}
tr.code = t->code;
tr.flags = t->flags;
tr.sender_euid = from_kuid(current_user_ns(), t->sender_euid);
if (t->from) {
struct task_struct *sender = t->from->proc->tsk;
tr.sender_pid = task_tgid_nr_ns(sender,
task_active_pid_ns(current));
} else {
tr.sender_pid = 0;
}
tr.data_size = t->buffer->data_size;
tr.offsets_size = t->buffer->offsets_size;
tr.data.ptr.buffer = (binder_uintptr_t)(
(uintptr_t)t->buffer->data +
proc->user_buffer_offset);
tr.data.ptr.offsets = tr.data.ptr.buffer +
ALIGN(t->buffer->data_size,
sizeof(void *));
if (put_user(cmd, (uint32_t __user *)ptr))
return -EFAULT;
ptr += sizeof(uint32_t);
if (copy_to_user(ptr, &tr, sizeof(tr)))
return -EFAULT;
ptr += sizeof(tr);
trace_binder_transaction_received(t);
binder_stat_br(proc, thread, cmd);
binder_debug(BINDER_DEBUG_TRANSACTION,
"%d:%d %s %d %d:%d, cmd %d size %zd-%zd ptr %016llx-%016llx\n",
proc->pid, thread->pid,
(cmd == BR_TRANSACTION) ? "BR_TRANSACTION" :
"BR_REPLY",
t->debug_id, t->from ? t->from->proc->pid : 0,
t->from ? t->from->pid : 0, cmd,
t->buffer->data_size, t->buffer->offsets_size,
(u64)tr.data.ptr.buffer, (u64)tr.data.ptr.offsets);
list_del(&t->work.entry);
t->buffer->allow_user_free = 1;
if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
t->to_parent = thread->transaction_stack;
t->to_thread = thread;
thread->transaction_stack = t;
} else {
t->buffer->transaction = NULL;
kfree(t);
binder_stats_deleted(BINDER_STAT_TRANSACTION);
}
break;
}
done:
*consumed = ptr - buffer;
if (proc->requested_threads + proc->ready_threads == 0 &&
proc->requested_threads_started < proc->max_threads &&
(thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
BINDER_LOOPER_STATE_ENTERED)) /* the user-space code fails to */
/*spawn a new thread if we leave this out */) {
proc->requested_threads++;
binder_debug(BINDER_DEBUG_THREADS,
"%d:%d BR_SPAWN_LOOPER\n",
proc->pid, thread->pid);
if (put_user(BR_SPAWN_LOOPER, (uint32_t __user *)buffer))
return -EFAULT;
binder_stat_br(proc, thread, BR_SPAWN_LOOPER);
}
return 0;
}
static void binder_release_work(struct list_head *list)
{
struct binder_work *w;
while (!list_empty(list)) {
w = list_first_entry(list, struct binder_work, entry);
list_del_init(&w->entry);
switch (w->type) {
case BINDER_WORK_TRANSACTION: {
struct binder_transaction *t;
t = container_of(w, struct binder_transaction, work);
if (t->buffer->target_node &&
!(t->flags & TF_ONE_WAY)) {
binder_send_failed_reply(t, BR_DEAD_REPLY);
} else {
binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
"undelivered transaction %d\n",
t->debug_id);
t->buffer->transaction = NULL;
kfree(t);
binder_stats_deleted(BINDER_STAT_TRANSACTION);
}
} break;
case BINDER_WORK_TRANSACTION_COMPLETE: {
binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
"undelivered TRANSACTION_COMPLETE\n");
kfree(w);
binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
} break;
case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
struct binder_ref_death *death;
death = container_of(w, struct binder_ref_death, work);
binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
"undelivered death notification, %016llx\n",
(u64)death->cookie);
kfree(death);
binder_stats_deleted(BINDER_STAT_DEATH);
} break;
default:
pr_err("unexpected work type, %d, not freed\n",
w->type);
break;
}
}
}
static struct binder_thread *binder_get_thread(struct binder_proc *proc)
{
struct binder_thread *thread = NULL;
struct rb_node *parent = NULL;
struct rb_node **p = &proc->threads.rb_node;
while (*p) {
parent = *p;
thread = rb_entry(parent, struct binder_thread, rb_node);
if (current->pid < thread->pid)
p = &(*p)->rb_left;
else if (current->pid > thread->pid)
p = &(*p)->rb_right;
else
break;
}
if (*p == NULL) {
thread = kzalloc(sizeof(*thread), GFP_KERNEL);
if (thread == NULL)
return NULL;
binder_stats_created(BINDER_STAT_THREAD);
thread->proc = proc;
thread->pid = current->pid;
init_waitqueue_head(&thread->wait);
INIT_LIST_HEAD(&thread->todo);
rb_link_node(&thread->rb_node, parent, p);
rb_insert_color(&thread->rb_node, &proc->threads);
thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN;
thread->return_error = BR_OK;
thread->return_error2 = BR_OK;
}
return thread;
}
static int binder_free_thread(struct binder_proc *proc,
struct binder_thread *thread)
{
struct binder_transaction *t;
struct binder_transaction *send_reply = NULL;
int active_transactions = 0;
rb_erase(&thread->rb_node, &proc->threads);
t = thread->transaction_stack;
if (t && t->to_thread == thread)
send_reply = t;
while (t) {
active_transactions++;
binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
"release %d:%d transaction %d %s, still active\n",
proc->pid, thread->pid,
t->debug_id,
(t->to_thread == thread) ? "in" : "out");
if (t->to_thread == thread) {
t->to_proc = NULL;
t->to_thread = NULL;
if (t->buffer) {
t->buffer->transaction = NULL;
t->buffer = NULL;
}
t = t->to_parent;
} else if (t->from == thread) {
t->from = NULL;
t = t->from_parent;
} else
BUG();
}
if (send_reply)
binder_send_failed_reply(send_reply, BR_DEAD_REPLY);
binder_release_work(&thread->todo);
kfree(thread);
binder_stats_deleted(BINDER_STAT_THREAD);
return active_transactions;
}
static unsigned int binder_poll(struct file *filp,
struct poll_table_struct *wait)
{
struct binder_proc *proc = filp->private_data;
struct binder_thread *thread = NULL;
int wait_for_proc_work;
binder_lock(__func__);
thread = binder_get_thread(proc);
wait_for_proc_work = thread->transaction_stack == NULL &&
list_empty(&thread->todo) && thread->return_error == BR_OK;
binder_unlock(__func__);
if (wait_for_proc_work) {
if (binder_has_proc_work(proc, thread))
return POLLIN;
poll_wait(filp, &proc->wait, wait);
if (binder_has_proc_work(proc, thread))
return POLLIN;
} else {
if (binder_has_thread_work(thread))
return POLLIN;
poll_wait(filp, &thread->wait, wait);
if (binder_has_thread_work(thread))
return POLLIN;
}
return 0;
}
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
int ret;
struct binder_proc *proc = filp->private_data;
struct binder_thread *thread;
unsigned int size = _IOC_SIZE(cmd);
void __user *ubuf = (void __user *)arg;
/*pr_info("binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/
trace_binder_ioctl(cmd, arg);
ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
if (ret)
goto err_unlocked;
binder_lock(__func__);
thread = binder_get_thread(proc);
if (thread == NULL) {
ret = -ENOMEM;
goto err;
}
switch (cmd) {
case BINDER_WRITE_READ: {
struct binder_write_read bwr;
if (size != sizeof(struct binder_write_read)) {
ret = -EINVAL;
goto err;
}
if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
ret = -EFAULT;
goto err;
}
binder_debug(BINDER_DEBUG_READ_WRITE,
"%d:%d write %lld at %016llx, read %lld at %016llx\n",
proc->pid, thread->pid,
(u64)bwr.write_size, (u64)bwr.write_buffer,
(u64)bwr.read_size, (u64)bwr.read_buffer);
if (bwr.write_size > 0) {
ret = binder_thread_write(proc, thread, bwr.write_buffer, bwr.write_size, &bwr.write_consumed);
trace_binder_write_done(ret);
if (ret < 0) {
bwr.read_consumed = 0;
if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
ret = -EFAULT;
goto err;
}
}
if (bwr.read_size > 0) {
ret = binder_thread_read(proc, thread, bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK);
trace_binder_read_done(ret);
if (!list_empty(&proc->todo))
wake_up_interruptible(&proc->wait);
if (ret < 0) {
if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
ret = -EFAULT;
goto err;
}
}
binder_debug(BINDER_DEBUG_READ_WRITE,
"%d:%d wrote %lld of %lld, read return %lld of %lld\n",
proc->pid, thread->pid,
(u64)bwr.write_consumed, (u64)bwr.write_size,
(u64)bwr.read_consumed, (u64)bwr.read_size);
if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
ret = -EFAULT;
goto err;
}
break;
}
case BINDER_SET_MAX_THREADS:
if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) {
ret = -EINVAL;
goto err;
}
break;
case BINDER_SET_CONTEXT_MGR:
if (binder_context_mgr_node != NULL) {
pr_err("BINDER_SET_CONTEXT_MGR already set\n");
ret = -EBUSY;
goto err;
}
ret = security_binder_set_context_mgr(proc->tsk);
if (ret < 0)
goto err;
if (uid_valid(binder_context_mgr_uid)) {
if (!uid_eq(binder_context_mgr_uid, current->cred->euid)) {
pr_err("BINDER_SET_CONTEXT_MGR bad uid %d != %d\n",
from_kuid(&init_user_ns, current->cred->euid),
from_kuid(&init_user_ns, binder_context_mgr_uid));
ret = -EPERM;
goto err;
}
} else
binder_context_mgr_uid = current->cred->euid;
binder_context_mgr_node = binder_new_node(proc, 0, 0);
if (binder_context_mgr_node == NULL) {
ret = -ENOMEM;
goto err;
}
binder_context_mgr_node->local_weak_refs++;
binder_context_mgr_node->local_strong_refs++;
binder_context_mgr_node->has_strong_ref = 1;
binder_context_mgr_node->has_weak_ref = 1;
break;
case BINDER_THREAD_EXIT:
binder_debug(BINDER_DEBUG_THREADS, "%d:%d exit\n",
proc->pid, thread->pid);
binder_free_thread(proc, thread);
thread = NULL;
break;
case BINDER_VERSION:
if (size != sizeof(struct binder_version)) {
ret = -EINVAL;
goto err;
}
if (put_user(BINDER_CURRENT_PROTOCOL_VERSION, &((struct binder_version *)ubuf)->protocol_version)) {
ret = -EINVAL;
goto err;
}
break;
default:
ret = -EINVAL;
goto err;
}
ret = 0;
err:
if (thread)
thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;
binder_unlock(__func__);
wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
if (ret && ret != -ERESTARTSYS)
pr_info("%d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
err_unlocked:
trace_binder_ioctl_done(ret);
return ret;
}
static void binder_vma_open(struct vm_area_struct *vma)
{
struct binder_proc *proc = vma->vm_private_data;
binder_debug(BINDER_DEBUG_OPEN_CLOSE,
"%d open vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
proc->pid, vma->vm_start, vma->vm_end,
(vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
(unsigned long)pgprot_val(vma->vm_page_prot));
}
static void binder_vma_close(struct vm_area_struct *vma)
{
struct binder_proc *proc = vma->vm_private_data;
binder_debug(BINDER_DEBUG_OPEN_CLOSE,
"%d close vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
proc->pid, vma->vm_start, vma->vm_end,
(vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
(unsigned long)pgprot_val(vma->vm_page_prot));
proc->vma = NULL;
proc->vma_vm_mm = NULL;
binder_defer_work(proc, BINDER_DEFERRED_PUT_FILES);
}
static int binder_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return VM_FAULT_SIGBUS;
}
static struct vm_operations_struct binder_vm_ops = {
.open = binder_vma_open,
.close = binder_vma_close,
.fault = binder_vm_fault,
};
static int binder_mmap(struct file *filp, struct vm_area_struct *vma)
{
int ret;
struct vm_struct *area;
struct binder_proc *proc = filp->private_data;
const char *failure_string;
struct binder_buffer *buffer;
if (proc->tsk != current)
return -EINVAL;
if ((vma->vm_end - vma->vm_start) > SZ_4M)
vma->vm_end = vma->vm_start + SZ_4M;
binder_debug(BINDER_DEBUG_OPEN_CLOSE,
"binder_mmap: %d %lx-%lx (%ld K) vma %lx pagep %lx\n",
proc->pid, vma->vm_start, vma->vm_end,
(vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
(unsigned long)pgprot_val(vma->vm_page_prot));
if (vma->vm_flags & FORBIDDEN_MMAP_FLAGS) {
ret = -EPERM;
failure_string = "bad vm_flags";
goto err_bad_arg;
}
vma->vm_flags = (vma->vm_flags | VM_DONTCOPY) & ~VM_MAYWRITE;
mutex_lock(&binder_mmap_lock);
if (proc->buffer) {
ret = -EBUSY;
failure_string = "already mapped";
goto err_already_mapped;
}
area = get_vm_area(vma->vm_end - vma->vm_start, VM_IOREMAP);
if (area == NULL) {
ret = -ENOMEM;
failure_string = "get_vm_area";
goto err_get_vm_area_failed;
}
proc->buffer = area->addr;
proc->user_buffer_offset = vma->vm_start - (uintptr_t)proc->buffer;
mutex_unlock(&binder_mmap_lock);
#ifdef CONFIG_CPU_CACHE_VIPT
if (cache_is_vipt_aliasing()) {
while (CACHE_COLOUR((vma->vm_start ^ (uint32_t)proc->buffer))) {
pr_info("binder_mmap: %d %lx-%lx maps %p bad alignment\n", proc->pid, vma->vm_start, vma->vm_end, proc->buffer);
vma->vm_start += PAGE_SIZE;
}
}
#endif
proc->pages = kzalloc(sizeof(proc->pages[0]) * ((vma->vm_end - vma->vm_start) / PAGE_SIZE), GFP_KERNEL);
if (proc->pages == NULL) {
ret = -ENOMEM;
failure_string = "alloc page array";
goto err_alloc_pages_failed;
}
proc->buffer_size = vma->vm_end - vma->vm_start;
vma->vm_ops = &binder_vm_ops;
vma->vm_private_data = proc;
if (binder_update_page_range(proc, 1, proc->buffer, proc->buffer + PAGE_SIZE, vma)) {
ret = -ENOMEM;
failure_string = "alloc small buf";
goto err_alloc_small_buf_failed;
}
buffer = proc->buffer;
INIT_LIST_HEAD(&proc->buffers);
list_add(&buffer->entry, &proc->buffers);
buffer->free = 1;
binder_insert_free_buffer(proc, buffer);
proc->free_async_space = proc->buffer_size / 2;
barrier();
proc->files = get_files_struct(current);
proc->vma = vma;
proc->vma_vm_mm = vma->vm_mm;
/*pr_info("binder_mmap: %d %lx-%lx maps %p\n",
proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/
return 0;
err_alloc_small_buf_failed:
kfree(proc->pages);
proc->pages = NULL;
err_alloc_pages_failed:
mutex_lock(&binder_mmap_lock);
vfree(proc->buffer);
proc->buffer = NULL;
err_get_vm_area_failed:
err_already_mapped:
mutex_unlock(&binder_mmap_lock);
err_bad_arg:
pr_err("binder_mmap: %d %lx-%lx %s failed %d\n",
proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);
return ret;
}
static int binder_open(struct inode *nodp, struct file *filp)
{
struct binder_proc *proc;
binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_open: %d:%d\n",
current->group_leader->pid, current->pid);
proc = kzalloc(sizeof(*proc), GFP_KERNEL);
if (proc == NULL)
return -ENOMEM;
get_task_struct(current);
proc->tsk = current;
INIT_LIST_HEAD(&proc->todo);
init_waitqueue_head(&proc->wait);
proc->default_priority = task_nice(current);
binder_lock(__func__);
binder_stats_created(BINDER_STAT_PROC);
hlist_add_head(&proc->proc_node, &binder_procs);
proc->pid = current->group_leader->pid;
INIT_LIST_HEAD(&proc->delivered_death);
filp->private_data = proc;
binder_unlock(__func__);
if (binder_debugfs_dir_entry_proc) {
char strbuf[11];
snprintf(strbuf, sizeof(strbuf), "%u", proc->pid);
proc->debugfs_entry = debugfs_create_file(strbuf, S_IRUGO,
binder_debugfs_dir_entry_proc, proc, &binder_proc_fops);
}
return 0;
}
static int binder_flush(struct file *filp, fl_owner_t id)
{
struct binder_proc *proc = filp->private_data;
binder_defer_work(proc, BINDER_DEFERRED_FLUSH);
return 0;
}
static void binder_deferred_flush(struct binder_proc *proc)
{
struct rb_node *n;
int wake_count = 0;
for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) {
struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node);
thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN;
if (thread->looper & BINDER_LOOPER_STATE_WAITING) {
wake_up_interruptible(&thread->wait);
wake_count++;
}
}
wake_up_interruptible_all(&proc->wait);
binder_debug(BINDER_DEBUG_OPEN_CLOSE,
"binder_flush: %d woke %d threads\n", proc->pid,
wake_count);
}
static int binder_release(struct inode *nodp, struct file *filp)
{
struct binder_proc *proc = filp->private_data;
debugfs_remove(proc->debugfs_entry);
binder_defer_work(proc, BINDER_DEFERRED_RELEASE);
return 0;
}
static int binder_node_release(struct binder_node *node, int refs)
{
struct binder_ref *ref;
int death = 0;
list_del_init(&node->work.entry);
binder_release_work(&node->async_todo);
if (hlist_empty(&node->refs)) {
kfree(node);
binder_stats_deleted(BINDER_STAT_NODE);
return refs;
}
node->proc = NULL;
node->local_strong_refs = 0;
node->local_weak_refs = 0;
hlist_add_head(&node->dead_node, &binder_dead_nodes);
hlist_for_each_entry(ref, &node->refs, node_entry) {
refs++;
if (!ref->death)
continue;
death++;
if (list_empty(&ref->death->work.entry)) {
ref->death->work.type = BINDER_WORK_DEAD_BINDER;
list_add_tail(&ref->death->work.entry,
&ref->proc->todo);
wake_up_interruptible(&ref->proc->wait);
} else
BUG();
}
binder_debug(BINDER_DEBUG_DEAD_BINDER,
"node %d now dead, refs %d, death %d\n",
node->debug_id, refs, death);
return refs;
}
static void binder_deferred_release(struct binder_proc *proc)
{
struct binder_transaction *t;
struct rb_node *n;
int threads, nodes, incoming_refs, outgoing_refs, buffers,
active_transactions, page_count;
BUG_ON(proc->vma);
BUG_ON(proc->files);
hlist_del(&proc->proc_node);
if (binder_context_mgr_node && binder_context_mgr_node->proc == proc) {
binder_debug(BINDER_DEBUG_DEAD_BINDER,
"%s: %d context_mgr_node gone\n",
__func__, proc->pid);
binder_context_mgr_node = NULL;
}
threads = 0;
active_transactions = 0;
while ((n = rb_first(&proc->threads))) {
struct binder_thread *thread;
thread = rb_entry(n, struct binder_thread, rb_node);
threads++;
active_transactions += binder_free_thread(proc, thread);
}
nodes = 0;
incoming_refs = 0;
while ((n = rb_first(&proc->nodes))) {
struct binder_node *node;
node = rb_entry(n, struct binder_node, rb_node);
nodes++;
rb_erase(&node->rb_node, &proc->nodes);
incoming_refs = binder_node_release(node, incoming_refs);
}
outgoing_refs = 0;
while ((n = rb_first(&proc->refs_by_desc))) {
struct binder_ref *ref;
ref = rb_entry(n, struct binder_ref, rb_node_desc);
outgoing_refs++;
binder_delete_ref(ref);
}
binder_release_work(&proc->todo);
binder_release_work(&proc->delivered_death);
buffers = 0;
while ((n = rb_first(&proc->allocated_buffers))) {
struct binder_buffer *buffer;
buffer = rb_entry(n, struct binder_buffer, rb_node);
t = buffer->transaction;
if (t) {
t->buffer = NULL;
buffer->transaction = NULL;
pr_err("release proc %d, transaction %d, not freed\n",
proc->pid, t->debug_id);
/*BUG();*/
}
binder_free_buf(proc, buffer);
buffers++;
}
binder_stats_deleted(BINDER_STAT_PROC);
page_count = 0;
if (proc->pages) {
int i;
for (i = 0; i < proc->buffer_size / PAGE_SIZE; i++) {
void *page_addr;
if (!proc->pages[i])
continue;
page_addr = proc->buffer + i * PAGE_SIZE;
binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
"%s: %d: page %d at %p not freed\n",
__func__, proc->pid, i, page_addr);
unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE);
__free_page(proc->pages[i]);
page_count++;
}
kfree(proc->pages);
vfree(proc->buffer);
}
put_task_struct(proc->tsk);
binder_debug(BINDER_DEBUG_OPEN_CLOSE,
"%s: %d threads %d, nodes %d (ref %d), refs %d, active transactions %d, buffers %d, pages %d\n",
__func__, proc->pid, threads, nodes, incoming_refs,
outgoing_refs, active_transactions, buffers, page_count);
kfree(proc);
}
static void binder_deferred_func(struct work_struct *work)
{
struct binder_proc *proc;
struct files_struct *files;
int defer;
do {
binder_lock(__func__);
mutex_lock(&binder_deferred_lock);
if (!hlist_empty(&binder_deferred_list)) {
proc = hlist_entry(binder_deferred_list.first,
struct binder_proc, deferred_work_node);
hlist_del_init(&proc->deferred_work_node);
defer = proc->deferred_work;
proc->deferred_work = 0;
} else {
proc = NULL;
defer = 0;
}
mutex_unlock(&binder_deferred_lock);
files = NULL;
if (defer & BINDER_DEFERRED_PUT_FILES) {
files = proc->files;
if (files)
proc->files = NULL;
}
if (defer & BINDER_DEFERRED_FLUSH)
binder_deferred_flush(proc);
if (defer & BINDER_DEFERRED_RELEASE)
binder_deferred_release(proc); /* frees proc */
binder_unlock(__func__);
if (files)
put_files_struct(files);
} while (proc);
}
static DECLARE_WORK(binder_deferred_work, binder_deferred_func);
static void
binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer)
{
mutex_lock(&binder_deferred_lock);
proc->deferred_work |= defer;
if (hlist_unhashed(&proc->deferred_work_node)) {
hlist_add_head(&proc->deferred_work_node,
&binder_deferred_list);
queue_work(binder_deferred_workqueue, &binder_deferred_work);
}
mutex_unlock(&binder_deferred_lock);
}
static void print_binder_transaction(struct seq_file *m, const char *prefix,
struct binder_transaction *t)
{
seq_printf(m,
"%s %d: %p from %d:%d to %d:%d code %x flags %x pri %ld r%d",
prefix, t->debug_id, t,
t->from ? t->from->proc->pid : 0,
t->from ? t->from->pid : 0,
t->to_proc ? t->to_proc->pid : 0,
t->to_thread ? t->to_thread->pid : 0,
t->code, t->flags, t->priority, t->need_reply);
if (t->buffer == NULL) {
seq_puts(m, " buffer free\n");
return;
}
if (t->buffer->target_node)
seq_printf(m, " node %d",
t->buffer->target_node->debug_id);
seq_printf(m, " size %zd:%zd data %p\n",
t->buffer->data_size, t->buffer->offsets_size,
t->buffer->data);
}
static void print_binder_buffer(struct seq_file *m, const char *prefix,
struct binder_buffer *buffer)
{
seq_printf(m, "%s %d: %p size %zd:%zd %s\n",
prefix, buffer->debug_id, buffer->data,
buffer->data_size, buffer->offsets_size,
buffer->transaction ? "active" : "delivered");
}
static void print_binder_work(struct seq_file *m, const char *prefix,
const char *transaction_prefix,
struct binder_work *w)
{
struct binder_node *node;
struct binder_transaction *t;
switch (w->type) {
case BINDER_WORK_TRANSACTION:
t = container_of(w, struct binder_transaction, work);
print_binder_transaction(m, transaction_prefix, t);
break;
case BINDER_WORK_TRANSACTION_COMPLETE:
seq_printf(m, "%stransaction complete\n", prefix);
break;
case BINDER_WORK_NODE:
node = container_of(w, struct binder_node, work);
seq_printf(m, "%snode work %d: u%016llx c%016llx\n",
prefix, node->debug_id,
(u64)node->ptr, (u64)node->cookie);
break;
case BINDER_WORK_DEAD_BINDER:
seq_printf(m, "%shas dead binder\n", prefix);
break;
case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
seq_printf(m, "%shas cleared dead binder\n", prefix);
break;
case BINDER_WORK_CLEAR_DEATH_NOTIFICATION:
seq_printf(m, "%shas cleared death notification\n", prefix);
break;
default:
seq_printf(m, "%sunknown work: type %d\n", prefix, w->type);
break;
}
}
static void print_binder_thread(struct seq_file *m,
struct binder_thread *thread,
int print_always)
{
struct binder_transaction *t;
struct binder_work *w;
size_t start_pos = m->count;
size_t header_pos;
seq_printf(m, " thread %d: l %02x\n", thread->pid, thread->looper);
header_pos = m->count;
t = thread->transaction_stack;
while (t) {
if (t->from == thread) {
print_binder_transaction(m,
" outgoing transaction", t);
t = t->from_parent;
} else if (t->to_thread == thread) {
print_binder_transaction(m,
" incoming transaction", t);
t = t->to_parent;
} else {
print_binder_transaction(m, " bad transaction", t);
t = NULL;
}
}
list_for_each_entry(w, &thread->todo, entry) {
print_binder_work(m, " ", " pending transaction", w);
}
if (!print_always && m->count == header_pos)
m->count = start_pos;
}
static void print_binder_node(struct seq_file *m, struct binder_node *node)
{
struct binder_ref *ref;
struct binder_work *w;
int count;
count = 0;
hlist_for_each_entry(ref, &node->refs, node_entry)
count++;
seq_printf(m, " node %d: u%016llx c%016llx hs %d hw %d ls %d lw %d is %d iw %d",
node->debug_id, (u64)node->ptr, (u64)node->cookie,
node->has_strong_ref, node->has_weak_ref,
node->local_strong_refs, node->local_weak_refs,
node->internal_strong_refs, count);
if (count) {
seq_puts(m, " proc");
hlist_for_each_entry(ref, &node->refs, node_entry)
seq_printf(m, " %d", ref->proc->pid);
}
seq_puts(m, "\n");
list_for_each_entry(w, &node->async_todo, entry)
print_binder_work(m, " ",
" pending async transaction", w);
}
static void print_binder_ref(struct seq_file *m, struct binder_ref *ref)
{
seq_printf(m, " ref %d: desc %d %snode %d s %d w %d d %p\n",
ref->debug_id, ref->desc, ref->node->proc ? "" : "dead ",
ref->node->debug_id, ref->strong, ref->weak, ref->death);
}
static void print_binder_proc(struct seq_file *m,
struct binder_proc *proc, int print_all)
{
struct binder_work *w;
struct rb_node *n;
size_t start_pos = m->count;
size_t header_pos;
seq_printf(m, "proc %d\n", proc->pid);
header_pos = m->count;
for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
print_binder_thread(m, rb_entry(n, struct binder_thread,
rb_node), print_all);
for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) {
struct binder_node *node = rb_entry(n, struct binder_node,
rb_node);
if (print_all || node->has_async_transaction)
print_binder_node(m, node);
}
if (print_all) {
for (n = rb_first(&proc->refs_by_desc);
n != NULL;
n = rb_next(n))
print_binder_ref(m, rb_entry(n, struct binder_ref,
rb_node_desc));
}
for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n))
print_binder_buffer(m, " buffer",
rb_entry(n, struct binder_buffer, rb_node));
list_for_each_entry(w, &proc->todo, entry)
print_binder_work(m, " ", " pending transaction", w);
list_for_each_entry(w, &proc->delivered_death, entry) {
seq_puts(m, " has delivered dead binder\n");
break;
}
if (!print_all && m->count == header_pos)
m->count = start_pos;
}
static const char * const binder_return_strings[] = {
"BR_ERROR",
"BR_OK",
"BR_TRANSACTION",
"BR_REPLY",
"BR_ACQUIRE_RESULT",
"BR_DEAD_REPLY",
"BR_TRANSACTION_COMPLETE",
"BR_INCREFS",
"BR_ACQUIRE",
"BR_RELEASE",
"BR_DECREFS",
"BR_ATTEMPT_ACQUIRE",
"BR_NOOP",
"BR_SPAWN_LOOPER",
"BR_FINISHED",
"BR_DEAD_BINDER",
"BR_CLEAR_DEATH_NOTIFICATION_DONE",
"BR_FAILED_REPLY"
};
static const char * const binder_command_strings[] = {
"BC_TRANSACTION",
"BC_REPLY",
"BC_ACQUIRE_RESULT",
"BC_FREE_BUFFER",
"BC_INCREFS",
"BC_ACQUIRE",
"BC_RELEASE",
"BC_DECREFS",
"BC_INCREFS_DONE",
"BC_ACQUIRE_DONE",
"BC_ATTEMPT_ACQUIRE",
"BC_REGISTER_LOOPER",
"BC_ENTER_LOOPER",
"BC_EXIT_LOOPER",
"BC_REQUEST_DEATH_NOTIFICATION",
"BC_CLEAR_DEATH_NOTIFICATION",
"BC_DEAD_BINDER_DONE"
};
static const char * const binder_objstat_strings[] = {
"proc",
"thread",
"node",
"ref",
"death",
"transaction",
"transaction_complete"
};
static void print_binder_stats(struct seq_file *m, const char *prefix,
struct binder_stats *stats)
{
int i;
BUILD_BUG_ON(ARRAY_SIZE(stats->bc) !=
ARRAY_SIZE(binder_command_strings));
for (i = 0; i < ARRAY_SIZE(stats->bc); i++) {
if (stats->bc[i])
seq_printf(m, "%s%s: %d\n", prefix,
binder_command_strings[i], stats->bc[i]);
}
BUILD_BUG_ON(ARRAY_SIZE(stats->br) !=
ARRAY_SIZE(binder_return_strings));
for (i = 0; i < ARRAY_SIZE(stats->br); i++) {
if (stats->br[i])
seq_printf(m, "%s%s: %d\n", prefix,
binder_return_strings[i], stats->br[i]);
}
BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
ARRAY_SIZE(binder_objstat_strings));
BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
ARRAY_SIZE(stats->obj_deleted));
for (i = 0; i < ARRAY_SIZE(stats->obj_created); i++) {
if (stats->obj_created[i] || stats->obj_deleted[i])
seq_printf(m, "%s%s: active %d total %d\n", prefix,
binder_objstat_strings[i],
stats->obj_created[i] - stats->obj_deleted[i],
stats->obj_created[i]);
}
}
static void print_binder_proc_stats(struct seq_file *m,
struct binder_proc *proc)
{
struct binder_work *w;
struct rb_node *n;
int count, strong, weak;
seq_printf(m, "proc %d\n", proc->pid);
count = 0;
for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
count++;
seq_printf(m, " threads: %d\n", count);
seq_printf(m, " requested threads: %d+%d/%d\n"
" ready threads %d\n"
" free async space %zd\n", proc->requested_threads,
proc->requested_threads_started, proc->max_threads,
proc->ready_threads, proc->free_async_space);
count = 0;
for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n))
count++;
seq_printf(m, " nodes: %d\n", count);
count = 0;
strong = 0;
weak = 0;
for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
struct binder_ref *ref = rb_entry(n, struct binder_ref,
rb_node_desc);
count++;
strong += ref->strong;
weak += ref->weak;
}
seq_printf(m, " refs: %d s %d w %d\n", count, strong, weak);
count = 0;
for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n))
count++;
seq_printf(m, " buffers: %d\n", count);
count = 0;
list_for_each_entry(w, &proc->todo, entry) {
switch (w->type) {
case BINDER_WORK_TRANSACTION:
count++;
break;
default:
break;
}
}
seq_printf(m, " pending transactions: %d\n", count);
print_binder_stats(m, " ", &proc->stats);
}
static int binder_state_show(struct seq_file *m, void *unused)
{
struct binder_proc *proc;
struct binder_node *node;
int do_lock = !binder_debug_no_lock;
if (do_lock)
binder_lock(__func__);
seq_puts(m, "binder state:\n");
if (!hlist_empty(&binder_dead_nodes))
seq_puts(m, "dead nodes:\n");
hlist_for_each_entry(node, &binder_dead_nodes, dead_node)
print_binder_node(m, node);
hlist_for_each_entry(proc, &binder_procs, proc_node)
print_binder_proc(m, proc, 1);
if (do_lock)
binder_unlock(__func__);
return 0;
}
static int binder_stats_show(struct seq_file *m, void *unused)
{
struct binder_proc *proc;
int do_lock = !binder_debug_no_lock;
if (do_lock)
binder_lock(__func__);
seq_puts(m, "binder stats:\n");
print_binder_stats(m, "", &binder_stats);
hlist_for_each_entry(proc, &binder_procs, proc_node)
print_binder_proc_stats(m, proc);
if (do_lock)
binder_unlock(__func__);
return 0;
}
static int binder_transactions_show(struct seq_file *m, void *unused)
{
struct binder_proc *proc;
int do_lock = !binder_debug_no_lock;
if (do_lock)
binder_lock(__func__);
seq_puts(m, "binder transactions:\n");
hlist_for_each_entry(proc, &binder_procs, proc_node)
print_binder_proc(m, proc, 0);
if (do_lock)
binder_unlock(__func__);
return 0;
}
static int binder_proc_show(struct seq_file *m, void *unused)
{
struct binder_proc *itr;
struct binder_proc *proc = m->private;
int do_lock = !binder_debug_no_lock;
bool valid_proc = false;
if (do_lock)
binder_lock(__func__);
hlist_for_each_entry(itr, &binder_procs, proc_node) {
if (itr == proc) {
valid_proc = true;
break;
}
}
if (valid_proc) {
seq_puts(m, "binder proc state:\n");
print_binder_proc(m, proc, 1);
}
if (do_lock)
binder_unlock(__func__);
return 0;
}
static void print_binder_transaction_log_entry(struct seq_file *m,
struct binder_transaction_log_entry *e)
{
seq_printf(m,
"%d: %s from %d:%d to %d:%d node %d handle %d size %d:%d\n",
e->debug_id, (e->call_type == 2) ? "reply" :
((e->call_type == 1) ? "async" : "call "), e->from_proc,
e->from_thread, e->to_proc, e->to_thread, e->to_node,
e->target_handle, e->data_size, e->offsets_size);
}
static int binder_transaction_log_show(struct seq_file *m, void *unused)
{
struct binder_transaction_log *log = m->private;
int i;
if (log->full) {
for (i = log->next; i < ARRAY_SIZE(log->entry); i++)
print_binder_transaction_log_entry(m, &log->entry[i]);
}
for (i = 0; i < log->next; i++)
print_binder_transaction_log_entry(m, &log->entry[i]);
return 0;
}
static const struct file_operations binder_fops = {
.owner = THIS_MODULE,
.poll = binder_poll,
.unlocked_ioctl = binder_ioctl,
.compat_ioctl = binder_ioctl,
.mmap = binder_mmap,
.open = binder_open,
.flush = binder_flush,
.release = binder_release,
};
static struct miscdevice binder_miscdev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "binder",
.fops = &binder_fops
};
BINDER_DEBUG_ENTRY(state);
BINDER_DEBUG_ENTRY(stats);
BINDER_DEBUG_ENTRY(transactions);
BINDER_DEBUG_ENTRY(transaction_log);
static int __init binder_init(void)
{
int ret;
binder_deferred_workqueue = create_singlethread_workqueue("binder");
if (!binder_deferred_workqueue)
return -ENOMEM;
binder_debugfs_dir_entry_root = debugfs_create_dir("binder", NULL);
if (binder_debugfs_dir_entry_root)
binder_debugfs_dir_entry_proc = debugfs_create_dir("proc",
binder_debugfs_dir_entry_root);
ret = misc_register(&binder_miscdev);
if (binder_debugfs_dir_entry_root) {
debugfs_create_file("state",
S_IRUGO,
binder_debugfs_dir_entry_root,
NULL,
&binder_state_fops);
debugfs_create_file("stats",
S_IRUGO,
binder_debugfs_dir_entry_root,
NULL,
&binder_stats_fops);
debugfs_create_file("transactions",
S_IRUGO,
binder_debugfs_dir_entry_root,
NULL,
&binder_transactions_fops);
debugfs_create_file("transaction_log",
S_IRUGO,
binder_debugfs_dir_entry_root,
&binder_transaction_log,
&binder_transaction_log_fops);
debugfs_create_file("failed_transaction_log",
S_IRUGO,
binder_debugfs_dir_entry_root,
&binder_transaction_log_failed,
&binder_transaction_log_fops);
}
return ret;
}
device_initcall(binder_init);
#define CREATE_TRACE_POINTS
#include "binder_trace.h"
MODULE_LICENSE("GPL v2");
| TeamTwisted/leanKernel-shamu | drivers/staging/android/binder.c | C | gpl-2.0 | 103,617 |
DROP FUNCTION IF EXISTS core.get_shipping_address_by_shipping_address_id(bigint);
CREATE FUNCTION core.get_shipping_address_by_shipping_address_id(bigint)
RETURNS text
AS
$$
BEGIN
IF($1 IS NULL OR $1 <=0) THEN
RETURN '';
END IF;
RETURN
core.append_if_not_null(po_box, '<br />') ||
core.append_if_not_null(address_line_1, '<br />') ||
core.append_if_not_null(address_line_2, '<br />') ||
core.append_if_not_null(street, '<br />') ||
city || '<br />' ||
state || '<br />' ||
country
FROM core.shipping_addresses
WHERE shipping_address_id=$1;
END
$$
LANGUAGE plpgsql;
--SELECT core.get_shipping_address_by_shipping_address_id(1);
| mixerp/mixerp | src/FrontEnd/db/1.x/1.1/src/02.functions-and-logic/core/core.get_shipping_address_by_shipping_address_id.sql | SQL | gpl-3.0 | 851 |
<?php error_reporting(E_ALL ^ E_NOTICE);?>
<?php require_once('../conexiones/conexione.php');
require_once('../evitar_mensaje_error/error.php');
mysql_select_db($base_datos, $conectar);
include ("../session/funciones_admin.php");
if (verificar_usuario()){
//print "Bienvenido (a), <strong>".$_SESSION['usuario'].", </strong>al sistema.";
} else { header("Location:../index.php");
}
$cuenta_actual = addslashes($_SESSION['usuario']);
include ("../seguridad/seguridad_diseno_plantillas.php");
$nivel_acceso = '3';
if ($seguridad_acceso['cod_seguridad'] <> $nivel_acceso) {
header("Location:../admin/acceso_denegado.php");
}
include ("../registro_movimientos/registro_movimientos.php");
$buscar = $_POST['palabra'];
$mostrar_datos_sql = "SELECT * FROM productos WHERE cod_productos_var like '$buscar' OR nombre_productos like '%$buscar%' order by nombre_productos";
$consulta = mysql_query($mostrar_datos_sql, $conectar) or die(mysql_error());
$matriz_consulta = mysql_fetch_assoc($consulta);
?>
<!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>ALMACEN</title>
</head>
<br>
<?php require_once("../busquedas/busqueda_productos_eliminar.php");?>
<body>
<p>
<?php
if ($buscar <> NULL) {
?>
<br>
<center>
<table width="90%">
<tr>
<td align="center"><strong>CODIGO</strong></td>
<td align="center"><strong>PRODUCTO</strong></td>
<!--<td><strong>Marca</strong></td>
<td><strong>Proveedor</strong></td>-->
<td align="center"><strong>UND</strong></td>
<td align="center"><strong>P.COMPRA</strong></td>
<td align="center"><strong>P.VENTA</strong></td>
<!--<td><strong>Margen Utilidad</strong></td>-->
<td align="center"><strong>DESCRIPCION</strong></td>
<td align="center"><strong>ELIM</strong></td>
</tr>
<?php do { ?>
<tr>
<td align="left"><?php echo $matriz_consulta['cod_productos_var']; ?></td>
<td align="left"><?php echo $matriz_consulta['nombre_productos']; ?></td>
<!--<td><?php //echo $matriz_consulta['nombre_marcas']; ?></td>
<td><?php //echo $matriz_consulta['nombre_proveedores']; ?></td>-->
<td align="right"><?php echo $matriz_consulta['unidades_faltantes']; ?></td>
<td align="right"><?php echo number_format($matriz_consulta['precio_costo']); ?></td>
<td align="right"><?php echo number_format($matriz_consulta['precio_venta']); ?></td>
<!--<td><?php //echo number_format($matriz_consulta['utilidad']); ?></td>-->
<td align="right"><?php echo $matriz_consulta['descripcion']; ?></td>
<td><a href="../modificar_eliminar/eliminar_productos.php?cod_productos=<?php echo $matriz_consulta['cod_productos']; ?>"><center><img src=../imagenes/eliminar.png></center></a></td>
</tr>
<?php } while ($matriz_consulta = mysql_fetch_assoc($consulta)); ?>
</table>
</body>
</html>
<?php
} else {
}
?>
<script>
window.onload = function() {
document.getElementById("foco").focus();
}
</script> | dataxe/proyectos | pinsalud/modificar_eliminar/productos_eliminar.php | PHP | gpl-3.0 | 2,988 |
<?php
/* ----------------------------------------------------------------------
* support/import/aat/import_tgn.php : Import Getty TGN XML-UTF8 files (2012 edition - should work for others as well)
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2013 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
define("__CA_DONT_DO_SEARCH_INDEXING__", 1);
define("__CA_DONT_LOG_CHANGES__", 1);
require_once("../../../setup.php");
if (!file_exists('./tgn_xml_12')) {
die("ERROR: you must place the 'tgn_xml_12' data file directory in the same directory as this script.\n");
}
// ---------------------------------------------------------------------------
// CHANGE THESE VALUES TO REFLECT YOUR CONFIGURATION
// ---------------------------------------------------------------------------
//
// Code for metadata element to insert description for places into.
// Set to null to not import descriptions.
$vs_description_element_code = 'generalNotes';
// Code for metadata element to insert georeferences for places into.
// Set to null to not import georefs.
$vs_georef_element_code = 'georeference';
// Code for relationship type to relate place types to.
// Set to null to not import place types
$vs_place_type_relationship_code = 'describes';
// ---------------------------------------------------------------------------
require_once(__CA_LIB_DIR__.'/core/Db.php');
require_once(__CA_LIB_DIR__.'/core/Utils/CLIProgressBar.php');
require_once(__CA_LIB_DIR__.'/ca/Utils/DataMigrationUtils.php');
require_once(__CA_MODELS_DIR__.'/ca_locales.php');
require_once(__CA_MODELS_DIR__.'/ca_places.php');
require_once(__CA_MODELS_DIR__.'/ca_places_x_places.php');
require_once(__CA_MODELS_DIR__.'/ca_relationship_types.php');
$_ = new Zend_Translate('gettext', __CA_APP_DIR__.'/locale/en_US/messages.mo', 'en_US');
$t_locale = new ca_locales();
$pn_en_locale_id = $t_locale->loadLocaleByCode('en_US');
// create place hierarchy (if it doesn't exist already)
$t_list = new ca_lists();
if (!$t_list->load(array('list_code' => 'place_hierarchies'))) {
$t_list->setMode(ACCESS_WRITE);
$t_list->set('list_code', 'place_hierarchies');
$t_list->set('is_system_list', 1);
$t_list->set('is_hierarchical', 1);
$t_list->set('use_as_vocabulary', 0);
$t_list->insert();
if ($t_list->numErrors()) {
print "[Error] couldn't create ca_list row for place hierarchies: ".join('; ', $t_list->getErrors())."\n";
die;
}
$t_list->addLabel(array('name' => 'Place hierarchies'), $pn_en_locale_id, null, true);
}
$vn_list_id = $t_list->getPrimaryKey();
// create place hierarchy
if (!($vn_tgn_id = caGetListItemID('place_hierarchies', 'tgn'))) {
$t_tgn = $t_list->addItem('tgn', true, false, null, null, 'tgn');
$t_tgn->addLabel(
array('name_singular' => 'Thesaurus of Geographic Names', 'name_plural' => 'Thesaurus of Geographic Names'),
$pn_en_locale_id, null, true
);
$vn_tgn_id = $t_tgn->getPrimaryKey();
} else {
$t_tgn = new ca_list_items($vn_tgn_id);
}
// Create list for place types (if it doesn't exist already)
$t_place_types = new ca_lists();
if (!$t_place_types->load(array('list_code' => 'tgn_place_types'))) {
$t_place_types->setMode(ACCESS_WRITE);
$t_place_types->set('list_code', 'tgn_place_types');
$t_place_types->set('is_system_list', 1);
$t_place_types->set('is_hierarchical', 1);
$t_place_types->set('use_as_vocabulary', 1);
$t_place_types->insert();
if ($t_place_types->numErrors()) {
print "[Error] couldn't create ca_list row for place types: ".join('; ', $t_place_types->getErrors())."\n";
die;
}
$t_place_types->addLabel(array('name' => 'Getty TGN place types'), $pn_en_locale_id, null, true);
}
$vn_place_type_list_id = $t_place_types->getPrimaryKey();
// load places
$o_xml = new XMLReader();
print "[Notice] READING TGN TERMS...\n";
$vn_last_message_length = 0;
$vn_term_count = 0;
$t_place = new ca_places();
$t_place->setMode(ACCESS_WRITE);
$t_place->logChanges(false); // Don't log changes to records during import β takes time and we don't need the logs
if (true) {
for($vn_file_index=1; $vn_file_index <= 15; $vn_file_index++) {
$o_xml->open("tgn_xml_12/TGN{$vn_file_index}.xml");
print "\n[Notice] READING TERMS FROM TGN{$vn_file_index}.xml...\n";
while($o_xml->read()) {
switch($o_xml->name) {
# ---------------------------
case 'Subject':
if ($o_xml->nodeType == XMLReader::END_ELEMENT) {
if ($va_subject['subject_id'] == '100000000') { break; } // skip top-level root
$vs_preferred_term = $va_subject['preferred_term'];
switch($va_subject['record_type']) {
default:
$vn_type_id = null;
$pb_is_enabled = true;
break;
}
print str_repeat(chr(8), $vn_last_message_length);
$vs_message = "[Notice] IMPORTING #".($vn_term_count+1)." [".$va_subject['subject_id']."] ".$vs_preferred_term;
if (($vn_l = 100-strlen($vs_message)) < 1) { $vn_l = 1; }
$vs_message .= str_repeat(' ', $vn_l);
$vn_last_message_length = strlen($vs_message);
print $vs_message;
$t_place->clear();
$t_place->set('parent_id', null);
$t_place->set('type_id', $vn_type_id);
$t_place->set('idno', $va_subject['subject_id']);
$t_place->set('hierarchy_id', $vn_tgn_id);
// Add description
if ($vs_description_element_code && $va_subject['description']) {
$t_place->addAttribute(
array($vs_description_element_code => $va_subject['description'], 'locale_id' => $pn_en_locale_id),
$vs_description_element_code
);
}
// Add georeference
if ($vs_georef_element_code && ($va_coords['latitude']['decimal'] && $va_coords['longitude']['decimal'])) {
$t_place->addAttribute(
array($vs_georef_element_code => "[".$va_coords['latitude']['decimal'].$va_coords['latitude']['direction'].",".$va_coords['longitude']['decimal'].$va_coords['longitude']['direction']."]", 'locale_id' => $pn_en_locale_id),
$vs_georef_element_code
);
DataMigrationUtils::postError($t_place, "[Error] While adding georeference to place");
}
if ($vn_place_id = $t_place->insert(array('dontSetHierarchicalIndexing' => true))) {
if (!($t_place->addLabel(
array('name' => $vs_preferred_term, 'description' => ''),
$pn_en_locale_id, null, true
))) {
print "[Error] Could not add preferred label to TGN term [".$va_subject['subject_id']."] ".$vs_preferred_term.": ".join("; ", $t_place->getErrors())."\n";
}
// add alternate labels
if(is_array($va_subject['non_preferred_terms'])) {
for($vn_i=0; $vn_i < sizeof($va_subject['non_preferred_terms']); $vn_i++) {
$vs_np_label = $va_subject['non_preferred_terms'][$vn_i];
$vs_np_term_type = $va_subject['non_preferred_term_types'][$vn_i];
switch($vs_np_term_type) {
default:
$vn_np_term_type_id = null;
break;
}
if (!($t_place->addLabel(
array('name' => $vs_np_label, 'description' => ''),
$pn_en_locale_id, $vn_np_term_type_id, false
))) {
print "[Error] Could not add non-preferred label to TGN term [".$va_subject['subject_id']."] ".$vs_np_label.": ".join("; ", $t_place->getErrors())."\n";
}
}
}
// Add place types
if ($vs_place_type_relationship_code && $va_subject['place_type_id']) {
$va_tmp = explode('/', $va_subject['place_type_id']);
if ($vn_item_id = DataMigrationUtils::getListItemID('tgn_place_types', $va_tmp[0], null, $pn_en_locale_id, array('name_singular' => $va_tmp[1], 'name_plural' => $va_tmp[1]), array())) {
$t_place->addRelationship('ca_list_items', $vn_item_id, $vs_place_type_relationship_code, null, null, null, null, array('allowDuplicates' => true));
DataMigrationUtils::postError($t_place, "[Error] While adding place type to place");
}
}
$vn_term_count++;
} else {
print "[Error] Could not import TGN term [".$va_subject['subject_id']."] ".$vs_preferred_term.": ".join("; ", $t_list->getErrors())."\n";
}
} else {
$va_subject = array('subject_id' => $o_xml->getAttribute('Subject_ID'));
$va_coords = array();
}
break;
# ---------------------------
case 'Descriptive_Note':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
while($o_xml->read()) {
switch($o_xml->name) {
case 'Note_Text':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['description'] = $o_xml->value;
break;
}
break;
case 'Descriptive_Note':
break(2);
}
}
}
break;
# ---------------------------
case 'Preferred_Place_Type':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
while($o_xml->read()) {
switch($o_xml->name) {
case 'Place_Type_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['place_type_id'] = $o_xml->value;
break(3);
}
break;
case 'Preferred_Place_Type':
break(2);
}
}
}
break;
# ---------------------------
case 'Record_Type':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['record_type'] = $o_xml->value;
break;
}
break;
# ---------------------------
case 'Parent_Relationships':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
$vn_parent_id = $vs_historic_flag = null;
while($o_xml->read()) {
switch($o_xml->name) {
case 'Parent_Subject_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$vn_parent_id = $o_xml->value;
break;
}
break;
case 'Historic_Flag':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$vs_historic_flag = $o_xml->value;
break;
}
break;
case 'Preferred_Parent':
$va_subject['preferred_parent_subject_id'] = $vn_parent_id;
break;
case 'Parent_Relationships':
break(2);
}
}
}
break;
# ---------------------------
case 'Preferred_Term':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
while($o_xml->read()) {
switch($o_xml->name) {
case 'Term_Type':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['preferred_term_type'] = $o_xml->value;
break;
}
break;
case 'Term_Text':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['preferred_term'] = $o_xml->value;
break;
}
break;
case 'Term_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['preferred_term_id'] = $o_xml->value;
break;
}
break;
case 'Preferred_Term':
break(2);
}
}
}
break;
# ---------------------------
case 'Non-Preferred_Term':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
while($o_xml->read()) {
switch($o_xml->name) {
case 'Term_Type':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['non_preferred_term_types'][] = $o_xml->value;
break;
}
break;
case 'Term_Text':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['non_preferred_terms'][] = $o_xml->value;
break;
}
break;
case 'Term_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['non_preferred_term_ids'][] = $o_xml->value;
break;
}
break;
case 'Non-Preferred_Term':
break(2);
}
}
}
break;
# ---------------------------
case 'VP_Subject_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['related_subjects'][] = $o_xml->value;
break;
}
break;
# ---------------------------
case 'Coordinates':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
$va_coords = array();
while($o_xml->read()) {
switch($o_xml->name) {
case 'Latitude':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
$va_coords['latitude'] = array();
while($o_xml->read()) {
switch($o_xml->name) {
case 'Decimal':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_coords['latitude']['decimal'] = abs($o_xml->value);
break;
}
break;
case 'Direction':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_coords['latitude']['direction'] = substr($o_xml->value,0, 1);
break;
}
break;
case 'Latitude':
break(2);
}
}
}
break;
case 'Longitude':
if ($o_xml->nodeType == XMLReader::ELEMENT) {
$va_coords['longitude'] = array();
while($o_xml->read()) {
switch($o_xml->name) {
case 'Decimal':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_coords['longitude']['decimal'] = abs($o_xml->value);
break;
}
break;
case 'Direction':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_coords['longitude']['direction'] = substr($o_xml->value,0,1);
break;
}
break;
case 'Longitude':
break(2);
}
}
}
break ;
case 'Coordinates':
break(2);
}
}
}
break;
# ---------------------------
}
}
$o_xml->close();
}
}
$t_place = new ca_places();
$t_parent = new ca_places();
$t_place->setMode(ACCESS_WRITE);
$vn_tgn_root_id = $t_parent->getHierarchyRootID($vn_tgn_id);
if (true) {
print "[Notice] LINKING TERMS IN HIERARCHY...\n";
$vn_last_message_length = 0;
$va_place_id_cache = array();
for($vn_file_index=1; $vn_file_index <= 15; $vn_file_index++) {
$o_xml->open("tgn_xml_12/TGN{$vn_file_index}.xml");
print "[Notice] READING TERMS FROM TGN{$vn_file_index}.xml...\n";
$va_subject = array();
while($o_xml->read()) {
switch($o_xml->name) {
# ---------------------------
case 'Subject':
if ($o_xml->nodeType == XMLReader::END_ELEMENT) {
$vs_child_id = $va_subject['subject_id'];
$vs_parent_id = $va_subject['preferred_parent_subject_id'];
if (!$vs_parent_id) { continue; }
print str_repeat(chr(8), $vn_last_message_length);
$vs_message = "[Error] LINKING {$vs_child_id} to parent {$vs_parent_id}";
if (($vn_l = 100-strlen($vs_message)) < 1) { $vn_l = 1; }
$vs_message .= str_repeat(' ', $vn_l);
$vn_last_message_length = strlen($vs_message);
print $vs_message;
if(!$t_place->load(array('idno' => $vs_child_id))) {
print "[Error] could not load item for {$vs_child_id} (was translated to item_id={$vn_child_item_id})\n";
continue;
}
if ($vs_parent_id == '100000000') {
//$t_parent->load($vn_tgn_root_id); // get root_id
$vn_parent_id = $vn_tgn_root_id;
} else {
if (!isset($va_place_id_cache[$vs_parent_id])) {
if(!$t_parent->load(array('idno' => $vs_parent_id))) {
print "[Error] No list item id for parent_id {$vs_parent_id} (were there previous errors?)\n";
continue;
}
$vn_parent_id = $va_place_id_cache[$vs_parent_id] = $t_parent->getPrimaryKey();
} else {
$vn_parent_id = $va_place_id_cache[$vs_parent_id];
}
$t_place->set('parent_id', $vn_parent_id);
$t_place->update(array('dontSetHierarchicalIndexing' => true, 'dontCheckCircularReferences' => true));
if ($t_place->numErrors()) {
print "[Error] could not set parent_id for {$vs_child_id} (was translated to item_id=".$t_place->getPrimaryKey()."): ".join('; ', $t_place->getErrors())."\n";
}
}
} else {
$va_subject = array('subject_id' => $o_xml->getAttribute('Subject_ID'));
}
break;
# ---------------------------
case 'Parent_Relationships':
$vn_parent_id = $vs_historic_flag = null;
while($o_xml->read()) {
switch($o_xml->name) {
case 'Preferred_Parent':
while($o_xml->read()) {
switch($o_xml->name) {
case 'Parent_Subject_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$vn_parent_id = $o_xml->value;
break;
}
break;
case 'Historic_Flag':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$vs_historic_flag = $o_xml->value;
break;
}
break;
case 'Preferred_Parent':
$va_subject['preferred_parent_subject_id'] = $vn_parent_id;
break(2);
}
}
break;
case 'Parent_Relationships':
break(2);
}
}
break;
# ---------------------------
}
}
}
}
// TODO: Fix self-referencing root problem (TGN imports "top of hierarchy" record as having itself as a parent)
print "[Notice] Rebuilding hier indices for hierarchy_id={$vn_tgn_id}...\n";
$t_place->rebuildHierarchicalIndex($vn_tgn_id);
if (true) {
print "[Notice] ADDING RELATED PLACE LINKS...\n";
$vn_last_message_length = 0;
$t_place = new ca_places();
$t_place->setMode(ACCESS_WRITE);
$t_link = new ca_places_x_places();
$t_link->setMode(ACCESS_WRITE);
$t_rel_type = new ca_relationship_types();
for($vn_file_index=1; $vn_file_index <= 15; $vn_file_index++) {
$o_xml->open("tgn_xml_12/TGN{$vn_file_index}.xml");
print "[Notice] READING TERMS FROM TGN{$vn_file_index}.xml...\n";
$va_subject = array();
while($o_xml->read()) {
switch($o_xml->name) {
# ---------------------------
case 'Subject':
if ($o_xml->nodeType == XMLReader::END_ELEMENT) {
// noop
$vs_child_id = $va_subject['subject_id'];
$vs_parent_id = $va_subject['preferred_parent_subject_id'];
if (!$vs_parent_id) { continue; }
print str_repeat(chr(8), $vn_last_message_length);
$vs_message = "[Error] LINKING {$vs_child_id} to parent {$vs_parent_id}";
if (($vn_l = 100-strlen($vs_message)) < 1) { $vn_l = 1; }
$vs_message .= str_repeat(' ', $vn_l);
$vn_last_message_length = strlen($vs_message);
print $vs_message;
if(!$t_place->load(array('idno' => $va_subject['subject_id']))) {
print "[Error] could not load place for ".$va_subject['subject_id']."\n";
continue;
}
if(!$t_related_place->load(array('idno' => $$va_subject['related_subject_id']))) {
print "[Error] could not load related place ".$va_subject['related_subject_id']."\n";
continue;
}
$va_tmp = explode("/", $va_subject['relationship_type']);
$vn_rel_type_id = $t_rel_type->getRelationshipTypeID($t_link->tableNum(), $va_tmp[0], $pn_en_locale_id, array('typename' => $va_tmp[1]), array('create' => true));
$t_link->set('term_left_id', $t_place->getPrimaryKey());
$t_link->set('term_right_id', $t_related_place->getPrimaryKey());
$t_link->set('type_id', $vn_rel_type_id);
$t_link->insert();
if ($t_link->numErrors()) {
print "[Error] could not link ".$va_subject['subject_id']." to ".$va_subject['related_subject_id'].": ".join('; ', $t_place->getErrors())."\n";
}
} else {
$va_subject = array('subject_id' => $o_xml->getAttribute('Subject_ID'));
}
break;
# ---------------------------
case 'Associative_Relationships':
$vn_parent_id = $vs_historic_flag = null;
while($o_xml->read()) {
switch($o_xml->name) {
case 'Associative_Relationship':
while($o_xml->read()) {
switch($o_xml->name) {
case 'Historic_Flag':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['historic_flag'] = $o_xml->value;
break;
}
break;
case 'Relationship_Type':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['relationship_type'] = $o_xml->value;
break;
}
break;
case 'VP_Subject_ID':
switch($o_xml->nodeType) {
case XMLReader::ELEMENT:
$o_xml->read();
$va_subject['related_subject_id'] = $o_xml->value;
break;
}
break;
}
}
break;
}
}
break;
# ---------------------------
}
}
}
}
if ($vn_list_item_relation_type_id_related > 0) {
print "[Notice] ADDING RELATED PLACE LINKS...\n";
$vn_last_message_length = 0;
$t_place = new ca_places();
$t_link = new ca_places_x_places();
$t_link->setMode(ACCESS_WRITE);
foreach($va_item_item_links as $vs_left_id => $vs_right_id) {
print str_repeat(chr(8), $vn_last_message_length);
$vs_message = "[Notice] LINKING {$vs_left_id} to {$vs_right_id}";
if (($vn_l = 100-strlen($vs_message)) < 1) { $vn_l = 1; }
$vs_message .= str_repeat(' ', $vn_l);
$vn_last_message_length = strlen($vs_message);
print $vs_message;
if (!($vn_left_item_id = $va_tgn_id_to_place_id[$vs_left_id])) {
print "[Error] no list item id for left_id {$vs_left_id} (were there previous errors?)\n";
continue;
}
if (!($vn_right_item_id = $va_tgn_id_to_place_id[$vs_right_id])) {
print "[Error] no list item id for right_id {$vs_right_id} (were there previous errors?)\n";
continue;
}
$t_link->set('term_left_id', $vn_left_item_id);
$t_link->set('term_right_id', $vn_right_item_id);
$t_link->set('type_id', $vn_list_item_relation_type_id_related);
$t_link->insert();
if ($t_link->numErrors()) {
print "[Error] could not set link between {$vs_left_id} (was translated to item_id={$vn_left_item_id}) and {$vs_right_id} (was translated to item_id={$vn_right_item_id}): ".join('; ', $t_link->getErrors())."\n";
}
}
} else {
print "[Warning] Skipped import of term-term relationships because the ca_list_items_x_list_items 'related' relationship type is not defined for your installation\n";
}
print "[Notice] IMPORT COMPLETE.\n";
?> | libis/ca_babtekst | support/import/tgn/import_tgn.php | PHP | gpl-3.0 | 24,601 |
/*
* Copyright (C) 2010 Google Inc. 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.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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.
*/
#ifndef AudioDestinationChromium_h
#define AudioDestinationChromium_h
#include "AudioBus.h"
#include "AudioDestination.h"
#include "WebAudioDevice.h"
#include "WebVector.h"
namespace WebKit { class WebAudioDevice; }
namespace WebCore {
// An AudioDestination using Chromium's audio system
class AudioDestinationChromium : public AudioDestination, public WebKit::WebAudioDevice::RenderCallback {
public:
AudioDestinationChromium(AudioSourceProvider&, double sampleRate);
virtual ~AudioDestinationChromium();
virtual void start();
virtual void stop();
bool isPlaying() { return m_isPlaying; }
double sampleRate() const { return m_sampleRate; }
// WebKit::WebAudioDevice::RenderCallback
virtual void render(const WebKit::WebVector<float*>& audioData, size_t numberOfFrames);
private:
AudioSourceProvider& m_provider;
AudioBus m_renderBus;
double m_sampleRate;
bool m_isPlaying;
OwnPtr<WebKit::WebAudioDevice> m_audioDevice;
};
} // namespace WebCore
#endif // AudioDestinationChromium_h
| danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Source/WebKit/chromium/src/AudioDestinationChromium.h | C | gpl-3.0 | 2,617 |
// { dg-options "-std=gnu++11" }
// { dg-do compile }
// Copyright (C) 2013-2016 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/>.
// NB: This file is for testing type_traits with NO OTHER INCLUDES.
#include <type_traits>
namespace std
{
typedef short test_type;
template struct is_empty<test_type>;
}
| selmentdev/selment-toolchain | source/gcc-latest/libstdc++-v3/testsuite/20_util/is_empty/requirements/explicit_instantiation.cc | C++ | gpl-3.0 | 996 |
// 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/>.
/**
* Fetch and render dates from timestamps.
*
* @module core/user_date
* @package core
* @copyright 2017 Ryan Wyllie <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery', 'core/ajax', 'core/sessionstorage', 'core/config'],
function($, Ajax, Storage, Config) {
/** @var {object} promisesCache Store all promises we've seen so far. */
var promisesCache = {};
/**
* Generate a cache key for the given request. The request should
* have a timestamp and format key.
*
* @param {object} request
* @return {string}
*/
var getKey = function(request) {
var language = $('html').attr('lang').replace('-', '_');
return 'core_user_date/' +
language + '/' +
Config.usertimezone + '/' +
request.timestamp + '/' +
request.format;
};
/**
* Retrieve a transformed date from the browser's storage.
*
* @param {string} key
* @return {string}
*/
var getFromLocalStorage = function(key) {
return Storage.get(key);
};
/**
* Save the transformed date in the browser's storage.
*
* @param {string} key
* @param {string} value
*/
var addToLocalStorage = function(key, value) {
Storage.set(key, value);
};
/**
* Check if a key is in the module's cache.
*
* @param {string} key
* @return {bool}
*/
var inPromisesCache = function(key) {
return (typeof promisesCache[key] !== 'undefined');
};
/**
* Retrieve a promise from the module's cache.
*
* @param {string} key
* @return {object} jQuery promise
*/
var getFromPromisesCache = function(key) {
return promisesCache[key];
};
/**
* Save the given promise in the module's cache.
*
* @param {string} key
* @param {object} promise
*/
var addToPromisesCache = function(key, promise) {
promisesCache[key] = promise;
};
/**
* Send a request to the server for each of the required timestamp
* and format combinations.
*
* Resolves the date's deferred with the values returned from the
* server and saves the value in local storage.
*
* @param {array} dates
* @return {object} jQuery promise
*/
var loadDatesFromServer = function(dates) {
var args = dates.map(function(data) {
return {
timestamp: data.timestamp,
format: data.format
};
});
var request = {
methodname: 'core_get_user_dates',
args: {
contextid: Config.contextid,
timestamps: args
}
};
return Ajax.call([request], true, true)[0].then(function(results) {
results.dates.forEach(function(value, index) {
var date = dates[index];
var key = getKey(date);
addToLocalStorage(key, value);
date.deferred.resolve(value);
});
})
.fail(function(ex) {
// If we failed to retrieve the dates then reject the date's
// deferred objects to make sure they don't hang.
dates.forEach(function(date) {
date.deferred.reject(ex);
});
});
};
/**
* Takes an array of request objects and returns a promise that
* is resolved with an array of formatted dates.
*
* The values in the returned array will be ordered the same as
* the request array.
*
* This function will check both the module's static promises cache
* and the browser's session storage to see if the user dates have
* already been loaded in order to avoid sending a network request
* if possible.
*
* Only dates not found in either cache will be sent to the server
* for transforming.
*
* A request object must have a timestamp key and a format key.
*
* E.g.
* var request = [
* {
* timestamp: 1293876000,
* format: '%d %B %Y'
* },
* {
* timestamp: 1293876000,
* format: '%A, %d %B %Y, %I:%M %p'
* }
* ];
*
* UserDate.get(request).done(function(dates) {
* console.log(dates[0]); // prints "1 January 2011".
* console.log(dates[1]); // prints "Saturday, 1 January 2011, 10:00 AM".
* });
*
* @param {array} requests
* @return {object} jQuery promise
*/
var get = function(requests) {
var ajaxRequests = [];
var promises = [];
// Loop over each of the requested timestamp/format combos
// and add a promise to the promises array for them.
requests.forEach(function(request) {
var key = getKey(request);
// If we've already got a promise then use it.
if (inPromisesCache(key)) {
promises.push(getFromPromisesCache(key));
} else {
var deferred = $.Deferred();
var cached = getFromLocalStorage(key);
if (cached) {
// If we were able to get the value from session storage
// then we can resolve the deferred with that value. No
// need to ask the server to transform it for us.
deferred.resolve(cached);
} else {
// Add this request to the list of ones we need to load
// from the server. Include the deferred so that it can
// be resolved when the server has responded with the
// transformed values.
request.deferred = deferred;
ajaxRequests.push(request);
}
// Remember this promise for next time so that we can
// bail out early if it is requested again.
addToPromisesCache(key, deferred.promise());
promises.push(deferred.promise());
}
});
// If we have any requests that we couldn't resolve from the caches
// then let's ask the server to get them for us.
if (ajaxRequests.length) {
loadDatesFromServer(ajaxRequests);
}
// Wait for all of the promises to resolve. Some of them may be waiting
// for a response from the server.
return $.when.apply($, promises).then(function() {
// This looks complicated but it's just converting an unknown
// length of arguments into an array for the promise to resolve
// with.
return arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments);
});
};
return {
get: get
};
});
| IvanHod/moodle | lib/amd/src/user_date.js | JavaScript | gpl-3.0 | 7,627 |
// This file has been generated by Py++.
#ifndef FontManager_hpp__pyplusplus_wrapper
#define FontManager_hpp__pyplusplus_wrapper
void register_FontManager_class();
#endif//FontManager_hpp__pyplusplus_wrapper
| geminy/aidear | oss/cegui/cegui-0.8.7/cegui/src/ScriptModules/Python/bindings/output/CEGUI/FontManager.pypp.hpp | C++ | gpl-3.0 | 211 |
<?php error_reporting(E_ALL ^ E_NOTICE);?>
<?php require_once('../conexiones/conexione.php');
require_once('../evitar_mensaje_error/error.php');
mysql_select_db($base_datos, $conectar);
include ("../session/funciones_admin.php");
if (verificar_usuario()){
//print "Bienvenido (a), <strong>".$_SESSION['usuario'].", </strong>al sistema.";
} else { header("Location:../index.php");
}
$cuenta_actual = addslashes($_SESSION['usuario']);
include ("../seguridad/seguridad_diseno_plantillas.php");
include ("../formato_entrada_sql/funcion_env_val_sql.php");
$cod_productos = $_GET['cod_productos'];
$cod_factura = $_GET['cod_factura'];
$cod_ventas = $_GET['cod_ventas'];
$pagina = $_GET['pagina'];
$datos_producto = "SELECT * FROM ventas WHERE cod_ventas = '$cod_ventas'";
$consulta_toten = mysql_query($datos_producto, $conectar) or die(mysql_error());
$producto_factura = mysql_fetch_assoc($consulta_toten);
$cantidad = $producto_factura['unidades_vendidas'];
$fecha = date("d/m/Y - H:i:s");
$buscar_producto_actual = "SELECT * FROM productos WHERE cod_productos_var = '$cod_productos'";
$consulta_total = mysql_query($buscar_producto_actual, $conectar) or die(mysql_error());
$producto_actual = mysql_fetch_assoc($consulta_total);
$unidades_faltantes = $producto_actual['unidades_faltantes'] + $cantidad;
$unidades_vendidas = $producto_actual['unidades_vendidas'] - $cantidad;
$total_mercancia = $unidades_faltantes * $producto_actual['precio_compra'];
$total_venta = ($producto_actual['total_venta']) - ($producto_actual['precio_compra'] * $cantidad);
$total_utilidad = $producto_actual['total_utilidad'] - (($producto_actual['precio_venta'] - $producto_actual['precio_compra']) * $cantidad);
if ((isset($cod_productos)) && ($cod_productos != "")) {
$borrar_de_ventas = sprintf("DELETE FROM ventas WHERE cod_ventas = '$cod_ventas'");
$Resultado2 = mysql_query($borrar_de_ventas, $conectar) or die(mysql_error());
$productos_regresados = sprintf("UPDATE productos SET unidades_faltantes = '$unidades_faltantes', unidades_vendidas = '$unidades_vendidas',
total_mercancia = '$total_mercancia', total_venta = '$total_venta', total_utilidad = '$total_utilidad' WHERE cod_productos_var = '$cod_productos'");
$Resultado3 = mysql_query($productos_regresados, $conectar) or die(mysql_error());
$factura_producto_cancelado = sprintf("INSERT INTO factura_producto_cancelado (vendedor, cliente, cod_productos, cod_factura,
nombre_productos, unidades_vendidas, vlr_unitario, vlr_total, fecha) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
envio_valores_tipo_sql($cuenta_actual, "text"),
envio_valores_tipo_sql($producto_factura['cod_clientes'], "text"),
envio_valores_tipo_sql($producto_factura['cod_productos'], "text"),
envio_valores_tipo_sql($producto_factura['cod_factura'], "text"),
envio_valores_tipo_sql($producto_factura['nombre_productos'], "text"),
envio_valores_tipo_sql($cantidad, "text"),
envio_valores_tipo_sql($producto_factura['precio_venta'], "text"),
envio_valores_tipo_sql($producto_factura['vlr_total_venta'], "text"),
envio_valores_tipo_sql($fecha, "text"));
$Resultado4 = mysql_query($factura_producto_cancelado, $conectar) or die(mysql_error());
echo "<META HTTP-EQUIV='REFRESH' CONTENT='0.2; ../admin/busq_facturas_fecha.php'>";
}
?>
<!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>ALMACEN</title>
</head>
<body>
</body>
</html>
| dataxe/proyectos | pinsalud/modificar_eliminar/eliminar_productos_factura.php | PHP | gpl-3.0 | 3,557 |
//>>built
define("gridx/nls/tr/QuickFilter",{filterLabel:"SΓΌzgeΓ§",clearButtonTitle:"SΓΌzgeci KaldΔ±r",buildFilterMenuLabel:"SΓΌzgeΓ§ OluΕtur…",apply:"SΓΌzgeci Uygula"});
| cosmoharrigan/viewer | public/lib/dojo/gridx/nls/tr/QuickFilter.js | JavaScript | agpl-3.0 | 180 |
"""
Setup script for the Open edX package.
"""
from setuptools import setup
setup(
name="Open edX",
version="0.6",
install_requires=["setuptools"],
requires=[],
# NOTE: These are not the names we should be installing. This tree should
# be reorganized to be a more conventional Python tree.
packages=[
"openedx.core.djangoapps.course_groups",
"openedx.core.djangoapps.credit",
"openedx.core.djangoapps.user_api",
"lms",
"cms",
],
entry_points={
"openedx.course_tab": [
"ccx = lms.djangoapps.ccx.plugins:CcxCourseTab",
"courseware = lms.djangoapps.courseware.tabs:CoursewareTab",
"course_info = lms.djangoapps.courseware.tabs:CourseInfoTab",
"discussion = lms.djangoapps.discussion.plugins:DiscussionTab",
"edxnotes = lms.djangoapps.edxnotes.plugins:EdxNotesTab",
"external_discussion = lms.djangoapps.courseware.tabs:ExternalDiscussionCourseTab",
"external_link = lms.djangoapps.courseware.tabs:ExternalLinkCourseTab",
"html_textbooks = lms.djangoapps.courseware.tabs:HtmlTextbookTabs",
"instructor = lms.djangoapps.instructor.views.instructor_dashboard:InstructorDashboardTab",
"notes = lms.djangoapps.notes.views:NotesTab",
"pdf_textbooks = lms.djangoapps.courseware.tabs:PDFTextbookTabs",
"progress = lms.djangoapps.courseware.tabs:ProgressTab",
"static_tab = xmodule.tabs:StaticTab",
"syllabus = lms.djangoapps.courseware.tabs:SyllabusTab",
"teams = lms.djangoapps.teams.plugins:TeamsTab",
"textbooks = lms.djangoapps.courseware.tabs:TextbookTabs",
"wiki = lms.djangoapps.course_wiki.tab:WikiTab",
],
"openedx.user_partition_scheme": [
"random = openedx.core.djangoapps.user_api.partition_schemes:RandomUserPartitionScheme",
"cohort = openedx.core.djangoapps.course_groups.partition_scheme:CohortPartitionScheme",
"verification = openedx.core.djangoapps.credit.partition_schemes:VerificationPartitionScheme",
],
"openedx.block_structure_transformer": [
"library_content = lms.djangoapps.course_blocks.transformers.library_content:ContentLibraryTransformer",
"split_test = lms.djangoapps.course_blocks.transformers.split_test:SplitTestTransformer",
"start_date = lms.djangoapps.course_blocks.transformers.start_date:StartDateTransformer",
"user_partitions = lms.djangoapps.course_blocks.transformers.user_partitions:UserPartitionTransformer",
"visibility = lms.djangoapps.course_blocks.transformers.visibility:VisibilityTransformer",
"hidden_content = lms.djangoapps.course_blocks.transformers.hidden_content:HiddenContentTransformer",
"course_blocks_api = lms.djangoapps.course_api.blocks.transformers.blocks_api:BlocksAPITransformer",
"milestones = lms.djangoapps.course_api.blocks.transformers.milestones:MilestonesTransformer",
"grades = lms.djangoapps.grades.transformer:GradesTransformer",
],
}
)
| louyihua/edx-platform | setup.py | Python | agpl-3.0 | 3,185 |
import os
import subprocess
import threading
import http.server, ssl
def domake():
# build directory
#os.chdir("./../")
server_address = ('localhost', 7443)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
server_side=True,
certfile='localhost.crt',
keyfile='localhost.key',
ssl_version=ssl.PROTOCOL_TLSv1)
print("7443 https server started")
httpd.serve_forever()
# ε©η¨ε·θ‘η·ε·θ‘ https δΌΊζε¨
make = threading.Thread(target=domake)
make.start() | 40423248/2017springcd_hw | localhttp.py | Python | agpl-3.0 | 706 |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_buf_text_h__
#define INCLUDE_buf_text_h__
#include "buffer.h"
typedef enum {
GIT_BOM_NONE = 0,
GIT_BOM_UTF8 = 1,
GIT_BOM_UTF16_LE = 2,
GIT_BOM_UTF16_BE = 3,
GIT_BOM_UTF32_LE = 4,
GIT_BOM_UTF32_BE = 5
} git_bom_t;
typedef struct {
git_bom_t bom; /* BOM found at head of text */
unsigned int nul, cr, lf, crlf; /* NUL, CR, LF and CRLF counts */
unsigned int printable, nonprintable; /* These are just approximations! */
} git_buf_text_stats;
/**
* Append string to buffer, prefixing each character from `esc_chars` with
* `esc_with` string.
*
* @param buf Buffer to append data to
* @param string String to escape and append
* @param esc_chars Characters to be escaped
* @param esc_with String to insert in from of each found character
* @return 0 on success, <0 on failure (probably allocation problem)
*/
extern int git_buf_text_puts_escaped(
git_buf *buf,
const char *string,
const char *esc_chars,
const char *esc_with);
/**
* Append string escaping characters that are regex special
*/
GIT_INLINE(int) git_buf_text_puts_escape_regex(git_buf *buf, const char *string)
{
return git_buf_text_puts_escaped(buf, string, "^.[]$()|*+?{}\\", "\\");
}
/**
* Unescape all characters in a buffer in place
*
* I.e. remove backslashes
*/
extern void git_buf_text_unescape(git_buf *buf);
/**
* Replace all \r\n with \n.
*
* @return 0 on success, -1 on memory error, GIT_PASSTHROUGH if the
* source buffer has mixed line endings.
*/
extern int git_buf_text_crlf_to_lf(git_buf *tgt, const git_buf *src);
/**
* Replace all \n with \r\n. Does not modify existing \r\n.
*
* @return 0 on success, -1 on memory error
*/
extern int git_buf_text_lf_to_crlf(git_buf *tgt, const git_buf *src);
/**
* Fill buffer with the common prefix of a array of strings
*
* Buffer will be set to empty if there is no common prefix
*/
extern int git_buf_text_common_prefix(git_buf *buf, const git_strarray *strs);
/**
* Check quickly if buffer looks like it contains binary data
*
* @param buf Buffer to check
* @return true if buffer looks like non-text data
*/
extern bool git_buf_text_is_binary(const git_buf *buf);
/**
* Check quickly if buffer contains a NUL byte
*
* @param buf Buffer to check
* @return true if buffer contains a NUL byte
*/
extern bool git_buf_text_contains_nul(const git_buf *buf);
/**
* Check if a buffer begins with a UTF BOM
*
* @param bom Set to the type of BOM detected or GIT_BOM_NONE
* @param buf Buffer in which to check the first bytes for a BOM
* @param offset Offset into buffer to look for BOM
* @return Number of bytes of BOM data (or 0 if no BOM found)
*/
extern int git_buf_text_detect_bom(
git_bom_t *bom, const git_buf *buf, size_t offset);
/**
* Gather stats for a piece of text
*
* Fill the `stats` structure with counts of unreadable characters, carriage
* returns, etc, so it can be used in heuristics. This automatically skips
* a trailing EOF (\032 character). Also it will look for a BOM at the
* start of the text and can be told to skip that as well.
*
* @param stats Structure to be filled in
* @param buf Text to process
* @param skip_bom Exclude leading BOM from stats if true
* @return Does the buffer heuristically look like binary data
*/
extern bool git_buf_text_gather_stats(
git_buf_text_stats *stats, const git_buf *buf, bool skip_bom);
#endif
| s-u/guitar | src/libgit2/buf_text.h | C | lgpl-2.1 | 3,589 |
//
// "$Id: Fl_Button.H 10386 2014-10-19 20:17:17Z AlbrechtS $"
//
// Button header file for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2014 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file. If this
// file is missing or damaged, see the license at:
//
// http://www.fltk.org/COPYING.php
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
/* \file
Fl_Button widget . */
#ifndef Fl_Button_H
#define Fl_Button_H
#ifndef Fl_Widget_H
#include "Fl_Widget.H"
#endif
// values for type()
#define FL_NORMAL_BUTTON 0 /**< value() will be set to 1 during the press of the button and
reverts back to 0 when the button is released */
#define FL_TOGGLE_BUTTON 1 ///< value() toggles between 0 and 1 at every click of the button
#define FL_RADIO_BUTTON (FL_RESERVED_TYPE+2) /**< is set to 1 at button press, and all other
buttons in the same group with <tt>type() == FL_RADIO_BUTTON</tt>
are set to zero.*/
#define FL_HIDDEN_BUTTON 3 ///< for Forms compatibility
extern FL_EXPORT Fl_Shortcut fl_old_shortcut(const char*);
class Fl_Widget_Tracker;
/**
\class Fl_Button
\brief Buttons generate callbacks when they are clicked by the user.
You control exactly when and how by changing the values for type() and
when(). Buttons can also generate callbacks in response to \c FL_SHORTCUT
events. The button can either have an explicit shortcut(int s) value or a
letter shortcut can be indicated in the label() with an '\&' character
before it. For the label shortcut it does not matter if \e Alt is held
down, but if you have an input field in the same window, the user will have
to hold down the \e Alt key so that the input field does not eat the event
first as an \c FL_KEYBOARD event.
\todo Refactor the doxygen comments for Fl_Button type() documentation.
For an Fl_Button object, the type() call returns one of:
\li \c FL_NORMAL_BUTTON (0): value() remains unchanged after button press.
\li \c FL_TOGGLE_BUTTON: value() is inverted after button press.
\li \c FL_RADIO_BUTTON: value() is set to 1 after button press, and all other
buttons in the current group with <tt>type() == FL_RADIO_BUTTON</tt>
are set to zero.
\todo Refactor the doxygen comments for Fl_Button when() documentation.
For an Fl_Button object, the following when() values are useful, the default
being \c FL_WHEN_RELEASE:
\li \c 0: The callback is not done, instead changed() is turned on.
\li \c FL_WHEN_RELEASE: The callback is done after the user successfully
clicks the button, or when a shortcut is typed.
\li \c FL_WHEN_CHANGED: The callback is done each time the value() changes
(when the user pushes and releases the button, and as the mouse is
dragged around in and out of the button).
*/
class FL_EXPORT Fl_Button : public Fl_Widget {
int shortcut_;
char value_;
char oldval;
uchar down_box_;
protected:
static Fl_Widget_Tracker *key_release_tracker;
static void key_release_timeout(void*);
void simulate_key_action();
virtual void draw();
public:
virtual int handle(int);
Fl_Button(int X, int Y, int W, int H, const char *L = 0);
int value(int v);
/**
Returns the current value of the button (0 or 1).
*/
char value() const {return value_;}
/**
Same as \c value(1).
\see value(int v)
*/
int set() {return value(1);}
/**
Same as \c value(0).
\see value(int v)
*/
int clear() {return value(0);}
void setonly(); // this should only be called on FL_RADIO_BUTTONs
/**
Returns the current shortcut key for the button.
\retval int
*/
int shortcut() const {return shortcut_;}
/**
Sets the shortcut key to \c s.
Setting this overrides the use of '\&' in the label().
The value is a bitwise OR of a key and a set of shift flags, for example:
<tt>FL_ALT | 'a'</tt>, or
<tt>FL_ALT | (FL_F + 10)</tt>, or just
<tt>'a'</tt>.
A value of 0 disables the shortcut.
The key can be any value returned by Fl::event_key(), but will usually be
an ASCII letter. Use a lower-case letter unless you require the shift key
to be held down.
The shift flags can be any set of values accepted by Fl::event_state().
If the bit is on, that shift key must be pushed. Meta, Alt, Ctrl, and
Shift must be off if they are not in the shift flags (zero for the other
bits indicates a "don't care" setting).
\param[in] s bitwise OR of key and shift flags
*/
void shortcut(int s) {shortcut_ = s;}
/**
Returns the current down box type, which is drawn when value() is non-zero.
\retval Fl_Boxtype
*/
Fl_Boxtype down_box() const {return (Fl_Boxtype)down_box_;}
/**
Sets the down box type. The default value of 0 causes FLTK to figure out
the correct matching down version of box().
Some derived classes (e.g. Fl_Round_Button and Fl_Light_Button use
down_box() for special purposes. See docs of these classes.
\param[in] b down box type
*/
void down_box(Fl_Boxtype b) {down_box_ = b;}
/// (for backwards compatibility)
void shortcut(const char *s) {shortcut(fl_old_shortcut(s));}
/// (for backwards compatibility)
Fl_Color down_color() const {return selection_color();}
/// (for backwards compatibility)
void down_color(unsigned c) {selection_color(c);}
};
#endif
//
// End of "$Id: Fl_Button.H 10386 2014-10-19 20:17:17Z AlbrechtS $".
//
| kctan0805/vdpm | share/fltk/fltk-1.3.3/FL/Fl_Button.H | C++ | lgpl-2.1 | 5,652 |
TypeScript is authored by:
* Aaron Holmes
* Abubaker Bashir
* Adam Freidin
* Adi Dahiya
* Adrian Leonhard
* Ahmad Farid
* Akshar Patel
* Alex Chugaev
* Alex Eagle
* Alexander Kuvaev
* Alexander Rusakov
* Ali Sabzevari
* Aliaksandr Radzivanovich
* Aluan Haddad
* Anatoly Ressin
* Anders Hejlsberg
* Andreas Martin
* Andrej Baran
* Andrew Casey
* Andrew Ochsner
* Andrew Stegmaier
* Andrew Z Allen
* AndrΓ‘s Parditka
* Andy Hanson
* Anil Anar
* Anton Khlynovskiy
* Anton Tolmachev
* Anubha Mathur
* Armando Aguirre
* Arnaud Tournier
* Arnav Singh
* Arthur Ozga
* Asad Saeeduddin
* Avery Morin
* Basarat Ali Syed
* Ben Duffield
* Ben Mosher
* Benjamin Bock
* Benjamin Lichtman
* Benny Neugebauer
* Bill Ticehurst
* Blaine Bublitz
* Blake Embrey
* @bootstraponline
* Bowden Kelly
* Brett Mayen
* Bryan Forbes
* Caitlin Potter
* @cedvdb
* Charles Pierce
* Charly POLY
* Chris Bubernak
* Christophe Vidal
* Chuck Jazdzewski
* Colby Russell
* Colin Snover
* Cotton Hou
* Cyrus Najmabadi
* Dafrok Zhang
* Dahan Gong
* Dan Corder
* Dan Quirk
* Daniel Hollocher
* Daniel KrΓ³l
* Daniel Lehenbauer
* Daniel Rosenwasser
* David Kmenta
* David Li
* David Sheldrick
* David Souther
* Denis Nedelyaev
* Dick van den Brink
* Diogo Franco (Kovensky)
* Dirk BΓ€umer
* Dirk Holtwick
* Dom Chen
* Donald Pipowitch
* Doug Ilijev
* @e-cloud
* ElisΓ©e Maurer
* Emilio GarcΓa-Pumarino
* Eric Tsang
* Erik Edrosa
* Erik McClenney
* Ethan Resnick
* Ethan Rubio
* Evan Martin
* Evan Sebastian
* Eyas Sharaiha
* Fabian Cook
* @falsandtru
* Filipe Silva
* @flowmemo
* Francois Wouts
* Frank Wallis
* Franklin Tse
* FrantiΕ‘ek Ε½iacik
* Gabe Moothart
* Gabriel Isenberg
* Gilad Peleg
* Godfrey Chan
* Graeme Wicksted
* Guilherme Oenning
* Guillaume Salles
* Guy Bedford
* Halasi TamΓ‘s
* Harald Niesche
* Hendrik Liebau
* Henry Mercer
* Herrington Darkholme
* Homa Wong
* Iain Monro
* Igor Novozhilov
* Ika
* Ingvar Stepanyan
* Isiah Meadows
* Ivan Enderlin
* Ivo Gabe de Wolff
* Iwata Hidetaka
* Jakub MΕokosiewicz
* James Henry
* James Whitney
* Jan Melcher
* Jason Freeman
* Jason Jarrett
* Jason Killian
* Jason Ramsay
* JBerger
* Jed Mao
* Jeffrey Morlan
* Jesse Schalken
* Jiri Tobisek
* Joe Calzaretta
* Joe Chung
* Joel Day
* Joey Wilson
* Johannes Rieken
* John Vilk
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Toland
* Jonathan Turner
* Jonathon Smith
* Josh Abernathy
* Josh Goldberg
* Josh Kalderimis
* Josh Soref
* Juan Luis Boya GarcΓa
* Julian Williams
* Justin Bay
* Justin Johansson
* K. PreiΓer
* Kagami Sascha Rosylight
* Kanchalai Tanglertsampan
* Kate MihΓ‘likovΓ‘
* Keith Mashinter
* Ken Howard
* Kenji Imamula
* Kevin Lang
* Kitson Kelly
* Klaus Meinhardt
* Kyle Kelley
* KΔrlis GaΕΔ£is
* Lorant Pinter
* Lucien Greathouse
* Lukas Elmer
* Magnus Hiie
* Magnus Kulke
* Manish Giri
* Marin Marinov
* Marius Schulz
* Martin Vseticka
* Masahiro Wakame
* Matt Bierner
* Matt McCutchen
* Matt Mitchell
* Mattias Buelens
* Mattias Buelens
* Max Deepfield
* Maxwell Paul Brickner
* Micah Zoltu
* Michael
* Michael Bromley
* Mike Busyrev
* Mine Starks
* Mohamed Hegazy
* Mohsen Azimi
* Myles Megyesi
* Natalie Coley
* Nathan Shively-Sanders
* Nathan Yee
* Nicolas Henry
* Nima Zahedi
* Noah Chen
* Noel Varanda
* Noj Vek
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Omer Sheikh
* Oskar Segersva¨rd
* Patrick Zhong
* Paul Jolly
* Paul van Brenk
* @pcbro
* Pedro Maltez
* Perry Jiang
* Peter Burns
* Philip Bulley
* Piero Cangianiello
* @piloopin
* Prayag Verma
* @progre
* Punya Biswal
* Rado Kirov
* Raj Dosanjh
* Reiner Dolp
* Richard KarmazΓn
* Richard Knoll
* Richard Sentino
* Robert Coie
* Rohit Verma
* Ron Buckton
* Rostislav Galimsky
* Rowan Wyborn
* Ryan Cavanaugh
* Ryohei Ikegami
* Sam El-Husseini
* Sarangan Rajamanickam
* Sergey Rubanov
* Sergey Shandar
* Sheetal Nandi
* Shengping Zhong
* Shyyko Serhiy
* Simon HΓΌrlimann
* Slawomir Sadziak
* Solal Pirelli
* Soo Jae Hwang
* Stan Thomas
* Stanislav Sysoev
* Stas Vilchik
* Steve Lucco
* Sudheesh Singanamalla
* SΓ©bastien Arod
* @T18970237136
* @t_
* Taras Mankovski
* Tarik Ozket
* Tetsuharu Ohzeki
* Thomas den Hollander
* Thomas Loubiou
* Tien Hoanhtien
* Tim Lancina
* Tim Perry
* Tim Viiding-Spader
* Tingan Ho
* Todd Thomson
* togru
* Tomas Grubliauskas
* Torben Fitschen
* @TravCav
* TruongSinh Tran-Nguyen
* Tycho Grouwstra
* Vadi Taslim
* Vakhurin Sergey
* Vidar Tonaas Fauske
* Viktor Zozulyak
* Vilic Vane
* Vladimir Kurchatkin
* Vladimir Matveev
* Wesley Wigham
* William Orr
* York Yao
* @yortus
* Yuichi Nukiyama
* Zeeshan Ahmed
* Zev Spitz
* Zhengbo Li | ozendelait/streamcollada | server/node_modules/typescript/AUTHORS.md | Markdown | lgpl-3.0 | 4,894 |
/*=========================================================================
Program: Visualization Toolkit
Module: vtkRenderWindow.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkGenericOpenGLRenderWindow - platform independent render window
// .SECTION Description
// vtkGenericOpenGLRenderWindow provides a skeleton for implementing a render window
// using one's own OpenGL context and drawable.
// To be effective, one must register an observer for WindowMakeCurrentEvent,
// WindowIsCurrentEvent and WindowFrameEvent. When this class sends a WindowIsCurrentEvent,
// the call data is an bool* which one can use to return whether the context is current.
#ifndef vtkGenericOpenGLRenderWindow_hpp
#define vtkGenericOpenGLRenderWindow_hpp
#include "vtkRenderingOpenGLModule.h" // For export macro
#include "vtkOpenGLRenderWindow.h"
class VTKRENDERINGOPENGL_EXPORT vtkGenericOpenGLRenderWindow : public vtkOpenGLRenderWindow
{
public:
static vtkGenericOpenGLRenderWindow* New();
vtkTypeMacro(vtkGenericOpenGLRenderWindow, vtkOpenGLRenderWindow);
void PrintSelf(ostream& os, vtkIndent indent);
protected:
vtkGenericOpenGLRenderWindow();
~vtkGenericOpenGLRenderWindow();
public:
//! Cleans up graphics resources allocated in the context for this VTK scene.
void Finalize();
//! flush the pending drawing operations
//! Class user may to watch for WindowFrameEvent and act on it
void Frame();
//! Makes the context current. It is the class user's
//! responsibility to watch for WindowMakeCurrentEvent and set it current.
void MakeCurrent();
//! Returns if the context is current. It is the class user's
//! responsibility to watch for WindowIsCurrentEvent and set the bool* flag
//! passed through the call data parameter.
bool IsCurrent();
//! Returns if OpenGL is supported. It is the class user's
//! responsibility to watch for WindowSupportsOpenGLEvent and set the int* flag
//! passed through the call data parameter.
int SupportsOpenGL();
//! Returns if the context is direct. It is the class user's
//! responsibility to watch for WindowIsDirectEvent and set the int* flag
//! passed through the call data parameter.
int IsDirect();
// {@
//! set the drawing buffers to use
void SetFrontBuffer(unsigned int);
void SetFrontLeftBuffer(unsigned int);
void SetFrontRightBuffer(unsigned int);
void SetBackBuffer(unsigned int);
void SetBackLeftBuffer(unsigned int);
void SetBackRightBuffer(unsigned int);
// }@
//! convenience function to push the state and push/init the transform matrices
void PushState();
//! convenience function to pop the state and pop the transform matrices
void PopState();
// {@
//! does nothing
void SetWindowId(void*);
void* GetGenericWindowId();
void SetDisplayId(void*);
void SetParentId(void*);
void* GetGenericDisplayId();
void* GetGenericParentId();
void* GetGenericContext();
void* GetGenericDrawable();
void SetWindowInfo(char*);
void SetParentInfo(char*);
int* GetScreenSize();
void Start();
void HideCursor();
void ShowCursor();
void SetFullScreen(int);
void WindowRemap();
int GetEventPending();
void SetNextWindowId(void*);
void SetNextWindowInfo(char*);
void CreateAWindow();
void DestroyWindow();
// }@
// Description:
// Allow to update state within observer callback without changing
// data argument and MTime.
void SetIsDirect(int newValue);
void SetSupportsOpenGL(int newValue);
void SetIsCurrent(bool newValue);
protected:
int DirectStatus;
int SupportsOpenGLStatus;
bool CurrentStatus;
private:
vtkGenericOpenGLRenderWindow(const vtkGenericOpenGLRenderWindow&); // Not implemented.
void operator=(const vtkGenericOpenGLRenderWindow&); // Not implemented.
};
#endif
| gisfromscratch/datavisualizer | lib/vtk/include/Rendering/OpenGL/vtkGenericOpenGLRenderWindow.h | C | apache-2.0 | 4,204 |
/**
* 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 org.apache.hadoop.mapreduce.security;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.security.token.JobTokenSecretManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
/**
*
* utilities for generating kyes, hashes and verifying them for shuffle
*
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class SecureShuffleUtils {
private static final Logger LOG =
LoggerFactory.getLogger(SecureShuffleUtils.class);
public static final String HTTP_HEADER_URL_HASH = "UrlHash";
public static final String HTTP_HEADER_REPLY_URL_HASH = "ReplyHash";
/**
* Base64 encoded hash of msg
* @param msg
*/
public static String generateHash(byte[] msg, SecretKey key) {
return new String(Base64.encodeBase64(generateByteHash(msg, key)),
Charsets.UTF_8);
}
/**
* calculate hash of msg
* @param msg
* @return
*/
private static byte[] generateByteHash(byte[] msg, SecretKey key) {
return JobTokenSecretManager.computeHash(msg, key);
}
/**
* verify that hash equals to HMacHash(msg)
* @param newHash
* @return true if is the same
*/
private static boolean verifyHash(byte[] hash, byte[] msg, SecretKey key) {
byte[] msg_hash = generateByteHash(msg, key);
return WritableComparator.compareBytes(msg_hash, 0, msg_hash.length, hash, 0, hash.length) == 0;
}
/**
* Aux util to calculate hash of a String
* @param enc_str
* @param key
* @return Base64 encodedHash
* @throws IOException
*/
public static String hashFromString(String enc_str, SecretKey key)
throws IOException {
return generateHash(enc_str.getBytes(Charsets.UTF_8), key);
}
/**
* verify that base64Hash is same as HMacHash(msg)
* @param base64Hash (Base64 encoded hash)
* @param msg
* @throws IOException if not the same
*/
public static void verifyReply(String base64Hash, String msg, SecretKey key)
throws IOException {
byte[] hash = Base64.decodeBase64(base64Hash.getBytes(Charsets.UTF_8));
boolean res = verifyHash(hash, msg.getBytes(Charsets.UTF_8), key);
if(res != true) {
throw new IOException("Verification of the hashReply failed");
}
}
/**
* Shuffle specific utils - build string for encoding from URL
* @param url
* @return string for encoding
*/
public static String buildMsgFrom(URL url) {
return buildMsgFrom(url.getPath(), url.getQuery(), url.getPort());
}
/**
* Shuffle specific utils - build string for encoding from URL
* @param request
* @return string for encoding
*/
public static String buildMsgFrom(HttpServletRequest request ) {
return buildMsgFrom(request.getRequestURI(), request.getQueryString(),
request.getLocalPort());
}
/**
* Shuffle specific utils - build string for encoding from URL
* @param uri_path
* @param uri_query
* @return string for encoding
*/
private static String buildMsgFrom(String uri_path, String uri_query, int port) {
return String.valueOf(port) + uri_path + "?" + uri_query;
}
/**
* byte array to Hex String
*
* @param ba
* @return string with HEX value of the key
*/
public static String toHex(byte[] ba) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String strHex = "";
try {
PrintStream ps = new PrintStream(baos, false, "UTF-8");
for (byte b : ba) {
ps.printf("%x", b);
}
strHex = baos.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
}
return strHex;
}
}
| dennishuo/hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/security/SecureShuffleUtils.java | Java | apache-2.0 | 4,861 |
/*
Copyright 2018 The Kubernetes Authors.
Licensed 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 options
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/util/sets"
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/component-base/config/options"
kubectrlmgrconfig "k8s.io/kubernetes/pkg/controller/apis/config"
)
// GenericControllerManagerConfigurationOptions holds the options which are generic.
type GenericControllerManagerConfigurationOptions struct {
*kubectrlmgrconfig.GenericControllerManagerConfiguration
Debugging *DebuggingOptions
}
// NewGenericControllerManagerConfigurationOptions returns generic configuration default values for both
// the kube-controller-manager and the cloud-contoller-manager. Any common changes should
// be made here. Any individual changes should be made in that controller.
func NewGenericControllerManagerConfigurationOptions(cfg *kubectrlmgrconfig.GenericControllerManagerConfiguration) *GenericControllerManagerConfigurationOptions {
o := &GenericControllerManagerConfigurationOptions{
GenericControllerManagerConfiguration: cfg,
Debugging: RecommendedDebuggingOptions(),
}
return o
}
// AddFlags adds flags related to generic for controller manager to the specified FlagSet.
func (o *GenericControllerManagerConfigurationOptions) AddFlags(fss *cliflag.NamedFlagSets, allControllers, disabledByDefaultControllers []string) {
if o == nil {
return
}
o.Debugging.AddFlags(fss.FlagSet("debugging"))
genericfs := fss.FlagSet("generic")
genericfs.DurationVar(&o.MinResyncPeriod.Duration, "min-resync-period", o.MinResyncPeriod.Duration, "The resync period in reflectors will be random between MinResyncPeriod and 2*MinResyncPeriod.")
genericfs.StringVar(&o.ClientConnection.ContentType, "kube-api-content-type", o.ClientConnection.ContentType, "Content type of requests sent to apiserver.")
genericfs.Float32Var(&o.ClientConnection.QPS, "kube-api-qps", o.ClientConnection.QPS, "QPS to use while talking with kubernetes apiserver.")
genericfs.Int32Var(&o.ClientConnection.Burst, "kube-api-burst", o.ClientConnection.Burst, "Burst to use while talking with kubernetes apiserver.")
genericfs.DurationVar(&o.ControllerStartInterval.Duration, "controller-start-interval", o.ControllerStartInterval.Duration, "Interval between starting controller managers.")
genericfs.StringSliceVar(&o.Controllers, "controllers", o.Controllers, fmt.Sprintf(""+
"A list of controllers to enable. '*' enables all on-by-default controllers, 'foo' enables the controller "+
"named 'foo', '-foo' disables the controller named 'foo'.\nAll controllers: %s\nDisabled-by-default controllers: %s",
strings.Join(allControllers, ", "), strings.Join(disabledByDefaultControllers, ", ")))
options.BindLeaderElectionFlags(&o.LeaderElection, genericfs)
}
// ApplyTo fills up generic config with options.
func (o *GenericControllerManagerConfigurationOptions) ApplyTo(cfg *kubectrlmgrconfig.GenericControllerManagerConfiguration) error {
if o == nil {
return nil
}
if err := o.Debugging.ApplyTo(&cfg.Debugging); err != nil {
return err
}
cfg.Port = o.Port
cfg.Address = o.Address
cfg.MinResyncPeriod = o.MinResyncPeriod
cfg.ClientConnection = o.ClientConnection
cfg.ControllerStartInterval = o.ControllerStartInterval
cfg.LeaderElection = o.LeaderElection
cfg.Controllers = o.Controllers
return nil
}
// Validate checks validation of GenericOptions.
func (o *GenericControllerManagerConfigurationOptions) Validate(allControllers []string, disabledByDefaultControllers []string) []error {
if o == nil {
return nil
}
errs := []error{}
errs = append(errs, o.Debugging.Validate()...)
allControllersSet := sets.NewString(allControllers...)
for _, controller := range o.Controllers {
if controller == "*" {
continue
}
controller = strings.TrimPrefix(controller, "-")
if !allControllersSet.Has(controller) {
errs = append(errs, fmt.Errorf("%q is not in the list of known controllers", controller))
}
}
return errs
}
| rancher/k3s | vendor/k8s.io/kubernetes/cmd/controller-manager/app/options/generic.go | GO | apache-2.0 | 4,510 |
/*
* 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 org.apache.kafka.common.network;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import java.util.Locale;
import java.util.Objects;
public final class ListenerName {
private static final String CONFIG_STATIC_PREFIX = "listener.name";
/**
* Create an instance with the security protocol name as the value.
*/
public static ListenerName forSecurityProtocol(SecurityProtocol securityProtocol) {
return new ListenerName(securityProtocol.name);
}
/**
* Create an instance with the provided value converted to uppercase.
*/
public static ListenerName normalised(String value) {
return new ListenerName(value.toUpperCase(Locale.ROOT));
}
private final String value;
public ListenerName(String value) {
Objects.requireNonNull(value, "value should not be null");
this.value = value;
}
public String value() {
return value;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ListenerName))
return false;
ListenerName that = (ListenerName) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "ListenerName(" + value + ")";
}
public String configPrefix() {
return CONFIG_STATIC_PREFIX + "." + value.toLowerCase(Locale.ROOT) + ".";
}
public String saslMechanismConfigPrefix(String saslMechanism) {
return configPrefix() + saslMechanismPrefix(saslMechanism);
}
public static String saslMechanismPrefix(String saslMechanism) {
return saslMechanism.toLowerCase(Locale.ROOT) + ".";
}
}
| ollie314/kafka | clients/src/main/java/org/apache/kafka/common/network/ListenerName.java | Java | apache-2.0 | 2,555 |
/**
* 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 org.apache.hadoop.hbase.regionserver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.MultithreadedTestUtil.RepeatingTestThread;
import org.apache.hadoop.hbase.MultithreadedTestUtil.TestContext;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.ServerCallable;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.Compression;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.junit.Test;
import com.google.common.collect.Lists;
import org.junit.experimental.categories.Category;
/**
* Tests bulk loading of HFiles and shows the atomicity or lack of atomicity of
* the region server's bullkLoad functionality.
*/
@Category(LargeTests.class)
public class TestHRegionServerBulkLoad {
final static Log LOG = LogFactory.getLog(TestHRegionServerBulkLoad.class);
private static HBaseTestingUtility UTIL = new HBaseTestingUtility();
private final static Configuration conf = UTIL.getConfiguration();
private final static byte[] QUAL = Bytes.toBytes("qual");
private final static int NUM_CFS = 10;
public static int BLOCKSIZE = 64 * 1024;
public static String COMPRESSION = Compression.Algorithm.NONE.getName();
private final static byte[][] families = new byte[NUM_CFS][];
static {
for (int i = 0; i < NUM_CFS; i++) {
families[i] = Bytes.toBytes(family(i));
}
}
static byte[] rowkey(int i) {
return Bytes.toBytes(String.format("row_%08d", i));
}
static String family(int i) {
return String.format("family_%04d", i);
}
/**
* Create an HFile with the given number of rows with a specified value.
*/
public static void createHFile(FileSystem fs, Path path, byte[] family,
byte[] qualifier, byte[] value, int numRows) throws IOException {
HFile.Writer writer = HFile
.getWriterFactory(conf, new CacheConfig(conf))
.withPath(fs, path)
.withBlockSize(BLOCKSIZE)
.withCompression(COMPRESSION)
.withComparator(KeyValue.KEY_COMPARATOR)
.create();
long now = System.currentTimeMillis();
try {
// subtract 2 since iterateOnSplits doesn't include boundary keys
for (int i = 0; i < numRows; i++) {
KeyValue kv = new KeyValue(rowkey(i), family, qualifier, now, value);
writer.append(kv);
}
} finally {
writer.close();
}
}
/**
* Thread that does full scans of the table looking for any partially
* completed rows.
*
* Each iteration of this loads 10 hdfs files, which occupies 5 file open file
* handles. So every 10 iterations (500 file handles) it does a region
* compaction to reduce the number of open file handles.
*/
public static class AtomicHFileLoader extends RepeatingTestThread {
final AtomicLong numBulkLoads = new AtomicLong();
final AtomicLong numCompactions = new AtomicLong();
private String tableName;
public AtomicHFileLoader(String tableName, TestContext ctx,
byte targetFamilies[][]) throws IOException {
super(ctx);
this.tableName = tableName;
}
public void doAnAction() throws Exception {
long iteration = numBulkLoads.getAndIncrement();
Path dir = UTIL.getDataTestDir(String.format("bulkLoad_%08d",
iteration));
// create HFiles for different column families
FileSystem fs = UTIL.getTestFileSystem();
byte[] val = Bytes.toBytes(String.format("%010d", iteration));
final List<Pair<byte[], String>> famPaths = new ArrayList<Pair<byte[], String>>(
NUM_CFS);
for (int i = 0; i < NUM_CFS; i++) {
Path hfile = new Path(dir, family(i));
byte[] fam = Bytes.toBytes(family(i));
createHFile(fs, hfile, fam, QUAL, val, 1000);
famPaths.add(new Pair<byte[], String>(fam, hfile.toString()));
}
// bulk load HFiles
HConnection conn = UTIL.getHBaseAdmin().getConnection();
byte[] tbl = Bytes.toBytes(tableName);
new ServerCallable<Void>(conn, tbl, Bytes
.toBytes("aaa")) {
@Override
public Void call() throws Exception {
LOG.debug("Going to connect to server " + location + " for row "
+ Bytes.toStringBinary(row));
byte[] regionName = location.getRegionInfo().getRegionName();
server.bulkLoadHFiles(famPaths, regionName);
return null;
}
}.withRetries();
// Periodically do compaction to reduce the number of open file handles.
if (numBulkLoads.get() % 10 == 0) {
// 10 * 50 = 500 open file handles!
new ServerCallable<Void>(conn, tbl,
Bytes.toBytes("aaa")) {
@Override
public Void call() throws Exception {
LOG.debug("compacting " + location + " for row "
+ Bytes.toStringBinary(row));
server.compactRegion(location.getRegionInfo(), true);
numCompactions.incrementAndGet();
return null;
}
}.withRetries();
}
}
}
/**
* Thread that does full scans of the table looking for any partially
* completed rows.
*/
public static class AtomicScanReader extends RepeatingTestThread {
byte targetFamilies[][];
HTable table;
AtomicLong numScans = new AtomicLong();
AtomicLong numRowsScanned = new AtomicLong();
String TABLE_NAME;
public AtomicScanReader(String TABLE_NAME, TestContext ctx,
byte targetFamilies[][]) throws IOException {
super(ctx);
this.TABLE_NAME = TABLE_NAME;
this.targetFamilies = targetFamilies;
table = new HTable(conf, TABLE_NAME);
}
public void doAnAction() throws Exception {
Scan s = new Scan();
for (byte[] family : targetFamilies) {
s.addFamily(family);
}
ResultScanner scanner = table.getScanner(s);
for (Result res : scanner) {
byte[] lastRow = null, lastFam = null, lastQual = null;
byte[] gotValue = null;
for (byte[] family : targetFamilies) {
byte qualifier[] = QUAL;
byte thisValue[] = res.getValue(family, qualifier);
if (gotValue != null && thisValue != null
&& !Bytes.equals(gotValue, thisValue)) {
StringBuilder msg = new StringBuilder();
msg.append("Failed on scan ").append(numScans)
.append(" after scanning ").append(numRowsScanned)
.append(" rows!\n");
msg.append("Current was " + Bytes.toString(res.getRow()) + "/"
+ Bytes.toString(family) + ":" + Bytes.toString(qualifier)
+ " = " + Bytes.toString(thisValue) + "\n");
msg.append("Previous was " + Bytes.toString(lastRow) + "/"
+ Bytes.toString(lastFam) + ":" + Bytes.toString(lastQual)
+ " = " + Bytes.toString(gotValue));
throw new RuntimeException(msg.toString());
}
lastFam = family;
lastQual = qualifier;
lastRow = res.getRow();
gotValue = thisValue;
}
numRowsScanned.getAndIncrement();
}
numScans.getAndIncrement();
}
}
/**
* Creates a table with given table name and specified number of column
* families if the table does not already exist.
*/
private void setupTable(String table, int cfs) throws IOException {
try {
LOG.info("Creating table " + table);
HTableDescriptor htd = new HTableDescriptor(table);
for (int i = 0; i < 10; i++) {
htd.addFamily(new HColumnDescriptor(family(i)));
}
UTIL.getHBaseAdmin().createTable(htd);
} catch (TableExistsException tee) {
LOG.info("Table " + table + " already exists");
}
}
/**
* Atomic bulk load.
*/
@Test
public void testAtomicBulkLoad() throws Exception {
String TABLE_NAME = "atomicBulkLoad";
int millisToRun = 30000;
int numScanners = 50;
UTIL.startMiniCluster(1);
try {
runAtomicBulkloadTest(TABLE_NAME, millisToRun, numScanners);
} finally {
UTIL.shutdownMiniCluster();
}
}
void runAtomicBulkloadTest(String tableName, int millisToRun, int numScanners)
throws Exception {
setupTable(tableName, 10);
TestContext ctx = new TestContext(UTIL.getConfiguration());
AtomicHFileLoader loader = new AtomicHFileLoader(tableName, ctx, null);
ctx.addThread(loader);
List<AtomicScanReader> scanners = Lists.newArrayList();
for (int i = 0; i < numScanners; i++) {
AtomicScanReader scanner = new AtomicScanReader(tableName, ctx, families);
scanners.add(scanner);
ctx.addThread(scanner);
}
ctx.startThreads();
ctx.waitFor(millisToRun);
ctx.stop();
LOG.info("Loaders:");
LOG.info(" loaded " + loader.numBulkLoads.get());
LOG.info(" compations " + loader.numCompactions.get());
LOG.info("Scanners:");
for (AtomicScanReader scanner : scanners) {
LOG.info(" scanned " + scanner.numScans.get());
LOG.info(" verified " + scanner.numRowsScanned.get() + " rows");
}
}
/**
* Run test on an HBase instance for 5 minutes. This assumes that the table
* under test only has a single region.
*/
public static void main(String args[]) throws Exception {
try {
Configuration c = HBaseConfiguration.create();
TestHRegionServerBulkLoad test = new TestHRegionServerBulkLoad();
test.setConf(c);
test.runAtomicBulkloadTest("atomicTableTest", 5 * 60 * 1000, 50);
} finally {
System.exit(0); // something hangs (believe it is lru threadpool)
}
}
private void setConf(Configuration c) {
UTIL = new HBaseTestingUtility(c);
}
@org.junit.Rule
public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
}
| zqxjjj/NobidaBase | target/hbase-0.94.9/hbase-0.94.9/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java | Java | apache-2.0 | 11,256 |
// force-host
// no-prefer-dynamic
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_derive(Unstable)]
pub fn derive(_input: TokenStream) -> TokenStream {
"unsafe fn foo() -> u32 { ::std::intrinsics::abort() }".parse().unwrap()
}
| graydon/rust | src/test/ui/proc-macro/auxiliary/derive-unstable.rs | Rust | apache-2.0 | 286 |
/*
Copyright 2016 Google LLC
Licensed 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 testutil
import (
"fmt"
"log"
"net"
"regexp"
"strconv"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// A Server is an in-process gRPC server, listening on a system-chosen port on
// the local loopback interface. Servers are for testing only and are not
// intended to be used in production code.
//
// To create a server, make a new Server, register your handlers, then call
// Start:
//
// srv, err := NewServer()
// ...
// mypb.RegisterMyServiceServer(srv.Gsrv, &myHandler)
// ....
// srv.Start()
//
// Clients should connect to the server with no security:
//
// conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
// ...
type Server struct {
Addr string
Port int
l net.Listener
Gsrv *grpc.Server
}
// NewServer creates a new Server. The Server will be listening for gRPC connections
// at the address named by the Addr field, without TLS.
func NewServer(opts ...grpc.ServerOption) (*Server, error) {
return NewServerWithPort(0, opts...)
}
// NewServerWithPort creates a new Server at a specific port. The Server will be listening
// for gRPC connections at the address named by the Addr field, without TLS.
func NewServerWithPort(port int, opts ...grpc.ServerOption) (*Server, error) {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return nil, err
}
s := &Server{
Addr: l.Addr().String(),
Port: parsePort(l.Addr().String()),
l: l,
Gsrv: grpc.NewServer(opts...),
}
return s, nil
}
// Start causes the server to start accepting incoming connections.
// Call Start after registering handlers.
func (s *Server) Start() {
go func() {
if err := s.Gsrv.Serve(s.l); err != nil {
log.Printf("testutil.Server.Start: %v", err)
}
}()
}
// Close shuts down the server.
func (s *Server) Close() {
s.Gsrv.Stop()
s.l.Close()
}
// PageBounds converts an incoming page size and token from an RPC request into
// slice bounds and the outgoing next-page token.
//
// PageBounds assumes that the complete, unpaginated list of items exists as a
// single slice. In addition to the page size and token, PageBounds needs the
// length of that slice.
//
// PageBounds's first two return values should be used to construct a sub-slice of
// the complete, unpaginated slice. E.g. if the complete slice is s, then
// s[from:to] is the desired page. Its third return value should be set as the
// NextPageToken field of the RPC response.
func PageBounds(pageSize int, pageToken string, length int) (from, to int, nextPageToken string, err error) {
from, to = 0, length
if pageToken != "" {
from, err = strconv.Atoi(pageToken)
if err != nil {
return 0, 0, "", status.Errorf(codes.InvalidArgument, "bad page token: %v", err)
}
if from >= length {
return length, length, "", nil
}
}
if pageSize > 0 && from+pageSize < length {
to = from + pageSize
nextPageToken = strconv.Itoa(to)
}
return from, to, nextPageToken, nil
}
var portParser = regexp.MustCompile(`:[0-9]+`)
func parsePort(addr string) int {
res := portParser.FindAllString(addr, -1)
if len(res) == 0 {
panic(fmt.Errorf("parsePort: found no numbers in %s", addr))
}
stringPort := res[0][1:] // strip the :
p, err := strconv.ParseInt(stringPort, 10, 32)
if err != nil {
panic(err)
}
return int(p)
}
| pweil-/origin | vendor/cloud.google.com/go/internal/testutil/server.go | GO | apache-2.0 | 3,870 |
/*
* 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 org.apache.ignite.internal.processors.cache;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.cache.Cache;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cache.eviction.lru.LruEvictionPolicy;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.util.typedef.PA;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.jetbrains.annotations.Nullable;
/**
*
*/
public class IgniteCacheLoadRebalanceEvictionSelfTest extends GridCommonAbstractTest {
/** */
public static final int LRU_MAX_SIZE = 10;
/** */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** */
private static final int ENTRIES_CNT = 10000;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
discoSpi.setIpFinder(IP_FINDER);
cfg.setDiscoverySpi(discoSpi);
LruEvictionPolicy evictionPolicy = new LruEvictionPolicy<>();
evictionPolicy.setMaxSize(LRU_MAX_SIZE);
CacheConfiguration<String, byte[]> cacheCfg = new CacheConfiguration<>();
cacheCfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
cacheCfg.setEvictSynchronized(false);
cacheCfg.setCacheMode(CacheMode.PARTITIONED);
cacheCfg.setBackups(1);
cacheCfg.setReadFromBackup(true);
cacheCfg.setEvictionPolicy(evictionPolicy);
cacheCfg.setOffHeapMaxMemory(1024 * 1024 * 1024L);
cacheCfg.setStatisticsEnabled(true);
cacheCfg.setWriteThrough(false);
cacheCfg.setReadThrough(false);
cacheCfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new Storage()));
cfg.setCacheConfiguration(cacheCfg);
return cfg;
}
/**
* @throws Exception If failed.
*/
public void testStartRebalancing() throws Exception {
List<IgniteInternalFuture<Object>> futs = new ArrayList<>();
int gridCnt = 4;
for (int i = 0; i < gridCnt; i++) {
final IgniteEx ig = startGrid(i);
futs.add(GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
ig.cache(null).localLoadCache(null);
return null;
}
}));
}
try {
for (IgniteInternalFuture<Object> fut : futs)
fut.get();
for (int i = 0; i < gridCnt; i++) {
IgniteEx grid = grid(i);
final IgniteCache<Object, Object> cache = grid.cache(null);
GridTestUtils.waitForCondition(new PA() {
@Override public boolean apply() {
return cache.localSize(CachePeekMode.ONHEAP) <= 10;
}
}, getTestTimeout());
}
}
finally {
stopAllGrids();
}
}
/**
*
*/
private static class Storage extends CacheStoreAdapter<Integer, byte[]> implements Serializable {
/** */
private static final byte[] data = new byte[1024];
/** {@inheritDoc} */
@Override public void write(Cache.Entry<? extends Integer, ? extends byte[]> e) throws CacheWriterException {
throw new UnsupportedOperationException("Unsupported");
}
/** {@inheritDoc} */
@Override public void writeAll(Collection<Cache.Entry<? extends Integer, ? extends byte[]>> entries)
throws CacheWriterException {
throw new UnsupportedOperationException("Unsupported");
}
/** {@inheritDoc} */
@Override public void delete(Object key) throws CacheWriterException {
throw new UnsupportedOperationException("Unsupported");
}
/** {@inheritDoc} */
@Override public void deleteAll(Collection<?> keys) throws CacheWriterException {
throw new UnsupportedOperationException("Unsupported");
}
/** {@inheritDoc} */
@Override public byte[] load(Integer key) throws CacheLoaderException {
return data;
}
/** {@inheritDoc} */
@Override public Map<Integer, byte[]> loadAll(Iterable<? extends Integer> keys) throws CacheLoaderException {
Map<Integer, byte[]> res = new HashMap<>();
for (Integer key : keys)
res.put(key, data);
return res;
}
/** {@inheritDoc} */
@Override public void loadCache(IgniteBiInClosure<Integer, byte[]> clo,
@Nullable Object... args) throws CacheLoaderException {
for (int i = 0; i < ENTRIES_CNT; i++)
clo.apply(i, data);
}
}
}
| tkpanther/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheLoadRebalanceEvictionSelfTest.java | Java | apache-2.0 | 6,716 |
/*
* 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 org.apache.lens.cube.error;
import java.util.*;
import org.apache.lens.api.serialize.SerializationTest;
import org.testng.annotations.Test;
public class ConflictingFieldsTest {
@Test
public void testIfConflictingFieldsIsSerializable() {
/* Payload class has to be Serializable because it is part of QueryContext collaboration graph,
which is serialized to be persisted on disk in lens */
SortedSet<String> testFields = new TreeSet<String>();
testFields.add("A");
testFields.add("B");
SerializationTest st = new SerializationTest();
st.verifySerializationAndDeserialization(new ConflictingFields(testFields));
}
}
| RaghavendraSingh/lens | lens-cube/src/test/java/org/apache/lens/cube/error/ConflictingFieldsTest.java | Java | apache-2.0 | 1,470 |
/*
*
* * Copyright 2015 AT&T Foundry
* *
* * Licensed 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 org.onlab.packet;
import org.slf4j.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.common.base.MoreObjects.toStringHelper;
import static org.onlab.packet.PacketUtils.checkHeaderLength;
import static org.onlab.packet.PacketUtils.checkInput;
import static org.slf4j.LoggerFactory.getLogger;
/**
* RADIUS packet.
*/
public class RADIUS extends BasePacket {
protected byte code;
protected byte identifier;
protected short length = RADIUS_MIN_LENGTH;
protected byte[] authenticator = new byte[16];
protected List<RADIUSAttribute> attributes = new ArrayList<>();
// RADIUS parameters
public static final short RADIUS_MIN_LENGTH = 20;
public static final short MAX_ATTR_VALUE_LENGTH = 253;
public static final short RADIUS_MAX_LENGTH = 4096;
// RADIUS packet types
public static final byte RADIUS_CODE_ACCESS_REQUEST = 0x01;
public static final byte RADIUS_CODE_ACCESS_ACCEPT = 0x02;
public static final byte RADIUS_CODE_ACCESS_REJECT = 0x03;
public static final byte RADIUS_CODE_ACCOUNTING_REQUEST = 0x04;
public static final byte RADIUS_CODE_ACCOUNTING_RESPONSE = 0x05;
public static final byte RADIUS_CODE_ACCESS_CHALLENGE = 0x0b;
private final Logger log = getLogger(getClass());
/**
* Default constructor.
*/
public RADIUS() {
}
/**
* Constructs a RADIUS packet with the given code and identifier.
*
* @param code code
* @param identifier identifier
*/
public RADIUS(byte code, byte identifier) {
this.code = code;
this.identifier = identifier;
}
/**
* Gets the code.
*
* @return code
*/
public byte getCode() {
return this.code;
}
/**
* Sets the code.
*
* @param code code
*/
public void setCode(byte code) {
this.code = code;
}
/**
* Gets the identifier.
*
* @return identifier
*/
public byte getIdentifier() {
return this.identifier;
}
/**
* Sets the identifier.
*
* @param identifier identifier
*/
public void setIdentifier(byte identifier) {
this.identifier = identifier;
}
/**
* Gets the authenticator.
*
* @return authenticator
*/
public byte[] getAuthenticator() {
return this.authenticator;
}
/**
* Sets the authenticator.
*
* @param authenticator authenticator
*/
public void setAuthenticator(byte[] authenticator) {
this.authenticator = authenticator;
}
/**
* Generates an authenticator code.
*
* @return the authenticator
*/
public byte[] generateAuthCode() {
new SecureRandom().nextBytes(this.authenticator);
return this.authenticator;
}
/**
* Checks if the packet's code field is valid.
*
* @return whether the code is valid
*/
public boolean isValidCode() {
return this.code == RADIUS_CODE_ACCESS_REQUEST ||
this.code == RADIUS_CODE_ACCESS_ACCEPT ||
this.code == RADIUS_CODE_ACCESS_REJECT ||
this.code == RADIUS_CODE_ACCOUNTING_REQUEST ||
this.code == RADIUS_CODE_ACCOUNTING_RESPONSE ||
this.code == RADIUS_CODE_ACCESS_CHALLENGE;
}
/**
* Adds a message authenticator to the packet based on the given key.
*
* @param key key to generate message authenticator
* @return the messgae authenticator RADIUS attribute
*/
public RADIUSAttribute addMessageAuthenticator(String key) {
// Message-Authenticator = HMAC-MD5 (Type, Identifier, Length,
// Request Authenticator, Attributes)
// When the message integrity check is calculated the signature string
// should be considered to be sixteen octets of zero.
byte[] hashOutput = new byte[16];
Arrays.fill(hashOutput, (byte) 0);
RADIUSAttribute authAttribute = this.getAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH);
if (authAttribute != null) {
// If Message-Authenticator was already present, override it
this.log.warn("Attempted to add duplicate Message-Authenticator");
authAttribute = this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, hashOutput);
} else {
// Else generate a new attribute padded with zeroes
authAttribute = this.setAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, hashOutput);
}
// Calculate the MD5 HMAC based on the message
try {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
hashOutput = mac.doFinal(this.serialize());
// Update HMAC in Message-Authenticator
authAttribute = this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, hashOutput);
} catch (Exception e) {
this.log.error("Failed to generate message authenticator: {}", e.getMessage());
}
return authAttribute;
}
/**
* Checks the message authenticator in the packet with one generated from
* the given key.
*
* @param key key to generate message authenticator
* @return whether the message authenticators match or not
*/
public boolean checkMessageAuthenticator(String key) {
byte[] newHash = new byte[16];
Arrays.fill(newHash, (byte) 0);
byte[] messageAuthenticator = this.getAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH).getValue();
this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, newHash);
// Calculate the MD5 HMAC based on the message
try {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
newHash = mac.doFinal(this.serialize());
} catch (Exception e) {
log.error("Failed to generate message authenticator: {}", e.getMessage());
}
this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, messageAuthenticator);
// Compare the calculated Message-Authenticator with the one in the message
return Arrays.equals(newHash, messageAuthenticator);
}
/**
* Encapsulates an EAP packet in this RADIUS packet.
*
* @param message EAP message object to be embedded in the RADIUS
* EAP-Message attributed
*/
public void encapsulateMessage(EAP message) {
if (message.length <= MAX_ATTR_VALUE_LENGTH) {
// Use the regular serialization method as it fits into one EAP-Message attribute
this.setAttribute(RADIUSAttribute.RADIUS_ATTR_EAP_MESSAGE,
message.serialize());
} else {
// Segment the message into chucks and embed them in several EAP-Message attributes
short remainingLength = message.length;
byte[] messageBuffer = message.serialize();
final ByteBuffer bb = ByteBuffer.wrap(messageBuffer);
while (bb.hasRemaining()) {
byte[] messageAttributeData;
if (remainingLength > MAX_ATTR_VALUE_LENGTH) {
// The remaining data is still too long to fit into one attribute, keep going
messageAttributeData = new byte[MAX_ATTR_VALUE_LENGTH];
bb.get(messageAttributeData, 0, MAX_ATTR_VALUE_LENGTH);
remainingLength -= MAX_ATTR_VALUE_LENGTH;
} else {
// The remaining data fits, this will be the last chunk
messageAttributeData = new byte[remainingLength];
bb.get(messageAttributeData, 0, remainingLength);
}
this.attributes.add(new RADIUSAttribute(RADIUSAttribute.RADIUS_ATTR_EAP_MESSAGE,
(byte) (messageAttributeData.length + 2), messageAttributeData));
// Adding the size of the data to the total RADIUS length
this.length += (short) (messageAttributeData.length & 0xFF);
// Adding the size of the overhead attribute type and length
this.length += 2;
}
}
}
/**
* Decapsulates an EAP packet from the RADIUS packet.
*
* @return An EAP object containing the reassembled EAP message
*/
public EAP decapsulateMessage() {
EAP message = new EAP();
ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
// Iterating through EAP-Message attributes to concatenate their value
for (RADIUSAttribute ra : this.getAttributeList(RADIUSAttribute.RADIUS_ATTR_EAP_MESSAGE)) {
try {
messageStream.write(ra.getValue());
} catch (IOException e) {
log.error("Error while reassembling EAP message: {}", e.getMessage());
}
}
// Assembling EAP object from the concatenated stream
message.deserialize(messageStream.toByteArray(), 0, messageStream.size());
return message;
}
/**
* Gets a list of attributes from the RADIUS packet.
*
* @param attrType the type field of the required attributes
* @return List of the attributes that matches the type or an empty list if there is none
*/
public ArrayList<RADIUSAttribute> getAttributeList(byte attrType) {
ArrayList<RADIUSAttribute> attrList = new ArrayList<>();
for (int i = 0; i < this.attributes.size(); i++) {
if (this.attributes.get(i).getType() == attrType) {
attrList.add(this.attributes.get(i));
}
}
return attrList;
}
/**
* Gets an attribute from the RADIUS packet.
*
* @param attrType the type field of the required attribute
* @return the first attribute that matches the type or null if does not exist
*/
public RADIUSAttribute getAttribute(byte attrType) {
for (int i = 0; i < this.attributes.size(); i++) {
if (this.attributes.get(i).getType() == attrType) {
return this.attributes.get(i);
}
}
return null;
}
/**
* Sets an attribute in the RADIUS packet.
*
* @param attrType the type field of the attribute to set
* @param value value to be set
* @return reference to the attribute object
*/
public RADIUSAttribute setAttribute(byte attrType, byte[] value) {
byte attrLength = (byte) (value.length + 2);
RADIUSAttribute newAttribute = new RADIUSAttribute(attrType, attrLength, value);
this.attributes.add(newAttribute);
this.length += (short) (attrLength & 0xFF);
return newAttribute;
}
/**
* Updates an attribute in the RADIUS packet.
*
* @param attrType the type field of the attribute to update
* @param value the value to update to
* @return reference to the attribute object
*/
public RADIUSAttribute updateAttribute(byte attrType, byte[] value) {
for (int i = 0; i < this.attributes.size(); i++) {
if (this.attributes.get(i).getType() == attrType) {
this.length -= (short) (this.attributes.get(i).getLength() & 0xFF);
RADIUSAttribute newAttr = new RADIUSAttribute(attrType, (byte) (value.length + 2), value);
this.attributes.set(i, newAttr);
this.length += (short) (newAttr.getLength() & 0xFF);
return newAttr;
}
}
return null;
}
/**
* Deserializer for RADIUS packets.
*
* @return deserializer
*/
public static Deserializer<RADIUS> deserializer() {
return (data, offset, length) -> {
checkInput(data, offset, length, RADIUS_MIN_LENGTH);
final ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
RADIUS radius = new RADIUS();
radius.code = bb.get();
radius.identifier = bb.get();
radius.length = bb.getShort();
bb.get(radius.authenticator, 0, 16);
checkHeaderLength(length, radius.length);
int remainingLength = radius.length - RADIUS_MIN_LENGTH;
while (remainingLength > 0 && bb.hasRemaining()) {
RADIUSAttribute attr = new RADIUSAttribute();
attr.setType(bb.get());
attr.setLength(bb.get());
short attrLength = (short) (attr.length & 0xff);
attr.value = new byte[attrLength - 2];
bb.get(attr.value, 0, attrLength - 2);
radius.attributes.add(attr);
remainingLength -= attrLength;
}
return radius;
};
}
@Override
public byte[] serialize() {
final byte[] data = new byte[this.length];
final ByteBuffer bb = ByteBuffer.wrap(data);
bb.put(this.code);
bb.put(this.identifier);
bb.putShort(this.length);
bb.put(this.authenticator);
for (int i = 0; i < this.attributes.size(); i++) {
RADIUSAttribute attr = this.attributes.get(i);
bb.put(attr.getType());
bb.put(attr.getLength());
bb.put(attr.getValue());
}
return data;
}
@Override
public IPacket deserialize(final byte[] data, final int offset,
final int length) {
final ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
this.code = bb.get();
this.identifier = bb.get();
this.length = bb.getShort();
bb.get(this.authenticator, 0, 16);
int remainingLength = this.length - RADIUS_MIN_LENGTH;
while (remainingLength > 0 && bb.hasRemaining()) {
RADIUSAttribute attr = new RADIUSAttribute();
attr.setType(bb.get());
attr.setLength(bb.get());
short attrLength = (short) (attr.length & 0xff);
attr.value = new byte[attrLength - 2];
bb.get(attr.value, 0, attrLength - 2);
this.attributes.add(attr);
remainingLength -= attr.length;
}
return this;
}
@Override
public String toString() {
return toStringHelper(getClass())
.add("code", Byte.toString(code))
.add("identifier", Byte.toString(identifier))
.add("length", Short.toString(length))
.add("authenticator", Arrays.toString(authenticator))
.toString();
// TODO: need to handle attributes
}
}
| donNewtonAlpha/onos | utils/misc/src/main/java/org/onlab/packet/RADIUS.java | Java | apache-2.0 | 15,678 |
#!/usr/bin/env bash
# Copyright 2015 The Kubernetes Authors.
#
# Licensed 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.
set -o errexit
set -o nounset
set -o pipefail
KUBE_ROOT=$(dirname "${BASH_SOURCE}")/..
source "${KUBE_ROOT}/hack/lib/init.sh"
kube::golang::setup_env
BINS=(
vendor/k8s.io/code-generator/cmd/go-to-protobuf
vendor/k8s.io/code-generator/cmd/go-to-protobuf/protoc-gen-gogo
)
make -C "${KUBE_ROOT}" WHAT="${BINS[*]}"
if [[ -z "$(which protoc)" || "$(protoc --version)" != "libprotoc 3."* ]]; then
echo "Generating protobuf requires protoc 3.0.0-beta1 or newer. Please download and"
echo "install the platform appropriate Protobuf package for your OS: "
echo
echo " https://github.com/google/protobuf/releases"
echo
echo "WARNING: Protobuf changes are not being validated"
exit 1
fi
gotoprotobuf=$(kube::util::find-binary "go-to-protobuf")
APIROOTS=( ${1} )
shift
# requires the 'proto' tag to build (will remove when ready)
# searches for the protoc-gen-gogo extension in the output directory
# satisfies import of github.com/gogo/protobuf/gogoproto/gogo.proto and the
# core Google protobuf types
PATH="${KUBE_ROOT}/_output/bin:${PATH}" \
"${gotoprotobuf}" \
--proto-import="${KUBE_ROOT}/vendor" \
--proto-import="${KUBE_ROOT}/third_party/protobuf" \
--packages=$(IFS=, ; echo "${APIROOTS[*]}") \
--go-header-file ${KUBE_ROOT}/hack/boilerplate/boilerplate.generatego.txt \
"$@"
| Stackdriver/heapster | vendor/k8s.io/kubernetes/hack/update-generated-protobuf-dockerized.sh | Shell | apache-2.0 | 1,919 |
/*
* Copyright 2008-2012 NVIDIA Corporation
*
* Licensed 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.
*/
#pragma once
#include <thrust/detail/config.h>
#include <thrust/system/omp/detail/tag.h>
#include <thrust/system/detail/generic/binary_search.h>
namespace thrust
{
namespace system
{
namespace omp
{
namespace detail
{
template <typename ForwardIterator, typename T, typename StrictWeakOrdering>
ForwardIterator lower_bound(tag,
ForwardIterator begin,
ForwardIterator end,
const T& value,
StrictWeakOrdering comp)
{
// omp prefers generic::lower_bound to cpp::lower_bound
return thrust::system::detail::generic::lower_bound(tag(), begin, end, value, comp);
}
template <typename ForwardIterator, typename T, typename StrictWeakOrdering, typename Backend>
ForwardIterator upper_bound(tag,
ForwardIterator begin,
ForwardIterator end,
const T& value,
StrictWeakOrdering comp)
{
// omp prefers generic::upper_bound to cpp::upper_bound
return thrust::system::detail::generic::upper_bound(tag(), begin, end, value, comp);
}
template <typename ForwardIterator, typename T, typename StrictWeakOrdering>
bool binary_search(tag,
ForwardIterator begin,
ForwardIterator end,
const T& value,
StrictWeakOrdering comp)
{
// omp prefers generic::binary_search to cpp::binary_search
return thrust::system::detail::generic::binary_search(tag(), begin, end, value, comp);
}
} // end detail
} // end omp
} // end system
} // end thrust
| Vishwa07/thrust | thrust/system/omp/detail/binary_search.h | C | apache-2.0 | 2,270 |
cask 'speedy' do
version '4.0.4'
sha256 '5dda979473073150d06cdeded654045063088e2f302cef45619281ac74242ca9'
url 'http://www.apimac.com/download/Speedy.zip'
appcast 'http://www.apimac.com/version_checking/speedy_mac.xml',
checkpoint: '6b0638d63dd078a73c3ffd8ae2a625123d52d9a30c4f220676aae8eb36718707'
name 'Speedy'
homepage 'http://www.apimac.com/mac/speedy/'
app 'Speedy.app'
end
| mauricerkelly/homebrew-cask | Casks/speedy.rb | Ruby | bsd-2-clause | 405 |
#ifndef ALITASKCDBCONNECT_H
#define ALITASKCDBCONNECT_H
//==============================================================================
// TaskCDBconnect - task just allowing connection to CDB (no lock)
//==============================================================================
#ifndef ALIANALYSISTASK_H
#include "AliAnalysisTask.h"
#endif
class AliCDBManager;
class AliGRPManager;
class AliESDEvent;
class AliESDInputHandler;
class AliTaskCDBconnect : public AliAnalysisTask {
private:
Bool_t fFallBackToRaw; // allow fallback to raw if cvmfs is not mounted
Int_t fRun; // Current run
ULong64_t fLock; // CDB lock
TString fStorage; // Storage (if cvmfs
TObjArray fSpecCDBUri; // Array with specific CDB storages
AliGRPManager *fGRPManager; //! Pointer to GRP manager
AliTaskCDBconnect(const AliTaskCDBconnect &other);
AliTaskCDBconnect& operator=(const AliTaskCDBconnect &other);
void InitGRP();
//
public:
AliTaskCDBconnect();
AliTaskCDBconnect(const char *name, const char *storage="raw://", Int_t run=0, Bool_t fallback=kFALSE);
virtual ~AliTaskCDBconnect();
Int_t GetRun() const {return fRun;}
AliGRPManager* GetGRPManager() const {return (AliGRPManager*)fGRPManager;}
virtual void Exec(Option_t *option);
virtual void CreateOutputObjects();
virtual void ConnectInputData(Option_t *option = "");
void SetSpecificStorage(const char* calibType, const char* dbString,
Int_t version = -1, Int_t subVersion = -1);
void SetFallBackToRaw(Bool_t v) {fFallBackToRaw = v;}
Bool_t GetFallBackToRaw() const {return fFallBackToRaw;}
ClassDef(AliTaskCDBconnect,5) // Class giving CDB connectivity
};
#endif
| dlodato/AliPhysics | PWGPP/AliTaskCDBconnect.h | C | bsd-3-clause | 2,031 |
<?php
/**
* Dailyscript - Web | App | Media
*
* Filtra numeros enteros entre letras
*
* @category Extensions
* @author IvΓ‘n D. MelΓ©ndez ([email protected])
* @package Filters
* @copyright Copyright (c) 2013 Dailyscript Team (http://www.dailyscript.com.co)
*/
class PageFilter implements FilterInterface {
/**
* Ejecuta el filtro para los string
*
* @param string $s
* @param array $options
* @return string
*/
public static function execute ($s, $options) {
$patron = '/[^0-9]/';
return preg_replace($patron, '', (string) $s);
}
}
?>
| KumbiaPHP/backend_manager | default/app/extensions/filters/page_filter.php | PHP | bsd-3-clause | 651 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/base/v8_unit_test.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#include "chrome/common/chrome_paths.h"
namespace {
// |args| are passed through the various JavaScript logging functions such as
// console.log. Returns a string appropriate for logging with LOG(severity).
std::string LogArgs2String(const v8::Arguments& args) {
std::string message;
bool first = true;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
if (first)
first = false;
else
message += " ";
v8::String::Utf8Value str(args[i]);
message += *str;
}
return message;
}
// Whether errors were seen.
bool had_errors = false;
// testDone results.
bool testResult_ok = false;
// Location of test data (currently test/data/webui).
FilePath test_data_directory;
// Location of generated test data (<(PROGRAM_DIR)/test_data).
FilePath gen_test_data_directory;
} // namespace
V8UnitTest::V8UnitTest() {
InitPathsAndLibraries();
}
V8UnitTest::~V8UnitTest() {}
void V8UnitTest::AddLibrary(const FilePath& library_path) {
user_libraries_.push_back(library_path);
}
bool V8UnitTest::ExecuteJavascriptLibraries() {
std::string utf8_content;
for (std::vector<FilePath>::iterator user_libraries_iterator =
user_libraries_.begin();
user_libraries_iterator != user_libraries_.end();
++user_libraries_iterator) {
std::string library_content;
FilePath library_file(*user_libraries_iterator);
if (!user_libraries_iterator->IsAbsolute()) {
FilePath gen_file = gen_test_data_directory.Append(library_file);
library_file = file_util::PathExists(gen_file) ? gen_file :
test_data_directory.Append(*user_libraries_iterator);
}
if (!file_util::ReadFileToString(library_file, &library_content)) {
ADD_FAILURE() << library_file.value();
return false;
}
ExecuteScriptInContext(library_content, library_file.MaybeAsASCII());
if (::testing::Test::HasFatalFailure())
return false;
}
return true;
}
bool V8UnitTest::RunJavascriptTestF(
const std::string& testFixture, const std::string& testName) {
had_errors = false;
testResult_ok = false;
std::string test_js;
if (!ExecuteJavascriptLibraries())
return false;
v8::Context::Scope context_scope(context_);
v8::HandleScope handle_scope;
v8::Handle<v8::Value> functionProperty =
context_->Global()->Get(v8::String::New("runTest"));
EXPECT_FALSE(functionProperty.IsEmpty());
if (::testing::Test::HasNonfatalFailure())
return false;
EXPECT_TRUE(functionProperty->IsFunction());
if (::testing::Test::HasNonfatalFailure())
return false;
v8::Handle<v8::Function> function =
v8::Handle<v8::Function>::Cast(functionProperty);
v8::Local<v8::Array> params = v8::Array::New();
params->Set(0, v8::String::New(testFixture.data(), testFixture.size()));
params->Set(1, v8::String::New(testName.data(), testName.size()));
v8::Handle<v8::Value> args[] = {
v8::Boolean::New(false),
v8::String::New("RUN_TEST_F"),
params
};
v8::TryCatch try_catch;
v8::Handle<v8::Value> result = function->Call(context_->Global(), 3, args);
// The test fails if an exception was thrown.
EXPECT_FALSE(result.IsEmpty());
if (::testing::Test::HasNonfatalFailure())
return false;
// Ok if ran successfully, passed tests, and didn't have console errors.
return result->BooleanValue() && testResult_ok && !had_errors;
}
void V8UnitTest::InitPathsAndLibraries() {
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory));
test_data_directory = test_data_directory.AppendASCII("webui");
ASSERT_TRUE(PathService::Get(chrome::DIR_GEN_TEST_DATA,
&gen_test_data_directory));
FilePath mockPath;
ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &mockPath));
mockPath = mockPath.AppendASCII("chrome");
mockPath = mockPath.AppendASCII("third_party");
mockPath = mockPath.AppendASCII("mock4js");
mockPath = mockPath.AppendASCII("mock4js.js");
AddLibrary(mockPath);
FilePath testApiPath;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &testApiPath));
testApiPath = testApiPath.AppendASCII("webui");
testApiPath = testApiPath.AppendASCII("test_api.js");
AddLibrary(testApiPath);
}
void V8UnitTest::SetUp() {
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::String> logString = v8::String::New("log");
v8::Handle<v8::FunctionTemplate> logFunction =
v8::FunctionTemplate::New(&V8UnitTest::Log);
global->Set(logString, logFunction);
// Set up chrome object for chrome.send().
v8::Handle<v8::ObjectTemplate> chrome = v8::ObjectTemplate::New();
global->Set(v8::String::New("chrome"), chrome);
chrome->Set(v8::String::New("send"),
v8::FunctionTemplate::New(&V8UnitTest::ChromeSend));
// Set up console object for console.log(), etc.
v8::Handle<v8::ObjectTemplate> console = v8::ObjectTemplate::New();
global->Set(v8::String::New("console"), console);
console->Set(logString, logFunction);
console->Set(v8::String::New("info"), logFunction);
console->Set(v8::String::New("warn"), logFunction);
console->Set(v8::String::New("error"),
v8::FunctionTemplate::New(&V8UnitTest::Error));
context_ = v8::Context::New(NULL, global);
}
void V8UnitTest::SetGlobalStringVar(const std::string& var_name,
const std::string& value) {
v8::Context::Scope context_scope(context_);
context_->Global()->Set(v8::String::New(var_name.c_str(), var_name.length()),
v8::String::New(value.c_str(), value.length()));
}
void V8UnitTest::ExecuteScriptInContext(const base::StringPiece& script_source,
const base::StringPiece& script_name) {
v8::Context::Scope context_scope(context_);
v8::HandleScope handle_scope;
v8::Handle<v8::String> source = v8::String::New(script_source.data(),
script_source.size());
v8::Handle<v8::String> name = v8::String::New(script_name.data(),
script_name.size());
v8::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
// Ensure the script compiled without errors.
if (script.IsEmpty())
FAIL() << ExceptionToString(try_catch);
v8::Handle<v8::Value> result = script->Run();
// Ensure the script ran without errors.
if (result.IsEmpty())
FAIL() << ExceptionToString(try_catch);
}
std::string V8UnitTest::ExceptionToString(const v8::TryCatch& try_catch) {
std::string str;
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch.Exception());
v8::Local<v8::Message> message(try_catch.Message());
if (message.IsEmpty()) {
str.append(base::StringPrintf("%s\n", *exception));
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
int colnum = message->GetStartColumn();
str.append(base::StringPrintf(
"%s:%i:%i %s\n", *filename, linenum, colnum, *exception));
v8::String::Utf8Value sourceline(message->GetSourceLine());
str.append(base::StringPrintf("%s\n", *sourceline));
}
return str;
}
void V8UnitTest::TestFunction(const std::string& function_name) {
v8::Context::Scope context_scope(context_);
v8::HandleScope handle_scope;
v8::Handle<v8::Value> functionProperty =
context_->Global()->Get(v8::String::New(function_name.c_str()));
ASSERT_FALSE(functionProperty.IsEmpty());
ASSERT_TRUE(functionProperty->IsFunction());
v8::Handle<v8::Function> function =
v8::Handle<v8::Function>::Cast(functionProperty);
v8::TryCatch try_catch;
v8::Handle<v8::Value> result = function->Call(context_->Global(), 0, NULL);
// The test fails if an exception was thrown.
if (result.IsEmpty())
FAIL() << ExceptionToString(try_catch);
}
// static
v8::Handle<v8::Value> V8UnitTest::Log(const v8::Arguments& args) {
LOG(INFO) << LogArgs2String(args);
return v8::Undefined();
}
v8::Handle<v8::Value> V8UnitTest::Error(const v8::Arguments& args) {
had_errors = true;
LOG(ERROR) << LogArgs2String(args);
return v8::Undefined();
}
v8::Handle<v8::Value> V8UnitTest::ChromeSend(const v8::Arguments& args) {
v8::HandleScope handle_scope;
// We expect to receive 2 args: ("testResult", [ok, message]). However,
// chrome.send may pass only one. Therefore we need to ensure we have at least
// 1, then ensure that the first is "testResult" before checking again for 2.
EXPECT_LE(1, args.Length());
if (::testing::Test::HasNonfatalFailure())
return v8::Undefined();
v8::String::Utf8Value message(args[0]);
EXPECT_EQ("testResult", std::string(*message, message.length()));
if (::testing::Test::HasNonfatalFailure())
return v8::Undefined();
EXPECT_EQ(2, args.Length());
if (::testing::Test::HasNonfatalFailure())
return v8::Undefined();
v8::Handle<v8::Array> testResult(args[1].As<v8::Array>());
EXPECT_EQ(2U, testResult->Length());
if (::testing::Test::HasNonfatalFailure())
return v8::Undefined();
testResult_ok = testResult->Get(0)->BooleanValue();
if (!testResult_ok) {
v8::String::Utf8Value message(testResult->Get(1));
LOG(ERROR) << *message;
}
return v8::Undefined();
}
| aYukiSekiguchi/ACCESS-Chromium | chrome/test/base/v8_unit_test.cc | C++ | bsd-3-clause | 9,652 |
<?php
/**
* This file is part of vfsStream.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package org\bovigo\vfs
*/
namespace org\bovigo\vfs;
require_once __DIR__ . '/vfsStreamWrapperBaseTestCase.php';
/**
* Test for org\bovigo\vfs\vfsStreamWrapper around mkdir().
*
* @package bovigo_vfs
* @subpackage test
*/
class vfsStreamWrapperMkDirTestCase extends vfsStreamWrapperBaseTestCase
{
/**
* mkdir() should not overwrite existing root
*
* @test
*/
public function mkdirNoNewRoot()
{
$this->assertFalse(mkdir(vfsStream::url('another')));
$this->assertEquals(2, count($this->foo->getChildren()));
$this->assertSame($this->foo, vfsStreamWrapper::getRoot());
}
/**
* mkdir() should not overwrite existing root
*
* @test
*/
public function mkdirNoNewRootRecursively()
{
$this->assertFalse(mkdir(vfsStream::url('another/more'), 0777, true));
$this->assertEquals(2, count($this->foo->getChildren()));
$this->assertSame($this->foo, vfsStreamWrapper::getRoot());
}
/**
* assert that mkdir() creates the correct directory structure
*
* @test
* @group permissions
*/
public function mkdirNonRecursively()
{
$this->assertFalse(mkdir($this->barURL . '/another/more'));
$this->assertEquals(2, count($this->foo->getChildren()));
$this->assertTrue(mkdir($this->fooURL . '/another'));
$this->assertEquals(3, count($this->foo->getChildren()));
$this->assertEquals(0777, $this->foo->getChild('another')->getPermissions());
}
/**
* assert that mkdir() creates the correct directory structure
*
* @test
* @group permissions
*/
public function mkdirRecursively()
{
$this->assertTrue(mkdir($this->fooURL . '/another/more', 0777, true));
$this->assertEquals(3, count($this->foo->getChildren()));
$another = $this->foo->getChild('another');
$this->assertTrue($another->hasChild('more'));
$this->assertEquals(0777, $this->foo->getChild('another')->getPermissions());
$this->assertEquals(0777, $this->foo->getChild('another')->getChild('more')->getPermissions());
}
/**
* @test
* @group issue_9
* @since 0.9.0
*/
public function mkdirWithDots()
{
$this->assertTrue(mkdir($this->fooURL . '/another/../more/.', 0777, true));
$this->assertEquals(3, count($this->foo->getChildren()));
$this->assertTrue($this->foo->hasChild('more'));
}
/**
* no root > new directory becomes root
*
* @test
* @group permissions
*/
public function mkdirWithoutRootCreatesNewRoot()
{
vfsStreamWrapper::register();
$this->assertTrue(@mkdir(vfsStream::url('foo')));
$this->assertEquals(vfsStreamContent::TYPE_DIR, vfsStreamWrapper::getRoot()->getType());
$this->assertEquals('foo', vfsStreamWrapper::getRoot()->getName());
$this->assertEquals(0777, vfsStreamWrapper::getRoot()->getPermissions());
}
/**
* trying to create a subdirectory of a file should not work
*
* @test
*/
public function mkdirOnFileReturnsFalse()
{
$this->assertFalse(mkdir($this->baz1URL . '/another/more', 0777, true));
}
/**
* assert that mkdir() creates the correct directory structure
*
* @test
* @group permissions
*/
public function mkdirNonRecursivelyDifferentPermissions()
{
$this->assertTrue(mkdir($this->fooURL . '/another', 0755));
$this->assertEquals(0755, $this->foo->getChild('another')->getPermissions());
}
/**
* assert that mkdir() creates the correct directory structure
*
* @test
* @group permissions
*/
public function mkdirRecursivelyDifferentPermissions()
{
$this->assertTrue(mkdir($this->fooURL . '/another/more', 0755, true));
$this->assertEquals(3, count($this->foo->getChildren()));
$another = $this->foo->getChild('another');
$this->assertTrue($another->hasChild('more'));
$this->assertEquals(0755, $this->foo->getChild('another')->getPermissions());
$this->assertEquals(0755, $this->foo->getChild('another')->getChild('more')->getPermissions());
}
/**
* assert that mkdir() creates the correct directory structure
*
* @test
* @group permissions
*/
public function mkdirRecursivelyUsesDefaultPermissions()
{
$this->foo->chmod(0700);
$this->assertTrue(mkdir($this->fooURL . '/another/more', 0777, true));
$this->assertEquals(3, count($this->foo->getChildren()));
$another = $this->foo->getChild('another');
$this->assertTrue($another->hasChild('more'));
$this->assertEquals(0777, $this->foo->getChild('another')->getPermissions());
$this->assertEquals(0777, $this->foo->getChild('another')->getChild('more')->getPermissions());
}
/**
* no root > new directory becomes root
*
* @test
* @group permissions
*/
public function mkdirWithoutRootCreatesNewRootDifferentPermissions()
{
vfsStreamWrapper::register();
$this->assertTrue(@mkdir(vfsStream::url('foo'), 0755));
$this->assertEquals(vfsStreamContent::TYPE_DIR, vfsStreamWrapper::getRoot()->getType());
$this->assertEquals('foo', vfsStreamWrapper::getRoot()->getName());
$this->assertEquals(0755, vfsStreamWrapper::getRoot()->getPermissions());
}
/**
* no root > new directory becomes root
*
* @test
* @group permissions
*/
public function mkdirWithoutRootCreatesNewRootWithDefaultPermissions()
{
vfsStreamWrapper::register();
$this->assertTrue(@mkdir(vfsStream::url('foo')));
$this->assertEquals(vfsStreamContent::TYPE_DIR, vfsStreamWrapper::getRoot()->getType());
$this->assertEquals('foo', vfsStreamWrapper::getRoot()->getName());
$this->assertEquals(0777, vfsStreamWrapper::getRoot()->getPermissions());
}
/**
* @test
* @group permissions
* @group bug_15
*/
public function mkdirDirCanNotCreateNewDirInNonWritingDirectory()
{
vfsStreamWrapper::register();
vfsStreamWrapper::setRoot(new vfsStreamDirectory('root'));
vfsStreamWrapper::getRoot()->addChild(new vfsStreamDirectory('restrictedFolder', 0000));
$this->assertFalse(is_writable(vfsStream::url('root/restrictedFolder/')));
$this->assertFalse(mkdir(vfsStream::url('root/restrictedFolder/newFolder')));
$this->assertFalse(vfsStreamWrapper::getRoot()->hasChild('restrictedFolder/newFolder'));
}
/**
* @test
* @group issue_28
*/
public function mkDirShouldNotOverwriteExistingDirectories()
{
vfsStream::setup('root');
$dir = vfsStream::url('root/dir');
$this->assertTrue(mkdir($dir));
$this->assertFalse(@mkdir($dir));
}
/**
* @test
* @group issue_28
* @expectedException PHPUnit_Framework_Error
* @expectedExceptionMessage mkdir(): Path vfs://root/dir exists
*/
public function mkDirShouldNotOverwriteExistingDirectoriesAndTriggerE_USER_WARNING()
{
vfsStream::setup('root');
$dir = vfsStream::url('root/dir');
$this->assertTrue(mkdir($dir));
$this->assertFalse(mkdir($dir));
}
/**
* @test
* @group issue_28
*/
public function mkDirShouldNotOverwriteExistingFiles()
{
$root = vfsStream::setup('root');
vfsStream::newFile('test.txt')->at($root);
$this->assertFalse(@mkdir(vfsStream::url('root/test.txt')));
}
/**
* @test
* @group issue_28
* @expectedException PHPUnit_Framework_Error
* @expectedExceptionMessage mkdir(): Path vfs://root/test.txt exists
*/
public function mkDirShouldNotOverwriteExistingFilesAndTriggerE_USER_WARNING()
{
$root = vfsStream::setup('root');
vfsStream::newFile('test.txt')->at($root);
$this->assertFalse(mkdir(vfsStream::url('root/test.txt')));
}
/**
* @test
* @group permissions
* @group bug_15
*/
public function canNotIterateOverNonReadableDirectory()
{
vfsStreamWrapper::register();
vfsStreamWrapper::setRoot(new vfsStreamDirectory('root', 0000));
$this->assertFalse(@opendir(vfsStream::url('root')));
$this->assertFalse(@dir(vfsStream::url('root')));
}
/**
* @test
*/
public function directoryIteration()
{
$dir = dir($this->fooURL);
$i = 0;
while (false !== ($entry = $dir->read())) {
$i++;
$this->assertTrue('bar' === $entry || 'baz2' === $entry);
}
$this->assertEquals(2, $i, 'Directory foo contains two children, but got ' . $i . ' children while iterating over directory contents');
$dir->rewind();
$i = 0;
while (false !== ($entry = $dir->read())) {
$i++;
$this->assertTrue('bar' === $entry || 'baz2' === $entry);
}
$this->assertEquals(2, $i, 'Directory foo contains two children, but got ' . $i . ' children while iterating over directory contents');
$dir->close();
}
/**
* @test
*/
public function directoryIterationWithDot()
{
$dir = dir($this->fooURL . '/.');
$i = 0;
while (false !== ($entry = $dir->read())) {
$i++;
$this->assertTrue('bar' === $entry || 'baz2' === $entry);
}
$this->assertEquals(2, $i, 'Directory foo contains two children, but got ' . $i . ' children while iterating over directory contents');
$dir->rewind();
$i = 0;
while (false !== ($entry = $dir->read())) {
$i++;
$this->assertTrue('bar' === $entry || 'baz2' === $entry);
}
$this->assertEquals(2, $i, 'Directory foo contains two children, but got ' . $i . ' children while iterating over directory contents');
$dir->close();
}
/**
* assure that a directory iteration works as expected
*
* @test
* @group regression
* @group bug_2
*/
public function directoryIterationWithOpenDir_Bug_2()
{
$handle = opendir($this->fooURL);
$i = 0;
while (false !== ($entry = readdir($handle))) {
$i++;
$this->assertTrue('bar' === $entry || 'baz2' === $entry);
}
$this->assertEquals(2, $i, 'Directory foo contains two children, but got ' . $i . ' children while iterating over directory contents');
rewind($handle);
$i = 0;
while (false !== ($entry = readdir($handle))) {
$i++;
$this->assertTrue('bar' === $entry || 'baz2' === $entry);
}
$this->assertEquals(2, $i, 'Directory foo contains two children, but got ' . $i . ' children while iterating over directory contents');
closedir($handle);
}
/**
* assure that a directory iteration works as expected
*
* @author Christoph Bloemer
* @test
* @group regression
* @group bug_4
*/
public function directoryIteration_Bug_4()
{
$dir = $this->fooURL;
$list1 = array();
if ($handle = opendir($dir)) {
while (false !== ($listItem = readdir($handle))) {
if ('.' != $listItem && '..' != $listItem) {
if (is_file($dir . '/' . $listItem) === true) {
$list1[] = 'File:[' . $listItem . ']';
} elseif (is_dir($dir . '/' . $listItem) === true) {
$list1[] = 'Folder:[' . $listItem . ']';
}
}
}
closedir($handle);
}
$list2 = array();
if ($handle = opendir($dir)) {
while (false !== ($listItem = readdir($handle))) {
if ('.' != $listItem && '..' != $listItem) {
if (is_file($dir . '/' . $listItem) === true) {
$list2[] = 'File:[' . $listItem . ']';
} elseif (is_dir($dir . '/' . $listItem) === true) {
$list2[] = 'Folder:[' . $listItem . ']';
}
}
}
closedir($handle);
}
$this->assertEquals($list1, $list2);
$this->assertEquals(2, count($list1));
$this->assertEquals(2, count($list2));
}
/**
* assure that a directory iteration works as expected
*
* @test
*/
public function directoryIterationShouldBeIndependent()
{
$list1 = array();
$list2 = array();
$handle1 = opendir($this->fooURL);
if (false !== ($listItem = readdir($handle1))) {
$list1[] = $listItem;
}
$handle2 = opendir($this->fooURL);
if (false !== ($listItem = readdir($handle2))) {
$list2[] = $listItem;
}
if (false !== ($listItem = readdir($handle1))) {
$list1[] = $listItem;
}
if (false !== ($listItem = readdir($handle2))) {
$list2[] = $listItem;
}
closedir($handle1);
closedir($handle2);
$this->assertEquals($list1, $list2);
$this->assertEquals(2, count($list1));
$this->assertEquals(2, count($list2));
}
/**
* assert is_dir() returns correct result
*
* @test
*/
public function is_dir()
{
$this->assertTrue(is_dir($this->fooURL));
$this->assertTrue(is_dir($this->fooURL . '/.'));
$this->assertTrue(is_dir($this->barURL));
$this->assertTrue(is_dir($this->barURL . '/.'));
$this->assertFalse(is_dir($this->baz1URL));
$this->assertFalse(is_dir($this->baz2URL));
$this->assertFalse(is_dir($this->fooURL . '/another'));
$this->assertFalse(is_dir(vfsStream::url('another')));
}
/**
* can not unlink without root
*
* @test
*/
public function canNotUnlinkDirectoryWithoutRoot()
{
vfsStreamWrapper::register();
$this->assertFalse(@rmdir(vfsStream::url('foo')));
}
/**
* rmdir() can not remove files
*
* @test
*/
public function rmdirCanNotRemoveFiles()
{
$this->assertFalse(rmdir($this->baz1URL));
$this->assertFalse(rmdir($this->baz2URL));
}
/**
* rmdir() can not remove a non-existing directory
*
* @test
*/
public function rmdirCanNotRemoveNonExistingDirectory()
{
$this->assertFalse(rmdir($this->fooURL . '/another'));
}
/**
* rmdir() can not remove non-empty directories
*
* @test
*/
public function rmdirCanNotRemoveNonEmptyDirectory()
{
$this->assertFalse(rmdir($this->fooURL));
$this->assertFalse(rmdir($this->barURL));
}
/**
* @test
*/
public function rmdirCanRemoveEmptyDirectory()
{
vfsStream::newDirectory('empty')->at($this->foo);
$this->assertTrue($this->foo->hasChild('empty'));
$this->assertTrue(rmdir($this->fooURL . '/empty'));
$this->assertFalse($this->foo->hasChild('empty'));
}
/**
* @test
*/
public function rmdirCanRemoveEmptyDirectoryWithDot()
{
vfsStream::newDirectory('empty')->at($this->foo);
$this->assertTrue($this->foo->hasChild('empty'));
$this->assertTrue(rmdir($this->fooURL . '/empty/.'));
$this->assertFalse($this->foo->hasChild('empty'));
}
/**
* rmdir() can remove empty directories
*
* @test
*/
public function rmdirCanRemoveEmptyRoot()
{
$this->foo->removeChild('bar');
$this->foo->removeChild('baz2');
$this->assertTrue(rmdir($this->fooURL));
$this->assertFalse(file_exists($this->fooURL)); // make sure statcache was cleared
$this->assertNull(vfsStreamWrapper::getRoot());
}
/**
* @test
* @group permissions
* @group bug_15
*/
public function rmdirDirCanNotRemoveDirFromNonWritingDirectory()
{
vfsStreamWrapper::register();
vfsStreamWrapper::setRoot(new vfsStreamDirectory('root', 0000));
vfsStreamWrapper::getRoot()->addChild(new vfsStreamDirectory('nonRemovableFolder'));
$this->assertFalse(is_writable(vfsStream::url('root')));
$this->assertFalse(rmdir(vfsStream::url('root/nonRemovableFolder')));
$this->assertTrue(vfsStreamWrapper::getRoot()->hasChild('nonRemovableFolder'));
}
/**
* @test
* @group permissions
* @group bug_17
*/
public function issue17()
{
vfsStreamWrapper::register();
vfsStreamWrapper::setRoot(new vfsStreamDirectory('root', 0770));
vfsStreamWrapper::getRoot()->chgrp(vfsStream::GROUP_USER_1)
->chown(vfsStream::OWNER_USER_1);
$this->assertFalse(mkdir(vfsStream::url('root/doesNotWork')));
$this->assertFalse(vfsStreamWrapper::getRoot()->hasChild('doesNotWork'));
}
/**
* @test
* @group bug_19
*/
public function accessWithDoubleDotReturnsCorrectContent()
{
$this->assertEquals('baz2',
file_get_contents(vfsStream::url('foo/bar/../baz2'))
);
}
/**
* @test
* @since 0.11.0
* @group issue_23
*/
public function unlinkCanNotRemoveNonEmptyDirectory()
{
try {
$this->assertFalse(unlink($this->barURL));
} catch (\PHPUnit_Framework_Error $fe) {
$this->assertEquals('unlink(vfs://foo/bar): Operation not permitted', $fe->getMessage());
}
$this->assertTrue($this->foo->hasChild('bar'));
$this->assertFileExists($this->barURL);
}
/**
* @test
* @since 0.11.0
* @group issue_23
*/
public function unlinkCanNotRemoveEmptyDirectory()
{
vfsStream::newDirectory('empty')->at($this->foo);
try {
$this->assertTrue(unlink($this->fooURL . '/empty'));
} catch (\PHPUnit_Framework_Error $fe) {
$this->assertEquals('unlink(vfs://foo/empty): Operation not permitted', $fe->getMessage());
}
$this->assertTrue($this->foo->hasChild('empty'));
$this->assertFileExists($this->fooURL . '/empty');
}
/**
* @test
* @group issue_32
*/
public function canCreateFolderOfSameNameAsParentFolder()
{
$root = vfsStream::setup('testFolder');
mkdir(vfsStream::url('testFolder') . '/testFolder/subTestFolder', 0777, true);
$this->assertTrue(file_exists(vfsStream::url('testFolder/testFolder/subTestFolder/.')));
}
/**
* @test
* @group issue_32
*/
public function canRetrieveFolderOfSameNameAsParentFolder()
{
$root = vfsStream::setup('testFolder');
mkdir(vfsStream::url('testFolder') . '/testFolder/subTestFolder', 0777, true);
$this->assertTrue($root->hasChild('testFolder'));
$this->assertNotNull($root->getChild('testFolder'));
}
}
?> | Gerencia-de-Configuracao-Software/SiGA | www/SiGA/vendor-dependencies/mikey179/vfsStream/src/test/php/org/bovigo/vfs/vfsStreamWrapperDirTestCase.php | PHP | gpl-3.0 | 19,389 |
#ifndef BOOST_NUMERIC_SAFE_COMMON_HPP
#define BOOST_NUMERIC_SAFE_COMMON_HPP
// Copyright (c) 2012 Robert Ramey
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <type_traits>
namespace boost {
namespace safe_numerics {
// default implementations for required meta-functions
template<typename T>
struct is_safe : public std::false_type
{};
template<typename T>
struct base_type {
using type = T;
};
template<class T>
constexpr const typename base_type<T>::type & base_value(const T & t) {
return static_cast<const typename base_type<T>::type & >(t);
}
template<typename T>
struct get_promotion_policy {
using type = void;
};
template<typename T>
struct get_exception_policy {
using type = void;
};
} // safe_numerics
} // boost
#endif // BOOST_NUMERIC_SAFE_COMMON_HPP
| kumakoko/KumaGL | third_lib/boost/1.75.0/boost/safe_numerics/safe_common.hpp | C++ | mit | 913 |
#!/bin/sh -e
DIRECTORY=$(dirname "${0}")
SCRIPT_DIRECTORY=$(
cd "${DIRECTORY}" || exit 1
pwd
)
# shellcheck source=/dev/null
. "${SCRIPT_DIRECTORY}/../../configuration/project.sh"
if [ "${1}" = --development ]; then
DEVELOPMENT=true
shift
else
DEVELOPMENT=false
fi
if [ "${DEVELOPMENT}" = true ]; then
WORKING_DIRECTORY=$(pwd)
# shellcheck disable=SC2068
docker run --interactive --tty --rm --name "${PROJECT_NAME_DASH}" --volume "${WORKING_DIRECTORY}:/${PROJECT_NAME_DASH}" "${VENDOR_NAME_LOWER}/${PROJECT_NAME_DASH}" $@
else
# shellcheck disable=SC2068
docker run --interactive --tty --rm --name "${PROJECT_NAME_DASH}" "${VENDOR_NAME_LOWER}/${PROJECT_NAME_DASH}" $@
fi
| FunTimeCoding/cpp-skeleton | script/docker/run.sh | Shell | mit | 714 |
#!/bin/bash -euo
# Add workaround for SSH-based Git connections from Rust/cargo. See https://github.com/rust-lang/cargo/issues/2078 for details.
# We set CARGO_HOME because we don't pass on HOME to conda-build, thus rendering the default "${HOME}/.cargo" defunct.
export CARGO_NET_GIT_FETCH_WITH_CLI=true CARGO_HOME="$(pwd)/.cargo"
RUST_BACKTRACE=1 C_INCLUDE_PATH=$PREFIX/include LIBRARY_PATH=$PREFIX/lib cargo install --verbose --root $PREFIX --path .
| cokelaer/bioconda-recipes | recipes/fastq-count/build.sh | Shell | mit | 456 |
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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
AUTHORS OR COPYRIGHT HOLDERS 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 <math.h>
#include "editor-support/cocostudio/CCActionFrameEasing.h"
#include "editor-support/cocostudio/DictionaryHelper.h"
#include "platform/CCStdC.h"
namespace cocostudio {
#ifndef M_PI_X_2
#define M_PI_X_2 (float)M_PI * 2.0f
#endif
ActionFrameEasing::ActionFrameEasing()
{
}
ActionFrameEasing::~ActionFrameEasing()
{
}
float ActionFrameEasing::bounceTime(float t)
{
if (t < 1 / 2.75) {
return 7.5625f * t * t;
}
else if (t < 2 / 2.75) {
t -= 1.5f / 2.75f;
return 7.5625f * t * t + 0.75f;
}
else if (t < 2.5 / 2.75) {
t -= 2.25f / 2.75f;
return 7.5625f * t * t + 0.9375f;
}
t -= 2.625f / 2.75f;
return 7.5625f * t * t + 0.984375f;
}
float ActionFrameEasing::easeValue(float t)
{
if (_type == FrameEasingType::kframeEasingInstant)
{
if (t < 1) return 0;
else return 1;
}
else if (_type == FrameEasingType::kframeEasingLinear)
{
return t;
}
else if (_type == FrameEasingType::kframeEasingCubicIn)
{
float rate = _fValue;
return powf(t,rate);
}
else if (_type == FrameEasingType::kframeEasingCubicOut)
{
float rate = _fValue;
return powf(t,1/rate);
}
else if (_type == FrameEasingType::kframeEasingCubicInOut)
{
float rate = _fValue;
t *= 2;
if (t < 1)
{
return 0.5f * powf (t, rate);
}
else
{
return 1.0f - 0.5f * powf(2-t, rate);
}
}
else if (_type == FrameEasingType::kframeEasingElasticIn)
{
float period = _fValue;
float newT = 0;
if (t == 0 || t == 1)
newT = t;
else {
float s = period / 4;
t = t - 1;
newT = -powf(2, 10 * t) * sinf( (t-s) * M_PI_X_2 / period);
}
return newT;
}
else if (_type == FrameEasingType::kframeEasingElasticOut)
{
float period = _fValue;
float newT = 0;
if (t == 0 || t == 1) {
newT = t;
} else {
float s = period / 4;
newT = powf(2, -10 * t) * sinf( (t-s) *M_PI_X_2 / period) + 1;
}
return newT;
}
else if (_type == FrameEasingType::kframeEasingElasticInOut)
{
float period = _fValue;
float newT = 0;
if( t == 0 || t == 1 )
newT = t;
else {
t = t * 2;
if(! period )
period = 0.3f * 1.5f;
float s = period / 4;
t = t -1;
if( t < 0 )
newT = -0.5f * powf(2, 10 * t) * sinf((t - s) * M_PI_X_2 / period);
else
newT = powf(2, -10 * t) * sinf((t - s) * M_PI_X_2 / period) * 0.5f + 1;
}
return newT;
}
else if (_type == FrameEasingType::kframeEasingBounceIn)
{
float newT = 1 - bounceTime(1-t);
return newT;
}
else if (_type == FrameEasingType::kframeEasingBounceOut)
{
float newT = bounceTime(t);
return newT;
}
else if (_type == FrameEasingType::kframeEasingBounceInOut)
{
float newT = 0;
if (t < 0.5) {
t = t * 2;
newT = (1 - bounceTime(1-t) ) * 0.5f;
} else
newT = bounceTime(t * 2 - 1) * 0.5f + 0.5f;
return newT;
}
else if (_type == FrameEasingType::kframeEasingBackIn)
{
float overshoot = 1.70158f;
return t * t * ((overshoot + 1) * t - overshoot);
}
else if (_type == FrameEasingType::kframeEasingBackOut)
{
float overshoot = 1.70158f;
t = t - 1;
return t * t * ((overshoot + 1) * t + overshoot) + 1;
}
else if (_type == FrameEasingType::kframeEasingBackInOut)
{
float overshoot = 1.70158f * 1.525f;
t = t * 2;
if (t < 1)
return (t * t * ((overshoot + 1) * t - overshoot)) / 2;
else {
t = t - 2;
return (t * t * ((overshoot + 1) * t + overshoot)) / 2 + 1;
}
}
return 0;
}
}
| tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/editor-support/cocostudio/CCActionFrameEasing.cpp | C++ | mit | 4,628 |
using System;
/// <summary>
/// Int16.Parse(String)
/// </summary>
public class Int16Parse1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Normally test a random string of int16 ");
try
{
string str = TestLibrary.Generator.GetInt16(-55).ToString();
Int16 i1 = Int16.Parse(str);
Int16 i2 = Convert.ToInt16(str);
if (i1 != i2)
{
TestLibrary.TestFramework.LogError("001", "the result is not the value as expected, the string is " + str);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Test the int16.MaxValue");
try
{
string str = "32767";
Int16 i1 = Int16.Parse(str);
if (i1 != 32767)
{
TestLibrary.TestFramework.LogError("003", "the result is not the value as expected ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Test the int16.MinValue");
try
{
string str = "-32768";
Int16 i1 = Int16.Parse(str);
if (i1 != -32768)
{
TestLibrary.TestFramework.LogError("005", "the result is not the value as expected ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: The argument with white space in both beginning and the end");
try
{
string str2;
string str = str2 = TestLibrary.Generator.GetInt16(-55).ToString();
str = " " + str;
str = str + " ";
Int16 i1 = Int16.Parse(str);
Int16 i2 = Int16.Parse(str2);
if (i1 != i2)
{
TestLibrary.TestFramework.LogError("007", "the result is not the value as expected,the string is :" + str);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Test the parameter \"-0\"");
try
{
Int16 i1 = Int16.Parse("-0");
if (i1 != 0)
{
TestLibrary.TestFramework.LogError("009", "the result is not the value as expected ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The argument is null reference");
try
{
string str = null;
Int16 i1 = Int16.Parse(str);
TestLibrary.TestFramework.LogError("101", "the Method did not throw an ArgumentNullException");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: Test format exception 1");
try
{
string str = "-123-567";
Int16 i1 = Int16.Parse(str);
TestLibrary.TestFramework.LogError("103", "the Method did not throw a FormatException");
retVal = false;
}
catch (FormatException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: Test format exception 2");
try
{
string str = "98d5t6w7";
Int16 i1 = Int16.Parse(str);
TestLibrary.TestFramework.LogError("105", "the Method did not throw a FormatException");
retVal = false;
}
catch (FormatException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: Test format exception 3, the string is white space");
try
{
string str = " ";
Int16 i1 = Int16.Parse(str);
TestLibrary.TestFramework.LogError("107", "the Method did not throw a FormatException");
retVal = false;
}
catch (FormatException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: The string represents a number less than int16.minvalue");
try
{
string str = (Int16.MinValue - 1).ToString();
Int16 i1 = Int16.Parse(str);
TestLibrary.TestFramework.LogError("109", "the Method did not throw a OverflowException");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: The string represents a number greater than int16.maxvalue");
try
{
string str = (Int16.MaxValue + 1).ToString();
Int16 i1 = Int16.Parse(str);
TestLibrary.TestFramework.LogError("111", "the Method did not throw a OverflowException");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
Int16Parse1 test = new Int16Parse1();
TestLibrary.TestFramework.BeginTestCase("Int16Parse1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| ktos/coreclr | tests/src/CoreMangLib/cti/system/int16/int16parse1.cs | C# | mit | 8,851 |
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
if(Ext.app.ContactForm) {
Ext.apply(Ext.app.ContactForm.prototype, {
formTitle: 'Contact Informatie (Dutch)',
firstName: 'Voornaam',
lastName: 'Achternaam',
surnamePrefix: 'Tussenvoegsel',
company: 'Bedrijf',
state: 'Provincie',
stateEmptyText: 'Kies een provincie...',
email: 'E-mail',
birth: 'Geb. Datum',
save: 'Opslaan',
cancel: 'Annuleren'
});
} | dinubalti/FirstSymfony | web/public/js/lib/ext-3.4.1/examples/locale/ContactForm-nl.js | JavaScript | mit | 1,121 |
/*
* Copyright (c) 2010, Swedish Institute of Computer Science
* 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.
* 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*/
/**
* \file
* Lexical analyzer for AQL, the Antelope Query Language.
* \author
* Nicolas Tsiftes <[email protected]>
*/
#include "aql.h"
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct keyword {
char *string;
token_t token;
};
/* The keywords are arranged primarily by length and
secondarily by expected lookup frequency. */
static const struct keyword keywords[] = {
{";", END},
{"(", LEFT_PAREN},
{")", RIGHT_PAREN},
{",", COMMA},
{"=", EQUAL},
{">", GT},
{"<", LT},
{".", DOT},
{"+", ADD},
{"-", SUB},
{"*", MUL},
{"/", DIV},
{"#", COMMENT},
{">=", GEQ},
{"<=", LEQ},
{"<>", NOT_EQUAL},
{"<-", ASSIGN},
{"OR", OR},
{"IS", IS},
{"ON", ON},
{"IN", IN},
{"AND", AND},
{"NOT", NOT},
{"SUM", SUM},
{"MAX", MAX},
{"MIN", MIN},
{"INT", INT},
{"INTO", INTO},
{"FROM", FROM},
{"MEAN", MEAN},
{"JOIN", JOIN},
{"LONG", LONG},
{"TYPE", TYPE},
{"WHERE", WHERE},
{"COUNT", COUNT},
{"INDEX", INDEX},
{"INSERT", INSERT},
{"SELECT", SELECT},
{"REMOVE", REMOVE},
{"CREATE", CREATE},
{"MEDIAN", MEDIAN},
{"DOMAIN", DOMAIN},
{"STRING", STRING},
{"INLINE", INLINE},
{"PROJECT", PROJECT},
{"MAXHEAP", MAXHEAP},
{"MEMHASH", MEMHASH},
{"RELATION", RELATION},
{"ATTRIBUTE", ATTRIBUTE}
};
/* Provides a pointer to the first keyword of a specific length. */
static const int8_t skip_hint[] = {0, 13, 21, 27, 33, 36, 44, 47, 48};
static char separators[] = "#.;,() \t\n";
int
lexer_start(lexer_t *lexer, char *input, token_t *token, value_t *value)
{
lexer->input = input;
lexer->prev_pos = input;
lexer->token = token;
lexer->value = value;
return 0;
}
static token_t
get_token_id(const char *string, const size_t length)
{
int start, end;
int i;
if(sizeof(skip_hint) < length || length < 1) {
return NONE;
}
start = skip_hint[length - 1];
if(sizeof(skip_hint) == length) {
end = sizeof(keywords) / sizeof(keywords[0]);
} else {
end = skip_hint[length];
}
for(i = start; i < end; i++) {
if(strncasecmp(keywords[i].string, string, length) == 0) {
return keywords[i].token;
}
}
return NONE;
}
static int
next_real(lexer_t *lexer, const char *s)
{
char *end;
long long_value;
#if DB_FEATURE_FLOATS
float float_value;
#endif /* DB_FEATURE_FLOATS */
errno = 0;
long_value = strtol(s, &end, 10);
#if DB_FEATURE_FLOATS
if(*end == '.') {
/* Process a float value. */
float_value = strtof(s, &end);
if(float_value == 0 && s == end) {
return -1;
}
memcpy(lexer->value, &float_value, sizeof(float_value));
*lexer->token = FLOAT_VALUE;
lexer->input = end;
return 1;
}
#endif /* DB_FEATURE_FLOATS */
/* Process an integer value. */
if(long_value == 0 && errno != 0) {
return -1;
}
memcpy(lexer->value, &long_value, sizeof(long_value));
*lexer->token = INTEGER_VALUE;
lexer->input = end;
return 1;
}
static int
next_string(lexer_t *lexer, const char *s)
{
char *end;
size_t length;
end = strchr(s, '\'');
if(end == NULL) {
return -1;
}
length = end - s;
*lexer->token = STRING_VALUE;
lexer->input = end + 1; /* Skip the closing delimiter. */
memcpy(lexer->value, s, length);
(*lexer->value)[length] = '\0';
return 1;
}
static int
next_token(lexer_t *lexer, const char *s)
{
size_t length;
length = strcspn(s, separators);
if(length == 0) {
/* We encountered a separator, so we try to get a token of
precisely 1 byte. */
length = 1;
}
*lexer->token = get_token_id(s, length);
lexer->input = s + length;
if(*lexer->token != NONE) {
return 1;
}
/* The input did not constitute a valid token,
so we regard it as an identifier. */
*lexer->token = IDENTIFIER;
memcpy(lexer->value, s, length);
(*lexer->value)[length] = '\0';
return 1;
}
int
lexer_next(lexer_t *lexer)
{
const char *s;
*lexer->token = NONE;
s = lexer->input;
s += strspn(s, " \t\n");
lexer->prev_pos = s;
switch(*s) {
case '\'':
/* Process the string that follows the delimiter. */
return next_string(lexer, s + 1);
case '\0':
return 0;
default:
if(isdigit((int)*s) || (*s == '-' && isdigit((int)s[1]))) {
return next_real(lexer, s);
}
/* Process a token. */
return next_token(lexer, s);
}
}
void
lexer_rewind(lexer_t *lexer)
{
lexer->input = lexer->prev_pos;
}
| jcook/crazyIoT | src/contiki-sensinode-cc-ports/apps/antelope/aql-lexer.c | C | mit | 6,058 |
using System;
using System.Globalization;
namespace StringTest
{
public class StringEmpty
{
#region main method
public static int Main()
{
StringEmpty stringempty = new StringEmpty();
TestLibrary.TestFramework.BeginTestCase("StringEmpty");
if (stringempty.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#endregion
#region public method
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
#endregion
#region Positive Test Cases
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Compare a string with System.Empty");
try
{
string teststring = string.Empty;
string teststring1 = "";
if (!teststring.Equals(teststring1))
{
return false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
} | ktos/coreclr | tests/src/CoreMangLib/cti/system/string/stringempty.cs | C# | mit | 1,868 |
var swfobject=function(){function u(){if(!s){try{var a=d.getElementsByTagName("body")[0].appendChild(d.createElement("span"));a.parentNode.removeChild(a)}catch(b){return}s=!0;for(var a=x.length,c=0;c<a;c++)x[c]()}}function L(a){s?a():x[x.length]=a}function M(a){if(typeof m.addEventListener!=i)m.addEventListener("load",a,!1);else if(typeof d.addEventListener!=i)d.addEventListener("load",a,!1);else if(typeof m.attachEvent!=i)U(m,"onload",a);else if("function"==typeof m.onload){var b=m.onload;m.onload=
function(){b();a()}}else m.onload=a}function V(){var a=d.getElementsByTagName("body")[0],b=d.createElement(r);b.setAttribute("type",y);var c=a.appendChild(b);if(c){var f=0;(function(){if(typeof c.GetVariable!=i){var g=c.GetVariable("$version");g&&(g=g.split(" ")[1].split(","),e.pv=[parseInt(g[0],10),parseInt(g[1],10),parseInt(g[2],10)])}else if(10>f){f++;setTimeout(arguments.callee,10);return}a.removeChild(b);c=null;D()})()}else D()}function D(){var a=p.length;if(0<a)for(var b=0;b<a;b++){var c=p[b].id,
f=p[b].callbackFn,g={success:!1,id:c};if(0<e.pv[0]){var d=n(c);if(d)if(z(p[b].swfVersion)&&!(e.wk&&312>e.wk))t(c,!0),f&&(g.success=!0,g.ref=E(c),f(g));else if(p[b].expressInstall&&F()){g={};g.data=p[b].expressInstall;g.width=d.getAttribute("width")||"0";g.height=d.getAttribute("height")||"0";d.getAttribute("class")&&(g.styleclass=d.getAttribute("class"));d.getAttribute("align")&&(g.align=d.getAttribute("align"));for(var h={},d=d.getElementsByTagName("param"),j=d.length,k=0;k<j;k++)"movie"!=d[k].getAttribute("name").toLowerCase()&&
(h[d[k].getAttribute("name")]=d[k].getAttribute("value"));G(g,h,c,f)}else W(d),f&&f(g)}else if(t(c,!0),f){if((c=E(c))&&typeof c.SetVariable!=i)g.success=!0,g.ref=c;f(g)}}}function E(a){var b=null;if((a=n(a))&&"OBJECT"==a.nodeName)typeof a.SetVariable!=i?b=a:(a=a.getElementsByTagName(r)[0])&&(b=a);return b}function F(){return!A&&z("6.0.65")&&(e.win||e.mac)&&!(e.wk&&312>e.wk)}function G(a,b,c,f){A=!0;H=f||null;N={success:!1,id:c};var g=n(c);if(g){"OBJECT"==g.nodeName?(w=I(g),B=null):(w=g,B=c);a.id=
O;if(typeof a.width==i||!/%$/.test(a.width)&&310>parseInt(a.width,10))a.width="310";if(typeof a.height==i||!/%$/.test(a.height)&&137>parseInt(a.height,10))a.height="137";d.title=d.title.slice(0,47)+" - Flash Player Installation";f=e.ie&&e.win?"ActiveX":"PlugIn";f="MMredirectURL="+m.location.toString().replace(/&/g,"%26")+"&MMplayerType="+f+"&MMdoctitle="+d.title;b.flashvars=typeof b.flashvars!=i?b.flashvars+("&"+f):f;e.ie&&(e.win&&4!=g.readyState)&&(f=d.createElement("div"),c+="SWFObjectNew",f.setAttribute("id",
c),g.parentNode.insertBefore(f,g),g.style.display="none",function(){g.readyState==4?g.parentNode.removeChild(g):setTimeout(arguments.callee,10)}());J(a,b,c)}}function W(a){if(e.ie&&e.win&&4!=a.readyState){var b=d.createElement("div");a.parentNode.insertBefore(b,a);b.parentNode.replaceChild(I(a),b);a.style.display="none";(function(){4==a.readyState?a.parentNode.removeChild(a):setTimeout(arguments.callee,10)})()}else a.parentNode.replaceChild(I(a),a)}function I(a){var b=d.createElement("div");if(e.win&&
e.ie)b.innerHTML=a.innerHTML;else if(a=a.getElementsByTagName(r)[0])if(a=a.childNodes)for(var c=a.length,f=0;f<c;f++)!(1==a[f].nodeType&&"PARAM"==a[f].nodeName)&&8!=a[f].nodeType&&b.appendChild(a[f].cloneNode(!0));return b}function J(a,b,c){var f,g=n(c);if(e.wk&&312>e.wk)return f;if(g)if(typeof a.id==i&&(a.id=c),e.ie&&e.win){var o="",h;for(h in a)a[h]!=Object.prototype[h]&&("data"==h.toLowerCase()?b.movie=a[h]:"styleclass"==h.toLowerCase()?o+=' class="'+a[h]+'"':"classid"!=h.toLowerCase()&&(o+=" "+
h+'="'+a[h]+'"'));h="";for(var j in b)b[j]!=Object.prototype[j]&&(h+='<param name="'+j+'" value="'+b[j]+'" />');g.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+o+">"+h+"</object>";C[C.length]=a.id;f=n(a.id)}else{j=d.createElement(r);j.setAttribute("type",y);for(var k in a)a[k]!=Object.prototype[k]&&("styleclass"==k.toLowerCase()?j.setAttribute("class",a[k]):"classid"!=k.toLowerCase()&&j.setAttribute(k,a[k]));for(o in b)b[o]!=Object.prototype[o]&&"movie"!=o.toLowerCase()&&
(a=j,h=o,k=b[o],c=d.createElement("param"),c.setAttribute("name",h),c.setAttribute("value",k),a.appendChild(c));g.parentNode.replaceChild(j,g);f=j}return f}function P(a){var b=n(a);b&&"OBJECT"==b.nodeName&&(e.ie&&e.win?(b.style.display="none",function(){if(4==b.readyState){var c=n(a);if(c){for(var f in c)"function"==typeof c[f]&&(c[f]=null);c.parentNode.removeChild(c)}}else setTimeout(arguments.callee,10)}()):b.parentNode.removeChild(b))}function n(a){var b=null;try{b=d.getElementById(a)}catch(c){}return b}
function U(a,b,c){a.attachEvent(b,c);v[v.length]=[a,b,c]}function z(a){var b=e.pv,a=a.split(".");a[0]=parseInt(a[0],10);a[1]=parseInt(a[1],10)||0;a[2]=parseInt(a[2],10)||0;return b[0]>a[0]||b[0]==a[0]&&b[1]>a[1]||b[0]==a[0]&&b[1]==a[1]&&b[2]>=a[2]?!0:!1}function Q(a,b,c,f){if(!e.ie||!e.mac){var g=d.getElementsByTagName("head")[0];if(g){c=c&&"string"==typeof c?c:"screen";f&&(K=l=null);if(!l||K!=c)f=d.createElement("style"),f.setAttribute("type","text/css"),f.setAttribute("media",c),l=g.appendChild(f),
e.ie&&(e.win&&typeof d.styleSheets!=i&&0<d.styleSheets.length)&&(l=d.styleSheets[d.styleSheets.length-1]),K=c;e.ie&&e.win?l&&typeof l.addRule==r&&l.addRule(a,b):l&&typeof d.createTextNode!=i&&l.appendChild(d.createTextNode(a+" {"+b+"}"))}}}function t(a,b){if(R){var c=b?"visible":"hidden";s&&n(a)?n(a).style.visibility=c:Q("#"+a,"visibility:"+c)}}function S(a){return null!=/[\\\"<>\.;]/.exec(a)&&typeof encodeURIComponent!=i?encodeURIComponent(a):a}var i="undefined",r="object",y="application/x-shockwave-flash",
O="SWFObjectExprInst",m=window,d=document,q=navigator,T=!1,x=[function(){T?V():D()}],p=[],C=[],v=[],w,B,H,N,s=!1,A=!1,l,K,R=!0,e=function(){var a=typeof d.getElementById!=i&&typeof d.getElementsByTagName!=i&&typeof d.createElement!=i,b=q.userAgent.toLowerCase(),c=q.platform.toLowerCase(),f=c?/win/.test(c):/win/.test(b),c=c?/mac/.test(c):/mac/.test(b),b=/webkit/.test(b)?parseFloat(b.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,g=!+"\v1",e=[0,0,0],h=null;if(typeof q.plugins!=i&&typeof q.plugins["Shockwave Flash"]==
r){if((h=q.plugins["Shockwave Flash"].description)&&!(typeof q.mimeTypes!=i&&q.mimeTypes[y]&&!q.mimeTypes[y].enabledPlugin))T=!0,g=!1,h=h.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),e[0]=parseInt(h.replace(/^(.*)\..*$/,"$1"),10),e[1]=parseInt(h.replace(/^.*\.(.*)\s.*$/,"$1"),10),e[2]=/[a-zA-Z]/.test(h)?parseInt(h.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}else if(typeof m.ActiveXObject!=i)try{var j=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");if(j&&(h=j.GetVariable("$version")))g=!0,h=h.split(" ")[1].split(","),
e=[parseInt(h[0],10),parseInt(h[1],10),parseInt(h[2],10)]}catch(k){}return{w3:a,pv:e,wk:b,ie:g,win:f,mac:c}}();(function(){e.w3&&((typeof d.readyState!=i&&"complete"==d.readyState||typeof d.readyState==i&&(d.getElementsByTagName("body")[0]||d.body))&&u(),s||(typeof d.addEventListener!=i&&d.addEventListener("DOMContentLoaded",u,!1),e.ie&&e.win&&(d.attachEvent("onreadystatechange",function(){"complete"==d.readyState&&(d.detachEvent("onreadystatechange",arguments.callee),u())}),m==top&&function(){if(!s){try{d.documentElement.doScroll("left")}catch(a){setTimeout(arguments.callee,
0);return}u()}}()),e.wk&&function(){s||(/loaded|complete/.test(d.readyState)?u():setTimeout(arguments.callee,0))}(),M(u)))})();(function(){e.ie&&e.win&&window.attachEvent("onunload",function(){for(var a=v.length,b=0;b<a;b++)v[b][0].detachEvent(v[b][1],v[b][2]);a=C.length;for(b=0;b<a;b++)P(C[b]);for(var c in e)e[c]=null;e=null;for(var f in swfobject)swfobject[f]=null;swfobject=null})})();return{registerObject:function(a,b,c,f){if(e.w3&&a&&b){var d={};d.id=a;d.swfVersion=b;d.expressInstall=c;d.callbackFn=
f;p[p.length]=d;t(a,!1)}else f&&f({success:!1,id:a})},getObjectById:function(a){if(e.w3)return E(a)},embedSWF:function(a,b,c,d,g,o,h,j,k,m){var n={success:!1,id:b};e.w3&&!(e.wk&&312>e.wk)&&a&&b&&c&&d&&g?(t(b,!1),L(function(){c+="";d+="";var e={};if(k&&typeof k===r)for(var l in k)e[l]=k[l];e.data=a;e.width=c;e.height=d;l={};if(j&&typeof j===r)for(var p in j)l[p]=j[p];if(h&&typeof h===r)for(var q in h)l.flashvars=typeof l.flashvars!=i?l.flashvars+("&"+q+"="+h[q]):q+"="+h[q];if(z(g))p=J(e,l,b),e.id==
b&&t(b,!0),n.success=!0,n.ref=p;else{if(o&&F()){e.data=o;G(e,l,b,m);return}t(b,!0)}m&&m(n)})):m&&m(n)},switchOffAutoHideShow:function(){R=!1},ua:e,getFlashPlayerVersion:function(){return{major:e.pv[0],minor:e.pv[1],release:e.pv[2]}},hasFlashPlayerVersion:z,createSWF:function(a,b,c){if(e.w3)return J(a,b,c)},showExpressInstall:function(a,b,c,d){e.w3&&F()&&G(a,b,c,d)},removeSWF:function(a){e.w3&&P(a)},createCSS:function(a,b,c,d){e.w3&&Q(a,b,c,d)},addDomLoadEvent:L,addLoadEvent:M,getQueryParamValue:function(a){var b=
d.location.search||d.location.hash;if(b){/\?/.test(b)&&(b=b.split("?")[1]);if(null==a)return S(b);for(var b=b.split("&"),c=0;c<b.length;c++)if(b[c].substring(0,b[c].indexOf("="))==a)return S(b[c].substring(b[c].indexOf("=")+1))}return""},expressInstallCallback:function(){if(A){var a=n(O);a&&w&&(a.parentNode.replaceChild(w,a),B&&(t(B,!0),e.ie&&e.win&&(w.style.display="block")),H&&H(N));A=!1}}}}();
| easytoolsoft/springboot-project-template | web/web-springmvc2/src/main/resources/static/javascripts/plugins/ckeditor/samples/plugins/htmlwriter/assets/outputforflash/swfobject.js | JavaScript | mit | 9,166 |
#ifndef HALIDE_TUPLE_H
#define HALIDE_TUPLE_H
/** \file
*
* Defines Tuple - the front-end handle on small arrays of expressions.
*/
#include "IR.h"
#include "IROperator.h"
#include "Util.h"
namespace Halide {
class FuncRefVar;
class FuncRefExpr;
/** Create a small array of Exprs for defining and calling functions
* with multiple outputs. */
class Tuple {
private:
std::vector<Expr> exprs;
public:
/** The number of elements in the tuple. */
size_t size() const { return exprs.size(); }
/** Get a reference to an element. */
Expr &operator[](size_t x) {
user_assert(x < exprs.size()) << "Tuple access out of bounds\n";
return exprs[x];
}
/** Get a copy of an element. */
Expr operator[](size_t x) const {
user_assert(x < exprs.size()) << "Tuple access out of bounds\n";
return exprs[x];
}
/** Construct a Tuple from some Exprs. */
//@{
template<typename ...Args>
Tuple(Expr a, Expr b, Args... args) {
exprs.push_back(a);
exprs.push_back(b);
Internal::collect_args(exprs, args...);
}
//@}
/** Construct a Tuple from a vector of Exprs */
explicit NO_INLINE Tuple(const std::vector<Expr> &e) : exprs(e) {
user_assert(e.size() > 0) << "Tuples must have at least one element\n";
}
/** Construct a Tuple from a function reference. */
// @{
EXPORT Tuple(const FuncRefVar &);
EXPORT Tuple(const FuncRefExpr &);
// @}
/** Treat the tuple as a vector of Exprs */
const std::vector<Expr> &as_vector() const {
return exprs;
}
};
/** Funcs with Tuple values return multiple buffers when you realize
* them. Tuples are to Exprs as Realizations are to Buffers. */
class Realization {
private:
std::vector<Buffer> buffers;
public:
/** The number of buffers in the Realization. */
size_t size() const { return buffers.size(); }
/** Get a reference to one of the buffers. */
Buffer &operator[](size_t x) {
user_assert(x < buffers.size()) << "Realization access out of bounds\n";
return buffers[x];
}
/** Get one of the buffers. */
Buffer operator[](size_t x) const {
user_assert(x < buffers.size()) << "Realization access out of bounds\n";
return buffers[x];
}
/** Single-element realizations are implicitly castable to Buffers. */
operator Buffer() const {
user_assert(buffers.size() == 1) << "Can only cast single-element realizations to buffers or images\n";
return buffers[0];
}
/** Construct a Realization from some Buffers. */
//@{
template<typename ...Args>
Realization(Buffer a, Buffer b, Args... args) : buffers({a, b}) {
Internal::collect_args(buffers, args...);
}
//@}
/** Construct a Realization from a vector of Buffers */
explicit Realization(const std::vector<Buffer> &e) : buffers(e) {
user_assert(e.size() > 0) << "Realizations must have at least one element\n";
}
/** Treat the Realization as a vector of Buffers */
const std::vector<Buffer> &as_vector() const {
return buffers;
}
};
/** Equivalents of some standard operators for tuples. */
// @{
inline Tuple tuple_select(Tuple condition, const Tuple &true_value, const Tuple &false_value) {
Tuple result(std::vector<Expr>(condition.size()));
for (size_t i = 0; i < result.size(); i++) {
result[i] = select(condition[i], true_value[i], false_value[i]);
}
return result;
}
inline Tuple tuple_select(Expr condition, const Tuple &true_value, const Tuple &false_value) {
Tuple result(std::vector<Expr>(true_value.size()));
for (size_t i = 0; i < result.size(); i++) {
result[i] = select(condition, true_value[i], false_value[i]);
}
return result;
}
// @}
}
#endif
| fengzhyuan/Halide | src/Tuple.h | C | mit | 3,856 |
Clazz.declarePackage ("javajs.api");
Clazz.declareInterface (javajs.api, "GenericMouseInterface");
| khaliiid/visualizer | src/lib/jsmol/j2s/javajs/api/GenericMouseInterface.js | JavaScript | mit | 99 |
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class Mijireh_RestJSON extends Mijireh_Rest {
/**
* @param string $url
*/
public function post($url, $data, $headers=array()) {
return parent::post($url, json_encode($data), $headers);
}
public function put($url, $data, $headers=array()) {
return parent::put($url, json_encode($data), $headers);
}
protected function prepRequest($opts, $url) {
$opts[CURLOPT_HTTPHEADER][] = 'Accept: application/json';
$opts[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
return parent::prepRequest($opts, $url);
}
public function processBody($body) {
return json_decode($body, true);
}
} | joshquila/demo2-youse | wp-content/plugins/woocommerce/includes/gateways/mijireh/includes/RestJSON.php | PHP | gpl-2.0 | 708 |
<?php
/**
* This file is automatically @generated by {@link BuildMetadataPHPFromXml}.
* Please don't modify it directly.
*/
return array (
'generalDesc' =>
array (
'NationalNumberPattern' => '
0\\d|
1\\d{2,6}|
8\\d{3,4}
',
'PossibleNumberPattern' => '\\d{2,6}',
),
'fixedLine' =>
array (
'NationalNumberPattern' => '
0\\d|
1\\d{2,6}|
8\\d{3,4}
',
'PossibleNumberPattern' => '\\d{2,6}',
),
'mobile' =>
array (
'NationalNumberPattern' => '
0\\d|
1\\d{2,6}|
8\\d{3,4}
',
'PossibleNumberPattern' => '\\d{2,6}',
),
'tollFree' =>
array (
'NationalNumberPattern' => '116000',
'PossibleNumberPattern' => '\\d{6}',
'ExampleNumber' => '116000',
),
'premiumRate' =>
array (
'NationalNumberPattern' => '
1180|
8(?:
2\\d{3}|
[89]\\d{2}
)
',
'PossibleNumberPattern' => '\\d{4,5}',
),
'sharedCost' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'personalNumber' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'voip' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'pager' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'uan' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'emergency' =>
array (
'NationalNumberPattern' => '
0[123]|
11[023]
',
'PossibleNumberPattern' => '\\d{2,3}',
'ExampleNumber' => '112',
),
'voicemail' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'shortCode' =>
array (
'NationalNumberPattern' => '
0[1-4]|
1(?:
1(?:
[02-4]|
6(?:
000|
111
)|
8[0189]
)|
55|
655|
77
)|
821[57]4
',
'PossibleNumberPattern' => '\\d{2,6}',
'ExampleNumber' => '112',
),
'standardRate' =>
array (
'NationalNumberPattern' => '1181',
'PossibleNumberPattern' => '\\d{4}',
'ExampleNumber' => '1181',
),
'carrierSpecific' =>
array (
'NationalNumberPattern' => '16\\d{2}',
'PossibleNumberPattern' => '\\d{4}',
'ExampleNumber' => '1655',
),
'noInternationalDialling' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
),
'id' => 'LV',
'countryCode' => 0,
'internationalPrefix' => '',
'sameMobileAndFixedLinePattern' => true,
'numberFormat' =>
array (
),
'intlNumberFormat' =>
array (
),
'mainCountryForCode' => false,
'leadingZeroPossible' => false,
'mobileNumberPortableRegion' => false,
);
| CTSATLAS/wordpress | wp-content/plugins/constant-contact-api/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/data/ShortNumberMetadata_LV.php | PHP | gpl-2.0 | 2,986 |
/* Copyright (C) 2015-2016 Andrew J. Kroll
and
Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
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
Contact information
-------------------
Circuits At Home, LTD
Web : https://www.circuitsathome.com
e-mail : [email protected]
*/
#if !defined(_UHS_host_h_) || defined(__ADDRESS_H__)
#error "Never include UHS_address.h directly; include UHS_Usb.h instead"
#else
#define __ADDRESS_H__
/* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */
/* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */
#define UHS_USB_NAK_MAX_POWER 14 // NAK binary order maximum value
#define UHS_USB_NAK_DEFAULT 13 // default 16K-1 NAKs before giving up
#define UHS_USB_NAK_NOWAIT 1 // Single NAK stops transfer
#define UHS_USB_NAK_NONAK 0 // Do not count NAKs, stop retrying after USB Timeout. Try not to use this.
#define bmUSB_DEV_ADDR_PORT 0x07
#define bmUSB_DEV_ADDR_PARENT 0x78
#define bmUSB_DEV_ADDR_HUB 0x40
// TODO: embed parent?
struct UHS_EpInfo {
uint8_t epAddr; // Endpoint address
uint8_t bIface;
uint16_t maxPktSize; // Maximum packet size
union {
uint8_t epAttribs;
struct {
uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise
uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise
uint8_t bmNeedPing : 1; // 1 == ping protocol needed for next out packet
uint8_t bmNakPower : 5; // Binary order for NAK_LIMIT value
} __attribute__((packed));
};
} __attribute__((packed));
// TODO: embed parent address and port into epinfo struct,
// and nuke this address stupidity.
// This is a compact scheme. Should also support full spec.
// This produces a 7 hub limit, 49 devices + 7 hubs, 56 total.
//
// 7 6 5 4 3 2 1 0
// ---------------------------------
// | | H | P | P | P | A | A | A |
// ---------------------------------
//
// H - if 1 the address is a hub address
// P - parent hub number
// A - port number of parent
//
struct UHS_DeviceAddress {
union {
struct {
uint8_t bmAddress : 3; // port number
uint8_t bmParent : 3; // parent hub address
uint8_t bmHub : 1; // hub flag
uint8_t bmReserved : 1; // reserved, must be zero
} __attribute__((packed));
uint8_t devAddress;
};
} __attribute__((packed));
struct UHS_Device {
volatile UHS_EpInfo *epinfo[UHS_HOST_MAX_INTERFACE_DRIVERS]; // endpoint info pointer
UHS_DeviceAddress address;
uint8_t epcount; // number of endpoints
uint8_t speed; // indicates device speed
} __attribute__((packed));
typedef void (*UsbDeviceHandleFunc)(UHS_Device *pdev);
class AddressPool {
UHS_EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device
// In order to avoid hub address duplication, this should use bits
uint8_t hubCounter; // hub counter
UHS_Device thePool[UHS_HOST_MAX_INTERFACE_DRIVERS];
// Initializes address pool entry
void UHS_NI InitEntry(uint8_t index) {
thePool[index].address.devAddress = 0;
thePool[index].epcount = 1;
thePool[index].speed = 0;
for(uint8_t i = 0; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) {
thePool[index].epinfo[i] = &dev0ep;
}
};
// Returns thePool index for a given address
uint8_t UHS_NI FindAddressIndex(uint8_t address = 0) {
for(uint8_t i = 1; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) {
if(thePool[i].address.devAddress == address)
return i;
}
return 0;
};
// Returns thePool child index for a given parent
uint8_t UHS_NI FindChildIndex(UHS_DeviceAddress addr, uint8_t start = 1) {
for(uint8_t i = (start < 1 || start >= UHS_HOST_MAX_INTERFACE_DRIVERS) ? 1 : start; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) {
if(thePool[i].address.bmParent == addr.bmAddress)
return i;
}
return 0;
};
// Frees address entry specified by index parameter
void UHS_NI FreeAddressByIndex(uint8_t index) {
// Zero field is reserved and should not be affected
if(index == 0)
return;
UHS_DeviceAddress uda = thePool[index].address;
// If a hub was switched off all port addresses should be freed
if(uda.bmHub == 1) {
for(uint8_t i = 1; (i = FindChildIndex(uda, i));)
FreeAddressByIndex(i);
// FIXME: use BIT MASKS
// If the hub had the last allocated address, hubCounter should be decremented
if(hubCounter == uda.bmAddress)
hubCounter--;
}
InitEntry(index);
}
void InitAllAddresses() {
for(uint8_t i = 1; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) InitEntry(i);
hubCounter = 0;
};
public:
AddressPool() {
hubCounter = 0;
// Zero address is reserved
InitEntry(0);
thePool[0].epinfo[0] = &dev0ep;
dev0ep.epAddr = 0;
#if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE
dev0ep.maxPktSize = 0x40; //starting at 0x40 and work down
#else
dev0ep.maxPktSize = 0x08;
#endif
dev0ep.epAttribs = 0; //set DATA0/1 toggles to 0
dev0ep.bmNakPower = UHS_USB_NAK_MAX_POWER;
InitAllAddresses();
};
// Returns a pointer to a specified address entry
UHS_Device* UHS_NI GetUsbDevicePtr(uint8_t addr) {
if(!addr)
return thePool;
uint8_t index = FindAddressIndex(addr);
return (!index) ? NULL : &thePool[index];
};
// Allocates new address
uint8_t UHS_NI AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 1) {
/* if (parent != 0 && port == 0)
USB_HOST_SERIAL.println("PRT:0"); */
UHS_DeviceAddress _parent;
_parent.devAddress = parent;
if(_parent.bmReserved || port > 7)
//if(parent > 127 || port > 7)
return 0;
// FIXME: use BIT MASKS
if(is_hub && hubCounter == 7)
return 0;
// finds first empty address entry starting from one
uint8_t index = FindAddressIndex(0);
if(!index) // if empty entry is not found
return 0;
UHS_DeviceAddress addr;
addr.devAddress = port;
addr.bmParent = _parent.bmAddress;
// FIXME: use BIT MASKS
if(is_hub) {
hubCounter++;
addr.bmHub = 1;
addr.bmAddress = hubCounter;
}
thePool[index].address = addr;
#if DEBUG_PRINTF_EXTRA_HUGE
#ifdef UHS_DEBUG_USB_ADDRESS
printf("Address: %x (%x.%x.%x)\r\n", addr.devAddress, addr.bmHub, addr.bmParent, addr.bmAddress);
#endif
#endif
return thePool[index].address.devAddress;
};
void UHS_NI FreeAddress(uint8_t addr) {
// if the root hub is disconnected all the addresses should be initialized
if(addr == 0x41) {
InitAllAddresses();
return;
}
uint8_t index = FindAddressIndex(addr);
FreeAddressByIndex(index);
};
};
#endif // __ADDRESS_H__
| aetel/3D-printer | prusa_i3/Firmware/Marlin-2.0.x/Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_address.h | C | gpl-2.0 | 9,147 |
/* Copyright (C) 1998-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Mark Kettenis <[email protected]>, 1998.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <utmp.h>
#include <utmpx.h>
void
endutxent (void)
{
__endutent ();
}
| vvavrychuk/glibc | login/endutxent.c | C | gpl-2.0 | 932 |
#ifndef _SLHC_H
#define _SLHC_H
/*
* Definitions for tcp compression routines.
*
* $Header: slcompress.h,v 1.10 89/12/31 08:53:02 van Exp $
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson ([email protected]), Dec 31, 1989:
* - Initial distribution.
*
*
* modified for KA9Q Internet Software Package by
* Katie Stevens ([email protected])
* University of California, Davis
* Computing Services
* - 01-31-90 initial adaptation
*
* - Feb 1991 [email protected]
* variable number of conversation slots
* allow zero or one slots
* separate routines
* status display
*/
/*
* Compressed packet format:
*
* The first octet contains the packet type (top 3 bits), TCP
* 'push' bit, and flags that indicate which of the 4 TCP sequence
* numbers have changed (bottom 5 bits). The next octet is a
* conversation number that associates a saved IP/TCP header with
* the compressed packet. The next two octets are the TCP checksum
* from the original datagram. The next 0 to 15 octets are
* sequence number changes, one change per bit set in the header
* (there may be no changes and there are two special cases where
* the receiver implicitly knows what changed -- see below).
*
* There are 5 numbers which can change (they are always inserted
* in the following order): TCP urgent pointer, window,
* acknowledgment, sequence number and IP ID. (The urgent pointer
* is different from the others in that its value is sent, not the
* change in value.) Since typical use of SLIP links is biased
* toward small packets (see comments on MTU/MSS below), changes
* use a variable length coding with one octet for numbers in the
* range 1 - 255 and 3 octets (0, MSB, LSB) for numbers in the
* range 256 - 65535 or 0. (If the change in sequence number or
* ack is more than 65535, an uncompressed packet is sent.)
*/
/*
* Packet types (must not conflict with IP protocol version)
*
* The top nibble of the first octet is the packet type. There are
* three possible types: IP (not proto TCP or tcp with one of the
* control flags set); uncompressed TCP (a normal IP/TCP packet but
* with the 8-bit protocol field replaced by an 8-bit connection id --
* this type of packet syncs the sender & receiver); and compressed
* TCP (described above).
*
* LSB of 4-bit field is TCP "PUSH" bit (a worthless anachronism) and
* is logically part of the 4-bit "changes" field that follows. Top
* three bits are actual packet type. For backward compatibility
* and in the interest of conserving bits, numbers are chosen so the
* IP protocol version number (4) which normally appears in this nibble
* means "IP packet".
*/
#include <linux/ip.h>
#include <linux/tcp.h>
/* SLIP compression masks for len/vers byte */
#define SL_TYPE_IP 0x40
#define SL_TYPE_UNCOMPRESSED_TCP 0x70
#define SL_TYPE_COMPRESSED_TCP 0x80
#define SL_TYPE_ERROR 0x00
/* Bits in first octet of compressed packet */
#define NEW_C 0x40 /* flag bits for what changed in a packet */
#define NEW_I 0x20
#define NEW_S 0x08
#define NEW_A 0x04
#define NEW_W 0x02
#define NEW_U 0x01
/* reserved, special-case values of above */
#define SPECIAL_I (NEW_S|NEW_W|NEW_U) /* echoed interactive traffic */
#define SPECIAL_D (NEW_S|NEW_A|NEW_W|NEW_U) /* unidirectional data */
#define SPECIALS_MASK (NEW_S|NEW_A|NEW_W|NEW_U)
#define TCP_PUSH_BIT 0x10
/*
* data type and sizes conversion assumptions:
*
* VJ code KA9Q style generic
* u_char byte_t unsigned char 8 bits
* u_short int16 unsigned short 16 bits
* u_int int16 unsigned short 16 bits
* u_long unsigned long unsigned long 32 bits
* int int32 long 32 bits
*/
typedef __u8 byte_t;
typedef __u32 int32;
/*
* "state" data for each active tcp conversation on the wire. This is
* basically a copy of the entire IP/TCP header from the last packet
* we saw from the conversation together with a small identifier
* the transmit & receive ends of the line use to locate saved header.
*/
struct cstate {
byte_t cs_this; /* connection id number (xmit) */
struct cstate *next; /* next in ring (xmit) */
struct iphdr cs_ip; /* ip/tcp hdr from most recent packet */
struct tcphdr cs_tcp;
unsigned char cs_ipopt[64];
unsigned char cs_tcpopt[64];
int cs_hsize;
};
#define NULLSLSTATE (struct cstate *)0
/*
* all the state data for one serial line (we need one of these per line).
*/
struct slcompress {
struct cstate *tstate; /* transmit connection states (array)*/
struct cstate *rstate; /* receive connection states (array)*/
byte_t tslot_limit; /* highest transmit slot id (0-l)*/
byte_t rslot_limit; /* highest receive slot id (0-l)*/
byte_t xmit_oldest; /* oldest xmit in ring */
byte_t xmit_current; /* most recent xmit id */
byte_t recv_current; /* most recent rcvd id */
byte_t flags;
#define SLF_TOSS 0x01 /* tossing rcvd frames until id received */
int32 sls_o_nontcp; /* outbound non-TCP packets */
int32 sls_o_tcp; /* outbound TCP packets */
int32 sls_o_uncompressed; /* outbound uncompressed packets */
int32 sls_o_compressed; /* outbound compressed packets */
int32 sls_o_searches; /* searches for connection state */
int32 sls_o_misses; /* times couldn't find conn. state */
int32 sls_i_uncompressed; /* inbound uncompressed packets */
int32 sls_i_compressed; /* inbound compressed packets */
int32 sls_i_error; /* inbound error packets */
int32 sls_i_tossed; /* inbound packets tossed because of error */
int32 sls_i_runt;
int32 sls_i_badcheck;
};
#define NULLSLCOMPR (struct slcompress *)0
#define __ARGS(x) x
/* In slhc.c: */
struct slcompress *slhc_init __ARGS((int rslots, int tslots));
void slhc_free __ARGS((struct slcompress *comp));
int slhc_compress __ARGS((struct slcompress *comp, unsigned char *icp,
int isize, unsigned char *ocp, unsigned char **cpp,
int compress_cid));
int slhc_uncompress __ARGS((struct slcompress *comp, unsigned char *icp,
int isize));
int slhc_remember __ARGS((struct slcompress *comp, unsigned char *icp,
int isize));
int slhc_toss __ARGS((struct slcompress *comp));
#endif /* _SLHC_H */
| proto3/linux-3.10 | include/net/slhc_vj.h | C | gpl-2.0 | 6,879 |
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Simplify Commerce Gateway for subscriptions
*
* @class WC_Addons_Gateway_Simplify_Commerce
* @extends WC_Gateway_Simplify_Commerce
* @since 2.2.0
* @version 1.0.0
* @package WooCommerce/Classes/Payment
* @author WooThemes
*/
class WC_Addons_Gateway_Simplify_Commerce extends WC_Gateway_Simplify_Commerce {
/**
* Constructor
*/
public function __construct() {
parent::__construct();
if ( class_exists( 'WC_Subscriptions_Order' ) ) {
add_action( 'scheduled_subscription_payment_' . $this->id, array( $this, 'scheduled_subscription_payment' ), 10, 3 );
add_filter( 'woocommerce_subscriptions_renewal_order_meta_query', array( $this, 'remove_renewal_order_meta' ), 10, 4 );
add_action( 'woocommerce_subscriptions_changed_failing_payment_method_' . $this->id, array( $this, 'update_failing_payment_method' ), 10, 3 );
}
if ( class_exists( 'WC_Pre_Orders_Order' ) ) {
add_action( 'wc_pre_orders_process_pre_order_completion_payment_' . $this->id, array( $this, 'process_pre_order_release_payment' ) );
}
}
/**
* Process the subscription
*
* @param int $order_id
* @return array
*/
public function process_subscription( $order_id ) {
$order = new WC_Order( $order_id );
$token = isset( $_POST['simplify_token'] ) ? wc_clean( $_POST['simplify_token'] ) : '';
try {
if ( empty( $token ) ) {
$error_msg = __( 'Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'woocommerce' );
if ( 'yes' == $this->sandbox ) {
$error_msg .= ' ' . __( 'Developers: Please make sure that you\'re including jQuery and there are no JavaScript errors on the page.', 'woocommerce' );
}
throw new Simplify_ApiException( $error_msg );
}
// Create customer
$customer = Simplify_Customer::createCustomer( array(
'token' => $token,
'email' => $order->billing_email,
'name' => trim( $order->billing_first_name . ' ' . $order->billing_last_name ),
'reference' => $order->id
) );
if ( is_object( $customer ) && '' != $customer->id ) {
$customer_id = wc_clean( $customer->id );
// Store the customer ID in the order
update_post_meta( $order_id, '_simplify_customer_id', $customer_id );
} else {
$error_msg = __( 'Error creating user in Simplify Commerce.', 'woocommerce' );
throw new Simplify_ApiException( $error_msg );
}
$initial_payment = WC_Subscriptions_Order::get_total_initial_payment( $order );
if ( $initial_payment > 0 ) {
$payment_response = $this->process_subscription_payment( $order, $initial_payment );
}
if ( isset( $payment_response ) && is_wp_error( $payment_response ) ) {
throw new Exception( $payment_response->get_error_message() );
} else {
// Remove cart
WC()->cart->empty_cart();
// Return thank you page redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
} catch ( Simplify_ApiException $e ) {
if ( $e instanceof Simplify_BadRequestException && $e->hasFieldErrors() && $e->getFieldErrors() ) {
foreach ( $e->getFieldErrors() as $error ) {
wc_add_notice( $error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')', 'error' );
}
} else {
wc_add_notice( $e->getMessage(), 'error' );
}
return array(
'result' => 'fail',
'redirect' => ''
);
}
}
/**
* Process the pre-order
*
* @param int $order_id
* @return array
*/
public function process_pre_order( $order_id ) {
if ( WC_Pre_Orders_Order::order_requires_payment_tokenization( $order_id ) ) {
$order = new WC_Order( $order_id );
$token = isset( $_POST['simplify_token'] ) ? wc_clean( $_POST['simplify_token'] ) : '';
try {
if ( $order->order_total * 100 < 50 ) {
$error_msg = __( 'Sorry, the minimum allowed order total is 0.50 to use this payment method.', 'woocommerce' );
throw new Simplify_ApiException( $error_msg );
}
if ( empty( $token ) ) {
$error_msg = __( 'Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'woocommerce' );
if ( 'yes' == $this->sandbox ) {
$error_msg .= ' ' . __( 'Developers: Please make sure that you\'re including jQuery and there are no JavaScript errors on the page.', 'woocommerce' );
}
throw new Simplify_ApiException( $error_msg );
}
// Create customer
$customer = Simplify_Customer::createCustomer( array(
'token' => $token,
'email' => $order->billing_email,
'name' => trim( $order->billing_first_name . ' ' . $order->billing_last_name ),
'reference' => $order->id
) );
if ( is_object( $customer ) && '' != $customer->id ) {
$customer_id = wc_clean( $customer->id );
// Store the customer ID in the order
update_post_meta( $order_id, '_simplify_customer_id', $customer_id );
} else {
$error_msg = __( 'Error creating user in Simplify Commerce.', 'woocommerce' );
throw new Simplify_ApiException( $error_msg );
}
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
WC()->cart->empty_cart();
// Is pre ordered!
WC_Pre_Orders_Order::mark_order_as_pre_ordered( $order );
// Return thank you page redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} catch ( Simplify_ApiException $e ) {
if ( $e instanceof Simplify_BadRequestException && $e->hasFieldErrors() && $e->getFieldErrors() ) {
foreach ( $e->getFieldErrors() as $error ) {
wc_add_notice( $error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')', 'error' );
}
} else {
wc_add_notice( $e->getMessage(), 'error' );
}
return array(
'result' => 'fail',
'redirect' => ''
);
}
} else {
return parent::process_payment( $order_id );
}
}
/**
* Process the payment
*
* @param int $order_id
* @return array
*/
public function process_payment( $order_id ) {
// Processing subscription
if ( class_exists( 'WC_Subscriptions_Order' ) && WC_Subscriptions_Order::order_contains_subscription( $order_id ) ) {
return $this->process_subscription( $order_id );
// Processing pre-order
} elseif ( class_exists( 'WC_Pre_Orders_Order' ) && WC_Pre_Orders_Order::order_contains_pre_order( $order_id ) ) {
return $this->process_pre_order( $order_id );
// Processing regular product
} else {
return parent::process_payment( $order_id );
}
}
/**
* process_subscription_payment function.
*
* @param WC_order $order
* @param integer $amount (default: 0)
* @return bool|WP_Error
*/
public function process_subscription_payment( $order = '', $amount = 0 ) {
$order_items = $order->get_items();
$order_item = array_shift( $order_items );
$subscription_name = sprintf( __( '%s - Subscription for "%s"', 'woocommerce' ), esc_html( get_bloginfo( 'name' ) ), $order_item['name'] ) . ' ' . sprintf( __( '(Order %s)', 'woocommerce' ), $order->get_order_number() );
if ( $amount * 100 < 50 ) {
return new WP_Error( 'simplify_error', __( 'Sorry, the minimum allowed order total is 0.50 to use this payment method.', 'woocommerce' ) );
}
$customer_id = get_post_meta( $order->id, '_simplify_customer_id', true );
if ( ! $customer_id ) {
return new WP_Error( 'simplify_error', __( 'Customer not found', 'woocommerce' ) );
}
// Charge the customer
$payment = Simplify_Payment::createPayment( array(
'amount' => $amount * 100, // In cents
'customer' => $customer_id,
'description' => trim( substr( $subscription_name, 0, 1024 ) ),
'currency' => strtoupper( get_woocommerce_currency() ),
'reference' => $order->id,
'card.addressCity' => $order->billing_city,
'card.addressCountry' => $order->billing_country,
'card.addressLine1' => $order->billing_address_1,
'card.addressLine2' => $order->billing_address_2,
'card.addressState' => $order->billing_state,
'card.addressZip' => $order->billing_postcode
) );
if ( 'APPROVED' == $payment->paymentStatus ) {
// Payment complete
$order->payment_complete( $payment->id );
// Add order note
$order->add_order_note( sprintf( __( 'Simplify payment approved (ID: %s, Auth Code: %s)', 'woocommerce' ), $payment->id, $payment->authCode ) );
return true;
} else {
$order->add_order_note( __( 'Simplify payment declined', 'woocommerce' ) );
return new WP_Error( 'simplify_payment_declined', __( 'Payment was declined - please try another card.', 'woocommerce' ) );
}
}
/**
* scheduled_subscription_payment function.
*
* @param float $amount_to_charge The amount to charge.
* @param WC_Order $order The WC_Order object of the order which the subscription was purchased in.
* @param int $product_id The ID of the subscription product for which this payment relates.
* @return void
*/
public function scheduled_subscription_payment( $amount_to_charge, $order, $product_id ) {
$result = $this->process_subscription_payment( $order, $amount_to_charge );
if ( is_wp_error( $result ) ) {
WC_Subscriptions_Manager::process_subscription_payment_failure_on_order( $order, $product_id );
} else {
WC_Subscriptions_Manager::process_subscription_payments_on_order( $order );
}
}
/**
* Don't transfer customer meta when creating a parent renewal order.
*
* @param string $order_meta_query MySQL query for pulling the metadata
* @param int $original_order_id Post ID of the order being used to purchased the subscription being renewed
* @param int $renewal_order_id Post ID of the order created for renewing the subscription
* @param string $new_order_role The role the renewal order is taking, one of 'parent' or 'child'
* @return string
*/
public function remove_renewal_order_meta( $order_meta_query, $original_order_id, $renewal_order_id, $new_order_role ) {
if ( 'parent' == $new_order_role ) {
$order_meta_query .= " AND `meta_key` NOT LIKE '_simplify_customer_id' ";
}
return $order_meta_query;
}
/**
* Update the customer_id for a subscription after using Simplify to complete a payment to make up for
* an automatic renewal payment which previously failed.
*
* @param WC_Order $original_order The original order in which the subscription was purchased.
* @param WC_Order $renewal_order The order which recorded the successful payment (to make up for the failed automatic payment).
* @param string $subscription_key A subscription key of the form created by @see WC_Subscriptions_Manager::get_subscription_key()
* @return void
*/
public function update_failing_payment_method( $original_order, $renewal_order, $subscription_key ) {
$new_customer_id = get_post_meta( $renewal_order->id, '_simplify_customer_id', true );
update_post_meta( $original_order->id, '_simplify_customer_id', $new_customer_id );
}
/**
* Process a pre-order payment when the pre-order is released
*
* @param WC_Order $order
* @return wp_error|null
*/
public function process_pre_order_release_payment( $order ) {
try {
$order_items = $order->get_items();
$order_item = array_shift( $order_items );
$pre_order_name = sprintf( __( '%s - Pre-order for "%s"', 'woocommerce' ), esc_html( get_bloginfo( 'name' ) ), $order_item['name'] ) . ' ' . sprintf( __( '(Order %s)', 'woocommerce' ), $order->get_order_number() );
$customer_id = get_post_meta( $order->id, '_simplify_customer_id', true );
if ( ! $customer_id ) {
return new WP_Error( 'simplify_error', __( 'Customer not found', 'woocommerce' ) );
}
// Charge the customer
$payment = Simplify_Payment::createPayment( array(
'amount' => $order->order_total * 100, // In cents
'customer' => $customer_id,
'description' => trim( substr( $pre_order_name, 0, 1024 ) ),
'currency' => strtoupper( get_woocommerce_currency() ),
'reference' => $order->id,
'card.addressCity' => $order->billing_city,
'card.addressCountry' => $order->billing_country,
'card.addressLine1' => $order->billing_address_1,
'card.addressLine2' => $order->billing_address_2,
'card.addressState' => $order->billing_state,
'card.addressZip' => $order->billing_postcode
) );
if ( 'APPROVED' == $payment->paymentStatus ) {
// Payment complete
$order->payment_complete( $payment->id );
// Add order note
$order->add_order_note( sprintf( __( 'Simplify payment approved (ID: %s, Auth Code: %s)', 'woocommerce' ), $payment->id, $payment->authCode ) );
} else {
return new WP_Error( 'simplify_payment_declined', __( 'Payment was declined - the customer need to try another card.', 'woocommerce' ) );
}
} catch ( Exception $e ) {
$order_note = sprintf( __( 'Simplify Transaction Failed (%s)', 'woocommerce' ), $e->getMessage() );
// Mark order as failed if not already set,
// otherwise, make sure we add the order note so we can detect when someone fails to check out multiple times
if ( 'failed' != $order->status ) {
$order->update_status( 'failed', $order_note );
} else {
$order->add_order_note( $order_note );
}
}
}
}
| joshquila/demo2-youse | wp-content/plugins/woocommerce/includes/gateways/simplify-commerce/class-wc-addons-gateway-simplify-commerce.php | PHP | gpl-2.0 | 13,502 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_ProductAlert
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* ProductAlert data helper
*
* @category Mage
* @package Mage_ProductAlert
* @author Magento Core Team <[email protected]>
*/
class Mage_ProductAlert_Helper_Data extends Mage_Core_Helper_Url
{
/**
* Current product instance (override registry one)
*
* @var null|Mage_Catalog_Model_Product
*/
protected $_product = null;
/**
* Get current product instance
*
* @return Mage_Catalog_Model_Product
*/
public function getProduct()
{
if (!is_null($this->_product)) {
return $this->_product;
}
return Mage::registry('product');
}
/**
* Set current product instance
*
* @param Mage_Catalog_Model_Product $product
* @return Mage_ProductAlert_Helper_Data
*/
public function setProduct($product)
{
$this->_product = $product;
return $this;
}
public function getCustomer()
{
return Mage::getSingleton('customer/session');
}
public function getStore()
{
return Mage::app()->getStore();
}
public function getSaveUrl($type)
{
return $this->_getUrl('productalert/add/' . $type, array(
'product_id' => $this->getProduct()->getId(),
Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => $this->getEncodedUrl()
));
}
public function createBlock($block)
{
$error = Mage::helper('core')->__('Invalid block type: %s', $block);
if (is_string($block)) {
if (strpos($block, '/') !== false) {
if (!$block = Mage::getConfig()->getBlockClassName($block)) {
Mage::throwException($error);
}
}
$fileName = mageFindClassFile($block);
if ($fileName!==false) {
include_once ($fileName);
$block = new $block(array());
}
}
if (!$block instanceof Mage_Core_Block_Abstract) {
Mage::throwException($error);
}
return $block;
}
/**
* Check whether stock alert is allowed
*
* @return bool
*/
public function isStockAlertAllowed()
{
return Mage::getStoreConfigFlag(Mage_ProductAlert_Model_Observer::XML_PATH_STOCK_ALLOW);
}
/**
* Check whether price alert is allowed
*
* @return bool
*/
public function isPriceAlertAllowed()
{
return Mage::getStoreConfigFlag(Mage_ProductAlert_Model_Observer::XML_PATH_PRICE_ALLOW);
}
}
| Eristoff47/P2 | src/public/app/code/core/Mage/ProductAlert/Helper/Data.php | PHP | gpl-2.0 | 3,545 |
using System;
using Server;
using Server.Network;
using System.Collections;
namespace Server.Gumps
{
public class ImageTileButtonInfo
{
private int m_ItemID;
private int m_Hue;
private int m_LocalizedTooltip;
private TextDefinition m_Label;
public virtual int ItemID
{
get{ return m_ItemID; }
set{ m_ItemID = value; }
}
public virtual int Hue
{
get{ return m_Hue; }
set{ m_Hue = value; }
}
public virtual int LocalizedTooltip
{
get{ return m_LocalizedTooltip; }
set{ m_LocalizedTooltip = value; }
}
public virtual TextDefinition Label
{
get{ return m_Label; }
set{ m_Label = value; }
}
public ImageTileButtonInfo( int itemID, int hue, TextDefinition label, int localizedTooltip )
{
m_Hue = hue;
m_ItemID = itemID;
m_Label = label;
m_LocalizedTooltip = localizedTooltip;
}
public ImageTileButtonInfo( int itemID, int hue, TextDefinition label ) : this( itemID, hue, label, -1 )
{
}
}
public class BaseImageTileButtonsGump : Gump
{
private ImageTileButtonInfo[] m_Buttons;
protected ImageTileButtonInfo[] Buttons { get { return m_Buttons; } }
protected virtual int XItems{ get{ return 2; } }
protected virtual int YItems{ get { return 5; } }
public BaseImageTileButtonsGump( TextDefinition header, ArrayList buttons ) : this( header, (ImageTileButtonInfo[])buttons.ToArray( typeof( ImageTileButtonInfo ) ) )
{
}
public BaseImageTileButtonsGump( TextDefinition header, ImageTileButtonInfo[] buttons ) : base( 10, 10 ) //Coords are 0, o on OSI, intentional difference
{
m_Buttons = buttons;
AddPage( 0 );
int x = XItems * 250;
int y = YItems * 64;
AddBackground( 0, 0, x+20, y+84, 0x13BE );
AddImageTiled( 10, 10, x, 20, 0xA40 );
AddImageTiled( 10, 40, x, y+4, 0xA40 );
AddImageTiled( 10, y+54, x, 20, 0xA40 );
AddAlphaRegion( 10, 10, x, y+64 );
AddButton( 10, y+54, 0xFB1, 0xFB2, 0, GumpButtonType.Reply, 0 ); //Cancel Button
AddHtmlLocalized( 45, y+56, x-50, 20, 1060051, 0x7FFF, false, false ); // CANCEL
TextDefinition.AddHtmlText( this, 14, 12, x, 20, header, false, false, 0x7FFF, 0xFFFFFF );
AddPage( 1 );
int itemsPerPage = XItems * YItems;
for( int i = 0; i < buttons.Length; i++ )
{
int position = i % itemsPerPage;
int innerX = (position % XItems) * 250 + 14;
int innerY = (position / XItems) * 64 + 44;
int pageNum = i / itemsPerPage + 1;
if( position == 0 && i != 0 )
{
AddButton( x-100, y+54, 0xFA5, 0xFA7, 0, GumpButtonType.Page, pageNum );
AddHtmlLocalized( x-60, y+56, 60, 20, 1043353, 0x7FFF, false, false ); // Next
AddPage( pageNum );
AddButton( x-200, y+54, 0xFAE, 0xFB0, 0, GumpButtonType.Page, pageNum - 1 );
AddHtmlLocalized( x-160, y+56, 60, 20, 1011393, 0x7FFF, false, false ); // Back
}
ImageTileButtonInfo b = buttons[i];
AddImageTiledButton( innerX, innerY, 0x918, 0x919, 100 + i, GumpButtonType.Reply, 0, b.ItemID, b.Hue, 15, 10, b.LocalizedTooltip );
TextDefinition.AddHtmlText( this, innerX + 84, innerY, 250, 60, b.Label, false, false, 0x7FFF, 0xFFFFFF );
}
}
public override void OnResponse( NetState sender, RelayInfo info )
{
int adjustedID = info.ButtonID - 100;
if( adjustedID >= 0 && adjustedID < Buttons.Length )
HandleButtonResponse( sender, adjustedID, Buttons[adjustedID] );
else
HandleCancel( sender );
}
public virtual void HandleButtonResponse( NetState sender, int adjustedButton, ImageTileButtonInfo buttonInfo )
{
}
public virtual void HandleCancel( NetState sender )
{
}
}
} | alucardxlx/caoticamente-shards | Scripts/Gumps/BaseImageTileButtonsGump.cs | C# | gpl-2.0 | 3,735 |
/*
* Sun RPC is a product of Sun Microsystems, Inc. and is provided for
* unrestricted use provided that this legend is included on all tape
* media and as a part of the software program in whole or part. Users
* may copy or modify Sun RPC without charge, but are not authorized
* to license or distribute it to anyone else except as part of a product or
* program developed by the user or with the express written consent of
* Sun Microsystems, Inc.
*
* SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
* WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
* PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
*
* Sun RPC is provided with no support and without any obligation on the
* part of Sun Microsystems, Inc. to assist in its use, correction,
* modification or enhancement.
*
* SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
* INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
* OR ANY PART THEREOF.
*
* In no event will Sun Microsystems, Inc. be liable for any lost revenue
* or profits or other special, indirect and consequential damages, even if
* Sun has been advised of the possibility of such damages.
*
* Sun Microsystems, Inc.
* 2550 Garcia Avenue
* Mountain View, California 94043
*/
#if 0
static char sccsid[] = "@(#)rpc_main.c 1.30 89/03/30 (C) 1987 SMI";
#endif
/*
* rpc_main.c, Top level of the RPC protocol compiler.
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include "rpc_parse.h"
#include "rpc_util.h"
#include "rpc_scan.h"
struct commandline {
int cflag; /* xdr C routines */
int hflag; /* header file */
int lflag; /* client side stubs */
int mflag; /* server side stubs */
int nflag; /* netid flag */
int sflag; /* server stubs for the given transport */
int tflag; /* dispatch Table file */
int Ssflag; /* produce server sample code */
int Scflag; /* produce client sample code */
char *infile; /* input module name */
char *outfile; /* output module name */
};
static char * extendfile(char *file, char *ext);
static void open_output(char *infile, char *outfile);
static void add_warning(void);
static void clear_args(void);
static void open_input(char *infile, char *define);
static int check_nettype(char *name, char **list_to_check);
static void c_output(char *infile, char *define, int extend, char *outfile);
static void c_initialize(void);
static char * generate_guard(char *pathname);
static void h_output(char *infile, char *define, int extend, char *outfile);
static void s_output(int argc, char **argv, char *infile,
char *define, int extend, char *outfile,
int nomain, int netflag);
static void l_output(char *infile, char *define, int extend, char *outfile);
static void t_output(char *infile, char *define, int extend, char *outfile);
static void svc_output(char *, char *, int, char *);
static void clnt_output(char *, char *, int, char *);
static int do_registers(int argc, char **argv);
static void addarg(char *cp);
static void putarg(int where, char *cp);
static void checkfiles(char *infile, char *outfile);
static int parseargs(int argc, char **argv, struct commandline *cmd);
static void usage(void);
static void options_usage(void);
/*
extern void write_sample_svc();
int write_sample_clnt();
void write_sample_clnt_main();
static svc_output();
*/
#define EXTEND 1 /* alias for TRUE */
#define DONT_EXTEND 0 /* alias for FALSE */
#define SVR4_CPP "/usr/ccs/lib/cpp"
#define SUNOS_CPP "/lib/cpp"
static int cppDefined = 0; /* explicit path for C preprocessor */
static char *cmdname;
static char *svcclosetime = "120";
static char *CPP = SVR4_CPP;
static char CPPFLAGS[] = "-C";
static char pathbuf[MAXPATHLEN + 1];
static char *allv[] = {
"rpcgen", "-s", "udp", "-s", "tcp",
};
static int allc = sizeof(allv)/sizeof(allv[0]);
static char *allnv[] = {
"rpcgen", "-s", "netpath",
};
static int allnc = sizeof(allnv)/sizeof(allnv[0]);
/*
* machinations for handling expanding argument list
*/
#if 0
static void addarg(); /* add another argument to the list */
static void putarg(); /* put argument at specified location */
static void clear_args(); /* clear argument list */
static void checkfiles(); /* check if out file already exists */
#endif
#define ARGLISTLEN 20
#define FIXEDARGS 2
static char *arglist[ARGLISTLEN];
static int argcount = FIXEDARGS;
int nonfatalerrors; /* errors */
int inetdflag/* = 1*/; /* Support for inetd */ /* is now the default */
int pmflag; /* Support for port monitors */
int logflag; /* Use syslog instead of fprintf for errors */
int tblflag; /* Support for dispatch table file */
/* length at which to start doing an inline */
#define INLINE 3
int Inline = INLINE; /* length at which to start doing an inline. 3 = default
* if 0, no xdr_inline code */
int indefinitewait; /* If started by port monitors, hang till it wants */
int exitnow; /* If started by port monitors, exit after the call */
int timerflag; /* TRUE if !indefinite && !exitnow */
int newstyle; /* newstyle of passing arguments (by value) */
int Cflag = 0 ; /* ANSI C syntax */
static int allfiles; /* generate all files */
#ifdef linux
int tirpcflag = 0; /* no tirpc by default */
#else
int tirpcflag = 1; /* generating code for tirpc, by default */
#endif
int
main(int argc, char **argv)
{
struct commandline cmd;
(void) memset((char *) &cmd, 0, sizeof(struct commandline));
clear_args();
if (!parseargs(argc, argv, &cmd))
usage();
if (cmd.cflag || cmd.hflag || cmd.lflag || cmd.tflag || cmd.sflag ||
cmd.mflag || cmd.nflag || cmd.Ssflag || cmd.Scflag) {
checkfiles(cmd.infile, cmd.outfile);
} else
checkfiles(cmd.infile, NULL);
if (cmd.cflag) {
c_output(cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile);
} else if (cmd.hflag) {
h_output(cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile);
} else if (cmd.lflag) {
l_output(cmd.infile, "-DRPC_CLNT", DONT_EXTEND, cmd.outfile);
} else if (cmd.sflag || cmd.mflag || (cmd.nflag)) {
s_output(argc, argv, cmd.infile, "-DRPC_SVC", DONT_EXTEND,
cmd.outfile, cmd.mflag, cmd.nflag);
} else if (cmd.tflag) {
t_output(cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile);
} else if (cmd.Ssflag) {
svc_output(cmd.infile, "-DRPC_SERVER", DONT_EXTEND, cmd.outfile);
} else if (cmd.Scflag) {
clnt_output(cmd.infile, "-DRPC_CLIENT", DONT_EXTEND, cmd.outfile);
} else {
/* the rescans are required, since cpp may effect input */
c_output(cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c");
reinitialize();
h_output(cmd.infile, "-DRPC_HDR", EXTEND, ".h");
reinitialize();
l_output(cmd.infile, "-DRPC_CLNT", EXTEND, "_clnt.c");
reinitialize();
if (inetdflag || !tirpcflag)
s_output(allc, allv, cmd.infile, "-DRPC_SVC", EXTEND,
"_svc.c", cmd.mflag, cmd.nflag);
else
s_output(allnc, allnv, cmd.infile, "-DRPC_SVC",
EXTEND, "_svc.c", cmd.mflag, cmd.nflag);
if (tblflag) {
reinitialize();
t_output(cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.i");
}
if (allfiles) {
reinitialize();
svc_output(cmd.infile, "-DRPC_SERVER", EXTEND, "_server.c");
}
if (allfiles) {
reinitialize();
clnt_output(cmd.infile, "-DRPC_CLIENT", EXTEND, "_client.c");
}
}
exit(nonfatalerrors);
/* NOTREACHED */
}
/*
* add extension to filename
*/
static char *
extendfile(char *file, char *ext)
{
char *res;
char *p;
res = alloc(strlen(file) + strlen(ext) + 1);
if (res == NULL) {
abort();
}
p = strrchr(file, '.');
if (p == NULL) {
p = file + strlen(file);
}
(void) strcpy(res, file);
(void) strcpy(res + (p - file), ext);
return (res);
}
/*
* Open output file with given extension
*/
static void
open_output(char *infile, char *outfile)
{
if (outfile == NULL) {
fout = stdout;
return;
}
if (infile != NULL && streq(outfile, infile)) {
f_print(stderr, "%s: output would overwrite %s\n", cmdname,
infile);
crash();
}
fout = fopen(outfile, "w");
if (fout == NULL) {
f_print(stderr, "%s: unable to open ", cmdname);
perror(outfile);
crash();
}
record_open(outfile);
}
static void
add_warning(void)
{
f_print(fout, "/*\n");
f_print(fout, " * Please do not edit this file.\n");
f_print(fout, " * It was generated using rpcgen.\n");
f_print(fout, " */\n\n");
}
/* clear list of arguments */
static void
clear_args(void)
{
int i;
for( i=FIXEDARGS; i<ARGLISTLEN; i++ )
arglist[i] = NULL;
argcount = FIXEDARGS;
}
/*
* Open input file with given define for C-preprocessor
*/
static void
open_input(char *infile, char *define)
{
int pd[2];
infilename = (infile == NULL) ? "<stdin>" : infile;
(void) pipe(pd);
switch (fork()) {
case 0:
putarg(0, "cpp");
putarg(1, CPPFLAGS);
addarg(define);
addarg(infile);
addarg((char *)NULL);
(void) close(1);
(void) dup2(pd[1], 1);
(void) close(pd[0]);
if (cppDefined)
execv(CPP, arglist);
else {
execvp("cpp", arglist);
if (errno == ENOENT)
execvp(SVR4_CPP, arglist);
if (errno == ENOENT)
execvp(SUNOS_CPP, arglist);
}
perror("execv");
exit(1);
case -1:
perror("fork");
exit(1);
}
(void) close(pd[1]);
fin = fdopen(pd[0], "r");
if (fin == NULL) {
f_print(stderr, "%s: ", cmdname);
perror(infilename);
crash();
}
}
/* valid tirpc nettypes */
static char* valid_ti_nettypes[] =
{
"netpath",
"visible",
"circuit_v",
"datagram_v",
"circuit_n",
"datagram_n",
"udp",
"tcp",
"raw",
NULL
};
/* valid inetd nettypes */
static char* valid_i_nettypes[] =
{
"udp",
"tcp",
NULL
};
static int
check_nettype(char *name, char **list_to_check)
{
int i;
for( i = 0; list_to_check[i] != NULL; i++ ) {
if( strcmp( name, list_to_check[i] ) == 0 ) {
return 1;
}
}
f_print( stderr, "illegal nettype :\'%s\'\n", name );
return 0;
}
/*
* Compile into an XDR routine output file
*/
static void
c_output(char *infile, char *define, int extend, char *outfile)
{
definition *def;
char *include;
char *outfilename;
long tell;
c_initialize();
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
open_output(infile, outfilename);
add_warning();
if (infile && (include = extendfile(infile, ".h"))) {
f_print(fout, "#include \"%s\"\n", include);
free(include);
/* .h file already contains rpc/rpc.h */
} else
f_print(fout, "#include <rpc/rpc.h>\n");
tell = ftell(fout);
while ((def = get_definition()) != NULL) {
emit(def);
}
if (extend && tell == ftell(fout)) {
(void) unlink(outfilename);
}
}
static void
c_initialize(void)
{
/* add all the starting basic types */
add_type(1,"int");
add_type(1,"int32_t");
add_type(1,"short");
add_type(1,"bool");
add_type(1,"u_int");
add_type(1,"u_int32_t");
add_type(1,"u_short");
}
char rpcgen_table_dcl[] = "struct rpcgen_table {\n\
char *(*proc)();\n\
xdrproc_t xdr_arg;\n\
unsigned len_arg;\n\
xdrproc_t xdr_res;\n\
unsigned len_res;\n\
};\n";
static char *
generate_guard(char *pathname)
{
char* filename, *guard, *tmp;
filename = strrchr(pathname, '/' ); /* find last component */
filename = ((filename == 0) ? pathname : filename+1);
guard = strdup(filename);
/* convert to upper case */
tmp = guard;
while (*tmp) {
if (islower(*tmp))
*tmp = toupper(*tmp);
tmp++;
}
guard = extendfile(guard, "_H_RPCGEN");
return( guard );
}
/*
* Compile into an XDR header file
*/
static void
h_output(char *infile, char *define, int extend, char *outfile)
{
definition *def;
char *outfilename;
long tell;
char *guard;
list *l;
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
open_output(infile, outfilename);
add_warning();
guard = generate_guard( outfilename ? outfilename: infile );
f_print(fout,"#ifndef _%s\n#define _%s\n\n", guard,
guard);
f_print(fout, "#include <rpc/rpc.h>\n\n");
f_print(fout, "#ifndef IXDR_GET_INT32\n");
f_print(fout, "#define IXDR_GET_INT32(buf) IXDR_GET_LONG((buf))\n");
f_print(fout, "#endif\n");
f_print(fout, "#ifndef IXDR_PUT_INT32\n");
f_print(fout, "#define IXDR_PUT_INT32(buf, v) IXDR_PUT_LONG((buf), (v))\n");
f_print(fout, "#endif\n");
f_print(fout, "#ifndef IXDR_GET_U_INT32\n");
f_print(fout, "#define IXDR_GET_U_INT32(buf) IXDR_GET_U_LONG((buf))\n");
f_print(fout, "#endif\n");
f_print(fout, "#ifndef IXDR_PUT_U_INT32\n");
f_print(fout, "#define IXDR_PUT_U_INT32(buf, v) IXDR_PUT_U_LONG((buf), (v))\n");
f_print(fout, "#endif\n");
tell = ftell(fout);
/* print data definitions */
while ((def = get_definition()) != NULL) {
print_datadef(def);
}
/* print function declarations.
Do this after data definitions because they might be used as
arguments for functions */
for (l = defined; l != NULL; l = l->next) {
print_funcdef(l->val);
}
if (extend && tell == ftell(fout)) {
(void) unlink(outfilename);
} else if (tblflag) {
f_print(fout, rpcgen_table_dcl);
}
f_print(fout, "\n#endif /* !_%s */\n", guard);
}
/*
* Compile into an RPC service
*/
static void
s_output(int argc, char **argv, char *infile, char *define, int extend,
char *outfile, int nomain, int netflag)
{
char *include;
definition *def;
int foundprogram = 0;
char *outfilename;
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
open_output(infile, outfilename);
add_warning();
if (infile && (include = extendfile(infile, ".h"))) {
f_print(fout, "#include \"%s\"\n", include);
free(include);
} else
f_print(fout, "#include <rpc/rpc.h>\n");
f_print(fout, "#include <stdio.h>\n");
f_print(fout, "#include <stdlib.h>/* getenv, exit */\n");
if (Cflag) {
f_print (fout, "#include <rpc/pmap_clnt.h> /* for pmap_unset */\n");
f_print (fout, "#include <string.h> /* strcmp */ \n");
}
if (strcmp(svcclosetime, "-1") == 0)
indefinitewait = 1;
else if (strcmp(svcclosetime, "0") == 0)
exitnow = 1;
else if (inetdflag || pmflag) {
f_print(fout, "#include <signal.h>\n");
timerflag = 1;
}
#ifndef linux
if( !tirpcflag && inetdflag )
f_print(fout, "#include <sys/ttycom.h>/* TIOCNOTTY */\n");
#else
if( !tirpcflag )
f_print(fout, "#include <sys/ttycom.h>/* TIOCNOTTY */\n");
#endif
if( Cflag && (inetdflag || pmflag ) ) {
f_print(fout, "#ifdef __cplusplus\n");
f_print(fout, "#include <sysent.h> /* getdtablesize, open */\n");
f_print(fout, "#endif /* __cplusplus */\n");
if( tirpcflag )
f_print(fout, "#include <unistd.h> /* setsid */\n");
}
if( tirpcflag )
f_print(fout, "#include <sys/types.h>\n");
f_print(fout, "#include <memory.h>\n");
#ifndef linux
f_print(fout, "#include <stropts.h>\n");
#endif
if (inetdflag || !tirpcflag ) {
f_print(fout, "#include <sys/socket.h>\n");
f_print(fout, "#include <netinet/in.h>\n");
}
if ( (netflag || pmflag) && tirpcflag ) {
f_print(fout, "#include <netconfig.h>\n");
}
if (/*timerflag &&*/ tirpcflag)
f_print(fout, "#include <sys/resource.h> /* rlimit */\n");
if (logflag || inetdflag || pmflag) {
#ifdef linux
f_print(fout, "#include <syslog.h>\n");
#else
f_print(fout, "#ifdef SYSLOG\n");
f_print(fout, "#include <syslog.h>\n");
f_print(fout, "#else\n");
f_print(fout, "#define LOG_ERR 1\n");
f_print(fout, "#define openlog(a, b, c)\n");
f_print(fout, "#endif\n");
#endif
}
/* for ANSI-C */
f_print(fout, "\n#ifdef __STDC__\n#define SIG_PF void(*)(int)\n#endif\n");
f_print(fout, "\n#ifdef DEBUG\n#define RPC_SVC_FG\n#endif\n");
if (timerflag)
f_print(fout, "\n#define _RPCSVC_CLOSEDOWN %s\n", svcclosetime);
while ((def = get_definition()) != NULL) {
foundprogram |= (def->def_kind == DEF_PROGRAM);
}
if (extend && !foundprogram) {
(void) unlink(outfilename);
return;
}
write_most(infile, netflag, nomain);
if (!nomain) {
if( !do_registers(argc, argv) ) {
if (outfilename)
(void) unlink(outfilename);
usage();
}
write_rest();
}
}
/*
* generate client side stubs
*/
static void
l_output(char *infile, char *define, int extend, char *outfile)
{
char *include;
definition *def;
int foundprogram = 0;
char *outfilename;
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
open_output(infile, outfilename);
add_warning();
if (Cflag)
f_print (fout, "#include <memory.h> /* for memset */\n");
if (infile && (include = extendfile(infile, ".h"))) {
f_print(fout, "#include \"%s\"\n", include);
free(include);
} else
f_print(fout, "#include <rpc/rpc.h>\n");
while ((def = get_definition()) != NULL) {
foundprogram |= (def->def_kind == DEF_PROGRAM);
}
if (extend && !foundprogram) {
(void) unlink(outfilename);
return;
}
write_stubs();
}
/*
* generate the dispatch table
*/
static void
t_output(char *infile, char *define, int extend, char *outfile)
{
definition *def;
int foundprogram = 0;
char *outfilename;
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
open_output(infile, outfilename);
add_warning();
while ((def = get_definition()) != NULL) {
foundprogram |= (def->def_kind == DEF_PROGRAM);
}
if (extend && !foundprogram) {
(void) unlink(outfilename);
return;
}
write_tables();
}
/* sample routine for the server template */
static void
svc_output(char *infile, char *define, int extend, char *outfile)
{
definition *def;
char *include;
char *outfilename;
long tell;
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
checkfiles(infile,outfilename); /*check if outfile already exists.
if so, print an error message and exit*/
open_output(infile, outfilename);
add_sample_msg();
if (infile && (include = extendfile(infile, ".h"))) {
f_print(fout, "#include \"%s\"\n", include);
free(include);
} else
f_print(fout, "#include <rpc/rpc.h>\n");
tell = ftell(fout);
while ((def = get_definition()) != NULL) {
write_sample_svc(def);
}
if (extend && tell == ftell(fout)) {
(void) unlink(outfilename);
}
}
/* sample main routine for client */
static void
clnt_output(char *infile, char *define, int extend, char *outfile)
{
definition *def;
char *include;
char *outfilename;
long tell;
int has_program = 0;
open_input(infile, define);
outfilename = extend ? extendfile(infile, outfile) : outfile;
checkfiles(infile, outfilename); /*check if outfile already exists.
if so, print an error message and exit*/
open_output(infile, outfilename);
add_sample_msg();
if (infile && (include = extendfile(infile, ".h"))) {
f_print(fout, "#include \"%s\"\n", include);
free(include);
} else
f_print(fout, "#include <rpc/rpc.h>\n");
tell = ftell(fout);
while ((def = get_definition()) != NULL) {
has_program += write_sample_clnt(def);
}
if (has_program)
write_sample_clnt_main();
if (extend && tell == ftell(fout)) {
(void) unlink(outfilename);
}
}
/*
* Perform registrations for service output
* Return 0 if failed; 1 otherwise.
*/
static int
do_registers(int argc, char **argv)
{
int i;
if (inetdflag || !tirpcflag) {
for (i = 1; i < argc; i++) {
if (streq(argv[i], "-s")) {
if (!check_nettype(argv[i + 1], valid_i_nettypes))
return 0;
write_inetd_register(argv[i + 1]);
i++;
}
}
} else {
for (i = 1; i < argc; i++)
if (streq(argv[i], "-s")) {
if (!check_nettype(argv[i + 1], valid_ti_nettypes))
return 0;
write_nettype_register(argv[i + 1]);
i++;
} else if (streq(argv[i], "-n")) {
write_netid_register(argv[i + 1]);
i++;
}
}
return 1;
}
/*
* Add another argument to the arg list
*/
static void
addarg(char *cp)
{
if (argcount >= ARGLISTLEN) {
f_print(stderr, "rpcgen: too many defines\n");
crash();
/*NOTREACHED*/
}
arglist[argcount++] = cp;
}
static void
putarg(int where, char *cp)
{
if (where >= ARGLISTLEN) {
f_print(stderr, "rpcgen: arglist coding error\n");
crash();
/*NOTREACHED*/
}
arglist[where] = cp;
}
/*
* if input file is stdin and an output file is specified then complain
* if the file already exists. Otherwise the file may get overwritten
* If input file does not exist, exit with an error
*/
static void
checkfiles(char *infile, char *outfile)
{
struct stat buf;
if(infile) /* infile ! = NULL */
if(stat(infile,&buf) < 0)
{
perror(infile);
crash();
};
if (outfile) {
if (stat(outfile, &buf) < 0)
return; /* file does not exist */
else {
f_print(stderr,
"file '%s' already exists and may be overwritten\n", outfile);
crash();
}
}
}
/*
* Parse command line arguments
*/
static int
parseargs(int argc, char **argv, struct commandline *cmd)
{
int i;
int j;
char c;
char flag[(1 << 8 * sizeof(char))];
int nflags;
cmdname = argv[0];
cmd->infile = cmd->outfile = NULL;
if (argc < 2) {
return (0);
}
allfiles = 0;
flag['c'] = 0;
flag['h'] = 0;
flag['l'] = 0;
flag['m'] = 0;
flag['o'] = 0;
flag['s'] = 0;
flag['n'] = 0;
flag['t'] = 0;
flag['S'] = 0;
flag['C'] = 0;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
if (cmd->infile) {
f_print( stderr, "Cannot specify more than one input file!\n");
return (0);
}
cmd->infile = argv[i];
} else {
for (j = 1; argv[i][j] != 0; j++) {
c = argv[i][j];
switch (c) {
case 'a':
allfiles = 1;
break;
case 'c':
case 'h':
case 'l':
case 'm':
case 't':
if (flag[(int) c]) {
return (0);
}
flag[(int) c] = 1;
break;
case 'S':
/* sample flag: Ss or Sc.
Ss means set flag['S'];
Sc means set flag['C']; */
c = argv[i][++j]; /* get next char */
if( c == 's' )
c = 'S';
else if( c == 'c' )
c = 'C';
else
return( 0 );
if (flag[(int) c]) {
return (0);
}
flag[(int) c] = 1;
break;
case 'C': /* ANSI C syntax */
Cflag = 1;
break;
case 'b': /* turn TIRPC flag off for
generating backward compatible
*/
tirpcflag = 0;
break;
case 'I':
inetdflag = 1;
break;
case 'N':
newstyle = 1;
break;
case 'L':
logflag = 1;
break;
case 'K':
if (++i == argc) {
return (0);
}
svcclosetime = argv[i];
goto nextarg;
case 'T':
tblflag = 1;
break;
case 'i' :
if (++i == argc) {
return (0);
}
Inline = atoi(argv[i]);
goto nextarg;
case 'n':
case 'o':
case 's':
if (argv[i][j - 1] != '-' ||
argv[i][j + 1] != 0) {
return (0);
}
flag[(int) c] = 1;
if (++i == argc) {
return (0);
}
if (c == 's') {
if (!streq(argv[i], "udp") &&
!streq(argv[i], "tcp")) {
return (0);
}
} else if (c == 'o') {
if (cmd->outfile) {
return (0);
}
cmd->outfile = argv[i];
}
goto nextarg;
case 'D':
if (argv[i][j - 1] != '-') {
return (0);
}
(void) addarg(argv[i]);
goto nextarg;
case 'Y':
if (++i == argc) {
return (0);
}
(void) strcpy(pathbuf, argv[i]);
(void) strcat(pathbuf, "/cpp");
CPP = pathbuf;
cppDefined = 1;
goto nextarg;
default:
return (0);
}
}
nextarg:
;
}
}
cmd->cflag = flag['c'];
cmd->hflag = flag['h'];
cmd->lflag = flag['l'];
cmd->mflag = flag['m'];
cmd->nflag = flag['n'];
cmd->sflag = flag['s'];
cmd->tflag = flag['t'];
cmd->Ssflag = flag['S'];
cmd->Scflag = flag['C'];
if( tirpcflag ) {
pmflag = inetdflag ? 0 : 1; /* pmflag or inetdflag is always TRUE */
if( (inetdflag && cmd->nflag)) { /* netid not allowed with inetdflag */
f_print(stderr, "Cannot use netid flag with inetd flag!\n");
return (0);
}
} else { /* 4.1 mode */
pmflag = 0; /* set pmflag only in tirpcmode */
inetdflag = 1; /* inetdflag is TRUE by default */
if( cmd->nflag ) { /* netid needs TIRPC */
f_print( stderr, "Cannot use netid flag without TIRPC!\n");
return( 0 );
}
}
if( newstyle && ( tblflag || cmd->tflag) ) {
f_print( stderr, "Cannot use table flags with newstyle!\n");
return( 0 );
}
/* check no conflicts with file generation flags */
nflags = cmd->cflag + cmd->hflag + cmd->lflag + cmd->mflag +
cmd->sflag + cmd->nflag + cmd->tflag + cmd->Ssflag + cmd->Scflag;
if (nflags == 0) {
if (cmd->outfile != NULL || cmd->infile == NULL) {
return (0);
}
} else if (nflags > 1) {
f_print( stderr, "Cannot have more than one file generation flag!\n");
return (0);
}
return (1);
}
static void
usage(void)
{
f_print(stderr, "usage: %s infile\n", cmdname);
f_print(stderr, "\t%s [-a][-b][-C][-Dname[=value]] -i size [-I [-K seconds]] [-L][-N][-T] infile\n",
cmdname);
f_print(stderr, "\t%s [-c | -h | -l | -m | -t | -Sc | -Ss] [-o outfile] [infile]\n",
cmdname);
f_print(stderr, "\t%s [-s nettype]* [-o outfile] [infile]\n", cmdname);
f_print(stderr, "\t%s [-n netid]* [-o outfile] [infile]\n", cmdname);
options_usage();
exit(1);
}
static void
options_usage(void)
{
f_print(stderr, "options:\n");
f_print(stderr, "-a\t\tgenerate all files, including samples\n");
f_print(stderr, "-b\t\tbackward compatibility mode (generates code for SunOS 4.1)\n");
f_print(stderr, "-c\t\tgenerate XDR routines\n");
f_print(stderr, "-C\t\tANSI C mode\n");
f_print(stderr, "-Dname[=value]\tdefine a symbol (same as #define)\n");
f_print(stderr, "-h\t\tgenerate header file\n");
f_print(stderr, "-i size\t\tsize at which to start generating inline code\n");
f_print(stderr, "-I\t\tgenerate code for inetd support in server (for SunOS 4.1)\n");
f_print(stderr, "-K seconds\tserver exits after K seconds of inactivity\n");
f_print(stderr, "-l\t\tgenerate client side stubs\n");
f_print(stderr, "-L\t\tserver errors will be printed to syslog\n");
f_print(stderr, "-m\t\tgenerate server side stubs\n");
f_print(stderr, "-n netid\tgenerate server code that supports named netid\n");
f_print(stderr, "-N\t\tsupports multiple arguments and call-by-value\n");
f_print(stderr, "-o outfile\tname of the output file\n");
f_print(stderr, "-s nettype\tgenerate server code that supports named nettype\n");
f_print(stderr, "-Sc\t\tgenerate sample client code that uses remote procedures\n");
f_print(stderr, "-Ss\t\tgenerate sample server code that defines remote procedures\n");
f_print(stderr, "-t\t\tgenerate RPC dispatch table\n");
f_print(stderr, "-T\t\tgenerate code to support RPC dispatch tables\n");
f_print(stderr, "-Y path\t\tdirectory name to find C preprocessor (cpp)\n");
exit(1);
}
| sigma-random/asuswrt-merlin | release/src/router/nfs-utils/tools/rpcgen/rpc_main.c | C | gpl-2.0 | 26,872 |
/* sonetdiag.c - SONET diagnostics */
/* Written 1995-1999 by Werner Almesberger, EPFL-LRC/ICA */
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <atm.h>
#include <linux/atmdev.h>
#include <linux/sonet.h>
struct opts {
const char *name;
int value;
} options[] = {
{ "sbip", SONET_INS_SBIP }, { "lbip", SONET_INS_LBIP },
{ "pbip", SONET_INS_PBIP }, { "frame",SONET_INS_FRAME },
{ "los", SONET_INS_LOS }, { "lais", SONET_INS_LAIS },
{ "pais", SONET_INS_PAIS }, { "hcs", SONET_INS_HCS },
{ NULL, 0 }
};
static void usage(const char *name)
{
fprintf(stderr,"usage: %s [ -z ] [ itf ] [ [-]error ...]\n",name);
fprintf(stderr," errors: sbip lbip pbip frame\n");
fprintf(stderr," los lais pais hcs\n");
exit(1);
}
int main(int argc,char **argv)
{
struct atmif_sioc req;
struct sonet_stats stats;
struct opts *walk;
const char *name;
char *opt,*end;
int zero,s,set,clear,error,minus;
zero = 0;
name = argv[0];
if (argc > 1 && argv[1][0] == '-') {
if (strcmp(argv[1],"-z")) usage(name);
zero = 1;
argc--;
argv++;
}
if ((s = socket(PF_ATMPVC,SOCK_DGRAM,0)) < 0) {
perror("socket");
return 1;
}
if (argc == 1) req.number = 0;
else {
req.number = strtol(argv[1],&end,10);
if (*end) req.number = 0;
else {
if (req.number < 0) usage(name);
argc--;
argv++;
}
}
argc--;
argv++;
set = clear = error = 0;
while (argc--) {
minus = *(opt = *argv++) == '-';
if (minus) opt++;
for (walk = options; walk->name; walk++)
if (!strcmp(walk->name,opt)) break;
if (walk->name)
if (minus) clear |= walk->value;
else set |= walk->value;
else {
fprintf(stderr,"unrecognized option: %s\n",opt);
error = 1;
}
}
if (error) return 1;
if (!set && !clear) {
req.arg = &stats;
req.length = sizeof(stats);
if (ioctl(s,zero ? SONET_GETSTATZ : SONET_GETSTAT,&req) < 0) {
perror(zero ? "ioctl SONET_GETSTATZ" : "ioctl SONET_GETSTAT");
return 1;
}
req.arg = &set;
req.length = sizeof(set);
if (ioctl(s,SONET_GETDIAG,&req) < 0)
if (errno != EINVAL) perror("ioctl SONET_GETDIAG");
if (stats.section_bip != -1)
printf("Section BIP errors: %10d\n",stats.section_bip);
if (stats.line_bip != -1)
printf("Line BIP errors: %10d\n",stats.line_bip);
if (stats.path_bip != -1)
printf("Path BIP errors: %10d\n",stats.path_bip);
if (stats.line_febe != -1)
printf("Line FEBE: %10d\n",stats.line_febe);
if (stats.path_febe != -1)
printf("Path FEBE: %10d\n",stats.path_febe);
if (stats.corr_hcs != -1)
printf("Correctable HCS: %10d\n",stats.corr_hcs);
if (stats.uncorr_hcs != -1)
printf("Uncorrectable HCS: %10d\n",stats.uncorr_hcs);
if (stats.tx_cells != -1)
printf("TX cells: %10d\n",stats.tx_cells);
if (stats.rx_cells != -1)
printf("RX cells: %10d\n",stats.rx_cells);
if (set) {
int i;
printf("\nDiagnostics:");
for (i = 0; options[i].name; i++)
if (set & options[i].value) printf(" %s",options[i].name);
putchar('\n');
}
}
else {
if (set) {
req.arg = &set;
req.length = sizeof(set);
if (ioctl(s,SONET_SETDIAG,&req) < 0)
perror("ioctl SONET_SETDIAG");
}
if (clear) {
req.arg = &clear;
req.length = sizeof(clear);
if (ioctl(s,SONET_CLRDIAG,&req) < 0)
perror("ioctl SONET_SETDIAG");
}
}
return 0;
}
| ysleu/RTL8685 | uClinux-dist/lib/libatm/src/maint/sonetdiag.c | C | gpl-2.0 | 3,626 |
/******************************************************************************
*
* (c) Copyright 2011-2013 Xilinx, Inc. All rights reserved.
*
* This file contains confidential and proprietary information of Xilinx, Inc.
* and is protected under U.S. and international copyright and other
* intellectual property laws.
*
* DISCLAIMER
* This disclaimer is not a license and does not grant any rights to the
* materials distributed herewith. Except as otherwise provided in a valid
* license issued to you by Xilinx, and to the maximum extent permitted by
* applicable law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL
* FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS,
* IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
* MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE;
* and (2) Xilinx shall not be liable (whether in contract or tort, including
* negligence, or under any other theory of liability) for any loss or damage
* of any kind or nature related to, arising under or in connection with these
* materials, including for any direct, or any indirect, special, incidental,
* or consequential loss or damage (including loss of data, profits, goodwill,
* or any type of loss or damage suffered as a result of any action brought by
* a third party) even if such damage or loss was reasonably foreseeable or
* Xilinx had been advised of the possibility of the same.
*
* CRITICAL APPLICATIONS
* Xilinx products are not designed or intended to be fail-safe, or for use in
* any application requiring fail-safe performance, such as life-support or
* safety devices or systems, Class III medical devices, nuclear facilities,
* applications related to the deployment of airbags, or any other applications
* that could lead to death, personal injury, or severe property or
* environmental damage (individually and collectively, "Critical
* Applications"). Customer assumes the sole risk and liability of any use of
* Xilinx products in Critical Applications, subject only to applicable laws
* and regulations governing limitations on product liability.
*
* THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE
* AT ALL TIMES.
*
******************************************************************************/
/****************************************************************************/
/**
*
* @file xadcps.h
*
* The XAdcPs driver supports the Xilinx XADC/ADC device.
*
* The XADC/ADC device has the following features:
* - 10-bit, 200-KSPS (kilo samples per second)
* Analog-to-Digital Converter (ADC)
* - Monitoring of on-chip supply voltages and temperature
* - 1 dedicated differential analog-input pair and
* 16 auxiliary differential analog-input pairs
* - Automatic alarms based on user defined limits for the on-chip
* supply voltages and temperature
* - Automatic Channel Sequencer, programmable averaging, programmable
* acquisition time for the external inputs, unipolar or differential
* input selection for the external inputs
* - Inbuilt Calibration
* - Optional interrupt request generation
*
*
* The user should refer to the hardware device specification for detailed
* information about the device.
*
* This header file contains the prototypes of driver functions that can
* be used to access the XADC/ADC device.
*
*
* <b> XADC Channel Sequencer Modes </b>
*
* The XADC Channel Sequencer supports the following operating modes:
*
* - <b> Default </b>: This is the default mode after power up.
* In this mode of operation the XADC operates in
* a sequence mode, monitoring the on chip sensors:
* Temperature, VCCINT, and VCCAUX.
* - <b> One pass through sequence </b>: In this mode the XADC
* converts the channels enabled in the Sequencer Channel Enable
* registers for a single pass and then stops.
* - <b> Continuous cycling of sequence </b>: In this mode the XADC
* converts the channels enabled in the Sequencer Channel Enable
* registers continuously.
* - <b> Single channel mode</b>: In this mode the XADC Channel
* Sequencer is disabled and the XADC operates in a
* Single Channel Mode.
* The XADC can operate either in a Continuous or Event
* driven sampling mode in the single channel mode.
* - <b> Simultaneous Sampling Mode</b>: In this mode the XADC Channel
* Sequencer will automatically sequence through eight fixed pairs
* of auxiliary analog input channels for simulataneous conversion.
* - <b> Independent ADC mode</b>: In this mode the first ADC (A) is used to
* is used to implement a fixed monitoring mode similar to the
* default mode but the alarm fucntions ar eenabled.
* The second ADC (B) is available to be used with external analog
* input channels only.
*
* Read the XADC spec for more information about the sequencer modes.
*
* <b> Initialization and Configuration </b>
*
* The device driver enables higher layer software (e.g., an application) to
* communicate to the XADC/ADC device.
*
* XAdcPs_CfgInitialize() API is used to initialize the XADC/ADC
* device. The user needs to first call the XAdcPs_LookupConfig() API which
* returns the Configuration structure pointer which is passed as a parameter to
* the XAdcPs_CfgInitialize() API.
*
*
* <b>Interrupts</b>
*
* The XADC/ADC device supports interrupt driven mode and the default
* operation mode is polling mode.
*
* The interrupt mode is available only if hardware is configured to support
* interrupts.
*
* This driver does not provide a Interrupt Service Routine (ISR) for the device.
* It is the responsibility of the application to provide one if needed. Refer to
* the interrupt example provided with this driver for details on using the
* device in interrupt mode.
*
*
* <b> Virtual Memory </b>
*
* This driver supports Virtual Memory. The RTOS is responsible for calculating
* the correct device base address in Virtual Memory space.
*
*
* <b> Threads </b>
*
* This driver is not thread safe. Any needs for threads or thread mutual
* exclusion must be satisfied by the layer above this driver.
*
*
* <b> Asserts </b>
*
* Asserts are used within all Xilinx drivers to enforce constraints on argument
* values. Asserts can be turned off on a system-wide basis by defining, at
* compile time, the NDEBUG identifier. By default, asserts are turned on and it
* is recommended that users leave asserts on during development.
*
*
* <b> Building the driver </b>
*
* The XAdcPs driver is composed of several source files. This allows the user
* to build and link only those parts of the driver that are necessary.
*
* <b> Limitations of the driver </b>
*
* XADC/ADC device can be accessed through the JTAG port and the PLB
* interface. The driver implementation does not support the simultaneous access
* of the device by both these interfaces. The user has to care of this situation
* in the user application code.
*
* <br><br>
*
* <pre>
*
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- ----- -------- -----------------------------------------------------
* 1.00a ssb 12/22/11 First release based on the XPS/AXI xadc driver
* 1.01a bss 02/18/13 Modified XAdcPs_SetSeqChEnables,XAdcPs_SetSeqAvgEnables
* XAdcPs_SetSeqInputMode and XAdcPs_SetSeqAcqTime APIs
* in xadcps.c to fix CR #693371
* </pre>
*
*****************************************************************************/
#ifndef XADCPS_H /* Prevent circular inclusions */
#define XADCPS_H /* by using protection macros */
#ifdef __cplusplus
extern "C" {
#endif
/***************************** Include Files ********************************/
#include "xil_types.h"
#include "xil_assert.h"
#include "xstatus.h"
#include "xadcps_hw.h"
/************************** Constant Definitions ****************************/
/**
* @name Indexes for the different channels.
* @{
*/
#define XADCPS_CH_TEMP 0x0 /**< On Chip Temperature */
#define XADCPS_CH_VCCINT 0x1 /**< VCCINT */
#define XADCPS_CH_VCCAUX 0x2 /**< VCCAUX */
#define XADCPS_CH_VPVN 0x3 /**< VP/VN Dedicated analog inputs */
#define XADCPS_CH_VREFP 0x4 /**< VREFP */
#define XADCPS_CH_VREFN 0x5 /**< VREFN */
#define XADCPS_CH_VBRAM 0x6 /**< On-chip VBRAM Data Reg, 7 series */
#define XADCPS_CH_SUPPLY_CALIB 0x07 /**< Supply Calib Data Reg */
#define XADCPS_CH_ADC_CALIB 0x08 /**< ADC Offset Channel Reg */
#define XADCPS_CH_GAINERR_CALIB 0x09 /**< Gain Error Channel Reg */
#define XADCPS_CH_VCCPINT 0x0D /**< On-chip PS VCCPINT Channel , Zynq */
#define XADCPS_CH_VCCPAUX 0x0E /**< On-chip PS VCCPAUX Channel , Zynq */
#define XADCPS_CH_VCCPDRO 0x0F /**< On-chip PS VCCPDRO Channel , Zynq */
#define XADCPS_CH_AUX_MIN 16 /**< Channel number for 1st Aux Channel */
#define XADCPS_CH_AUX_MAX 31 /**< Channel number for Last Aux channel */
/*@}*/
/**
* @name Indexes for reading the Calibration Coefficient Data.
* @{
*/
#define XADCPS_CALIB_SUPPLY_COEFF 0 /**< Supply Offset Calib Coefficient */
#define XADCPS_CALIB_ADC_COEFF 1 /**< ADC Offset Calib Coefficient */
#define XADCPS_CALIB_GAIN_ERROR_COEFF 2 /**< Gain Error Calib Coefficient*/
/*@}*/
/**
* @name Indexes for reading the Minimum/Maximum Measurement Data.
* @{
*/
#define XADCPS_MAX_TEMP 0 /**< Maximum Temperature Data */
#define XADCPS_MAX_VCCINT 1 /**< Maximum VCCINT Data */
#define XADCPS_MAX_VCCAUX 2 /**< Maximum VCCAUX Data */
#define XADCPS_MAX_VBRAM 3 /**< Maximum VBRAM Data */
#define XADCPS_MIN_TEMP 4 /**< Minimum Temperature Data */
#define XADCPS_MIN_VCCINT 5 /**< Minimum VCCINT Data */
#define XADCPS_MIN_VCCAUX 6 /**< Minimum VCCAUX Data */
#define XADCPS_MIN_VBRAM 7 /**< Minimum VBRAM Data */
#define XADCPS_MAX_VCCPINT 8 /**< Maximum VCCPINT Register , Zynq */
#define XADCPS_MAX_VCCPAUX 9 /**< Maximum VCCPAUX Register , Zynq */
#define XADCPS_MAX_VCCPDRO 0xA /**< Maximum VCCPDRO Register , Zynq */
#define XADCPS_MIN_VCCPINT 0xC /**< Minimum VCCPINT Register , Zynq */
#define XADCPS_MIN_VCCPAUX 0xD /**< Minimum VCCPAUX Register , Zynq */
#define XADCPS_MIN_VCCPDRO 0xE /**< Minimum VCCPDRO Register , Zynq */
/*@}*/
/**
* @name Alarm Threshold(Limit) Register (ATR) indexes.
* @{
*/
#define XADCPS_ATR_TEMP_UPPER 0 /**< High user Temperature */
#define XADCPS_ATR_VCCINT_UPPER 1 /**< VCCINT high voltage limit register */
#define XADCPS_ATR_VCCAUX_UPPER 2 /**< VCCAUX high voltage limit register */
#define XADCPS_ATR_OT_UPPER 3 /**< VCCAUX high voltage limit register */
#define XADCPS_ATR_TEMP_LOWER 4 /**< Upper Over Temperature limit Reg */
#define XADCPS_ATR_VCCINT_LOWER 5 /**< VCCINT high voltage limit register */
#define XADCPS_ATR_VCCAUX_LOWER 6 /**< VCCAUX low voltage limit register */
#define XADCPS_ATR_OT_LOWER 7 /**< Lower Over Temperature limit */
#define XADCPS_ATR_VBRAM_UPPER_ 8 /**< VRBAM Upper Alarm Reg, 7 Series */
#define XADCPS_ATR_VCCPINT_UPPER 9 /**< VCCPINT Upper Alarm Reg, Zynq */
#define XADCPS_ATR_VCCPAUX_UPPER 0xA /**< VCCPAUX Upper Alarm Reg, Zynq */
#define XADCPS_ATR_VCCPDRO_UPPER 0xB /**< VCCPDRO Upper Alarm Reg, Zynq */
#define XADCPS_ATR_VBRAM_LOWER 0xC /**< VRBAM Lower Alarm Reg, 7 Series */
#define XADCPS_ATR_VCCPINT_LOWER 0xD /**< VCCPINT Lower Alarm Reg , Zynq */
#define XADCPS_ATR_VCCPAUX_LOWER 0xE /**< VCCPAUX Lower Alarm Reg , Zynq */
#define XADCPS_ATR_VCCPDRO_LOWER 0xF /**< VCCPDRO Lower Alarm Reg , Zynq */
/*@}*/
/**
* @name Averaging to be done for the channels.
* @{
*/
#define XADCPS_AVG_0_SAMPLES 0 /**< No Averaging */
#define XADCPS_AVG_16_SAMPLES 1 /**< Average 16 samples */
#define XADCPS_AVG_64_SAMPLES 2 /**< Average 64 samples */
#define XADCPS_AVG_256_SAMPLES 3 /**< Average 256 samples */
/*@}*/
/**
* @name Channel Sequencer Modes of operation
* @{
*/
#define XADCPS_SEQ_MODE_SAFE 0 /**< Default Safe Mode */
#define XADCPS_SEQ_MODE_ONEPASS 1 /**< Onepass through Sequencer */
#define XADCPS_SEQ_MODE_CONTINPASS 2 /**< Continuous Cycling Sequencer */
#define XADCPS_SEQ_MODE_SINGCHAN 3 /**< Single channel -No Sequencing */
#define XADCPS_SEQ_MODE_SIMUL_SAMPLING 4 /**< Simultaneous sampling */
#define XADCPS_SEQ_MODE_INDEPENDENT 8 /**< Independent mode */
/*@}*/
/**
* @name Power Down Modes
* @{
*/
#define XADCPS_PD_MODE_NONE 0 /**< No Power Down */
#define XADCPS_PD_MODE_ADCB 1 /**< Power Down ADC B */
#define XADCPS_PD_MODE_XADC 2 /**< Power Down ADC A and ADC B */
/*@}*/
/**************************** Type Definitions ******************************/
/**
* This typedef contains configuration information for the XADC/ADC
* device.
*/
typedef struct {
u16 DeviceId; /**< Unique ID of device */
u32 BaseAddress; /**< Device base address */
} XAdcPs_Config;
/**
* The driver's instance data. The user is required to allocate a variable
* of this type for every XADC/ADC device in the system. A pointer to
* a variable of this type is then passed to the driver API functions.
*/
typedef struct {
XAdcPs_Config Config; /**< XAdcPs_Config of current device */
u32 IsReady; /**< Device is initialized and ready */
} XAdcPs;
/***************** Macros (Inline Functions) Definitions ********************/
/****************************************************************************/
/**
*
* This macro checks if the XADC device is in Event Sampling mode.
*
* @param InstancePtr is a pointer to the XAdcPs instance.
*
* @return
* - TRUE if the device is in Event Sampling Mode.
* - FALSE if the device is in Continuous Sampling Mode.
*
* @note C-Style signature:
* int XAdcPs_IsEventSamplingMode(XAdcPs *InstancePtr);
*
*****************************************************************************/
#define XAdcPs_IsEventSamplingModeSet(InstancePtr) \
(((XAdcPs_ReadInternalReg(InstancePtr, \
XADCPS_CFR0_OFFSET) & XADCPS_CFR0_EC_MASK) ? \
TRUE : FALSE))
/****************************************************************************/
/**
*
* This macro checks if the XADC device is in External Mux mode.
*
* @param InstancePtr is a pointer to the XAdcPs instance.
*
* @return
* - TRUE if the device is in External Mux Mode.
* - FALSE if the device is NOT in External Mux Mode.
*
* @note C-Style signature:
* int XAdcPs_IsExternalMuxMode(XAdcPs *InstancePtr);
*
*****************************************************************************/
#define XAdcPs_IsExternalMuxModeSet(InstancePtr) \
(((XAdcPs_ReadInternalReg(InstancePtr, \
XADCPS_CFR0_OFFSET) & XADCPS_CFR0_MUX_MASK) ? \
TRUE : FALSE))
/****************************************************************************/
/**
*
* This macro converts XADC Raw Data to Temperature(centigrades).
*
* @param AdcData is the Raw ADC Data from XADC.
*
* @return The Temperature in centigrades.
*
* @note C-Style signature:
* float XAdcPs_RawToTemperature(u32 AdcData);
*
*****************************************************************************/
#define XAdcPs_RawToTemperature(AdcData) \
((((float)(AdcData)/65536.0f)/0.00198421639f ) - 273.15f)
/****************************************************************************/
/**
*
* This macro converts XADC/ADC Raw Data to Voltage(volts).
*
* @param AdcData is the XADC/ADC Raw Data.
*
* @return The Voltage in volts.
*
* @note C-Style signature:
* float XAdcPs_RawToVoltage(u32 AdcData);
*
*****************************************************************************/
#define XAdcPs_RawToVoltage(AdcData) \
((((float)(AdcData))* (3.0f))/65536.0f)
/****************************************************************************/
/**
*
* This macro converts Temperature in centigrades to XADC/ADC Raw Data.
*
* @param Temperature is the Temperature in centigrades to be
* converted to XADC/ADC Raw Data.
*
* @return The XADC/ADC Raw Data.
*
* @note C-Style signature:
* int XAdcPs_TemperatureToRaw(float Temperature);
*
*****************************************************************************/
#define XAdcPs_TemperatureToRaw(Temperature) \
((int)(((Temperature) + 273.15f)*65536.0f*0.00198421639f))
/****************************************************************************/
/**
*
* This macro converts Voltage in Volts to XADC/ADC Raw Data.
*
* @param Voltage is the Voltage in volts to be converted to
* XADC/ADC Raw Data.
*
* @return The XADC/ADC Raw Data.
*
* @note C-Style signature:
* int XAdcPs_VoltageToRaw(float Voltage);
*
*****************************************************************************/
#define XAdcPs_VoltageToRaw(Voltage) \
((int)((Voltage)*65536.0f/3.0f))
/****************************************************************************/
/**
*
* This macro is used for writing to the XADC Registers using the
* command FIFO.
*
* @param InstancePtr is a pointer to the XAdcPs instance.
*
* @return None.
*
* @note C-Style signature:
* void XAdcPs_WriteFifo(XAdcPs *InstancePtr, u32 Data);
*
*****************************************************************************/
#define XAdcPs_WriteFifo(InstancePtr, Data) \
XAdcPs_WriteReg((InstancePtr)->Config.BaseAddress, \
XADCPS_CMDFIFO_OFFSET, Data);
/****************************************************************************/
/**
*
* This macro is used for reading from the XADC Registers using the
* data FIFO.
*
* @param InstancePtr is a pointer to the XAdcPs instance.
*
* @return Data read from the FIFO
*
* @note C-Style signature:
* u32 XAdcPs_ReadFifo(XAdcPs *InstancePtr);
*
*****************************************************************************/
#define XAdcPs_ReadFifo(InstancePtr) \
XAdcPs_ReadReg((InstancePtr)->Config.BaseAddress, \
XADCPS_RDFIFO_OFFSET);
/************************** Function Prototypes *****************************/
/**
* Functions in xadcps_sinit.c
*/
XAdcPs_Config *XAdcPs_LookupConfig(u16 DeviceId);
/**
* Functions in xadcps.c
*/
int XAdcPs_CfgInitialize(XAdcPs *InstancePtr,
XAdcPs_Config *ConfigPtr,
u32 EffectiveAddr);
u32 XAdcPs_GetStatus(XAdcPs *InstancePtr);
u32 XAdcPs_GetAlarmOutputStatus(XAdcPs *InstancePtr);
void XAdcPs_StartAdcConversion(XAdcPs *InstancePtr);
void XAdcPs_Reset(XAdcPs *InstancePtr);
u16 XAdcPs_GetAdcData(XAdcPs *InstancePtr, u8 Channel);
u16 XAdcPs_GetCalibCoefficient(XAdcPs *InstancePtr, u8 CoeffType);
u16 XAdcPs_GetMinMaxMeasurement(XAdcPs *InstancePtr, u8 MeasurementType);
void XAdcPs_SetAvg(XAdcPs *InstancePtr, u8 Average);
u8 XAdcPs_GetAvg(XAdcPs *InstancePtr);
int XAdcPs_SetSingleChParams(XAdcPs *InstancePtr,
u8 Channel,
int IncreaseAcqCycles,
int IsEventMode,
int IsDifferentialMode);
void XAdcPs_SetAlarmEnables(XAdcPs *InstancePtr, u16 AlmEnableMask);
u16 XAdcPs_GetAlarmEnables(XAdcPs *InstancePtr);
void XAdcPs_SetCalibEnables(XAdcPs *InstancePtr, u16 Calibration);
u16 XAdcPs_GetCalibEnables(XAdcPs *InstancePtr);
void XAdcPs_SetSequencerMode(XAdcPs *InstancePtr, u8 SequencerMode);
u8 XAdcPs_GetSequencerMode(XAdcPs *InstancePtr);
void XAdcPs_SetAdcClkDivisor(XAdcPs *InstancePtr, u8 Divisor);
u8 XAdcPs_GetAdcClkDivisor(XAdcPs *InstancePtr);
int XAdcPs_SetSeqChEnables(XAdcPs *InstancePtr, u32 ChEnableMask);
u32 XAdcPs_GetSeqChEnables(XAdcPs *InstancePtr);
int XAdcPs_SetSeqAvgEnables(XAdcPs *InstancePtr, u32 AvgEnableChMask);
u32 XAdcPs_GetSeqAvgEnables(XAdcPs *InstancePtr);
int XAdcPs_SetSeqInputMode(XAdcPs *InstancePtr, u32 InputModeChMask);
u32 XAdcPs_GetSeqInputMode(XAdcPs *InstancePtr);
int XAdcPs_SetSeqAcqTime(XAdcPs *InstancePtr, u32 AcqCyclesChMask);
u32 XAdcPs_GetSeqAcqTime(XAdcPs *InstancePtr);
void XAdcPs_SetAlarmThreshold(XAdcPs *InstancePtr, u8 AlarmThrReg, u16 Value);
u16 XAdcPs_GetAlarmThreshold(XAdcPs *InstancePtr, u8 AlarmThrReg);
void XAdcPs_EnableUserOverTemp(XAdcPs *InstancePtr);
void XAdcPs_DisableUserOverTemp(XAdcPs *InstancePtr);
/**
* Functions in xadcps_selftest.c
*/
int XAdcPs_SelfTest(XAdcPs *InstancePtr);
/**
* Functions in xadcps_intr.c
*/
void XAdcPs_IntrEnable(XAdcPs *InstancePtr, u32 Mask);
void XAdcPs_IntrDisable(XAdcPs *InstancePtr, u32 Mask);
u32 XAdcPs_IntrGetEnabled(XAdcPs *InstancePtr);
u32 XAdcPs_IntrGetStatus(XAdcPs *InstancePtr);
void XAdcPs_IntrClear(XAdcPs *InstancePtr, u32 Mask);
#ifdef __cplusplus
}
#endif
#endif /* End of protection macro. */
| starsoc/u-boot-star-x7 | zynq/include/xadcps.h | C | gpl-2.0 | 20,131 |
/*
lm85.c - Part of lm_sensors, Linux kernel modules for hardware
monitoring
Copyright (c) 1998, 1999 Frodo Looijaard <[email protected]>
Copyright (c) 2002, 2003 Philip Pokorny <[email protected]>
Copyright (c) 2003 Margit Schubert-While <[email protected]>
Copyright (c) 2004 Justin Thiessen <[email protected]>
Chip details at <http://www.national.com/ds/LM/LM85.pdf>
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.
*/
#include <linux/config.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/i2c-sensor.h>
#include <linux/i2c-vid.h>
/* Addresses to scan */
static unsigned short normal_i2c[] = { 0x2c, 0x2d, 0x2e, I2C_CLIENT_END };
static unsigned int normal_isa[] = { I2C_CLIENT_ISA_END };
/* Insmod parameters */
SENSORS_INSMOD_6(lm85b, lm85c, adm1027, adt7463, emc6d100, emc6d102);
/* The LM85 registers */
#define LM85_REG_IN(nr) (0x20 + (nr))
#define LM85_REG_IN_MIN(nr) (0x44 + (nr) * 2)
#define LM85_REG_IN_MAX(nr) (0x45 + (nr) * 2)
#define LM85_REG_TEMP(nr) (0x25 + (nr))
#define LM85_REG_TEMP_MIN(nr) (0x4e + (nr) * 2)
#define LM85_REG_TEMP_MAX(nr) (0x4f + (nr) * 2)
/* Fan speeds are LSB, MSB (2 bytes) */
#define LM85_REG_FAN(nr) (0x28 + (nr) *2)
#define LM85_REG_FAN_MIN(nr) (0x54 + (nr) *2)
#define LM85_REG_PWM(nr) (0x30 + (nr))
#define ADT7463_REG_OPPOINT(nr) (0x33 + (nr))
#define ADT7463_REG_TMIN_CTL1 0x36
#define ADT7463_REG_TMIN_CTL2 0x37
#define LM85_REG_DEVICE 0x3d
#define LM85_REG_COMPANY 0x3e
#define LM85_REG_VERSTEP 0x3f
/* These are the recognized values for the above regs */
#define LM85_DEVICE_ADX 0x27
#define LM85_COMPANY_NATIONAL 0x01
#define LM85_COMPANY_ANALOG_DEV 0x41
#define LM85_COMPANY_SMSC 0x5c
#define LM85_VERSTEP_VMASK 0xf0
#define LM85_VERSTEP_GENERIC 0x60
#define LM85_VERSTEP_LM85C 0x60
#define LM85_VERSTEP_LM85B 0x62
#define LM85_VERSTEP_ADM1027 0x60
#define LM85_VERSTEP_ADT7463 0x62
#define LM85_VERSTEP_ADT7463C 0x6A
#define LM85_VERSTEP_EMC6D100_A0 0x60
#define LM85_VERSTEP_EMC6D100_A1 0x61
#define LM85_VERSTEP_EMC6D102 0x65
#define LM85_REG_CONFIG 0x40
#define LM85_REG_ALARM1 0x41
#define LM85_REG_ALARM2 0x42
#define LM85_REG_VID 0x43
/* Automated FAN control */
#define LM85_REG_AFAN_CONFIG(nr) (0x5c + (nr))
#define LM85_REG_AFAN_RANGE(nr) (0x5f + (nr))
#define LM85_REG_AFAN_SPIKE1 0x62
#define LM85_REG_AFAN_SPIKE2 0x63
#define LM85_REG_AFAN_MINPWM(nr) (0x64 + (nr))
#define LM85_REG_AFAN_LIMIT(nr) (0x67 + (nr))
#define LM85_REG_AFAN_CRITICAL(nr) (0x6a + (nr))
#define LM85_REG_AFAN_HYST1 0x6d
#define LM85_REG_AFAN_HYST2 0x6e
#define LM85_REG_TACH_MODE 0x74
#define LM85_REG_SPINUP_CTL 0x75
#define ADM1027_REG_TEMP_OFFSET(nr) (0x70 + (nr))
#define ADM1027_REG_CONFIG2 0x73
#define ADM1027_REG_INTMASK1 0x74
#define ADM1027_REG_INTMASK2 0x75
#define ADM1027_REG_EXTEND_ADC1 0x76
#define ADM1027_REG_EXTEND_ADC2 0x77
#define ADM1027_REG_CONFIG3 0x78
#define ADM1027_REG_FAN_PPR 0x7b
#define ADT7463_REG_THERM 0x79
#define ADT7463_REG_THERM_LIMIT 0x7A
#define EMC6D100_REG_ALARM3 0x7d
/* IN5, IN6 and IN7 */
#define EMC6D100_REG_IN(nr) (0x70 + ((nr)-5))
#define EMC6D100_REG_IN_MIN(nr) (0x73 + ((nr)-5) * 2)
#define EMC6D100_REG_IN_MAX(nr) (0x74 + ((nr)-5) * 2)
#define EMC6D102_REG_EXTEND_ADC1 0x85
#define EMC6D102_REG_EXTEND_ADC2 0x86
#define EMC6D102_REG_EXTEND_ADC3 0x87
#define EMC6D102_REG_EXTEND_ADC4 0x88
#define LM85_ALARM_IN0 0x0001
#define LM85_ALARM_IN1 0x0002
#define LM85_ALARM_IN2 0x0004
#define LM85_ALARM_IN3 0x0008
#define LM85_ALARM_TEMP1 0x0010
#define LM85_ALARM_TEMP2 0x0020
#define LM85_ALARM_TEMP3 0x0040
#define LM85_ALARM_ALARM2 0x0080
#define LM85_ALARM_IN4 0x0100
#define LM85_ALARM_RESERVED 0x0200
#define LM85_ALARM_FAN1 0x0400
#define LM85_ALARM_FAN2 0x0800
#define LM85_ALARM_FAN3 0x1000
#define LM85_ALARM_FAN4 0x2000
#define LM85_ALARM_TEMP1_FAULT 0x4000
#define LM85_ALARM_TEMP3_FAULT 0x8000
/* Conversions. Rounding and limit checking is only done on the TO_REG
variants. Note that you should be a bit careful with which arguments
these macros are called: arguments may be evaluated more than once.
*/
/* IN are scaled acording to built-in resistors */
static int lm85_scaling[] = { /* .001 Volts */
2500, 2250, 3300, 5000, 12000,
3300, 1500, 1800 /*EMC6D100*/
};
#define SCALE(val,from,to) (((val)*(to) + ((from)/2))/(from))
#define INS_TO_REG(n,val) \
SENSORS_LIMIT(SCALE(val,lm85_scaling[n],192),0,255)
#define INSEXT_FROM_REG(n,val,ext,scale) \
SCALE((val)*(scale) + (ext),192*(scale),lm85_scaling[n])
#define INS_FROM_REG(n,val) INSEXT_FROM_REG(n,val,0,1)
/* FAN speed is measured using 90kHz clock */
#define FAN_TO_REG(val) (SENSORS_LIMIT( (val)<=0?0: 5400000/(val),0,65534))
#define FAN_FROM_REG(val) ((val)==0?-1:(val)==0xffff?0:5400000/(val))
/* Temperature is reported in .001 degC increments */
#define TEMP_TO_REG(val) \
SENSORS_LIMIT(SCALE(val,1000,1),-127,127)
#define TEMPEXT_FROM_REG(val,ext,scale) \
SCALE((val)*scale + (ext),scale,1000)
#define TEMP_FROM_REG(val) \
TEMPEXT_FROM_REG(val,0,1)
#define PWM_TO_REG(val) (SENSORS_LIMIT(val,0,255))
#define PWM_FROM_REG(val) (val)
/* ZONEs have the following parameters:
* Limit (low) temp, 1. degC
* Hysteresis (below limit), 1. degC (0-15)
* Range of speed control, .1 degC (2-80)
* Critical (high) temp, 1. degC
*
* FAN PWMs have the following parameters:
* Reference Zone, 1, 2, 3, etc.
* Spinup time, .05 sec
* PWM value at limit/low temp, 1 count
* PWM Frequency, 1. Hz
* PWM is Min or OFF below limit, flag
* Invert PWM output, flag
*
* Some chips filter the temp, others the fan.
* Filter constant (or disabled) .1 seconds
*/
/* These are the zone temperature range encodings in .001 degree C */
static int lm85_range_map[] = {
2000, 2500, 3300, 4000, 5000, 6600,
8000, 10000, 13300, 16000, 20000, 26600,
32000, 40000, 53300, 80000
};
static int RANGE_TO_REG( int range )
{
int i;
if ( range < lm85_range_map[0] ) {
return 0 ;
} else if ( range > lm85_range_map[15] ) {
return 15 ;
} else { /* find closest match */
for ( i = 14 ; i >= 0 ; --i ) {
if ( range > lm85_range_map[i] ) { /* range bracketed */
if ((lm85_range_map[i+1] - range) <
(range - lm85_range_map[i])) {
i++;
break;
}
break;
}
}
}
return( i & 0x0f );
}
#define RANGE_FROM_REG(val) (lm85_range_map[(val)&0x0f])
/* These are the Acoustic Enhancement, or Temperature smoothing encodings
* NOTE: The enable/disable bit is INCLUDED in these encodings as the
* MSB (bit 3, value 8). If the enable bit is 0, the encoded value
* is ignored, or set to 0.
*/
/* These are the PWM frequency encodings */
static int lm85_freq_map[] = { /* .1 Hz */
100, 150, 230, 300, 380, 470, 620, 940
};
static int FREQ_TO_REG( int freq )
{
int i;
if( freq >= lm85_freq_map[7] ) { return 7 ; }
for( i = 0 ; i < 7 ; ++i )
if( freq <= lm85_freq_map[i] )
break ;
return( i & 0x07 );
}
#define FREQ_FROM_REG(val) (lm85_freq_map[(val)&0x07])
/* Since we can't use strings, I'm abusing these numbers
* to stand in for the following meanings:
* 1 -- PWM responds to Zone 1
* 2 -- PWM responds to Zone 2
* 3 -- PWM responds to Zone 3
* 23 -- PWM responds to the higher temp of Zone 2 or 3
* 123 -- PWM responds to highest of Zone 1, 2, or 3
* 0 -- PWM is always at 0% (ie, off)
* -1 -- PWM is always at 100%
* -2 -- PWM responds to manual control
*/
static int lm85_zone_map[] = { 1, 2, 3, -1, 0, 23, 123, -2 };
#define ZONE_FROM_REG(val) (lm85_zone_map[((val)>>5)&0x07])
static int ZONE_TO_REG( int zone )
{
int i;
for( i = 0 ; i <= 7 ; ++i )
if( zone == lm85_zone_map[i] )
break ;
if( i > 7 ) /* Not found. */
i = 3; /* Always 100% */
return( (i & 0x07)<<5 );
}
#define HYST_TO_REG(val) (SENSORS_LIMIT(((val)+500)/1000,0,15))
#define HYST_FROM_REG(val) ((val)*1000)
#define OFFSET_TO_REG(val) (SENSORS_LIMIT((val)/25,-127,127))
#define OFFSET_FROM_REG(val) ((val)*25)
#define PPR_MASK(fan) (0x03<<(fan *2))
#define PPR_TO_REG(val,fan) (SENSORS_LIMIT((val)-1,0,3)<<(fan *2))
#define PPR_FROM_REG(val,fan) ((((val)>>(fan * 2))&0x03)+1)
/* i2c-vid.h defines vid_from_reg() */
#define VID_FROM_REG(val,vrm) (vid_from_reg((val),(vrm)))
#define ALARMS_FROM_REG(val) (val)
/* Unlike some other drivers we DO NOT set initial limits. Use
* the config file to set limits. Some users have reported
* motherboards shutting down when we set limits in a previous
* version of the driver.
*/
/* Chip sampling rates
*
* Some sensors are not updated more frequently than once per second
* so it doesn't make sense to read them more often than that.
* We cache the results and return the saved data if the driver
* is called again before a second has elapsed.
*
* Also, there is significant configuration data for this chip
* given the automatic PWM fan control that is possible. There
* are about 47 bytes of config data to only 22 bytes of actual
* readings. So, we keep the config data up to date in the cache
* when it is written and only sample it once every 1 *minute*
*/
#define LM85_DATA_INTERVAL (HZ + HZ / 2)
#define LM85_CONFIG_INTERVAL (1 * 60 * HZ)
/* For each registered LM85, we need to keep some data in memory. That
data is pointed to by lm85_list[NR]->data. The structure itself is
dynamically allocated, at the same time when a new lm85 client is
allocated. */
/* LM85 can automatically adjust fan speeds based on temperature
* This structure encapsulates an entire Zone config. There are
* three zones (one for each temperature input) on the lm85
*/
struct lm85_zone {
s8 limit; /* Low temp limit */
u8 hyst; /* Low limit hysteresis. (0-15) */
u8 range; /* Temp range, encoded */
s8 critical; /* "All fans ON" temp limit */
u8 off_desired; /* Actual "off" temperature specified. Preserved
* to prevent "drift" as other autofan control
* values change.
*/
u8 max_desired; /* Actual "max" temperature specified. Preserved
* to prevent "drift" as other autofan control
* values change.
*/
};
struct lm85_autofan {
u8 config; /* Register value */
u8 freq; /* PWM frequency, encoded */
u8 min_pwm; /* Minimum PWM value, encoded */
u8 min_off; /* Min PWM or OFF below "limit", flag */
};
struct lm85_data {
struct i2c_client client;
struct semaphore lock;
enum chips type;
struct semaphore update_lock;
int valid; /* !=0 if following fields are valid */
unsigned long last_reading; /* In jiffies */
unsigned long last_config; /* In jiffies */
u8 in[8]; /* Register value */
u8 in_max[8]; /* Register value */
u8 in_min[8]; /* Register value */
s8 temp[3]; /* Register value */
s8 temp_min[3]; /* Register value */
s8 temp_max[3]; /* Register value */
s8 temp_offset[3]; /* Register value */
u16 fan[4]; /* Register value */
u16 fan_min[4]; /* Register value */
u8 pwm[3]; /* Register value */
u8 spinup_ctl; /* Register encoding, combined */
u8 tach_mode; /* Register encoding, combined */
u8 temp_ext[3]; /* Decoded values */
u8 in_ext[8]; /* Decoded values */
u8 adc_scale; /* ADC Extended bits scaling factor */
u8 fan_ppr; /* Register value */
u8 smooth[3]; /* Register encoding */
u8 vid; /* Register value */
u8 vrm; /* VRM version */
u8 syncpwm3; /* Saved PWM3 for TACH 2,3,4 config */
u8 oppoint[3]; /* Register value */
u16 tmin_ctl; /* Register value */
unsigned long therm_total; /* Cummulative therm count */
u8 therm_limit; /* Register value */
u32 alarms; /* Register encoding, combined */
struct lm85_autofan autofan[3];
struct lm85_zone zone[3];
};
static int lm85_attach_adapter(struct i2c_adapter *adapter);
static int lm85_detect(struct i2c_adapter *adapter, int address,
int kind);
static int lm85_detach_client(struct i2c_client *client);
static int lm85_read_value(struct i2c_client *client, u8 register);
static int lm85_write_value(struct i2c_client *client, u8 register, int value);
static struct lm85_data *lm85_update_device(struct device *dev);
static void lm85_init_client(struct i2c_client *client);
static struct i2c_driver lm85_driver = {
.owner = THIS_MODULE,
.name = "lm85",
.id = I2C_DRIVERID_LM85,
.flags = I2C_DF_NOTIFY,
.attach_adapter = lm85_attach_adapter,
.detach_client = lm85_detach_client,
};
/* 4 Fans */
static ssize_t show_fan(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", FAN_FROM_REG(data->fan[nr]) );
}
static ssize_t show_fan_min(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", FAN_FROM_REG(data->fan_min[nr]) );
}
static ssize_t set_fan_min(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->fan_min[nr] = FAN_TO_REG(val);
lm85_write_value(client, LM85_REG_FAN_MIN(nr), data->fan_min[nr]);
up(&data->update_lock);
return count;
}
#define show_fan_offset(offset) \
static ssize_t show_fan_##offset (struct device *dev, char *buf) \
{ \
return show_fan(dev, buf, offset - 1); \
} \
static ssize_t show_fan_##offset##_min (struct device *dev, char *buf) \
{ \
return show_fan_min(dev, buf, offset - 1); \
} \
static ssize_t set_fan_##offset##_min (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_fan_min(dev, buf, count, offset - 1); \
} \
static DEVICE_ATTR(fan##offset##_input, S_IRUGO, show_fan_##offset, \
NULL); \
static DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
show_fan_##offset##_min, set_fan_##offset##_min);
show_fan_offset(1);
show_fan_offset(2);
show_fan_offset(3);
show_fan_offset(4);
/* vid, vrm, alarms */
static ssize_t show_vid_reg(struct device *dev, char *buf)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf, "%ld\n", (long) vid_from_reg(data->vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid_reg, NULL);
static ssize_t show_vrm_reg(struct device *dev, char *buf)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->vrm);
}
static ssize_t store_vrm_reg(struct device *dev, const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
u32 val;
val = simple_strtoul(buf, NULL, 10);
data->vrm = val;
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm_reg, store_vrm_reg);
static ssize_t show_alarms_reg(struct device *dev, char *buf)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf, "%ld\n", (long) ALARMS_FROM_REG(data->alarms));
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms_reg, NULL);
/* pwm */
static ssize_t show_pwm(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", PWM_FROM_REG(data->pwm[nr]) );
}
static ssize_t set_pwm(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->pwm[nr] = PWM_TO_REG(val);
lm85_write_value(client, LM85_REG_PWM(nr), data->pwm[nr]);
up(&data->update_lock);
return count;
}
static ssize_t show_pwm_enable(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
int pwm_zone;
pwm_zone = ZONE_FROM_REG(data->autofan[nr].config);
return sprintf(buf,"%d\n", (pwm_zone != 0 && pwm_zone != -1) );
}
#define show_pwm_reg(offset) \
static ssize_t show_pwm_##offset (struct device *dev, char *buf) \
{ \
return show_pwm(dev, buf, offset - 1); \
} \
static ssize_t set_pwm_##offset (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_pwm(dev, buf, count, offset - 1); \
} \
static ssize_t show_pwm_enable##offset (struct device *dev, char *buf) \
{ \
return show_pwm_enable(dev, buf, offset - 1); \
} \
static DEVICE_ATTR(pwm##offset, S_IRUGO | S_IWUSR, \
show_pwm_##offset, set_pwm_##offset); \
static DEVICE_ATTR(pwm##offset##_enable, S_IRUGO, \
show_pwm_enable##offset, NULL);
show_pwm_reg(1);
show_pwm_reg(2);
show_pwm_reg(3);
/* Voltages */
static ssize_t show_in(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf( buf, "%d\n", INSEXT_FROM_REG(nr,
data->in[nr],
data->in_ext[nr],
data->adc_scale) );
}
static ssize_t show_in_min(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", INS_FROM_REG(nr, data->in_min[nr]) );
}
static ssize_t set_in_min(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->in_min[nr] = INS_TO_REG(nr, val);
lm85_write_value(client, LM85_REG_IN_MIN(nr), data->in_min[nr]);
up(&data->update_lock);
return count;
}
static ssize_t show_in_max(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", INS_FROM_REG(nr, data->in_max[nr]) );
}
static ssize_t set_in_max(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->in_max[nr] = INS_TO_REG(nr, val);
lm85_write_value(client, LM85_REG_IN_MAX(nr), data->in_max[nr]);
up(&data->update_lock);
return count;
}
#define show_in_reg(offset) \
static ssize_t show_in_##offset (struct device *dev, char *buf) \
{ \
return show_in(dev, buf, offset); \
} \
static ssize_t show_in_##offset##_min (struct device *dev, char *buf) \
{ \
return show_in_min(dev, buf, offset); \
} \
static ssize_t show_in_##offset##_max (struct device *dev, char *buf) \
{ \
return show_in_max(dev, buf, offset); \
} \
static ssize_t set_in_##offset##_min (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_in_min(dev, buf, count, offset); \
} \
static ssize_t set_in_##offset##_max (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_in_max(dev, buf, count, offset); \
} \
static DEVICE_ATTR(in##offset##_input, S_IRUGO, show_in_##offset, \
NULL); \
static DEVICE_ATTR(in##offset##_min, S_IRUGO | S_IWUSR, \
show_in_##offset##_min, set_in_##offset##_min); \
static DEVICE_ATTR(in##offset##_max, S_IRUGO | S_IWUSR, \
show_in_##offset##_max, set_in_##offset##_max);
show_in_reg(0);
show_in_reg(1);
show_in_reg(2);
show_in_reg(3);
show_in_reg(4);
/* Temps */
static ssize_t show_temp(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMPEXT_FROM_REG(data->temp[nr],
data->temp_ext[nr],
data->adc_scale) );
}
static ssize_t show_temp_min(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMP_FROM_REG(data->temp_min[nr]) );
}
static ssize_t set_temp_min(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->temp_min[nr] = TEMP_TO_REG(val);
lm85_write_value(client, LM85_REG_TEMP_MIN(nr), data->temp_min[nr]);
up(&data->update_lock);
return count;
}
static ssize_t show_temp_max(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMP_FROM_REG(data->temp_max[nr]) );
}
static ssize_t set_temp_max(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->temp_max[nr] = TEMP_TO_REG(val);
lm85_write_value(client, LM85_REG_TEMP_MAX(nr), data->temp_max[nr]);
up(&data->update_lock);
return count;
}
#define show_temp_reg(offset) \
static ssize_t show_temp_##offset (struct device *dev, char *buf) \
{ \
return show_temp(dev, buf, offset - 1); \
} \
static ssize_t show_temp_##offset##_min (struct device *dev, char *buf) \
{ \
return show_temp_min(dev, buf, offset - 1); \
} \
static ssize_t show_temp_##offset##_max (struct device *dev, char *buf) \
{ \
return show_temp_max(dev, buf, offset - 1); \
} \
static ssize_t set_temp_##offset##_min (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_temp_min(dev, buf, count, offset - 1); \
} \
static ssize_t set_temp_##offset##_max (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_temp_max(dev, buf, count, offset - 1); \
} \
static DEVICE_ATTR(temp##offset##_input, S_IRUGO, show_temp_##offset, \
NULL); \
static DEVICE_ATTR(temp##offset##_min, S_IRUGO | S_IWUSR, \
show_temp_##offset##_min, set_temp_##offset##_min); \
static DEVICE_ATTR(temp##offset##_max, S_IRUGO | S_IWUSR, \
show_temp_##offset##_max, set_temp_##offset##_max);
show_temp_reg(1);
show_temp_reg(2);
show_temp_reg(3);
/* Automatic PWM control */
static ssize_t show_pwm_auto_channels(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", ZONE_FROM_REG(data->autofan[nr].config));
}
static ssize_t set_pwm_auto_channels(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->autofan[nr].config = (data->autofan[nr].config & (~0xe0))
| ZONE_TO_REG(val) ;
lm85_write_value(client, LM85_REG_AFAN_CONFIG(nr),
data->autofan[nr].config);
up(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_pwm_min(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", PWM_FROM_REG(data->autofan[nr].min_pwm));
}
static ssize_t set_pwm_auto_pwm_min(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->autofan[nr].min_pwm = PWM_TO_REG(val);
lm85_write_value(client, LM85_REG_AFAN_MINPWM(nr),
data->autofan[nr].min_pwm);
up(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_pwm_minctl(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", data->autofan[nr].min_off);
}
static ssize_t set_pwm_auto_pwm_minctl(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->autofan[nr].min_off = val;
lm85_write_value(client, LM85_REG_AFAN_SPIKE1, data->smooth[0]
| data->syncpwm3
| (data->autofan[0].min_off ? 0x20 : 0)
| (data->autofan[1].min_off ? 0x40 : 0)
| (data->autofan[2].min_off ? 0x80 : 0)
);
up(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_pwm_freq(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", FREQ_FROM_REG(data->autofan[nr].freq));
}
static ssize_t set_pwm_auto_pwm_freq(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->autofan[nr].freq = FREQ_TO_REG(val);
lm85_write_value(client, LM85_REG_AFAN_RANGE(nr),
(data->zone[nr].range << 4)
| data->autofan[nr].freq
);
up(&data->update_lock);
return count;
}
#define pwm_auto(offset) \
static ssize_t show_pwm##offset##_auto_channels (struct device *dev, \
char *buf) \
{ \
return show_pwm_auto_channels(dev, buf, offset - 1); \
} \
static ssize_t set_pwm##offset##_auto_channels (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_pwm_auto_channels(dev, buf, count, offset - 1); \
} \
static ssize_t show_pwm##offset##_auto_pwm_min (struct device *dev, \
char *buf) \
{ \
return show_pwm_auto_pwm_min(dev, buf, offset - 1); \
} \
static ssize_t set_pwm##offset##_auto_pwm_min (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_pwm_auto_pwm_min(dev, buf, count, offset - 1); \
} \
static ssize_t show_pwm##offset##_auto_pwm_minctl (struct device *dev, \
char *buf) \
{ \
return show_pwm_auto_pwm_minctl(dev, buf, offset - 1); \
} \
static ssize_t set_pwm##offset##_auto_pwm_minctl (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_pwm_auto_pwm_minctl(dev, buf, count, offset - 1); \
} \
static ssize_t show_pwm##offset##_auto_pwm_freq (struct device *dev, \
char *buf) \
{ \
return show_pwm_auto_pwm_freq(dev, buf, offset - 1); \
} \
static ssize_t set_pwm##offset##_auto_pwm_freq(struct device *dev, \
const char *buf, size_t count) \
{ \
return set_pwm_auto_pwm_freq(dev, buf, count, offset - 1); \
} \
static DEVICE_ATTR(pwm##offset##_auto_channels, S_IRUGO | S_IWUSR, \
show_pwm##offset##_auto_channels, \
set_pwm##offset##_auto_channels); \
static DEVICE_ATTR(pwm##offset##_auto_pwm_min, S_IRUGO | S_IWUSR, \
show_pwm##offset##_auto_pwm_min, \
set_pwm##offset##_auto_pwm_min); \
static DEVICE_ATTR(pwm##offset##_auto_pwm_minctl, S_IRUGO | S_IWUSR, \
show_pwm##offset##_auto_pwm_minctl, \
set_pwm##offset##_auto_pwm_minctl); \
static DEVICE_ATTR(pwm##offset##_auto_pwm_freq, S_IRUGO | S_IWUSR, \
show_pwm##offset##_auto_pwm_freq, \
set_pwm##offset##_auto_pwm_freq);
pwm_auto(1);
pwm_auto(2);
pwm_auto(3);
/* Temperature settings for automatic PWM control */
static ssize_t show_temp_auto_temp_off(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMP_FROM_REG(data->zone[nr].limit) -
HYST_FROM_REG(data->zone[nr].hyst));
}
static ssize_t set_temp_auto_temp_off(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
int min;
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
min = TEMP_FROM_REG(data->zone[nr].limit);
data->zone[nr].off_desired = TEMP_TO_REG(val);
data->zone[nr].hyst = HYST_TO_REG(min - val);
if ( nr == 0 || nr == 1 ) {
lm85_write_value(client, LM85_REG_AFAN_HYST1,
(data->zone[0].hyst << 4)
| data->zone[1].hyst
);
} else {
lm85_write_value(client, LM85_REG_AFAN_HYST2,
(data->zone[2].hyst << 4)
);
}
up(&data->update_lock);
return count;
}
static ssize_t show_temp_auto_temp_min(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMP_FROM_REG(data->zone[nr].limit) );
}
static ssize_t set_temp_auto_temp_min(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->zone[nr].limit = TEMP_TO_REG(val);
lm85_write_value(client, LM85_REG_AFAN_LIMIT(nr),
data->zone[nr].limit);
/* Update temp_auto_max and temp_auto_range */
data->zone[nr].range = RANGE_TO_REG(
TEMP_FROM_REG(data->zone[nr].max_desired) -
TEMP_FROM_REG(data->zone[nr].limit));
lm85_write_value(client, LM85_REG_AFAN_RANGE(nr),
((data->zone[nr].range & 0x0f) << 4)
| (data->autofan[nr].freq & 0x07));
/* Update temp_auto_hyst and temp_auto_off */
data->zone[nr].hyst = HYST_TO_REG(TEMP_FROM_REG(
data->zone[nr].limit) - TEMP_FROM_REG(
data->zone[nr].off_desired));
if ( nr == 0 || nr == 1 ) {
lm85_write_value(client, LM85_REG_AFAN_HYST1,
(data->zone[0].hyst << 4)
| data->zone[1].hyst
);
} else {
lm85_write_value(client, LM85_REG_AFAN_HYST2,
(data->zone[2].hyst << 4)
);
}
up(&data->update_lock);
return count;
}
static ssize_t show_temp_auto_temp_max(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMP_FROM_REG(data->zone[nr].limit) +
RANGE_FROM_REG(data->zone[nr].range));
}
static ssize_t set_temp_auto_temp_max(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
int min;
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
min = TEMP_FROM_REG(data->zone[nr].limit);
data->zone[nr].max_desired = TEMP_TO_REG(val);
data->zone[nr].range = RANGE_TO_REG(
val - min);
lm85_write_value(client, LM85_REG_AFAN_RANGE(nr),
((data->zone[nr].range & 0x0f) << 4)
| (data->autofan[nr].freq & 0x07));
up(&data->update_lock);
return count;
}
static ssize_t show_temp_auto_temp_crit(struct device *dev, char *buf, int nr)
{
struct lm85_data *data = lm85_update_device(dev);
return sprintf(buf,"%d\n", TEMP_FROM_REG(data->zone[nr].critical));
}
static ssize_t set_temp_auto_temp_crit(struct device *dev, const char *buf,
size_t count, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
down(&data->update_lock);
data->zone[nr].critical = TEMP_TO_REG(val);
lm85_write_value(client, LM85_REG_AFAN_CRITICAL(nr),
data->zone[nr].critical);
up(&data->update_lock);
return count;
}
#define temp_auto(offset) \
static ssize_t show_temp##offset##_auto_temp_off (struct device *dev, \
char *buf) \
{ \
return show_temp_auto_temp_off(dev, buf, offset - 1); \
} \
static ssize_t set_temp##offset##_auto_temp_off (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_temp_auto_temp_off(dev, buf, count, offset - 1); \
} \
static ssize_t show_temp##offset##_auto_temp_min (struct device *dev, \
char *buf) \
{ \
return show_temp_auto_temp_min(dev, buf, offset - 1); \
} \
static ssize_t set_temp##offset##_auto_temp_min (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_temp_auto_temp_min(dev, buf, count, offset - 1); \
} \
static ssize_t show_temp##offset##_auto_temp_max (struct device *dev, \
char *buf) \
{ \
return show_temp_auto_temp_max(dev, buf, offset - 1); \
} \
static ssize_t set_temp##offset##_auto_temp_max (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_temp_auto_temp_max(dev, buf, count, offset - 1); \
} \
static ssize_t show_temp##offset##_auto_temp_crit (struct device *dev, \
char *buf) \
{ \
return show_temp_auto_temp_crit(dev, buf, offset - 1); \
} \
static ssize_t set_temp##offset##_auto_temp_crit (struct device *dev, \
const char *buf, size_t count) \
{ \
return set_temp_auto_temp_crit(dev, buf, count, offset - 1); \
} \
static DEVICE_ATTR(temp##offset##_auto_temp_off, S_IRUGO | S_IWUSR, \
show_temp##offset##_auto_temp_off, \
set_temp##offset##_auto_temp_off); \
static DEVICE_ATTR(temp##offset##_auto_temp_min, S_IRUGO | S_IWUSR, \
show_temp##offset##_auto_temp_min, \
set_temp##offset##_auto_temp_min); \
static DEVICE_ATTR(temp##offset##_auto_temp_max, S_IRUGO | S_IWUSR, \
show_temp##offset##_auto_temp_max, \
set_temp##offset##_auto_temp_max); \
static DEVICE_ATTR(temp##offset##_auto_temp_crit, S_IRUGO | S_IWUSR, \
show_temp##offset##_auto_temp_crit, \
set_temp##offset##_auto_temp_crit);
temp_auto(1);
temp_auto(2);
temp_auto(3);
int lm85_attach_adapter(struct i2c_adapter *adapter)
{
if (!(adapter->class & I2C_CLASS_HWMON))
return 0;
return i2c_detect(adapter, &addr_data, lm85_detect);
}
int lm85_detect(struct i2c_adapter *adapter, int address,
int kind)
{
int company, verstep ;
struct i2c_client *new_client = NULL;
struct lm85_data *data;
int err = 0;
const char *type_name = "";
if (i2c_is_isa_adapter(adapter)) {
/* This chip has no ISA interface */
goto ERROR0 ;
};
if (!i2c_check_functionality(adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
/* We need to be able to do byte I/O */
goto ERROR0 ;
};
/* OK. For now, we presume we have a valid client. We now create the
client structure, even though we cannot fill it completely yet.
But it allows us to access lm85_{read,write}_value. */
if (!(data = kmalloc(sizeof(struct lm85_data), GFP_KERNEL))) {
err = -ENOMEM;
goto ERROR0;
}
memset(data, 0, sizeof(struct lm85_data));
new_client = &data->client;
i2c_set_clientdata(new_client, data);
new_client->addr = address;
new_client->adapter = adapter;
new_client->driver = &lm85_driver;
new_client->flags = 0;
/* Now, we do the remaining detection. */
company = lm85_read_value(new_client, LM85_REG_COMPANY);
verstep = lm85_read_value(new_client, LM85_REG_VERSTEP);
dev_dbg(&adapter->dev, "Detecting device at %d,0x%02x with"
" COMPANY: 0x%02x and VERSTEP: 0x%02x\n",
i2c_adapter_id(new_client->adapter), new_client->addr,
company, verstep);
/* If auto-detecting, Determine the chip type. */
if (kind <= 0) {
dev_dbg(&adapter->dev, "Autodetecting device at %d,0x%02x ...\n",
i2c_adapter_id(adapter), address );
if( company == LM85_COMPANY_NATIONAL
&& verstep == LM85_VERSTEP_LM85C ) {
kind = lm85c ;
} else if( company == LM85_COMPANY_NATIONAL
&& verstep == LM85_VERSTEP_LM85B ) {
kind = lm85b ;
} else if( company == LM85_COMPANY_NATIONAL
&& (verstep & LM85_VERSTEP_VMASK) == LM85_VERSTEP_GENERIC ) {
dev_err(&adapter->dev, "Unrecognized version/stepping 0x%02x"
" Defaulting to LM85.\n", verstep);
kind = any_chip ;
} else if( company == LM85_COMPANY_ANALOG_DEV
&& verstep == LM85_VERSTEP_ADM1027 ) {
kind = adm1027 ;
} else if( company == LM85_COMPANY_ANALOG_DEV
&& (verstep == LM85_VERSTEP_ADT7463
|| verstep == LM85_VERSTEP_ADT7463C) ) {
kind = adt7463 ;
} else if( company == LM85_COMPANY_ANALOG_DEV
&& (verstep & LM85_VERSTEP_VMASK) == LM85_VERSTEP_GENERIC ) {
dev_err(&adapter->dev, "Unrecognized version/stepping 0x%02x"
" Defaulting to Generic LM85.\n", verstep );
kind = any_chip ;
} else if( company == LM85_COMPANY_SMSC
&& (verstep == LM85_VERSTEP_EMC6D100_A0
|| verstep == LM85_VERSTEP_EMC6D100_A1) ) {
/* Unfortunately, we can't tell a '100 from a '101
* from the registers. Since a '101 is a '100
* in a package with fewer pins and therefore no
* 3.3V, 1.5V or 1.8V inputs, perhaps if those
* inputs read 0, then it's a '101.
*/
kind = emc6d100 ;
} else if( company == LM85_COMPANY_SMSC
&& verstep == LM85_VERSTEP_EMC6D102) {
kind = emc6d102 ;
} else if( company == LM85_COMPANY_SMSC
&& (verstep & LM85_VERSTEP_VMASK) == LM85_VERSTEP_GENERIC) {
dev_err(&adapter->dev, "lm85: Detected SMSC chip\n");
dev_err(&adapter->dev, "lm85: Unrecognized version/stepping 0x%02x"
" Defaulting to Generic LM85.\n", verstep );
kind = any_chip ;
} else if( kind == any_chip
&& (verstep & LM85_VERSTEP_VMASK) == LM85_VERSTEP_GENERIC) {
dev_err(&adapter->dev, "Generic LM85 Version 6 detected\n");
/* Leave kind as "any_chip" */
} else {
dev_dbg(&adapter->dev, "Autodetection failed\n");
/* Not an LM85 ... */
if( kind == any_chip ) { /* User used force=x,y */
dev_err(&adapter->dev, "Generic LM85 Version 6 not"
" found at %d,0x%02x. Try force_lm85c.\n",
i2c_adapter_id(adapter), address );
}
err = 0 ;
goto ERROR1;
}
}
/* Fill in the chip specific driver values */
if ( kind == any_chip ) {
type_name = "lm85";
} else if ( kind == lm85b ) {
type_name = "lm85b";
} else if ( kind == lm85c ) {
type_name = "lm85c";
} else if ( kind == adm1027 ) {
type_name = "adm1027";
} else if ( kind == adt7463 ) {
type_name = "adt7463";
} else if ( kind == emc6d100){
type_name = "emc6d100";
} else if ( kind == emc6d102 ) {
type_name = "emc6d102";
}
strlcpy(new_client->name, type_name, I2C_NAME_SIZE);
/* Fill in the remaining client fields */
data->type = kind;
data->valid = 0;
init_MUTEX(&data->update_lock);
/* Tell the I2C layer a new client has arrived */
if ((err = i2c_attach_client(new_client)))
goto ERROR1;
/* Set the VRM version */
data->vrm = i2c_which_vrm();
/* Initialize the LM85 chip */
lm85_init_client(new_client);
/* Register sysfs hooks */
device_create_file(&new_client->dev, &dev_attr_fan1_input);
device_create_file(&new_client->dev, &dev_attr_fan2_input);
device_create_file(&new_client->dev, &dev_attr_fan3_input);
device_create_file(&new_client->dev, &dev_attr_fan4_input);
device_create_file(&new_client->dev, &dev_attr_fan1_min);
device_create_file(&new_client->dev, &dev_attr_fan2_min);
device_create_file(&new_client->dev, &dev_attr_fan3_min);
device_create_file(&new_client->dev, &dev_attr_fan4_min);
device_create_file(&new_client->dev, &dev_attr_pwm1);
device_create_file(&new_client->dev, &dev_attr_pwm2);
device_create_file(&new_client->dev, &dev_attr_pwm3);
device_create_file(&new_client->dev, &dev_attr_pwm1_enable);
device_create_file(&new_client->dev, &dev_attr_pwm2_enable);
device_create_file(&new_client->dev, &dev_attr_pwm3_enable);
device_create_file(&new_client->dev, &dev_attr_in0_input);
device_create_file(&new_client->dev, &dev_attr_in1_input);
device_create_file(&new_client->dev, &dev_attr_in2_input);
device_create_file(&new_client->dev, &dev_attr_in3_input);
device_create_file(&new_client->dev, &dev_attr_in4_input);
device_create_file(&new_client->dev, &dev_attr_in0_min);
device_create_file(&new_client->dev, &dev_attr_in1_min);
device_create_file(&new_client->dev, &dev_attr_in2_min);
device_create_file(&new_client->dev, &dev_attr_in3_min);
device_create_file(&new_client->dev, &dev_attr_in4_min);
device_create_file(&new_client->dev, &dev_attr_in0_max);
device_create_file(&new_client->dev, &dev_attr_in1_max);
device_create_file(&new_client->dev, &dev_attr_in2_max);
device_create_file(&new_client->dev, &dev_attr_in3_max);
device_create_file(&new_client->dev, &dev_attr_in4_max);
device_create_file(&new_client->dev, &dev_attr_temp1_input);
device_create_file(&new_client->dev, &dev_attr_temp2_input);
device_create_file(&new_client->dev, &dev_attr_temp3_input);
device_create_file(&new_client->dev, &dev_attr_temp1_min);
device_create_file(&new_client->dev, &dev_attr_temp2_min);
device_create_file(&new_client->dev, &dev_attr_temp3_min);
device_create_file(&new_client->dev, &dev_attr_temp1_max);
device_create_file(&new_client->dev, &dev_attr_temp2_max);
device_create_file(&new_client->dev, &dev_attr_temp3_max);
device_create_file(&new_client->dev, &dev_attr_vrm);
device_create_file(&new_client->dev, &dev_attr_cpu0_vid);
device_create_file(&new_client->dev, &dev_attr_alarms);
device_create_file(&new_client->dev, &dev_attr_pwm1_auto_channels);
device_create_file(&new_client->dev, &dev_attr_pwm2_auto_channels);
device_create_file(&new_client->dev, &dev_attr_pwm3_auto_channels);
device_create_file(&new_client->dev, &dev_attr_pwm1_auto_pwm_min);
device_create_file(&new_client->dev, &dev_attr_pwm2_auto_pwm_min);
device_create_file(&new_client->dev, &dev_attr_pwm3_auto_pwm_min);
device_create_file(&new_client->dev, &dev_attr_pwm1_auto_pwm_minctl);
device_create_file(&new_client->dev, &dev_attr_pwm2_auto_pwm_minctl);
device_create_file(&new_client->dev, &dev_attr_pwm3_auto_pwm_minctl);
device_create_file(&new_client->dev, &dev_attr_pwm1_auto_pwm_freq);
device_create_file(&new_client->dev, &dev_attr_pwm2_auto_pwm_freq);
device_create_file(&new_client->dev, &dev_attr_pwm3_auto_pwm_freq);
device_create_file(&new_client->dev, &dev_attr_temp1_auto_temp_off);
device_create_file(&new_client->dev, &dev_attr_temp2_auto_temp_off);
device_create_file(&new_client->dev, &dev_attr_temp3_auto_temp_off);
device_create_file(&new_client->dev, &dev_attr_temp1_auto_temp_min);
device_create_file(&new_client->dev, &dev_attr_temp2_auto_temp_min);
device_create_file(&new_client->dev, &dev_attr_temp3_auto_temp_min);
device_create_file(&new_client->dev, &dev_attr_temp1_auto_temp_max);
device_create_file(&new_client->dev, &dev_attr_temp2_auto_temp_max);
device_create_file(&new_client->dev, &dev_attr_temp3_auto_temp_max);
device_create_file(&new_client->dev, &dev_attr_temp1_auto_temp_crit);
device_create_file(&new_client->dev, &dev_attr_temp2_auto_temp_crit);
device_create_file(&new_client->dev, &dev_attr_temp3_auto_temp_crit);
return 0;
/* Error out and cleanup code */
ERROR1:
kfree(data);
ERROR0:
return err;
}
int lm85_detach_client(struct i2c_client *client)
{
i2c_detach_client(client);
kfree(i2c_get_clientdata(client));
return 0;
}
int lm85_read_value(struct i2c_client *client, u8 reg)
{
int res;
/* What size location is it? */
switch( reg ) {
case LM85_REG_FAN(0) : /* Read WORD data */
case LM85_REG_FAN(1) :
case LM85_REG_FAN(2) :
case LM85_REG_FAN(3) :
case LM85_REG_FAN_MIN(0) :
case LM85_REG_FAN_MIN(1) :
case LM85_REG_FAN_MIN(2) :
case LM85_REG_FAN_MIN(3) :
case LM85_REG_ALARM1 : /* Read both bytes at once */
res = i2c_smbus_read_byte_data(client, reg) & 0xff ;
res |= i2c_smbus_read_byte_data(client, reg+1) << 8 ;
break ;
case ADT7463_REG_TMIN_CTL1 : /* Read WORD MSB, LSB */
res = i2c_smbus_read_byte_data(client, reg) << 8 ;
res |= i2c_smbus_read_byte_data(client, reg+1) & 0xff ;
break ;
default: /* Read BYTE data */
res = i2c_smbus_read_byte_data(client, reg);
break ;
}
return res ;
}
int lm85_write_value(struct i2c_client *client, u8 reg, int value)
{
int res ;
switch( reg ) {
case LM85_REG_FAN(0) : /* Write WORD data */
case LM85_REG_FAN(1) :
case LM85_REG_FAN(2) :
case LM85_REG_FAN(3) :
case LM85_REG_FAN_MIN(0) :
case LM85_REG_FAN_MIN(1) :
case LM85_REG_FAN_MIN(2) :
case LM85_REG_FAN_MIN(3) :
/* NOTE: ALARM is read only, so not included here */
res = i2c_smbus_write_byte_data(client, reg, value & 0xff) ;
res |= i2c_smbus_write_byte_data(client, reg+1, (value>>8) & 0xff) ;
break ;
case ADT7463_REG_TMIN_CTL1 : /* Write WORD MSB, LSB */
res = i2c_smbus_write_byte_data(client, reg, (value>>8) & 0xff);
res |= i2c_smbus_write_byte_data(client, reg+1, value & 0xff) ;
break ;
default: /* Write BYTE data */
res = i2c_smbus_write_byte_data(client, reg, value);
break ;
}
return res ;
}
void lm85_init_client(struct i2c_client *client)
{
int value;
struct lm85_data *data = i2c_get_clientdata(client);
dev_dbg(&client->dev, "Initializing device\n");
/* Warn if part was not "READY" */
value = lm85_read_value(client, LM85_REG_CONFIG);
dev_dbg(&client->dev, "LM85_REG_CONFIG is: 0x%02x\n", value);
if( value & 0x02 ) {
dev_err(&client->dev, "Client (%d,0x%02x) config is locked.\n",
i2c_adapter_id(client->adapter), client->addr );
};
if( ! (value & 0x04) ) {
dev_err(&client->dev, "Client (%d,0x%02x) is not ready.\n",
i2c_adapter_id(client->adapter), client->addr );
};
if( value & 0x10
&& ( data->type == adm1027
|| data->type == adt7463 ) ) {
dev_err(&client->dev, "Client (%d,0x%02x) VxI mode is set. "
"Please report this to the lm85 maintainer.\n",
i2c_adapter_id(client->adapter), client->addr );
};
/* WE INTENTIONALLY make no changes to the limits,
* offsets, pwms, fans and zones. If they were
* configured, we don't want to mess with them.
* If they weren't, the default is 100% PWM, no
* control and will suffice until 'sensors -s'
* can be run by the user.
*/
/* Start monitoring */
value = lm85_read_value(client, LM85_REG_CONFIG);
/* Try to clear LOCK, Set START, save everything else */
value = (value & ~ 0x02) | 0x01 ;
dev_dbg(&client->dev, "Setting CONFIG to: 0x%02x\n", value);
lm85_write_value(client, LM85_REG_CONFIG, value);
}
static struct lm85_data *lm85_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm85_data *data = i2c_get_clientdata(client);
int i;
down(&data->update_lock);
if ( !data->valid ||
time_after(jiffies, data->last_reading + LM85_DATA_INTERVAL) ) {
/* Things that change quickly */
dev_dbg(&client->dev, "Reading sensor values\n");
/* Have to read extended bits first to "freeze" the
* more significant bits that are read later.
*/
if ( (data->type == adm1027) || (data->type == adt7463) ) {
int ext1 = lm85_read_value(client,
ADM1027_REG_EXTEND_ADC1);
int ext2 = lm85_read_value(client,
ADM1027_REG_EXTEND_ADC2);
int val = (ext1 << 8) + ext2;
for(i = 0; i <= 4; i++)
data->in_ext[i] = (val>>(i * 2))&0x03;
for(i = 0; i <= 2; i++)
data->temp_ext[i] = (val>>((i + 5) * 2))&0x03;
}
/* adc_scale is 2^(number of LSBs). There are 4 extra bits in
the emc6d102 and 2 in the adt7463 and adm1027. In all
other chips ext is always 0 and the value of scale is
irrelevant. So it is left in 4*/
data->adc_scale = (data->type == emc6d102 ) ? 16 : 4;
for (i = 0; i <= 4; ++i) {
data->in[i] =
lm85_read_value(client, LM85_REG_IN(i));
}
for (i = 0; i <= 3; ++i) {
data->fan[i] =
lm85_read_value(client, LM85_REG_FAN(i));
}
for (i = 0; i <= 2; ++i) {
data->temp[i] =
lm85_read_value(client, LM85_REG_TEMP(i));
}
for (i = 0; i <= 2; ++i) {
data->pwm[i] =
lm85_read_value(client, LM85_REG_PWM(i));
}
data->alarms = lm85_read_value(client, LM85_REG_ALARM1);
if ( data->type == adt7463 ) {
if( data->therm_total < ULONG_MAX - 256 ) {
data->therm_total +=
lm85_read_value(client, ADT7463_REG_THERM );
}
} else if ( data->type == emc6d100 ) {
/* Three more voltage sensors */
for (i = 5; i <= 7; ++i) {
data->in[i] =
lm85_read_value(client, EMC6D100_REG_IN(i));
}
/* More alarm bits */
data->alarms |=
lm85_read_value(client, EMC6D100_REG_ALARM3) << 16;
} else if (data->type == emc6d102 ) {
/* Have to read LSB bits after the MSB ones because
the reading of the MSB bits has frozen the
LSBs (backward from the ADM1027).
*/
int ext1 = lm85_read_value(client,
EMC6D102_REG_EXTEND_ADC1);
int ext2 = lm85_read_value(client,
EMC6D102_REG_EXTEND_ADC2);
int ext3 = lm85_read_value(client,
EMC6D102_REG_EXTEND_ADC3);
int ext4 = lm85_read_value(client,
EMC6D102_REG_EXTEND_ADC4);
data->in_ext[0] = ext3 & 0x0f;
data->in_ext[1] = ext4 & 0x0f;
data->in_ext[2] = (ext4 >> 4) & 0x0f;
data->in_ext[3] = (ext3 >> 4) & 0x0f;
data->in_ext[4] = (ext2 >> 4) & 0x0f;
data->temp_ext[0] = ext1 & 0x0f;
data->temp_ext[1] = ext2 & 0x0f;
data->temp_ext[2] = (ext1 >> 4) & 0x0f;
}
data->last_reading = jiffies ;
}; /* last_reading */
if ( !data->valid ||
time_after(jiffies, data->last_config + LM85_CONFIG_INTERVAL) ) {
/* Things that don't change often */
dev_dbg(&client->dev, "Reading config values\n");
for (i = 0; i <= 4; ++i) {
data->in_min[i] =
lm85_read_value(client, LM85_REG_IN_MIN(i));
data->in_max[i] =
lm85_read_value(client, LM85_REG_IN_MAX(i));
}
if ( data->type == emc6d100 ) {
for (i = 5; i <= 7; ++i) {
data->in_min[i] =
lm85_read_value(client, EMC6D100_REG_IN_MIN(i));
data->in_max[i] =
lm85_read_value(client, EMC6D100_REG_IN_MAX(i));
}
}
for (i = 0; i <= 3; ++i) {
data->fan_min[i] =
lm85_read_value(client, LM85_REG_FAN_MIN(i));
}
for (i = 0; i <= 2; ++i) {
data->temp_min[i] =
lm85_read_value(client, LM85_REG_TEMP_MIN(i));
data->temp_max[i] =
lm85_read_value(client, LM85_REG_TEMP_MAX(i));
}
data->vid = lm85_read_value(client, LM85_REG_VID);
for (i = 0; i <= 2; ++i) {
int val ;
data->autofan[i].config =
lm85_read_value(client, LM85_REG_AFAN_CONFIG(i));
val = lm85_read_value(client, LM85_REG_AFAN_RANGE(i));
data->autofan[i].freq = val & 0x07 ;
data->zone[i].range = (val >> 4) & 0x0f ;
data->autofan[i].min_pwm =
lm85_read_value(client, LM85_REG_AFAN_MINPWM(i));
data->zone[i].limit =
lm85_read_value(client, LM85_REG_AFAN_LIMIT(i));
data->zone[i].critical =
lm85_read_value(client, LM85_REG_AFAN_CRITICAL(i));
}
i = lm85_read_value(client, LM85_REG_AFAN_SPIKE1);
data->smooth[0] = i & 0x0f ;
data->syncpwm3 = i & 0x10 ; /* Save PWM3 config */
data->autofan[0].min_off = (i & 0x20) != 0 ;
data->autofan[1].min_off = (i & 0x40) != 0 ;
data->autofan[2].min_off = (i & 0x80) != 0 ;
i = lm85_read_value(client, LM85_REG_AFAN_SPIKE2);
data->smooth[1] = (i>>4) & 0x0f ;
data->smooth[2] = i & 0x0f ;
i = lm85_read_value(client, LM85_REG_AFAN_HYST1);
data->zone[0].hyst = (i>>4) & 0x0f ;
data->zone[1].hyst = i & 0x0f ;
i = lm85_read_value(client, LM85_REG_AFAN_HYST2);
data->zone[2].hyst = (i>>4) & 0x0f ;
if ( (data->type == lm85b) || (data->type == lm85c) ) {
data->tach_mode = lm85_read_value(client,
LM85_REG_TACH_MODE );
data->spinup_ctl = lm85_read_value(client,
LM85_REG_SPINUP_CTL );
} else if ( (data->type == adt7463) || (data->type == adm1027) ) {
if ( data->type == adt7463 ) {
for (i = 0; i <= 2; ++i) {
data->oppoint[i] = lm85_read_value(client,
ADT7463_REG_OPPOINT(i) );
}
data->tmin_ctl = lm85_read_value(client,
ADT7463_REG_TMIN_CTL1 );
data->therm_limit = lm85_read_value(client,
ADT7463_REG_THERM_LIMIT );
}
for (i = 0; i <= 2; ++i) {
data->temp_offset[i] = lm85_read_value(client,
ADM1027_REG_TEMP_OFFSET(i) );
}
data->tach_mode = lm85_read_value(client,
ADM1027_REG_CONFIG3 );
data->fan_ppr = lm85_read_value(client,
ADM1027_REG_FAN_PPR );
}
data->last_config = jiffies;
}; /* last_config */
data->valid = 1;
up(&data->update_lock);
return data;
}
static int __init sm_lm85_init(void)
{
return i2c_add_driver(&lm85_driver);
}
static void __exit sm_lm85_exit(void)
{
i2c_del_driver(&lm85_driver);
}
/* Thanks to Richard Barrington for adding the LM85 to sensors-detect.
* Thanks to Margit Schubert-While <[email protected]> for help with
* post 2.7.0 CVS changes.
*/
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Philip Pokorny <[email protected]>, Margit Schubert-While <[email protected]>, Justin Thiessen <[email protected]");
MODULE_DESCRIPTION("LM85-B, LM85-C driver");
module_init(sm_lm85_init);
module_exit(sm_lm85_exit);
| proto3/linux-3.10 | drivers/i2c/chips/lm85.c | C | gpl-2.0 | 52,721 |
<?php
// +----------------------------------------------------------------------+
// | PEAR :: File :: Gettext :: MO |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is available at http://www.php.net/license/3_0.txt |
// | If you did not receive a copy of the PHP license and are unable |
// | to obtain it through the world-wide-web, please send a note to |
// | [email protected] so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Michael Wallner <[email protected]> |
// +----------------------------------------------------------------------+
//
// $Id: MO.php 9858 2008-06-25 11:34:30Z fabien $
/**
* File::Gettext::MO
*
* @author Michael Wallner <[email protected]>
* @license PHP License
*/
require_once dirname(__FILE__).'/TGettext.class.php';
/**
* File_Gettext_MO
*
* GNU MO file reader and writer.
*
* @author Michael Wallner <[email protected]>
* @version $Revision: 9858 $
* @access public
* @package System.I18N.core
*/
class TGettext_MO extends TGettext
{
/**
* file handle
*
* @access private
* @var resource
*/
protected $_handle = null;
/**
* big endianess
*
* Whether to write with big endian byte order.
*
* @access public
* @var bool
*/
protected $writeBigEndian = false;
/**
* Constructor
*
* @access public
* @return object File_Gettext_MO
* @param string $file path to GNU MO file
*/
function TGettext_MO($file = '')
{
$this->file = $file;
}
/**
* _read
*
* @access private
* @return mixed
* @param int $bytes
*/
function _read($bytes = 1)
{
if (0 < $bytes = abs($bytes)) {
return fread($this->_handle, $bytes);
}
return null;
}
/**
* _readInt
*
* @access private
* @return int
* @param bool $bigendian
*/
function _readInt($bigendian = false)
{
//unpack returns a reference????
$unpacked = unpack($bigendian ? 'N' : 'V', $this->_read(4));
return array_shift($unpacked);
}
/**
* _writeInt
*
* @access private
* @return int
* @param int $int
*/
function _writeInt($int)
{
return $this->_write(pack($this->writeBigEndian ? 'N' : 'V', (int) $int));
}
/**
* _write
*
* @access private
* @return int
* @param string $data
*/
function _write($data)
{
return fwrite($this->_handle, $data);
}
/**
* _writeStr
*
* @access private
* @return int
* @param string $string
*/
function _writeStr($string)
{
return $this->_write($string . "\0");
}
/**
* _readStr
*
* @access private
* @return string
* @param array $params associative array with offset and length
* of the string
*/
function _readStr($params)
{
fseek($this->_handle, $params['offset']);
return $this->_read($params['length']);
}
/**
* Load MO file
*
* @access public
* @return mixed Returns true on success or PEAR_Error on failure.
* @param string $file
*/
function load($file = null)
{
if (!isset($file)) {
$file = $this->file;
}
// open MO file
if (!is_resource($this->_handle = @fopen($file, 'rb'))) {
return false;
}
// lock MO file shared
if (!@flock($this->_handle, LOCK_SH)) {
@fclose($this->_handle);
return false;
}
// read (part of) magic number from MO file header and define endianess
//unpack returns a reference????
$unpacked = unpack('c', $this->_read(4));
switch ($magic = array_shift($unpacked))
{
case -34:
$be = false;
break;
case -107:
$be = true;
break;
default:
return false;
}
// check file format revision - we currently only support 0
if (0 !== ($_rev = $this->_readInt($be))) {
return false;
}
// count of strings in this file
$count = $this->_readInt($be);
// offset of hashing table of the msgids
$offset_original = $this->_readInt($be);
// offset of hashing table of the msgstrs
$offset_translat = $this->_readInt($be);
// move to msgid hash table
fseek($this->_handle, $offset_original);
// read lengths and offsets of msgids
$original = array();
for ($i = 0; $i < $count; $i++) {
$original[$i] = array(
'length' => $this->_readInt($be),
'offset' => $this->_readInt($be)
);
}
// move to msgstr hash table
fseek($this->_handle, $offset_translat);
// read lengths and offsets of msgstrs
$translat = array();
for ($i = 0; $i < $count; $i++) {
$translat[$i] = array(
'length' => $this->_readInt($be),
'offset' => $this->_readInt($be)
);
}
// read all
for ($i = 0; $i < $count; $i++) {
$this->strings[$this->_readStr($original[$i])] =
$this->_readStr($translat[$i]);
}
// done
@flock($this->_handle, LOCK_UN);
@fclose($this->_handle);
$this->_handle = null;
// check for meta info
if (isset($this->strings[''])) {
$this->meta = parent::meta2array($this->strings['']);
unset($this->strings['']);
}
return true;
}
/**
* Save MO file
*
* @access public
* @return mixed Returns true on success or PEAR_Error on failure.
* @param string $file
*/
function save($file = null)
{
if (!isset($file)) {
$file = $this->file;
}
// open MO file
if (!is_resource($this->_handle = @fopen($file, 'wb'))) {
return false;
}
// lock MO file exclusively
if (!@flock($this->_handle, LOCK_EX)) {
@fclose($this->_handle);
return false;
}
// write magic number
if ($this->writeBigEndian) {
$this->_write(pack('c*', 0x95, 0x04, 0x12, 0xde));
} else {
$this->_write(pack('c*', 0xde, 0x12, 0x04, 0x95));
}
// write file format revision
$this->_writeInt(0);
$count = count($this->strings) + ($meta = (count($this->meta) ? 1 : 0));
// write count of strings
$this->_writeInt($count);
$offset = 28;
// write offset of orig. strings hash table
$this->_writeInt($offset);
$offset += ($count * 8);
// write offset transl. strings hash table
$this->_writeInt($offset);
// write size of hash table (we currently ommit the hash table)
$this->_writeInt(0);
$offset += ($count * 8);
// write offset of hash table
$this->_writeInt($offset);
// unshift meta info
if ($meta) {
$meta = '';
foreach ($this->meta as $key => $val) {
$meta .= $key . ': ' . $val . "\n";
}
$strings = array('' => $meta) + $this->strings;
} else {
$strings = $this->strings;
}
// write offsets for original strings
foreach (array_keys($strings) as $o) {
$len = strlen($o);
$this->_writeInt($len);
$this->_writeInt($offset);
$offset += $len + 1;
}
// write offsets for translated strings
foreach ($strings as $t) {
$len = strlen($t);
$this->_writeInt($len);
$this->_writeInt($offset);
$offset += $len + 1;
}
// write original strings
foreach (array_keys($strings) as $o) {
$this->_writeStr($o);
}
// write translated strings
foreach ($strings as $t) {
$this->_writeStr($t);
}
// done
@flock($this->_handle, LOCK_UN);
@fclose($this->_handle);
return true;
}
} | Desarrollo-CeSPI/choique | lib/vendor/symfony/lib/i18n/Gettext/MO.php | PHP | gpl-2.0 | 8,946 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Core
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Factory class
*
* @category Mage
* @package Mage_Core
* @author Magento Core Team <[email protected]>
*/
class Mage_Core_Model_Factory
{
/**
* Xml path to url rewrite model class alias
*/
const XML_PATH_URL_REWRITE_MODEL = 'global/url_rewrite/model';
const XML_PATH_INDEX_INDEX_MODEL = 'global/index/index_model';
/**
* Config instance
*
* @var Mage_Core_Model_Config
*/
protected $_config;
/**
* Initialize factory
*
* @param array $arguments
*/
public function __construct(array $arguments = array())
{
$this->_config = !empty($arguments['config']) ? $arguments['config'] : Mage::getConfig();
}
/**
* Retrieve model object
*
* @param string $modelClass
* @param array|object $arguments
* @return bool|Mage_Core_Model_Abstract
*/
public function getModel($modelClass = '', $arguments = array())
{
return Mage::getModel($modelClass, $arguments);
}
/**
* Retrieve model object singleton
*
* @param string $modelClass
* @param array $arguments
* @return Mage_Core_Model_Abstract
*/
public function getSingleton($modelClass = '', array $arguments = array())
{
return Mage::getSingleton($modelClass, $arguments);
}
/**
* Retrieve object of resource model
*
* @param string $modelClass
* @param array $arguments
* @return Object
*/
public function getResourceModel($modelClass, $arguments = array())
{
return Mage::getResourceModel($modelClass, $arguments);
}
/**
* Retrieve helper instance
*
* @param string $helperClass
* @return Mage_Core_Helper_Abstract
*/
public function getHelper($helperClass)
{
return Mage::helper($helperClass);
}
/**
* Get config instance
*
* @return Mage_Core_Model_Config
*/
public function getConfig()
{
return $this->_config;
}
/**
* Retrieve url_rewrite instance
*
* @return Mage_Core_Model_Url_Rewrite
*/
public function getUrlRewriteInstance()
{
return $this->getModel($this->getUrlRewriteClassAlias());
}
/**
* Retrieve alias for url_rewrite model
*
* @return string
*/
public function getUrlRewriteClassAlias()
{
return (string)$this->_config->getNode(self::XML_PATH_URL_REWRITE_MODEL);
}
/**
* @return string
*/
public function getIndexClassAlias()
{
return (string)$this->_config->getNode(self::XML_PATH_INDEX_INDEX_MODEL);
}
}
| Eristoff47/P2 | src/public/app/code/core/Mage/Core/Model/Factory.php | PHP | gpl-2.0 | 3,635 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_fields
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
if (JFactory::getApplication()->isClient('site'))
{
JSession::checkToken('get') or die(JText::_('JINVALID_TOKEN'));
}
JHtml::_('behavior.core');
JHtml::_('bootstrap.tooltip', '.hasTooltip', array('placement' => 'bottom'));
JHtml::_('bootstrap.popover', '.hasPopover', array('placement' => 'bottom'));
JHtml::_('formbehavior.chosen', 'select');
JHtml::_('script', 'com_fields/admin-fields-modal.js', array('version' => 'auto', 'relative' => true));
// Special case for the search field tooltip.
$searchFilterDesc = $this->filterForm->getFieldAttribute('search', 'description', null, 'filter');
JHtml::_('bootstrap.tooltip', '#filter_search', array('title' => JText::_($searchFilterDesc), 'placement' => 'bottom'));
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
$editor = JFactory::getApplication()->input->get('editor', '', 'cmd');
?>
<div class="container-popup">
<form action="<?php echo JRoute::_('index.php?option=com_fields&view=fields&layout=modal&tmpl=component&' . JSession::getFormToken() . '=1'); ?>" method="post" name="adminForm" id="adminForm">
<?php echo JLayoutHelper::render('joomla.searchtools.default', array('view' => $this)); ?>
<?php if (empty($this->items)) : ?>
<div class="alert alert-no-items">
<?php echo JText::_('JGLOBAL_NO_MATCHING_RESULTS'); ?>
</div>
<?php else : ?>
<table class="table table-striped" id="moduleList">
<thead>
<tr>
<th width="1%" class="nowrap center">
<?php echo JHtml::_('searchtools.sort', 'JSTATUS', 'a.state', $listDirn, $listOrder); ?>
</th>
<th class="title">
<?php echo JHtml::_('searchtools.sort', 'JGLOBAL_TITLE', 'a.title', $listDirn, $listOrder); ?>
</th>
<th width="15%" class="nowrap hidden-phone">
<?php echo JHtml::_('searchtools.sort', 'COM_FIELDS_FIELD_GROUP_LABEL', 'group_title', $listDirn, $listOrder); ?>
</th>
<th width="10%" class="nowrap hidden-phone">
<?php echo JHtml::_('searchtools.sort', 'COM_FIELDS_FIELD_TYPE_LABEL', 'a.type', $listDirn, $listOrder); ?>
</th>
<th width="10%" class="nowrap hidden-phone">
<?php echo JHtml::_('searchtools.sort', 'JGRID_HEADING_ACCESS', 'a.access', $listDirn, $listOrder); ?>
</th>
<th width="10%" class="nowrap hidden-phone">
<?php echo JHtml::_('searchtools.sort', 'JGRID_HEADING_LANGUAGE', 'language', $listDirn, $listOrder); ?>
</th>
<th width="1%" class="nowrap hidden-phone">
<?php echo JHtml::_('searchtools.sort', 'JGRID_HEADING_ID', 'a.id', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="8">
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
</tfoot>
<tbody>
<?php
$iconStates = array(
-2 => 'icon-trash',
0 => 'icon-unpublish',
1 => 'icon-publish',
2 => 'icon-archive',
);
foreach ($this->items as $i => $item) :
?>
<tr class="row<?php echo $i % 2; ?>">
<td class="center">
<span class="<?php echo $iconStates[$this->escape($item->state)]; ?>" aria-hidden="true"></span>
</td>
<td class="has-context">
<a class="btn btn-small btn-block btn-success" href="#" onclick="Joomla.fieldIns('<?php echo $this->escape($item->id); ?>', '<?php echo $this->escape($editor); ?>');"><?php echo $this->escape($item->title); ?></a>
</td>
<td class="small hidden-phone">
<a class="btn btn-small btn-block btn-warning" href="#" onclick="Joomla.fieldgroupIns('<?php echo $this->escape($item->group_id); ?>', '<?php echo $this->escape($editor); ?>');"><?php echo $item->group_id ? $this->escape($item->group_title) : JText::_('JNONE'); ?></a>
</td>
<td class="small hidden-phone">
<?php echo $item->type; ?>
</td>
<td class="small hidden-phone">
<?php echo $this->escape($item->access_level); ?>
</td>
<td class="small hidden-phone">
<?php echo JLayoutHelper::render('joomla.content.language', $item); ?>
</td>
<td class="hidden-phone">
<?php echo (int) $item->id; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<?php echo JHtml::_('form.token'); ?>
</form>
</div>
| chrisdavenport/joomla-cms | administrator/components/com_fields/views/fields/tmpl/modal.php | PHP | gpl-2.0 | 4,723 |
# ext-locale-nl/overrides
This folder contains overrides which will automatically be required by package users.
| lightbase/WSCacicNeo | wscacicneo/static/ext-js/packages/ext-locale-nl/overrides/Readme.md | Markdown | gpl-2.0 | 113 |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestEmployeeSeparationTemplate(unittest.TestCase):
pass
| ovresko/erpnext | erpnext/hr/doctype/employee_separation_template/test_employee_separation_template.py | Python | gpl-3.0 | 246 |
/*
DO NOT MODIFY - This file has been generated and will be regenerated
Semantic UI v2.1.4
*/
/*!
* # Semantic UI - Sidebar
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.sidebar = function(parameters) {
var
$allModules = $(this),
$window = $(window),
$document = $(document),
$html = $('html'),
$head = $('head'),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.sidebar.settings, parameters)
: $.extend({}, $.fn.sidebar.settings),
selector = settings.selector,
className = settings.className,
namespace = settings.namespace,
regExp = settings.regExp,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$sidebars = $module.children(selector.sidebar),
$fixed = $context.children(selector.fixed),
$pusher = $context.children(selector.pusher),
$style,
element = this,
instance = $module.data(moduleNamespace),
elementNamespace,
id,
currentScroll,
transitionEvent,
module
;
module = {
initialize: function() {
module.debug('Initializing sidebar', parameters);
module.create.id();
transitionEvent = module.get.transitionEvent();
if(module.is.ios()) {
module.set.ios();
}
// avoids locking rendering if initialized in onReady
if(settings.delaySetup) {
requestAnimationFrame(module.setup.layout);
}
else {
module.setup.layout();
}
requestAnimationFrame(function() {
module.setup.cache();
});
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
create: {
id: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
}
},
destroy: function() {
module.verbose('Destroying previous module for', $module);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
if(module.is.ios()) {
module.remove.ios();
}
// bound by uuid
$context.off(elementNamespace);
$window.off(elementNamespace);
$document.off(elementNamespace);
},
event: {
clickaway: function(event) {
var
clickedInPusher = ($pusher.find(event.target).length > 0 || $pusher.is(event.target)),
clickedContext = ($context.is(event.target))
;
if(clickedInPusher) {
module.verbose('User clicked on dimmed page');
module.hide();
}
if(clickedContext) {
module.verbose('User clicked on dimmable context (scaled out page)');
module.hide();
}
},
touch: function(event) {
//event.stopPropagation();
},
containScroll: function(event) {
if(element.scrollTop <= 0) {
element.scrollTop = 1;
}
if((element.scrollTop + element.offsetHeight) >= element.scrollHeight) {
element.scrollTop = element.scrollHeight - element.offsetHeight - 1;
}
},
scroll: function(event) {
if( $(event.target).closest(selector.sidebar).length === 0 ) {
event.preventDefault();
}
}
},
bind: {
clickaway: function() {
module.verbose('Adding clickaway events to context', $context);
if(settings.closable) {
$context
.on('click' + elementNamespace, module.event.clickaway)
.on('touchend' + elementNamespace, module.event.clickaway)
;
}
},
scrollLock: function() {
if(settings.scrollLock) {
module.debug('Disabling page scroll');
$window
.on('DOMMouseScroll' + elementNamespace, module.event.scroll)
;
}
module.verbose('Adding events to contain sidebar scroll');
$document
.on('touchmove' + elementNamespace, module.event.touch)
;
$module
.on('scroll' + eventNamespace, module.event.containScroll)
;
}
},
unbind: {
clickaway: function() {
module.verbose('Removing clickaway events from context', $context);
$context.off(elementNamespace);
},
scrollLock: function() {
module.verbose('Removing scroll lock from page');
$document.off(elementNamespace);
$window.off(elementNamespace);
$module.off('scroll' + eventNamespace);
}
},
add: {
inlineCSS: function() {
var
width = module.cache.width || $module.outerWidth(),
height = module.cache.height || $module.outerHeight(),
isRTL = module.is.rtl(),
direction = module.get.direction(),
distance = {
left : width,
right : -width,
top : height,
bottom : -height
},
style
;
if(isRTL){
module.verbose('RTL detected, flipping widths');
distance.left = -width;
distance.right = width;
}
style = '<style>';
if(direction === 'left' || direction === 'right') {
module.debug('Adding CSS rules for animation distance', width);
style += ''
+ ' .ui.visible.' + direction + '.sidebar ~ .fixed,'
+ ' .ui.visible.' + direction + '.sidebar ~ .pusher {'
+ ' -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' }'
;
}
else if(direction === 'top' || direction == 'bottom') {
style += ''
+ ' .ui.visible.' + direction + '.sidebar ~ .fixed,'
+ ' .ui.visible.' + direction + '.sidebar ~ .pusher {'
+ ' -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' }'
;
}
/* IE is only browser not to create context with transforms */
/* https://www.w3.org/Bugs/Public/show_bug.cgi?id=16328 */
if( module.is.ie() ) {
if(direction === 'left' || direction === 'right') {
module.debug('Adding CSS rules for animation distance', width);
style += ''
+ ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {'
+ ' -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' }'
;
}
else if(direction === 'top' || direction == 'bottom') {
style += ''
+ ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {'
+ ' -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' }'
;
}
/* opposite sides visible forces content overlay */
style += ''
+ ' body.pushable > .ui.visible.left.sidebar ~ .ui.visible.right.sidebar ~ .pusher:after,'
+ ' body.pushable > .ui.visible.right.sidebar ~ .ui.visible.left.sidebar ~ .pusher:after {'
+ ' -webkit-transform: translate3d(0px, 0, 0);'
+ ' transform: translate3d(0px, 0, 0);'
+ ' }'
;
}
style += '</style>';
$style = $(style)
.appendTo($head)
;
module.debug('Adding sizing css to head', $style);
}
},
refresh: function() {
module.verbose('Refreshing selector cache');
$context = $(settings.context);
$sidebars = $context.children(selector.sidebar);
$pusher = $context.children(selector.pusher);
$fixed = $context.children(selector.fixed);
module.clear.cache();
},
refreshSidebars: function() {
module.verbose('Refreshing other sidebars');
$sidebars = $context.children(selector.sidebar);
},
repaint: function() {
module.verbose('Forcing repaint event');
element.style.display = 'none';
var ignored = element.offsetHeight;
element.scrollTop = element.scrollTop;
element.style.display = '';
},
setup: {
cache: function() {
module.cache = {
width : $module.outerWidth(),
height : $module.outerHeight(),
rtl : ($module.css('direction') == 'rtl')
};
},
layout: function() {
if( $context.children(selector.pusher).length === 0 ) {
module.debug('Adding wrapper element for sidebar');
module.error(error.pusher);
$pusher = $('<div class="pusher" />');
$context
.children()
.not(selector.omitted)
.not($sidebars)
.wrapAll($pusher)
;
module.refresh();
}
if($module.nextAll(selector.pusher).length === 0 || $module.nextAll(selector.pusher)[0] !== $pusher[0]) {
module.debug('Moved sidebar to correct parent element');
module.error(error.movedSidebar, element);
$module.detach().prependTo($context);
module.refresh();
}
module.clear.cache();
module.set.pushable();
module.set.direction();
}
},
attachEvents: function(selector, event) {
var
$toggle = $(selector)
;
event = $.isFunction(module[event])
? module[event]
: module.toggle
;
if($toggle.length > 0) {
module.debug('Attaching sidebar events to element', selector, event);
$toggle
.on('click' + eventNamespace, event)
;
}
else {
module.error(error.notFound, selector);
}
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(module.is.hidden()) {
module.refreshSidebars();
if(settings.overlay) {
module.error(error.overlay);
settings.transition = 'overlay';
}
module.refresh();
if(module.othersActive()) {
module.debug('Other sidebars currently visible');
if(settings.exclusive) {
// if not overlay queue animation after hide
if(settings.transition != 'overlay') {
module.hideOthers(module.show);
return;
}
else {
module.hideOthers();
}
}
else {
settings.transition = 'overlay';
}
}
module.pushPage(function() {
callback.call(element);
settings.onShow.call(element);
});
settings.onChange.call(element);
settings.onVisible.call(element);
}
else {
module.debug('Sidebar is already visible');
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(module.is.visible() || module.is.animating()) {
module.debug('Hiding sidebar', callback);
module.refreshSidebars();
module.pullPage(function() {
callback.call(element);
settings.onHidden.call(element);
});
settings.onChange.call(element);
settings.onHide.call(element);
}
},
othersAnimating: function() {
return ($sidebars.not($module).filter('.' + className.animating).length > 0);
},
othersVisible: function() {
return ($sidebars.not($module).filter('.' + className.visible).length > 0);
},
othersActive: function() {
return(module.othersVisible() || module.othersAnimating());
},
hideOthers: function(callback) {
var
$otherSidebars = $sidebars.not($module).filter('.' + className.visible),
sidebarCount = $otherSidebars.length,
callbackCount = 0
;
callback = callback || function(){};
$otherSidebars
.sidebar('hide', function() {
callbackCount++;
if(callbackCount == sidebarCount) {
callback();
}
})
;
},
toggle: function() {
module.verbose('Determining toggled direction');
if(module.is.hidden()) {
module.show();
}
else {
module.hide();
}
},
pushPage: function(callback) {
var
transition = module.get.transition(),
$transition = (transition === 'overlay' || module.othersActive())
? $module
: $pusher,
animate,
dim,
transitionEnd
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if(settings.transition == 'scale down') {
module.scrollToTop();
}
module.set.transition(transition);
module.repaint();
animate = function() {
module.bind.clickaway();
module.add.inlineCSS();
module.set.animating();
module.set.visible();
};
dim = function() {
module.set.dimmed();
};
transitionEnd = function(event) {
if( event.target == $transition[0] ) {
$transition.off(transitionEvent + elementNamespace, transitionEnd);
module.remove.animating();
module.bind.scrollLock();
callback.call(element);
}
};
$transition.off(transitionEvent + elementNamespace);
$transition.on(transitionEvent + elementNamespace, transitionEnd);
requestAnimationFrame(animate);
if(settings.dimPage && !module.othersVisible()) {
requestAnimationFrame(dim);
}
},
pullPage: function(callback) {
var
transition = module.get.transition(),
$transition = (transition == 'overlay' || module.othersActive())
? $module
: $pusher,
animate,
transitionEnd
;
callback = $.isFunction(callback)
? callback
: function(){}
;
module.verbose('Removing context push state', module.get.direction());
module.unbind.clickaway();
module.unbind.scrollLock();
animate = function() {
module.set.transition(transition);
module.set.animating();
module.remove.visible();
if(settings.dimPage && !module.othersVisible()) {
$pusher.removeClass(className.dimmed);
}
};
transitionEnd = function(event) {
if( event.target == $transition[0] ) {
$transition.off(transitionEvent + elementNamespace, transitionEnd);
module.remove.animating();
module.remove.transition();
module.remove.inlineCSS();
if(transition == 'scale down' || (settings.returnScroll && module.is.mobile()) ) {
module.scrollBack();
}
callback.call(element);
}
};
$transition.off(transitionEvent + elementNamespace);
$transition.on(transitionEvent + elementNamespace, transitionEnd);
requestAnimationFrame(animate);
},
scrollToTop: function() {
module.verbose('Scrolling to top of page to avoid animation issues');
currentScroll = $(window).scrollTop();
$module.scrollTop(0);
window.scrollTo(0, 0);
},
scrollBack: function() {
module.verbose('Scrolling back to original page position');
window.scrollTo(0, currentScroll);
},
clear: {
cache: function() {
module.verbose('Clearing cached dimensions');
module.cache = {};
}
},
set: {
// ios only (scroll on html not document). This prevent auto-resize canvas/scroll in ios
ios: function() {
$html.addClass(className.ios);
},
// container
pushed: function() {
$context.addClass(className.pushed);
},
pushable: function() {
$context.addClass(className.pushable);
},
// pusher
dimmed: function() {
$pusher.addClass(className.dimmed);
},
// sidebar
active: function() {
$module.addClass(className.active);
},
animating: function() {
$module.addClass(className.animating);
},
transition: function(transition) {
transition = transition || module.get.transition();
$module.addClass(transition);
},
direction: function(direction) {
direction = direction || module.get.direction();
$module.addClass(className[direction]);
},
visible: function() {
$module.addClass(className.visible);
},
overlay: function() {
$module.addClass(className.overlay);
}
},
remove: {
inlineCSS: function() {
module.debug('Removing inline css styles', $style);
if($style && $style.length > 0) {
$style.remove();
}
},
// ios scroll on html not document
ios: function() {
$html.removeClass(className.ios);
},
// context
pushed: function() {
$context.removeClass(className.pushed);
},
pushable: function() {
$context.removeClass(className.pushable);
},
// sidebar
active: function() {
$module.removeClass(className.active);
},
animating: function() {
$module.removeClass(className.animating);
},
transition: function(transition) {
transition = transition || module.get.transition();
$module.removeClass(transition);
},
direction: function(direction) {
direction = direction || module.get.direction();
$module.removeClass(className[direction]);
},
visible: function() {
$module.removeClass(className.visible);
},
overlay: function() {
$module.removeClass(className.overlay);
}
},
get: {
direction: function() {
if($module.hasClass(className.top)) {
return className.top;
}
else if($module.hasClass(className.right)) {
return className.right;
}
else if($module.hasClass(className.bottom)) {
return className.bottom;
}
return className.left;
},
transition: function() {
var
direction = module.get.direction(),
transition
;
transition = ( module.is.mobile() )
? (settings.mobileTransition == 'auto')
? settings.defaultTransition.mobile[direction]
: settings.mobileTransition
: (settings.transition == 'auto')
? settings.defaultTransition.computer[direction]
: settings.transition
;
module.verbose('Determined transition', transition);
return transition;
},
transitionEvent: function() {
var
element = document.createElement('element'),
transitions = {
'transition' :'transitionend',
'OTransition' :'oTransitionEnd',
'MozTransition' :'transitionend',
'WebkitTransition' :'webkitTransitionEnd'
},
transition
;
for(transition in transitions){
if( element.style[transition] !== undefined ){
return transitions[transition];
}
}
}
},
is: {
ie: function() {
var
isIE11 = (!(window.ActiveXObject) && 'ActiveXObject' in window),
isIE = ('ActiveXObject' in window)
;
return (isIE11 || isIE);
},
ios: function() {
var
userAgent = navigator.userAgent,
isIOS = userAgent.match(regExp.ios),
isMobileChrome = userAgent.match(regExp.mobileChrome)
;
if(isIOS && !isMobileChrome) {
module.verbose('Browser was found to be iOS', userAgent);
return true;
}
else {
return false;
}
},
mobile: function() {
var
userAgent = navigator.userAgent,
isMobile = userAgent.match(regExp.mobile)
;
if(isMobile) {
module.verbose('Browser was found to be mobile', userAgent);
return true;
}
else {
module.verbose('Browser is not mobile, using regular transition', userAgent);
return false;
}
},
hidden: function() {
return !module.is.visible();
},
visible: function() {
return $module.hasClass(className.visible);
},
// alias
open: function() {
return module.is.visible();
},
closed: function() {
return module.is.hidden();
},
vertical: function() {
return $module.hasClass(className.top);
},
animating: function() {
return $context.hasClass(className.animating);
},
rtl: function () {
if(module.cache.rtl === undefined) {
module.cache.rtl = ($module.css('direction') == 'rtl');
}
return module.cache.rtl;
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
}
;
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
module.invoke('destroy');
}
module.initialize();
}
});
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.sidebar.settings = {
name : 'Sidebar',
namespace : 'sidebar',
debug : false,
verbose : false,
performance : true,
transition : 'auto',
mobileTransition : 'auto',
defaultTransition : {
computer: {
left : 'uncover',
right : 'uncover',
top : 'overlay',
bottom : 'overlay'
},
mobile: {
left : 'uncover',
right : 'uncover',
top : 'overlay',
bottom : 'overlay'
}
},
context : 'body',
exclusive : false,
closable : true,
dimPage : true,
scrollLock : false,
returnScroll : false,
delaySetup : false,
duration : 500,
onChange : function(){},
onShow : function(){},
onHide : function(){},
onHidden : function(){},
onVisible : function(){},
className : {
active : 'active',
animating : 'animating',
dimmed : 'dimmed',
ios : 'ios',
pushable : 'pushable',
pushed : 'pushed',
right : 'right',
top : 'top',
left : 'left',
bottom : 'bottom',
visible : 'visible'
},
selector: {
fixed : '.fixed',
omitted : 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed',
pusher : '.pusher',
sidebar : '.ui.sidebar'
},
regExp: {
ios : /(iPad|iPhone|iPod)/g,
mobileChrome : /(CriOS)/g,
mobile : /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g
},
error : {
method : 'The method you called is not defined.',
pusher : 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element',
movedSidebar : 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag',
overlay : 'The overlay setting is no longer supported, use animation: overlay',
notFound : 'There were no elements that matched the specified selector'
}
};
})( jQuery, window , document );
| dubsky/robolos | src/client/semantic-ui/definitions/modules/sidebar.js | JavaScript | gpl-3.0 | 33,155 |
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local instance = mob:getInstance()
instance:setProgress(instance:getProgress() + 1)
end;
| Arcscion/Shadowlyre | scripts/zones/Arrapago_Remnants/mobs/Merrow_Shadowdancer.lua | Lua | gpl-3.0 | 349 |
/* Implementation of the ANY intrinsic
Copyright (C) 2002-2016 Free Software Foundation, Inc.
Contributed by Paul Brook <[email protected]>
This file is part of the GNU Fortran runtime library (libgfortran).
Libgfortran 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.
Libgfortran 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.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#include "libgfortran.h"
#include <stdlib.h>
#include <assert.h>
#if defined (HAVE_GFC_LOGICAL_1)
extern void any_l1 (gfc_array_l1 * const restrict,
gfc_array_l1 * const restrict, const index_type * const restrict);
export_proto(any_l1);
void
any_l1 (gfc_array_l1 * const restrict retarray,
gfc_array_l1 * const restrict array,
const index_type * const restrict pdim)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type sstride[GFC_MAX_DIMENSIONS];
index_type dstride[GFC_MAX_DIMENSIONS];
const GFC_LOGICAL_1 * restrict base;
GFC_LOGICAL_1 * restrict dest;
index_type rank;
index_type n;
index_type len;
index_type delta;
index_type dim;
int src_kind;
int continue_loop;
/* Make dim zero based to avoid confusion. */
dim = (*pdim) - 1;
rank = GFC_DESCRIPTOR_RANK (array) - 1;
src_kind = GFC_DESCRIPTOR_SIZE (array);
len = GFC_DESCRIPTOR_EXTENT(array,dim);
if (len < 0)
len = 0;
delta = GFC_DESCRIPTOR_STRIDE_BYTES(array,dim);
for (n = 0; n < dim; n++)
{
sstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(array,n);
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n);
if (extent[n] < 0)
extent[n] = 0;
}
for (n = dim; n < rank; n++)
{
sstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(array,n + 1);
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n + 1);
if (extent[n] < 0)
extent[n] = 0;
}
if (retarray->base_addr == NULL)
{
size_t alloc_size, str;
for (n = 0; n < rank; n++)
{
if (n == 0)
str = 1;
else
str = GFC_DESCRIPTOR_STRIDE(retarray,n-1) * extent[n-1];
GFC_DIMENSION_SET(retarray->dim[n], 0, extent[n] - 1, str);
}
retarray->offset = 0;
retarray->dtype = (array->dtype & ~GFC_DTYPE_RANK_MASK) | rank;
alloc_size = GFC_DESCRIPTOR_STRIDE(retarray,rank-1) * extent[rank-1];
if (alloc_size == 0)
{
/* Make sure we have a zero-sized array. */
GFC_DIMENSION_SET(retarray->dim[0], 0, -1, 1);
return;
}
else
retarray->base_addr = xmallocarray (alloc_size, sizeof (GFC_LOGICAL_1));
}
else
{
if (rank != GFC_DESCRIPTOR_RANK (retarray))
runtime_error ("rank of return array incorrect in"
" ANY intrinsic: is %ld, should be %ld",
(long int) GFC_DESCRIPTOR_RANK (retarray),
(long int) rank);
if (unlikely (compile_options.bounds_check))
{
for (n=0; n < rank; n++)
{
index_type ret_extent;
ret_extent = GFC_DESCRIPTOR_EXTENT(retarray,n);
if (extent[n] != ret_extent)
runtime_error ("Incorrect extent in return value of"
" ANY intrinsic in dimension %d:"
" is %ld, should be %ld", (int) n + 1,
(long int) ret_extent, (long int) extent[n]);
}
}
}
for (n = 0; n < rank; n++)
{
count[n] = 0;
dstride[n] = GFC_DESCRIPTOR_STRIDE(retarray,n);
if (extent[n] <= 0)
return;
}
base = array->base_addr;
if (src_kind == 1 || src_kind == 2 || src_kind == 4 || src_kind == 8
#ifdef HAVE_GFC_LOGICAL_16
|| src_kind == 16
#endif
)
{
if (base)
base = GFOR_POINTER_TO_L1 (base, src_kind);
}
else
internal_error (NULL, "Funny sized logical array in ANY intrinsic");
dest = retarray->base_addr;
continue_loop = 1;
while (continue_loop)
{
const GFC_LOGICAL_1 * restrict src;
GFC_LOGICAL_1 result;
src = base;
{
result = 0;
if (len <= 0)
*dest = 0;
else
{
for (n = 0; n < len; n++, src += delta)
{
/* Return true if any of the elements are set. */
if (*src)
{
result = 1;
break;
}
}
*dest = result;
}
}
/* Advance to the next element. */
count[0]++;
base += sstride[0];
dest += dstride[0];
n = 0;
while (count[n] == extent[n])
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
base -= sstride[n] * extent[n];
dest -= dstride[n] * extent[n];
n++;
if (n == rank)
{
/* Break out of the look. */
continue_loop = 0;
break;
}
else
{
count[n]++;
base += sstride[n];
dest += dstride[n];
}
}
}
}
#endif
| selmentdev/selment-toolchain | source/gcc-latest/libgfortran/generated/any_l1.c | C | gpl-3.0 | 5,703 |
SET CLIENT_MIN_MESSAGES TO WARNING;
| mixerp/mixerp | src/FrontEnd/db/1.x/1.1/src/00.db core/0.verbosity.sql | SQL | gpl-3.0 | 36 |
<h1>Références complètes des saisies</h1>
[(#ENV{format}|=={brut}|oui)<textarea style="width:100%; height:100%;">]
[(#VAL|saisies_generer_aide)]
[(#ENV{format}|=={brut}|oui)</textarea>]
| umibulle/romette | plugins/saisies/aide/saisies.html | HTML | gpl-3.0 | 190 |
<?php
require_once("db_common.php");
/*! Implementation of DataWrapper for Oracle
**/
class OracleDBDataWrapper extends DBDataWrapper{
private $last_id=""; //id of previously inserted record
private $insert_operation=false; //flag of insert operation
public function query($sql){
LogMaster::log($sql);
$stm = oci_parse($this->connection,$sql);
if ($stm===false) throw new Exception("Oracle - sql parsing failed\n".oci_error($this->connection));
$out = array(0=>null);
if($this->insert_operation){
oci_bind_by_name($stm,":outID",$out[0],999);
$this->insert_operation=false;
}
$mode = ($this->is_record_transaction() || $this->is_global_transaction())?OCI_DEFAULT:OCI_COMMIT_ON_SUCCESS;
$res=oci_execute($stm,$mode);
if ($res===false) throw new Exception("Oracle - sql execution failed\n".oci_error($this->connection));
$this->last_id=$out[0];
return $stm;
}
public function get_next($res){
$data = oci_fetch_assoc($res);
if (array_key_exists("VALUE",$data))
$data["value"]=$data["VALUE"];
return $data;
}
protected function get_new_id(){
/*
Oracle doesn't support identity or auto-increment fields
Insert SQL returns new ID value, which stored in last_id field
*/
return $this->last_id;
}
protected function insert_query($data,$request){
$sql = parent::insert_query($data,$request);
$this->insert_operation=true;
return $sql." returning ".$this->config->id["db_name"]." into :outID";
}
protected function select_query($select,$from,$where,$sort,$start,$count){
$sql="SELECT ".$select." FROM ".$from;
if ($where) $sql.=" WHERE ".$where;
if ($sort) $sql.=" ORDER BY ".$sort;
if ($start || $count)
$sql="SELECT * FROM ( select /*+ FIRST_ROWS(".$count.")*/dhx_table.*, ROWNUM rnum FROM (".$sql.") dhx_table where ROWNUM <= ".($count+$start)." ) where rnum >".$start;
return $sql;
}
public function escape($data){
/*
as far as I can see the only way to escape data is by using oci_bind_by_name
while it is neat solution in common case, it conflicts with existing SQL building logic
fallback to simple escaping
*/
return str_replace("'","''",$data);
}
public function begin_transaction(){
//auto-start of transaction
}
public function commit_transaction(){
oci_commit($this->connection);
}
public function rollback_transaction(){
oci_rollback($this->connection);
}
}
?> | iw3hxn/LibrERP | web_client/ea_web-github/addons/web_calendar/static/lib/dhtmlxScheduler/codebase/connector/db_oracle.php | PHP | agpl-3.0 | 2,476 |
/**
* @preserve
* FullCalendar v1.6.4
* http://arshaw.com/fullcalendar/
*
* Use fullcalendar.css for basic styling.
* For event drag & drop, requires jQuery UI draggable.
* For event resizing, requires jQuery UI resizable.
*
* Copyright (c) 2011 Adam Shaw
* Dual licensed under the MIT and GPL licenses, located in
* MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
*
* Date: Sat Nov 19 18:21:10 2011 -0800
*
* AMD by instructure
* Also other edits, marked by INSTRUCTURE:
*/
define(['jquery'], function($, undefined) {
var defaults = {
// display
defaultView: 'month',
aspectRatio: 1.35,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
weekends: true,
weekNumbers: false,
weekNumberCalculation: 'iso',
weekNumberTitle: 'W',
// editing
//editable: false,
//disableDragging: false,
//disableResizing: false,
allDayDefault: true,
ignoreTimezone: true,
// event ajax
lazyFetching: true,
startParam: 'start',
endParam: 'end',
// time formats
titleFormat: {
month: 'MMMM yyyy',
week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}",
day: 'dddd, MMM d, yyyy'
},
columnFormat: {
month: 'ddd',
week: 'ddd M/d',
day: 'dddd M/d'
},
timeFormat: { // for event elements
'': 'h(:mm)t' // default
},
// locale
isRTL: false,
firstDay: 0,
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
buttonText: {
prev: "<span class='fc-text-arrow'>‹</span>",
next: "<span class='fc-text-arrow'>›</span>",
prevYear: "<span class='fc-text-arrow'>«</span>",
nextYear: "<span class='fc-text-arrow'>»</span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
// jquery-ui theming
theme: false,
buttonIcons: {
prev: 'circle-triangle-w',
next: 'circle-triangle-e'
},
//selectable: false,
unselectAuto: true,
dropAccept: '*',
handleWindowResize: true
};
// right-to-left defaults
var rtlDefaults = {
header: {
left: 'next,prev today',
center: '',
right: 'title'
},
buttonText: {
prev: "<span class='fc-text-arrow'>›</span>",
next: "<span class='fc-text-arrow'>‹</span>",
prevYear: "<span class='fc-text-arrow'>»</span>",
nextYear: "<span class='fc-text-arrow'>«</span>"
},
buttonIcons: {
prev: 'circle-triangle-e',
next: 'circle-triangle-w'
}
};
;;
var fc = $.fullCalendar = { version: "1.6.4" };
var fcViews = fc.views = {};
$.fn.fullCalendar = function(options) {
// method calling
if (typeof options == 'string') {
var args = Array.prototype.slice.call(arguments, 1);
var res;
this.each(function() {
var calendar = $.data(this, 'fullCalendar');
if (calendar && $.isFunction(calendar[options])) {
var r = calendar[options].apply(calendar, args);
if (res === undefined) {
res = r;
}
if (options == 'destroy') {
$.removeData(this, 'fullCalendar');
}
}
});
if (res !== undefined) {
return res;
}
return this;
}
options = options || {};
// would like to have this logic in EventManager, but needs to happen before options are recursively extended
var eventSources = options.eventSources || [];
delete options.eventSources;
if (options.events) {
eventSources.push(options.events);
delete options.events;
}
options = $.extend(true, {},
defaults,
(options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
options
);
this.each(function(i, _element) {
var element = $(_element);
var calendar = new Calendar(element, options, eventSources);
element.data('fullCalendar', calendar); // TODO: look into memory leak implications
calendar.render();
});
return this;
};
// function for adding/overriding defaults
function setDefaults(d) {
$.extend(true, defaults, d);
}
;;
function Calendar(element, options, eventSources) {
var t = this;
// exports
t.options = options;
t.render = render;
t.destroy = destroy;
t.refetchEvents = refetchEvents;
t.reportEvents = reportEvents;
t.reportEventChange = reportEventChange;
t.rerenderEvents = rerenderEvents;
t.changeView = changeView;
t.select = select;
t.unselect = unselect;
t.prev = prev;
t.next = next;
t.prevYear = prevYear;
t.nextYear = nextYear;
t.today = today;
t.gotoDate = gotoDate;
t.incrementDate = incrementDate;
t.formatDate = function(format, date) { return formatDate(format, date, options) };
t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
t.getDate = getDate;
t.getView = getView;
t.option = option;
t.trigger = trigger;
// imports
EventManager.call(t, options, eventSources);
var isFetchNeeded = t.isFetchNeeded;
var fetchEvents = t.fetchEvents;
// locals
var _element = element[0];
var header;
var headerElement;
var content;
var tm; // for making theme classes
var currentView;
var elementOuterWidth;
var suggestedViewHeight;
var resizeUID = 0;
var ignoreWindowResize = 0;
var date = new Date();
var events = [];
var _dragElement;
/* Main Rendering
-----------------------------------------------------------------------------*/
setYMD(date, options.year, options.month, options.date);
function render(inc) {
if (!content) {
initialRender();
}
else if (elementVisible()) {
// mainly for the public API
calcSize();
_renderView(inc);
}
}
function initialRender() {
tm = options.theme ? 'ui' : 'fc';
element.addClass('fc');
if (options.isRTL) {
element.addClass('fc-rtl');
}
else {
element.addClass('fc-ltr');
}
if (options.theme) {
element.addClass('ui-widget');
}
content = $("<div class='fc-content' style='position:relative'/>")
.prependTo(element);
header = new Header(t, options);
headerElement = header.render();
if (headerElement) {
element.prepend(headerElement);
}
changeView(options.defaultView);
if (options.handleWindowResize) {
$(window).resize(windowResize);
}
// needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
if (!bodyVisible()) {
lateRender();
}
}
// called when we know the calendar couldn't be rendered when it was initialized,
// but we think it's ready now
function lateRender() {
setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
renderView();
}
},0);
}
function destroy() {
if (currentView) {
trigger('viewDestroy', currentView, currentView, currentView.element);
currentView.triggerEventDestroy();
}
$(window).unbind('resize', windowResize);
header.destroy();
content.remove();
element.removeClass('fc fc-rtl ui-widget');
}
function elementVisible() {
return element.is(':visible');
}
function bodyVisible() {
return $('body').is(':visible');
}
/* View Rendering
-----------------------------------------------------------------------------*/
function changeView(newViewName) {
if (!currentView || newViewName != currentView.name) {
_changeView(newViewName);
}
}
function _changeView(newViewName) {
ignoreWindowResize++;
if (currentView) {
trigger('viewDestroy', currentView, currentView, currentView.element);
unselect();
currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
freezeContentHeight();
currentView.element.remove();
header.deactivateButton(currentView.name);
}
header.activateButton(newViewName);
currentView = new fcViews[newViewName](
$("<div class='fc-view fc-view-" + newViewName + "' style='position:relative'/>")
.appendTo(content),
t // the calendar object
);
renderView();
unfreezeContentHeight();
ignoreWindowResize--;
}
function renderView(inc) {
if (
!currentView.start || // never rendered before
inc || date < currentView.start || date >= currentView.end // or new date range
) {
if (elementVisible()) {
_renderView(inc);
}
}
}
function _renderView(inc) { // assumes elementVisible
ignoreWindowResize++;
if (currentView.start) { // already been rendered?
trigger('viewDestroy', currentView, currentView, currentView.element);
unselect();
clearEvents();
}
freezeContentHeight();
currentView.render(date, inc || 0); // the view's render method ONLY renders the skeleton, nothing else
setSize();
unfreezeContentHeight();
(currentView.afterRender || noop)();
updateTitle();
updateTodayButton();
trigger('viewRender', currentView, currentView, currentView.element);
currentView.trigger('viewDisplay', _element); // deprecated
ignoreWindowResize--;
getAndRenderEvents();
}
/* Resizing
-----------------------------------------------------------------------------*/
function updateSize() {
if (elementVisible()) {
unselect();
clearEvents();
calcSize();
setSize();
renderEvents();
}
}
function calcSize() { // assumes elementVisible
if (options.contentHeight) {
suggestedViewHeight = options.contentHeight;
}
else if (options.height) {
suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
}
else {
suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
}
}
function setSize() { // assumes elementVisible
if (suggestedViewHeight === undefined) {
calcSize(); // for first time
// NOTE: we don't want to recalculate on every renderView because
// it could result in oscillating heights due to scrollbars.
}
ignoreWindowResize++;
currentView.setHeight(suggestedViewHeight);
currentView.setWidth(content.width());
ignoreWindowResize--;
elementOuterWidth = element.outerWidth();
}
function windowResize() {
if (!ignoreWindowResize) {
if (currentView.start) { // view has already been rendered
var uid = ++resizeUID;
setTimeout(function() { // add a delay
if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
ignoreWindowResize++; // in case the windowResize callback changes the height
updateSize();
currentView.trigger('windowResize', _element);
ignoreWindowResize--;
}
}
}, 200);
}else{
// calendar must have been initialized in a 0x0 iframe that has just been resized
lateRender();
}
}
}
/* Event Fetching/Rendering
-----------------------------------------------------------------------------*/
// TODO: going forward, most of this stuff should be directly handled by the view
function refetchEvents() { // can be called as an API method
clearEvents();
fetchAndRenderEvents();
}
function rerenderEvents(modifiedEventID) { // can be called as an API method
clearEvents();
renderEvents(modifiedEventID);
}
function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack
if (elementVisible()) {
currentView.setEventData(events); // for View.js, TODO: unify with renderEvents
currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements
currentView.trigger('eventAfterAllRender');
}
}
function clearEvents() {
currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
currentView.clearEvents(); // actually remove the DOM elements
currentView.clearEventData(); // for View.js, TODO: unify with clearEvents
}
function getAndRenderEvents() {
if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
fetchAndRenderEvents();
}
else {
renderEvents();
}
}
function fetchAndRenderEvents() {
fetchEvents(currentView.visStart, currentView.visEnd);
// ... will call reportEvents
// ... which will call renderEvents
}
// called when event data arrives
function reportEvents(_events) {
events = _events;
renderEvents();
}
// called when a single event's data has been changed
function reportEventChange(eventID) {
rerenderEvents(eventID);
}
/* Header Updating
-----------------------------------------------------------------------------*/
function updateTitle() {
header.updateTitle(currentView.title);
}
function updateTodayButton() {
var today = new Date();
if (today >= currentView.start && today < currentView.end) {
header.disableButton('today');
}
else {
header.enableButton('today');
}
}
/* Selection
-----------------------------------------------------------------------------*/
function select(start, end, allDay) {
currentView.select(start, end, allDay===undefined ? true : allDay);
}
function unselect() { // safe to be called before renderView
if (currentView) {
currentView.unselect();
}
}
/* Date
-----------------------------------------------------------------------------*/
function prev() {
renderView(-1);
}
function next() {
renderView(1);
}
function prevYear() {
addYears(date, -1);
renderView();
}
function nextYear() {
addYears(date, 1);
renderView();
}
function today() {
date = new Date();
renderView();
}
function gotoDate(year, month, dateOfMonth) {
if (year instanceof Date) {
date = cloneDate(year); // provided 1 argument, a Date
}else{
setYMD(date, year, month, dateOfMonth);
}
renderView();
}
function incrementDate(years, months, days) {
if (years !== undefined) {
addYears(date, years);
}
if (months !== undefined) {
addMonths(date, months);
}
if (days !== undefined) {
addDays(date, days);
}
renderView();
}
function getDate() {
return cloneDate(date);
}
/* Height "Freezing"
-----------------------------------------------------------------------------*/
function freezeContentHeight() {
content.css({
width: '100%',
height: content.height(),
overflow: 'hidden'
});
}
function unfreezeContentHeight() {
content.css({
width: '',
height: '',
overflow: ''
});
}
/* Misc
-----------------------------------------------------------------------------*/
function getView() {
return currentView;
}
function option(name, value) {
if (value === undefined) {
return options[name];
}
if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
options[name] = value;
updateSize();
}
}
function trigger(name, thisObj) {
if (options[name]) {
return options[name].apply(
thisObj || _element,
Array.prototype.slice.call(arguments, 2)
);
}
}
/* External Dragging
------------------------------------------------------------------------*/
if (options.droppable) {
$(document)
.bind('dragstart', function(ev, ui) {
var _e = ev.target;
var e = $(_e);
// INSTRUCTURE: enable dragging to another calendar by checking element
// is not contained in *this* calendar, instead of *any* calendar
if (!$.contains(_element, _e)) { // not already inside this calendar
var accept = options.dropAccept;
if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
_dragElement = _e;
currentView.dragStart(_dragElement, ev, ui);
}
}
})
.bind('dragstop', function(ev, ui) {
if (_dragElement) {
currentView.dragStop(_dragElement, ev, ui);
_dragElement = null;
}
});
}
}
;;
function Header(calendar, options) {
var t = this;
// exports
t.render = render;
t.destroy = destroy;
t.updateTitle = updateTitle;
t.activateButton = activateButton;
t.deactivateButton = deactivateButton;
t.disableButton = disableButton;
t.enableButton = enableButton;
// locals
var element = $([]);
var tm;
function render() {
tm = options.theme ? 'ui' : 'fc';
var sections = options.header;
if (sections) {
element = $("<table class='fc-header' style='width:100%'/>")
.append(
$("<tr/>")
.append(renderSection('left'))
.append(renderSection('center'))
.append(renderSection('right'))
);
return element;
}
}
function destroy() {
element.remove();
}
function renderSection(position) {
var e = $("<td class='fc-header-" + position + "'/>");
var buttonStr = options.header[position];
if (buttonStr) {
$.each(buttonStr.split(' '), function(i) {
if (i > 0) {
e.append("<span class='fc-header-space'/>");
}
var prevButton;
$.each(this.split(','), function(j, buttonName) {
if (buttonName == 'title') {
e.append("<span class='fc-header-title'><h2> </h2></span>");
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
prevButton = null;
}else{
var buttonClick;
if (calendar[buttonName]) {
buttonClick = calendar[buttonName]; // calendar method
}
else if (fcViews[buttonName]) {
buttonClick = function() {
button.removeClass(tm + '-state-hover'); // forget why
calendar.changeView(buttonName);
};
}
if (buttonClick) {
var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
var button = $(
"<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
(icon ?
"<span class='fc-icon-wrap'>" +
"<span class='ui-icon ui-icon-" + icon + "'/>" +
"</span>" :
text
) +
"</span>"
)
.click(function() {
if (!button.hasClass(tm + '-state-disabled')) {
buttonClick();
}
})
.mousedown(function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-down');
})
.mouseup(function() {
button.removeClass(tm + '-state-down');
})
.hover(
function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-hover');
},
function() {
button
.removeClass(tm + '-state-hover')
.removeClass(tm + '-state-down');
}
)
.appendTo(e);
disableTextSelection(button);
if (!prevButton) {
button.addClass(tm + '-corner-left');
}
prevButton = button;
}
}
});
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
});
}
return e;
}
function updateTitle(html) {
element.find('h2')
.html(html);
}
function activateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-active');
}
function deactivateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-active');
}
function disableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-disabled');
}
function enableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-disabled');
}
}
;;
fc.sourceNormalizers = [];
fc.sourceFetchers = [];
var ajaxDefaults = {
dataType: 'json',
cache: false
};
var eventGUID = 1;
function EventManager(options, _sources) {
var t = this;
// exports
t.isFetchNeeded = isFetchNeeded;
t.fetchEvents = fetchEvents;
t.addEventSource = addEventSource;
t.removeEventSource = removeEventSource;
t.updateEvent = updateEvent;
t.renderEvent = renderEvent;
t.removeEvents = removeEvents;
t.clientEvents = clientEvents;
t.normalizeEvent = normalizeEvent;
// imports
var trigger = t.trigger;
var getView = t.getView;
var reportEvents = t.reportEvents;
// locals
var stickySource = { events: [] };
var sources = [ stickySource ];
var rangeStart, rangeEnd;
var currentFetchID = 0;
var pendingSourceCnt = 0;
var loadingLevel = 0;
var cache = [];
for (var i=0; i<_sources.length; i++) {
_addEventSource(_sources[i]);
}
/* Fetching
-----------------------------------------------------------------------------*/
function isFetchNeeded(start, end) {
return !rangeStart || start < rangeStart || end > rangeEnd;
}
function fetchEvents(start, end) {
rangeStart = start;
rangeEnd = end;
cache = [];
var fetchID = ++currentFetchID;
var len = sources.length;
pendingSourceCnt = len;
for (var i=0; i<len; i++) {
fetchEventSource(sources[i], fetchID);
}
}
function fetchEventSource(source, fetchID) {
_fetchEventSource(source, function(events) {
if (fetchID == currentFetchID) {
if (events) {
if (options.eventDataTransform) {
events = $.map(events, options.eventDataTransform);
}
if (source.eventDataTransform) {
events = $.map(events, source.eventDataTransform);
}
// TODO: this technique is not ideal for static array event sources.
// For arrays, we'll want to process all events right in the beginning, then never again.
for (var i=0; i<events.length; i++) {
events[i].source = source;
normalizeEvent(events[i]);
}
cache = cache.concat(events);
}
pendingSourceCnt--;
if (!pendingSourceCnt) {
reportEvents(cache);
}
}
});
}
function _fetchEventSource(source, callback) {
var i;
var fetchers = fc.sourceFetchers;
var res;
for (i=0; i<fetchers.length; i++) {
res = fetchers[i](source, rangeStart, rangeEnd, callback);
if (res === true) {
// the fetcher is in charge. made its own async request
return;
}
else if (typeof res == 'object') {
// the fetcher returned a new source. process it
_fetchEventSource(res, callback);
return;
}
}
var events = source.events;
if (events) {
if ($.isFunction(events)) {
pushLoading();
events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
callback(events);
popLoading();
});
}
else if ($.isArray(events)) {
callback(events);
}
else {
callback();
}
}else{
var url = source.url;
if (url) {
var success = source.success;
var error = source.error;
var complete = source.complete;
// retrieve any outbound GET/POST $.ajax data from the options
var customData;
if ($.isFunction(source.data)) {
// supplied as a function that returns a key/value object
customData = source.data();
}
else {
// supplied as a straight key/value object
customData = source.data;
}
// use a copy of the custom data so we can modify the parameters
// and not affect the passed-in object.
var data = $.extend({}, customData || {});
var startParam = firstDefined(source.startParam, options.startParam);
var endParam = firstDefined(source.endParam, options.endParam);
if (startParam) {
data[startParam] = Math.round(+rangeStart / 1000);
}
if (endParam) {
data[endParam] = Math.round(+rangeEnd / 1000);
}
pushLoading();
$.ajax($.extend({}, ajaxDefaults, source, {
data: data,
success: function(events) {
events = events || [];
var res = applyAll(success, this, arguments);
if ($.isArray(res)) {
events = res;
}
callback(events);
},
error: function() {
applyAll(error, this, arguments);
callback();
},
complete: function() {
applyAll(complete, this, arguments);
popLoading();
}
}));
}else{
callback();
}
}
}
/* Sources
-----------------------------------------------------------------------------*/
function addEventSource(source) {
source = _addEventSource(source);
if (source) {
pendingSourceCnt++;
fetchEventSource(source, currentFetchID); // will eventually call reportEvents
}
}
function _addEventSource(source) {
if ($.isFunction(source) || $.isArray(source)) {
source = { events: source };
}
else if (typeof source == 'string') {
source = { url: source };
}
if (typeof source == 'object') {
normalizeSource(source);
sources.push(source);
return source;
}
}
function removeEventSource(source) {
sources = $.grep(sources, function(src) {
return !isSourcesEqual(src, source);
});
// remove all client events from that source
cache = $.grep(cache, function(e) {
return !isSourcesEqual(e.source, source);
});
reportEvents(cache);
}
/* Manipulation
-----------------------------------------------------------------------------*/
function updateEvent(event) { // update an existing event
var i, len = cache.length, e,
defaultEventEnd = getView().defaultEventEnd, // getView???
startDelta = event.start - event._start,
endDelta = event.end ?
(event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
: 0; // was null and event was just resized
for (i=0; i<len; i++) {
e = cache[i];
if (e._id == event._id && e != event) {
e.start = new Date(+e.start + startDelta);
if (event.end) {
if (e.end) {
e.end = new Date(+e.end + endDelta);
}else{
e.end = new Date(+defaultEventEnd(e) + endDelta);
}
}else{
e.end = null;
}
e.title = event.title;
e.url = event.url;
e.allDay = event.allDay;
e.className = event.className;
e.editable = event.editable;
e.color = event.color;
e.backgroundColor = event.backgroundColor;
e.borderColor = event.borderColor;
e.textColor = event.textColor;
normalizeEvent(e);
}
}
normalizeEvent(event);
reportEvents(cache);
}
function renderEvent(event, stick) {
normalizeEvent(event);
if (!event.source) {
if (stick) {
stickySource.events.push(event);
event.source = stickySource;
}
cache.push(event);
}
reportEvents(cache);
}
function removeEvents(filter) {
if (!filter) { // remove all
cache = [];
// clear all array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = [];
}
}
}else{
if (!$.isFunction(filter)) { // an event ID
var id = filter + '';
filter = function(e) {
return e._id == id;
};
}
cache = $.grep(cache, filter, true);
// remove events from array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = $.grep(sources[i].events, filter, true);
}
}
}
reportEvents(cache);
}
function clientEvents(filter) {
if ($.isFunction(filter)) {
return $.grep(cache, filter);
}
else if (filter) { // an event ID
filter += '';
return $.grep(cache, function(e) {
return e._id == filter;
});
}
return cache; // else, return all
}
/* Loading State
-----------------------------------------------------------------------------*/
function pushLoading() {
if (!loadingLevel++) {
trigger('loading', null, true, getView());
}
}
function popLoading() {
if (!--loadingLevel) {
trigger('loading', null, false, getView());
}
}
/* Event Normalization
-----------------------------------------------------------------------------*/
function normalizeEvent(event) {
var source = event.source || {};
var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
if (event.date) {
if (!event.start) {
event.start = event.date;
}
delete event.date;
}
event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
event.end = parseDate(event.end, ignoreTimezone);
if (event.end && event.end <= event.start) {
event.end = null;
}
event._end = event.end ? cloneDate(event.end) : null;
if (event.allDay === undefined) {
event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
}
if (event.className) {
if (typeof event.className == 'string') {
event.className = event.className.split(/\s+/);
}
}else{
event.className = [];
}
// TODO: if there is no start date, return false to indicate an invalid event
}
/* Utils
------------------------------------------------------------------------------*/
function normalizeSource(source) {
if (source.className) {
// TODO: repeat code, same code for event classNames
if (typeof source.className == 'string') {
source.className = source.className.split(/\s+/);
}
}else{
source.className = [];
}
var normalizers = fc.sourceNormalizers;
for (var i=0; i<normalizers.length; i++) {
normalizers[i](source);
}
}
function isSourcesEqual(source1, source2) {
return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
}
function getSourcePrimitive(source) {
return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
}
}
;;
fc.addDays = addDays;
fc.cloneDate = cloneDate;
fc.parseDate = parseDate;
fc.parseISO8601 = parseISO8601;
fc.parseTime = parseTime;
fc.formatDate = formatDate;
fc.formatDates = formatDates;
/* Date Math
-----------------------------------------------------------------------------*/
var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
DAY_MS = 86400000,
HOUR_MS = 3600000,
MINUTE_MS = 60000;
function addYears(d, n, keepTime) {
d.setFullYear(d.getFullYear() + n);
if (!keepTime) {
clearTime(d);
}
return d;
}
function addMonths(d, n, keepTime) { // prevents day overflow/underflow
if (+d) { // prevent infinite looping on invalid dates
var m = d.getMonth() + n,
check = cloneDate(d);
check.setDate(1);
check.setMonth(m);
d.setMonth(m);
if (!keepTime) {
clearTime(d);
}
while (d.getMonth() != check.getMonth()) {
d.setDate(d.getDate() + (d < check ? 1 : -1));
}
}
return d;
}
function addDays(d, n, keepTime) { // deals with daylight savings
if (+d) {
var dd = d.getDate() + n,
check = cloneDate(d);
check.setHours(9); // set to middle of day
check.setDate(dd);
d.setDate(dd);
if (!keepTime) {
clearTime(d);
}
fixDate(d, check);
}
return d;
}
function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
if (+d) { // prevent infinite looping on invalid dates
while (d.getDate() != check.getDate()) {
d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
}
}
}
function addMinutes(d, n) {
d.setMinutes(d.getMinutes() + n);
return d;
}
function clearTime(d) {
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
}
function cloneDate(d, dontKeepTime) {
if (dontKeepTime) {
return clearTime(new Date(+d));
}
return new Date(+d);
}
function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
var i=0, d;
do {
d = new Date(1970, i++, 1);
} while (d.getHours()); // != 0
return d;
}
function dayDiff(d1, d2) { // d1 - d2
return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
}
function setYMD(date, y, m, d) {
if (y !== undefined && y != date.getFullYear()) {
date.setDate(1);
date.setMonth(0);
date.setFullYear(y);
}
if (m !== undefined && m != date.getMonth()) {
date.setDate(1);
date.setMonth(m);
}
if (d !== undefined) {
date.setDate(d);
}
}
/* Date Parsing
-----------------------------------------------------------------------------*/
function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
if (typeof s == 'object') { // already a Date object
return s;
}
if (typeof s == 'number') { // a UNIX timestamp
return new Date(s * 1000);
}
if (typeof s == 'string') {
if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
return new Date(parseFloat(s) * 1000);
}
if (ignoreTimezone === undefined) {
ignoreTimezone = true;
}
return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
}
// TODO: never return invalid dates (like from new Date(<string>)), return null instead
return null;
}
function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
// derived from http://delete.me.uk/2005/03/iso8601.html
// TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);
if (!m) {
return null;
}
var date = new Date(m[1], 0, 1);
if (ignoreTimezone || !m[13]) {
var check = new Date(m[1], 0, 1, 9, 0);
if (m[3]) {
date.setMonth(m[3] - 1);
check.setMonth(m[3] - 1);
}
if (m[5]) {
date.setDate(m[5]);
check.setDate(m[5]);
}
fixDate(date, check);
if (m[7]) {
date.setHours(m[7]);
}
if (m[8]) {
date.setMinutes(m[8]);
}
if (m[10]) {
date.setSeconds(m[10]);
}
if (m[12]) {
date.setMilliseconds(Number("0." + m[12]) * 1000);
}
fixDate(date, check);
}else{
date.setUTCFullYear(
m[1],
m[3] ? m[3] - 1 : 0,
m[5] || 1
);
date.setUTCHours(
m[7] || 0,
m[8] || 0,
m[10] || 0,
m[12] ? Number("0." + m[12]) * 1000 : 0
);
if (m[14]) {
var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
offset *= m[15] == '-' ? 1 : -1;
date = new Date(+date + (offset * 60 * 1000));
}
}
return date;
}
function parseTime(s) { // returns minutes since start of day
if (typeof s == 'number') { // an hour
return s * 60;
}
if (typeof s == 'object') { // a Date object
return s.getHours() * 60 + s.getMinutes();
}
var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
if (m) {
var h = parseInt(m[1], 10);
if (m[3]) {
h %= 12;
if (m[3].toLowerCase().charAt(0) == 'p') {
h += 12;
}
}
return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
}
}
/* Date Formatting
-----------------------------------------------------------------------------*/
// TODO: use same function formatDate(date, [date2], format, [options])
function formatDate(date, format, options) {
return formatDates(date, null, format, options);
}
function formatDates(date1, date2, format, options) {
options = options || defaults;
var date = date1,
otherDate = date2,
i, len = format.length, c,
i2, formatter,
res = '';
for (i=0; i<len; i++) {
c = format.charAt(i);
if (c == "'") {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == "'") {
if (date) {
if (i2 == i+1) {
res += "'";
}else{
res += format.substring(i+1, i2);
}
i = i2;
}
break;
}
}
}
else if (c == '(') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ')') {
var subres = formatDate(date, format.substring(i+1, i2), options);
if (parseInt(subres.replace(/\D/, ''), 10)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '[') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ']') {
var subformat = format.substring(i+1, i2);
var subres = formatDate(date, subformat, options);
if (subres != formatDate(otherDate, subformat, options)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '{') {
date = date2;
otherDate = date1;
}
else if (c == '}') {
date = date1;
otherDate = date2;
}
else {
for (i2=len; i2>i; i2--) {
if (formatter = dateFormatters[format.substring(i, i2)]) {
if (date) {
res += formatter(date, options);
}
i = i2 - 1;
break;
}
}
if (i2 == i) {
if (date) {
res += c;
}
}
}
}
return res;
};
var dateFormatters = {
s : function(d) { return d.getSeconds() },
ss : function(d) { return zeroPad(d.getSeconds()) },
m : function(d) { return d.getMinutes() },
mm : function(d) { return zeroPad(d.getMinutes()) },
h : function(d) { return d.getHours() % 12 || 12 },
hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
H : function(d) { return d.getHours() },
HH : function(d) { return zeroPad(d.getHours()) },
d : function(d) { return d.getDate() },
dd : function(d) { return zeroPad(d.getDate()) },
ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
dddd: function(d,o) { return o.dayNames[d.getDay()] },
M : function(d) { return d.getMonth() + 1 },
MM : function(d) { return zeroPad(d.getMonth() + 1) },
MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
yy : function(d) { return (d.getFullYear()+'').substring(2) },
yyyy: function(d) { return d.getFullYear() },
t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
S : function(d) {
var date = d.getDate();
if (date > 10 && date < 20) {
return 'th';
}
return ['st', 'nd', 'rd'][date%10-1] || 'th';
},
w : function(d, o) { // local
return o.weekNumberCalculation(d);
},
W : function(d) { // ISO
return iso8601Week(d);
}
};
fc.dateFormatters = dateFormatters;
/* thanks jQuery UI (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js)
*
* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* `date` - the date to get the week for
* `number` - the number of the week within the year that contains this date
*/
function iso8601Week(date) {
var time;
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
;;
fc.applyAll = applyAll;
/* Event Date Math
-----------------------------------------------------------------------------*/
function exclEndDay(event) {
if (event.end) {
return _exclEndDay(event.end, event.allDay);
}else{
return addDays(cloneDate(event.start), 1);
}
}
function _exclEndDay(end, allDay) {
end = cloneDate(end);
return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
// why don't we check for seconds/ms too?
}
/* Event Element Binding
-----------------------------------------------------------------------------*/
function lazySegBind(container, segs, bindHandlers) {
container.unbind('mouseover').mouseover(function(ev) {
var parent=ev.target, e,
i, seg;
while (parent != this) {
e = parent;
parent = parent.parentNode;
}
if ((i = e._fci) !== undefined) {
e._fci = undefined;
seg = segs[i];
bindHandlers(seg.event, seg.element, seg);
$(ev.target).trigger(ev);
}
ev.stopPropagation();
});
}
/* Element Dimensions
-----------------------------------------------------------------------------*/
function setOuterWidth(element, width, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.width(Math.max(0, width - hsides(e, includeMargins)));
}
}
function setOuterHeight(element, height, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.height(Math.max(0, height - vsides(e, includeMargins)));
}
}
function hsides(element, includeMargins) {
return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
}
function hpadding(element) {
return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
(parseFloat($.css(element[0], 'paddingRight', true)) || 0);
}
function hmargins(element) {
return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
(parseFloat($.css(element[0], 'marginRight', true)) || 0);
}
function hborders(element) {
return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
}
function vsides(element, includeMargins) {
return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
}
function vpadding(element) {
return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
(parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
}
function vmargins(element) {
return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
(parseFloat($.css(element[0], 'marginBottom', true)) || 0);
}
function vborders(element) {
return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
}
/* Misc Utils
-----------------------------------------------------------------------------*/
//TODO: arraySlice
//TODO: isFunction, grep ?
function noop() { }
function dateCompare(a, b) {
return a - b;
}
function arrayMax(a) {
return Math.max.apply(Math, a);
}
function zeroPad(n) {
return (n < 10 ? '0' : '') + n;
}
function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
if (obj[name] !== undefined) {
return obj[name];
}
var parts = name.split(/(?=[A-Z])/),
i=parts.length-1, res;
for (; i>=0; i--) {
res = obj[parts[i].toLowerCase()];
if (res !== undefined) {
return res;
}
}
return obj[''];
}
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />');
}
function disableTextSelection(element) {
element
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; });
}
/*
function enableTextSelection(element) {
element
.attr('unselectable', 'off')
.css('MozUserSelect', '')
.unbind('selectstart.ui');
}
*/
function markFirstLast(e) {
e.children()
.removeClass('fc-first fc-last')
.filter(':first-child')
.addClass('fc-first')
.end()
.filter(':last-child')
.addClass('fc-last');
}
function setDayID(cell, date) {
cell.each(function(i, _cell) {
_cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
// TODO: make a way that doesn't rely on order of classes
});
}
function getSkinCss(event, opt) {
var source = event.source || {};
var eventColor = event.color;
var sourceColor = source.color;
var optionColor = opt('eventColor');
var backgroundColor =
event.backgroundColor ||
eventColor ||
source.backgroundColor ||
sourceColor ||
opt('eventBackgroundColor') ||
optionColor;
var borderColor =
event.borderColor ||
eventColor ||
source.borderColor ||
sourceColor ||
opt('eventBorderColor') ||
optionColor;
var textColor =
event.textColor ||
source.textColor ||
opt('eventTextColor');
var statements = [];
if (backgroundColor) {
statements.push('background-color:' + backgroundColor);
}
if (borderColor) {
statements.push('border-color:' + borderColor);
}
if (textColor) {
statements.push('color:' + textColor);
}
return statements.join(';');
}
function applyAll(functions, thisObj, args) {
if ($.isFunction(functions)) {
functions = [ functions ];
}
if (functions) {
var i;
var ret;
for (i=0; i<functions.length; i++) {
ret = functions[i].apply(thisObj, args) || ret;
}
return ret;
}
}
function firstDefined() {
for (var i=0; i<arguments.length; i++) {
if (arguments[i] !== undefined) {
return arguments[i];
}
}
}
;;
fcViews.month = MonthView;
function MonthView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'month');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addMonths(date, delta);
date.setDate(1);
}
var firstDay = opt('firstDay');
var start = cloneDate(date, true);
start.setDate(1);
var end = addMonths(cloneDate(start), 1);
var visStart = cloneDate(start);
addDays(visStart, -((visStart.getDay() - firstDay + 7) % 7));
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
addDays(visEnd, (7 - visEnd.getDay() + firstDay) % 7);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
var rowCnt = Math.round(dayDiff(visEnd, visStart) / 7); // should be no need for Math.round
if (opt('weekMode') == 'fixed') {
addDays(visEnd, (6 - rowCnt) * 7); // add weeks to make up for it
rowCnt = 6;
}
t.title = formatDate(start, opt('titleFormat'));
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderBasic(rowCnt, colCnt, true);
}
}
;;
fcViews.basicWeek = BasicWeekView;
function BasicWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicWeek');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
renderBasic(1, colCnt, false);
}
}
;;
fcViews.basicDay = BasicDayView;
function BasicDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicDay');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
}
skipHiddenDays(date, delta < 0 ? -1 : 1);
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderBasic(1, 1, false);
}
}
;;
setDefaults({
weekMode: 'fixed'
});
function BasicView(element, calendar, viewName) {
var t = this;
// exports
t.renderBasic = renderBasic;
t.setHeight = setHeight;
t.setWidth = setWidth;
t.renderDayOverlay = renderDayOverlay;
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // for selection (kinda hacky)
t.dragStart = dragStart;
t.dragStop = dragStop;
t.defaultEventEnd = defaultEventEnd;
t.getHoverListener = function() { return hoverListener };
t.colLeft = colLeft;
t.colRight = colRight;
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getIsCellAllDay = function() { return true };
t.allDayRow = allDayRow;
t.getRowCnt = function() { return rowCnt };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getDaySegmentContainer = function() { return daySegmentContainer };
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
BasicEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var daySelectionMousedown = t.daySelectionMousedown;
var cellToDate = t.cellToDate;
var dateToCell = t.dateToCell;
var rangeToSegments = t.rangeToSegments;
var formatDate = calendar.formatDate;
// locals
var table;
var head;
var headCells;
var body;
var bodyRows;
var bodyCells;
var bodyFirstCells;
var firstRowCellInners;
var firstRowCellContentInners;
var daySegmentContainer;
var viewWidth;
var viewHeight;
var colWidth;
var weekNumberWidth;
var rowCnt, colCnt;
var showNumbers;
var coordinateGrid;
var hoverListener;
var colPositions;
var colContentPositions;
var tm;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-grid'));
function renderBasic(_rowCnt, _colCnt, _showNumbers) {
rowCnt = _rowCnt;
colCnt = _colCnt;
showNumbers = _showNumbers;
updateOptions();
if (!body) {
buildEventContainer();
}
buildTable();
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
}
function buildEventContainer() {
daySegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(element);
}
function buildTable() {
var html = buildTableHTML();
if (table) {
table.remove();
}
table = $(html).appendTo(element);
head = table.find('thead');
headCells = head.find('.fc-day-header');
body = table.find('tbody');
bodyRows = body.find('tr');
bodyCells = body.find('.fc-day');
bodyFirstCells = bodyRows.find('td:first-child');
firstRowCellInners = bodyRows.eq(0).find('.fc-day > div');
firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div');
markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
markFirstLast(bodyRows); // marks first+last td's
bodyRows.eq(0).addClass('fc-first');
bodyRows.filter(':last').addClass('fc-last');
bodyCells.each(function(i, _cell) {
var date = cellToDate(
Math.floor(i / colCnt),
i % colCnt
);
trigger('dayRender', t, date, $(_cell));
});
dayBind(bodyCells);
}
/* HTML Building
-----------------------------------------------------------*/
function buildTableHTML() {
var html =
"<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
buildHeadHTML() +
buildBodyHTML() +
"</table>";
return html;
}
function buildHeadHTML() {
var headerClass = tm + "-widget-header";
var html = '';
var col;
var date;
html += "<thead><tr>";
if (showWeekNumbers) {
html +=
"<th class='fc-week-number " + headerClass + "'>" +
htmlEscape(weekNumberTitle) +
"</th>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
html +=
"<th class='fc-day-header fc-" + dayIDs[date.getDay()] + " " + headerClass + "'>" +
htmlEscape(formatDate(date, colFormat)) +
"</th>";
}
html += "</tr></thead>";
return html;
}
function buildBodyHTML() {
var contentClass = tm + "-widget-content";
var html = '';
var row;
var col;
var date;
html += "<tbody>";
for (row=0; row<rowCnt; row++) {
html += "<tr class='fc-week'>";
if (showWeekNumbers) {
date = cellToDate(row, 0);
html +=
"<td class='fc-week-number " + contentClass + "'>" +
"<div>" +
htmlEscape(formatDate(date, weekNumberFormat)) +
"</div>" +
"</td>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(row, col);
html += buildCellHTML(date);
}
html += "</tr>";
}
html += "</tbody>";
return html;
}
function buildCellHTML(date) {
var contentClass = tm + "-widget-content";
var month = t.start.getMonth();
var today = clearTime(new Date());
var html = '';
var classNames = [
'fc-day',
'fc-' + dayIDs[date.getDay()],
contentClass
];
if (date.getMonth() != month) {
classNames.push('fc-other-month');
}
if (+date == +today) {
classNames.push(
'fc-today',
tm + '-state-highlight'
);
}
else if (date < today) {
classNames.push('fc-past');
}
else {
classNames.push('fc-future');
}
html +=
"<td" +
" class='" + classNames.join(' ') + "'" +
" data-date='" + formatDate(date, 'yyyy-MM-dd') + "'" +
">" +
"<div>";
if (showNumbers) {
html += "<div class='fc-day-number'>" + date.getDate() + "</div>";
}
html +=
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
return html;
}
/* Dimensions
-----------------------------------------------------------*/
function setHeight(height) {
viewHeight = height;
var bodyHeight = viewHeight - head.height();
var rowHeight;
var rowHeightLast;
var cell;
if (opt('weekMode') == 'variable') {
rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
}else{
rowHeight = Math.floor(bodyHeight / rowCnt);
rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
}
bodyFirstCells.each(function(i, _cell) {
if (i < rowCnt) {
cell = $(_cell);
cell.find('> div').css(
'min-height',
(i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
);
}
});
}
function setWidth(width) {
viewWidth = width;
colPositions.clear();
colContentPositions.clear();
weekNumberWidth = 0;
if (showWeekNumbers) {
weekNumberWidth = head.find('th.fc-week-number').outerWidth();
}
colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
setOuterWidth(headCells.slice(0, -1), colWidth);
}
/* Day clicking and binding
-----------------------------------------------------------*/
function dayBind(days) {
days.click(dayClick)
.mousedown(daySelectionMousedown);
}
function dayClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var date = parseISO8601($(this).data('date'));
trigger('dayClick', this, date, true, ev);
}
}
/* Semi-transparent Overlay Helpers
------------------------------------------------------*/
// TODO: should be consolidated with AgendaView's methods
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var segments = rangeToSegments(overlayStart, overlayEnd);
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
dayBind(
renderCellOverlay(
segment.row,
segment.leftCol,
segment.row,
segment.rightCol
)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
return renderOverlay(rect, element);
}
/* Selection
-----------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
return cloneDate(startDate);
}
function renderSelection(startDate, endDate, allDay) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
}
function clearSelection() {
clearOverlays();
}
function reportDayClick(date, allDay, ev) {
var cell = dateToCell(date);
var _element = bodyCells[cell.row*colCnt + cell.col];
trigger('dayClick', _element, date, allDay, ev);
}
/* External Dragging
-----------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
var d = cellToDate(cell);
trigger('drop', _dragElement, d, true, ev, ui);
}
}
/* Utilities
--------------------------------------------------------*/
function defaultEventEnd(event) {
return cloneDate(event.start);
}
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
// INSTRUCTURE: use bodyRows instead of headCells to calculate cell widths
// so we can hide the thead with css.
bodyRows.first().find('td').each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
bodyRows.each(function(i, _e) {
if (i < rowCnt) {
e = $(_e);
n = e.offset().top;
if (i) {
p[1] = n;
}
p = [n];
rows[i] = p;
}
});
p[1] = n + e.outerHeight();
});
hoverListener = new HoverListener(coordinateGrid);
colPositions = new HorizontalPositionCache(function(col) {
return firstRowCellInners.eq(col);
});
colContentPositions = new HorizontalPositionCache(function(col) {
return firstRowCellContentInners.eq(col);
});
function colLeft(col) {
return colPositions.left(col);
}
function colRight(col) {
return colPositions.right(col);
}
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function allDayRow(i) {
return bodyRows.eq(i);
}
}
;;
function BasicEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
// imports
DayEventRenderer.call(t);
function renderEvents(events, modifiedEventId) {
t.renderDayEvents(events, modifiedEventId);
}
function clearEvents() {
t.getDaySegmentContainer().empty();
}
// TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
}
;;
fcViews.agendaWeek = AgendaWeekView;
function AgendaWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaWeek');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderAgenda(colCnt);
}
}
;;
fcViews.agendaDay = AgendaDayView;
function AgendaDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaDay');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var skipHiddenDays = t.skipHiddenDays;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
}
skipHiddenDays(date, delta < 0 ? -1 : 1);
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderAgenda(1);
}
}
;;
setDefaults({
allDaySlot: true,
allDayText: 'all-day',
firstHour: 6,
slotMinutes: 30,
defaultEventMinutes: 120,
axisFormat: 'h(:mm)tt',
timeFormat: {
agenda: 'h:mm{ - h:mm}'
},
dragOpacity: {
agenda: .5
},
minTime: 0,
maxTime: 24,
slotEventOverlap: true
});
// TODO: make it work in quirks mode (event corners, all-day height)
// TODO: test liquid width, especially in IE6
function AgendaView(element, calendar, viewName) {
var t = this;
// exports
t.renderAgenda = renderAgenda;
t.setWidth = setWidth;
t.setHeight = setHeight;
t.afterRender = afterRender;
t.defaultEventEnd = defaultEventEnd;
t.timePosition = timePosition;
t.getIsCellAllDay = getIsCellAllDay;
t.allDayRow = getAllDayRow;
t.getCoordinateGrid = function() { return coordinateGrid }; // specifically for AgendaEventRenderer
t.getHoverListener = function() { return hoverListener };
t.colLeft = colLeft;
t.colRight = colRight;
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getDaySegmentContainer = function() { return daySegmentContainer };
t.getSlotSegmentContainer = function() { return slotSegmentContainer };
t.getMinMinute = function() { return minMinute };
t.getMaxMinute = function() { return maxMinute };
t.getSlotContainer = function() { return slotContainer };
t.getRowCnt = function() { return 1 };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getSnapHeight = function() { return snapHeight };
t.getSnapMinutes = function() { return snapMinutes };
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderDayOverlay = renderDayOverlay;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // selection mousedown hack
t.dragStart = dragStart;
t.dragStop = dragStop;
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
AgendaEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var reportSelection = t.reportSelection;
var unselect = t.unselect;
var daySelectionMousedown = t.daySelectionMousedown;
var slotSegHtml = t.slotSegHtml;
var cellToDate = t.cellToDate;
var dateToCell = t.dateToCell;
var rangeToSegments = t.rangeToSegments;
var formatDate = calendar.formatDate;
// locals
var dayTable;
var dayHead;
var dayHeadCells;
var dayBody;
var dayBodyCells;
var dayBodyCellInners;
var dayBodyCellContentInners;
var dayBodyFirstCell;
var dayBodyFirstCellStretcher;
var slotLayer;
var daySegmentContainer;
var allDayTable;
var allDayRow;
var slotScroller;
var slotContainer;
var slotSegmentContainer;
var slotTable;
var selectionHelper;
var viewWidth;
var viewHeight;
var axisWidth;
var colWidth;
var gutterWidth;
var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
var snapMinutes;
var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
var snapHeight; // holds the pixel hight of a "selection" slot
var colCnt;
var slotCnt;
var coordinateGrid;
var hoverListener;
var colPositions;
var colContentPositions;
var slotTopCache = {};
var tm;
var rtl;
var minMinute, maxMinute;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
-----------------------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-agenda'));
function renderAgenda(c) {
colCnt = c;
updateOptions();
if (!dayTable) { // first time rendering?
buildSkeleton(); // builds day table, slot area, events containers
}
else {
buildDayTable(); // rebuilds day table
}
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
rtl = opt('isRTL')
minMinute = parseTime(opt('minTime'));
maxMinute = parseTime(opt('maxTime'));
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
snapMinutes = opt('snapMinutes') || opt('slotMinutes');
}
/* Build DOM
-----------------------------------------------------------------------*/
function buildSkeleton() {
var headerClass = tm + "-widget-header";
var contentClass = tm + "-widget-content";
var s;
var d;
var i;
var maxd;
var minutes;
var slotNormal = opt('slotMinutes') % 15 == 0;
buildDayTable();
slotLayer =
$("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
.appendTo(element);
if (opt('allDaySlot')) {
daySegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotLayer);
s =
"<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
"<tr>" +
"<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
"<td>" +
"<div class='fc-day-content'><div style='position:relative'/></div>" +
"</td>" +
"<th class='" + headerClass + " fc-agenda-gutter'> </th>" +
"</tr>" +
"</table>";
allDayTable = $(s).appendTo(slotLayer);
allDayRow = allDayTable.find('tr');
dayBind(allDayRow.find('td'));
slotLayer.append(
"<div class='fc-agenda-divider " + headerClass + "'>" +
"<div class='fc-agenda-divider-inner'/>" +
"</div>"
);
}else{
daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
}
slotScroller =
$("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
.appendTo(slotLayer);
slotContainer =
$("<div style='position:relative;width:100%;overflow:hidden'/>")
.appendTo(slotScroller);
slotSegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotContainer);
s =
"<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
"<tbody>";
d = zeroDate();
maxd = addMinutes(cloneDate(d), maxMinute);
addMinutes(d, minMinute);
slotCnt = 0;
for (i=0; d < maxd; i++) {
minutes = d.getMinutes();
s +=
"<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
"<th class='fc-agenda-axis " + headerClass + "'>" +
((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') +
"</th>" +
"<td class='" + contentClass + "'>" +
"<div style='position:relative'> </div>" +
"</td>" +
"</tr>";
addMinutes(d, opt('slotMinutes'));
slotCnt++;
}
s +=
"</tbody>" +
"</table>";
slotTable = $(s).appendTo(slotContainer);
slotBind(slotTable.find('td'));
}
/* Build Day Table
-----------------------------------------------------------------------*/
function buildDayTable() {
var html = buildDayTableHTML();
if (dayTable) {
dayTable.remove();
}
dayTable = $(html).appendTo(element);
dayHead = dayTable.find('thead');
dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter
dayBody = dayTable.find('tbody');
dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter
dayBodyCellInners = dayBodyCells.find('> div');
dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div');
dayBodyFirstCell = dayBodyCells.eq(0);
dayBodyFirstCellStretcher = dayBodyCellInners.eq(0);
markFirstLast(dayHead.add(dayHead.find('tr')));
markFirstLast(dayBody.add(dayBody.find('tr')));
// TODO: now that we rebuild the cells every time, we should call dayRender
}
function buildDayTableHTML() {
var html =
"<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
buildDayTableHeadHTML() +
buildDayTableBodyHTML() +
"</table>";
return html;
}
function buildDayTableHeadHTML() {
var headerClass = tm + "-widget-header";
var date;
var html = '';
var weekText;
var col;
html +=
"<thead>" +
"<tr>";
if (showWeekNumbers) {
date = cellToDate(0, 0);
weekText = formatDate(date, weekNumberFormat);
if (rtl) {
weekText += weekNumberTitle;
}
else {
weekText = weekNumberTitle + weekText;
}
html +=
"<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" +
htmlEscape(weekText) +
"</th>";
}
else {
html += "<th class='fc-agenda-axis " + headerClass + "'> </th>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
html +=
"<th class='fc-" + dayIDs[date.getDay()] + " fc-col" + col + ' ' + headerClass + "'>" +
htmlEscape(formatDate(date, colFormat)) +
"</th>";
}
html +=
"<th class='fc-agenda-gutter " + headerClass + "'> </th>" +
"</tr>" +
"</thead>";
return html;
}
function buildDayTableBodyHTML() {
var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called
var contentClass = tm + "-widget-content";
var date;
var today = clearTime(new Date());
var col;
var cellsHTML;
var cellHTML;
var classNames;
var html = '';
html +=
"<tbody>" +
"<tr>" +
"<th class='fc-agenda-axis " + headerClass + "'> </th>";
cellsHTML = '';
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
classNames = [
'fc-col' + col,
'fc-' + dayIDs[date.getDay()],
contentClass
];
if (+date == +today) {
classNames.push(
tm + '-state-highlight',
'fc-today'
);
}
else if (date < today) {
classNames.push('fc-past');
}
else {
classNames.push('fc-future');
}
cellHTML =
"<td class='" + classNames.join(' ') + "'>" +
"<div>" +
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
cellsHTML += cellHTML;
}
html += cellsHTML;
html +=
"<td class='fc-agenda-gutter " + contentClass + "'> </td>" +
"</tr>" +
"</tbody>";
return html;
}
// TODO: data-date on the cells
/* Dimensions
-----------------------------------------------------------------------*/
function setHeight(height) {
if (height === undefined) {
height = viewHeight;
}
viewHeight = height;
slotTopCache = {};
var headHeight = dayBody.position().top;
var allDayHeight = slotScroller.position().top; // including divider
var bodyHeight = Math.min( // total body height, including borders
height - headHeight, // when scrollbars
slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
);
dayBodyFirstCellStretcher
.height(bodyHeight - vsides(dayBodyFirstCell));
slotLayer.css('top', headHeight);
slotScroller.height(bodyHeight - allDayHeight - 1);
// the stylesheet guarantees that the first row has no border.
// this allows .height() to work well cross-browser.
slotHeight = slotTable.find('tr:first').height() + 1; // +1 for bottom border
snapRatio = opt('slotMinutes') / snapMinutes;
snapHeight = slotHeight / snapRatio;
}
function setWidth(width) {
viewWidth = width;
colPositions.clear();
colContentPositions.clear();
var axisFirstCells = dayHead.find('th:first');
if (allDayTable) {
axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
}
axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
axisWidth = 0;
setOuterWidth(
axisFirstCells
.width('')
.each(function(i, _cell) {
axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
}),
axisWidth
);
var gutterCells = dayTable.find('.fc-agenda-gutter');
if (allDayTable) {
gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
}
var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
gutterWidth = slotScroller.width() - slotTableWidth;
if (gutterWidth) {
setOuterWidth(gutterCells, gutterWidth);
gutterCells
.show()
.prev()
.removeClass('fc-last');
}else{
gutterCells
.hide()
.prev()
.addClass('fc-last');
}
colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
}
/* Scrolling
-----------------------------------------------------------------------*/
function resetScroll() {
var d0 = zeroDate();
var scrollDate = cloneDate(d0);
scrollDate.setHours(opt('firstHour'));
var top = timePosition(d0, scrollDate) + 1; // +1 for the border
function scroll() {
slotScroller.scrollTop(top);
}
scroll();
setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
}
function afterRender() { // after the view has been freshly rendered and sized
resetScroll();
}
/* Slot/Day clicking and binding
-----------------------------------------------------------------------*/
function dayBind(cells) {
cells.click(slotClick)
.mousedown(daySelectionMousedown);
}
function slotBind(cells) {
cells.click(slotClick)
.mousedown(slotSelectionMousedown);
}
function slotClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
var date = cellToDate(0, col);
var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
if (rowMatch) {
var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
var hours = Math.floor(mins/60);
date.setHours(hours);
date.setMinutes(mins%60 + minMinute);
trigger('dayClick', dayBodyCells[col], date, false, ev);
}else{
trigger('dayClick', dayBodyCells[col], date, true, ev);
}
}
}
/* Semi-transparent Overlay Helpers
-----------------------------------------------------*/
// TODO: should be consolidated with BasicView's methods
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var segments = rangeToSegments(overlayStart, overlayEnd);
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
dayBind(
renderCellOverlay(
segment.row,
segment.leftCol,
segment.row,
segment.rightCol
)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
return renderOverlay(rect, slotLayer);
}
function renderSlotOverlay(overlayStart, overlayEnd) {
for (var i=0; i<colCnt; i++) {
var dayStart = cellToDate(0, i);
var dayEnd = addDays(cloneDate(dayStart), 1);
var stretchStart = new Date(Math.max(dayStart, overlayStart));
var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
if (stretchStart < stretchEnd) {
var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords
var top = timePosition(dayStart, stretchStart);
var bottom = timePosition(dayStart, stretchEnd);
rect.top = top;
rect.height = bottom - top;
slotBind(
renderOverlay(rect, slotContainer)
);
}
}
}
/* Coordinate Utilities
-----------------------------------------------------------------------------*/
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
dayHeadCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
if (opt('allDaySlot')) {
e = allDayRow;
n = e.offset().top;
rows[0] = [n, n+e.outerHeight()];
}
var slotTableTop = slotContainer.offset().top;
var slotScrollerTop = slotScroller.offset().top;
var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
function constrain(n) {
return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
}
for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
rows.push([
constrain(slotTableTop + snapHeight*i),
constrain(slotTableTop + snapHeight*(i+1))
]);
}
});
hoverListener = new HoverListener(coordinateGrid);
colPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellInners.eq(col);
});
colContentPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellContentInners.eq(col);
});
function colLeft(col) {
return colPositions.left(col);
}
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colRight(col) {
return colPositions.right(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function getIsCellAllDay(cell) {
return opt('allDaySlot') && !cell.row;
}
function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system
var d = cellToDate(0, cell.col);
var slotIndex = cell.row;
if (opt('allDaySlot')) {
slotIndex--;
}
if (slotIndex >= 0) {
addMinutes(d, minMinute + slotIndex * snapMinutes);
}
return d;
}
// get the Y coordinate of the given time on the given day (both Date objects)
function timePosition(day, time) { // both date objects. day holds 00:00 of current day
day = cloneDate(day, true);
if (time < addMinutes(cloneDate(day), minMinute)) {
return 0;
}
if (time >= addMinutes(cloneDate(day), maxMinute)) {
return slotTable.height();
}
var slotMinutes = opt('slotMinutes'),
minutes = time.getHours()*60 + time.getMinutes() - minMinute,
slotI = Math.floor(minutes / slotMinutes),
slotTop = slotTopCache[slotI];
if (slotTop === undefined) {
slotTop = slotTopCache[slotI] =
slotTable.find('tr').eq(slotI).find('td div')[0].offsetTop;
// .eq() is faster than ":eq()" selector
// [0].offsetTop is faster than .position().top (do we really need this optimization?)
// a better optimization would be to cache all these divs
}
return Math.max(0, Math.round(
slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
));
}
function getAllDayRow(index) {
return allDayRow;
}
function defaultEventEnd(event) {
var start = cloneDate(event.start);
if (event.allDay) {
return start;
}
return addMinutes(start, opt('defaultEventMinutes'));
}
/* Selection
---------------------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
if (allDay) {
return cloneDate(startDate);
}
return addMinutes(cloneDate(startDate), opt('slotMinutes'));
}
function renderSelection(startDate, endDate, allDay) { // only for all-day
if (allDay) {
if (opt('allDaySlot')) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
}
}else{
renderSlotSelection(startDate, endDate);
}
}
function renderSlotSelection(startDate, endDate) {
var helperOption = opt('selectHelper');
coordinateGrid.build();
if (helperOption) {
var col = dateToCell(startDate).col;
if (col >= 0 && col < colCnt) { // only works when times are on same day
var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords
var top = timePosition(startDate, startDate);
var bottom = timePosition(startDate, endDate);
if (bottom > top) { // protect against selections that are entirely before or after visible range
rect.top = top;
rect.height = bottom - top;
rect.left += 2;
rect.width -= 5;
if ($.isFunction(helperOption)) {
var helperRes = helperOption(startDate, endDate);
if (helperRes) {
rect.position = 'absolute';
selectionHelper = $(helperRes)
.css(rect)
.appendTo(slotContainer);
}
}else{
rect.isStart = true; // conside rect a "seg" now
rect.isEnd = true; //
selectionHelper = $(slotSegHtml(
{
title: '',
start: startDate,
end: endDate,
className: ['fc-select-helper'],
editable: false
},
rect
));
selectionHelper.css('opacity', opt('dragOpacity'));
}
if (selectionHelper) {
slotBind(selectionHelper);
slotContainer.append(selectionHelper);
setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
setOuterHeight(selectionHelper, rect.height, true);
}
}
}
}else{
renderSlotOverlay(startDate, endDate);
}
}
function clearSelection() {
clearOverlays();
if (selectionHelper) {
selectionHelper.remove();
selectionHelper = null;
}
}
function slotSelectionMousedown(ev) {
if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
unselect(ev);
var dates;
hoverListener.start(function(cell, origCell) {
clearSelection();
if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) {
var d1 = realCellToDate(origCell);
var d2 = realCellToDate(cell);
dates = [
d1,
addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes
d2,
addMinutes(cloneDate(d2), snapMinutes)
].sort(dateCompare);
renderSlotSelection(dates[0], dates[3]);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], false, ev);
}
reportSelection(dates[0], dates[3], false, ev);
}
});
}
}
function reportDayClick(date, allDay, ev) {
trigger('dayClick', dayBodyCells[dateToCell(date).col], date, allDay, ev);
}
/* External Dragging
--------------------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
if (getIsCellAllDay(cell)) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}else{
var d1 = realCellToDate(cell);
var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
renderSlotOverlay(d1, d2);
}
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
trigger('drop', _dragElement, realCellToDate(cell), getIsCellAllDay(cell), ev, ui);
}
}
}
;;
function AgendaEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
t.slotSegHtml = slotSegHtml;
// imports
DayEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var eventElementHandlers = t.eventElementHandlers;
var setHeight = t.setHeight;
var getDaySegmentContainer = t.getDaySegmentContainer;
var getSlotSegmentContainer = t.getSlotSegmentContainer;
var getHoverListener = t.getHoverListener;
var getMaxMinute = t.getMaxMinute;
var getMinMinute = t.getMinMinute;
var timePosition = t.timePosition;
var getIsCellAllDay = t.getIsCellAllDay;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var cellToDate = t.cellToDate;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var getSnapHeight = t.getSnapHeight;
var getSnapMinutes = t.getSnapMinutes;
var getSlotContainer = t.getSlotContainer;
var reportEventElement = t.reportEventElement;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var renderDayEvents = t.renderDayEvents;
var calendar = t.calendar;
var formatDate = calendar.formatDate;
var formatDates = calendar.formatDates;
// overrides
t.draggableDayEvent = draggableDayEvent;
/* Rendering
----------------------------------------------------------------------------*/
function renderEvents(events, modifiedEventId) {
var i, len=events.length,
dayEvents=[],
slotEvents=[];
for (i=0; i<len; i++) {
if (events[i].allDay) {
dayEvents.push(events[i]);
}else{
slotEvents.push(events[i]);
}
}
if (opt('allDaySlot')) {
renderDayEvents(dayEvents, modifiedEventId);
setHeight(); // no params means set to viewHeight
}
renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
}
function clearEvents() {
getDaySegmentContainer().empty();
getSlotSegmentContainer().empty();
}
function compileSlotSegs(events) {
var colCnt = getColCnt(),
minMinute = getMinMinute(),
maxMinute = getMaxMinute(),
d,
visEventEnds = $.map(events, slotEventEnd),
i,
j, seg,
colSegs,
segs = [];
for (i=0; i<colCnt; i++) {
d = cellToDate(0, i);
addMinutes(d, minMinute);
colSegs = sliceSegs(
events,
visEventEnds,
d,
addMinutes(cloneDate(d), maxMinute-minMinute)
);
colSegs = placeSlotSegs(colSegs); // returns a new order
for (j=0; j<colSegs.length; j++) {
seg = colSegs[j];
seg.col = i;
segs.push(seg);
}
}
return segs;
}
function sliceSegs(events, visEventEnds, start, end) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
eventStart = event.start;
eventEnd = visEventEnds[i];
if (eventEnd > start && eventStart < end) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd
});
}
}
return segs.sort(compareSlotSegs);
}
function slotEventEnd(event) {
if (event.end) {
return cloneDate(event.end);
}else{
return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
}
}
// renders events in the 'time slots' at the bottom
// TODO: when we refactor this, when user returns `false` eventRender, don't have empty space
// TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp)
function renderSlotSegs(segs, modifiedEventId) {
var i, segCnt=segs.length, seg,
event,
top,
bottom,
columnLeft,
columnRight,
columnWidth,
width,
left,
right,
html = '',
eventElements,
eventElement,
triggerRes,
titleElement,
height,
slotSegmentContainer = getSlotSegmentContainer(),
isRTL = opt('isRTL');
// calculate position/dimensions, create html
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
top = timePosition(seg.start, seg.start);
bottom = timePosition(seg.start, seg.end);
columnLeft = colContentLeft(seg.col);
columnRight = colContentRight(seg.col);
columnWidth = columnRight - columnLeft;
// shave off space on right near scrollbars (2.5%)
// TODO: move this to CSS somehow
columnRight -= columnWidth * .025;
columnWidth = columnRight - columnLeft;
width = columnWidth * (seg.forwardCoord - seg.backwardCoord);
if (opt('slotEventOverlap')) {
// double the width while making sure resize handle is visible
// (assumed to be 20px wide)
width = Math.max(
(width - (20/2)) * 2,
width // narrow columns will want to make the segment smaller than
// the natural width. don't allow it
);
}
if (isRTL) {
right = columnRight - seg.backwardCoord * columnWidth;
left = right - width;
}
else {
left = columnLeft + seg.backwardCoord * columnWidth;
right = left + width;
}
// make sure horizontal coordinates are in bounds
left = Math.max(left, columnLeft);
right = Math.min(right, columnRight);
width = right - left;
seg.top = top;
seg.left = left;
seg.outerWidth = width;
seg.outerHeight = bottom - top;
html += slotSegHtml(event, seg);
}
slotSegmentContainer[0].innerHTML = html; // faster than html()
eventElements = slotSegmentContainer.children();
// retrieve elements, run through eventRender callback, bind event handlers
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
eventElement = $(eventElements[i]); // faster than eq()
triggerRes = trigger('eventRender', event, event, eventElement);
if (triggerRes === false) {
eventElement.remove();
}else{
if (triggerRes && triggerRes !== true) {
eventElement.remove();
eventElement = $(triggerRes)
.css({
position: 'absolute',
top: seg.top,
left: seg.left
})
.appendTo(slotSegmentContainer);
}
seg.element = eventElement;
if (event._id === modifiedEventId) {
bindSlotSeg(event, eventElement, seg);
}else{
eventElement[0]._fci = i; // for lazySegBind
}
reportEventElement(event, eventElement);
}
}
lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
// record event sides and title positions
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
seg.vsides = vsides(eventElement, true);
seg.hsides = hsides(eventElement, true);
titleElement = eventElement.find('.fc-event-title');
if (titleElement.length) {
seg.contentTop = titleElement[0].offsetTop;
}
}
}
// set all positions/dimensions at once
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
height = Math.max(0, seg.outerHeight - seg.vsides);
eventElement[0].style.height = height + 'px';
event = seg.event;
if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
// not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
eventElement.find('div.fc-event-time')
.text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
eventElement.find('div.fc-event-title')
.remove();
}
trigger('eventAfterRender', event, event, eventElement);
}
}
}
function slotSegHtml(event, seg) {
var html = "<";
var url = event.url;
var skinCss = getSkinCss(event, opt);
var classes = ['fc-event', 'fc-event-vert'];
if (isEventDraggable(event)) {
classes.push('fc-event-draggable');
}
if (seg.isStart) {
classes.push('fc-event-start');
}
if (seg.isEnd) {
classes.push('fc-event-end');
}
classes = classes.concat(event.className);
if (event.source) {
classes = classes.concat(event.source.className || []);
}
if (url) {
html += "a href='" + htmlEscape(event.url) + "'";
}else{
html += "div";
}
html +=
" class='" + classes.join(' ') + "'" +
" style=" +
"'" +
"position:absolute;" +
"top:" + seg.top + "px;" +
"left:" + seg.left + "px;" +
skinCss +
"'" +
">" +
"<div class='fc-event-inner'>" +
"<div class='fc-event-time'>" +
htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
"</div>" +
"<div class='fc-event-title'>" +
htmlEscape(event.title || '') +
"</div>" +
"</div>" +
"<div class='fc-event-bg'></div>";
if (seg.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-s'>=</div>";
}
html +=
"</" + (url ? "a" : "div") + ">";
return html;
}
function bindSlotSeg(event, eventElement, seg) {
var timeElement = eventElement.find('div.fc-event-time');
if (isEventDraggable(event)) {
draggableSlotEvent(event, eventElement, timeElement);
}
if (seg.isEnd && isEventResizable(event)) {
resizableSlotEvent(event, eventElement, timeElement);
}
eventElementHandlers(event, eventElement);
}
/* Dragging
-----------------------------------------------------------------------------------*/
// when event starts out FULL-DAY
// overrides DayEventRenderer's version because it needs to account for dragging elements
// to and from the slot area.
function draggableDayEvent(event, eventElement, seg) {
var isStart = seg.isStart;
var origWidth;
var revert;
var allDay = true;
var dayDelta;
var hoverListener = getHoverListener();
var colWidth = getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
var minMinute = getMinMinute();
eventElement.draggable({
opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
revertDuration: opt('dragRevertDuration'),
// INSTRUCTURE: Additional drag options to help with dragging to other calendars
helper: opt('dragHelper'),
appendTo: opt('dragAppendTo'),
zIndex: opt('dragZIndex'),
cursorAt: opt('dragCursorAt'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
origWidth = eventElement.width();
hoverListener.start(function(cell, origCell) {
clearOverlays();
if (cell) {
revert = false;
var origDate = cellToDate(0, origCell.col);
var date = cellToDate(0, cell.col);
dayDelta = dayDiff(date, origDate);
if (!cell.row) {
// on full-days
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
resetElement();
}else{
// mouse is over bottom slots
if (isStart) {
if (allDay) {
// convert event to temporary slot-event
eventElement.width(colWidth - 10); // don't use entire width
setOuterHeight(
eventElement,
snapHeight * Math.round(
(event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /
snapMinutes
)
);
eventElement.draggable('option', 'grid', [colWidth, 1]);
allDay = false;
}
}else{
revert = true;
}
}
revert = revert || (allDay && !dayDelta);
}else{
resetElement();
revert = true;
}
eventElement.draggable('option', 'revert', revert);
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (revert) {
// hasn't moved or is out of bounds (draggable has already reverted)
resetElement();
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}else{
// changed!
var minuteDelta = 0;
if (!allDay) {
minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)
* snapMinutes
+ minMinute
- (event.start.getHours() * 60 + event.start.getMinutes());
}
eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
}
}
});
function resetElement() {
if (!allDay) {
eventElement
.width(origWidth)
.height('')
.draggable('option', 'grid', null);
allDay = true;
}
}
}
// when event starts out IN TIMESLOTS
function draggableSlotEvent(event, eventElement, timeElement) {
var coordinateGrid = t.getCoordinateGrid();
var colCnt = getColCnt();
var colWidth = getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
// states
var origPosition; // original position of the element, not the mouse
var origCell;
var isInBounds, prevIsInBounds;
var isAllDay, prevIsAllDay;
var colDelta, prevColDelta;
var dayDelta; // derived from colDelta
var minuteDelta, prevMinuteDelta;
eventElement.draggable({
scroll: false,
grid: [ colWidth, snapHeight ],
axis: colCnt==1 ? 'y' : false,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
// INSTRUCTURE: Additional drag options to help with dragging to other calendars
helper: opt('dragHelper'),
appendTo: opt('dragAppendTo'),
zIndex: opt('dragZIndex'),
cursorAt: opt('dragCursorAt'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
coordinateGrid.build();
// initialize states
origPosition = eventElement.position();
origCell = coordinateGrid.cell(ev.pageX, ev.pageY);
isInBounds = prevIsInBounds = true;
isAllDay = prevIsAllDay = getIsCellAllDay(origCell);
colDelta = prevColDelta = 0;
dayDelta = 0;
minuteDelta = prevMinuteDelta = 0;
},
drag: function(ev, ui) {
// NOTE: this `cell` value is only useful for determining in-bounds and all-day.
// Bad for anything else due to the discrepancy between the mouse position and the
// element position while snapping. (problem revealed in PR #55)
//
// PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event.
// We should overhaul the dragging system and stop relying on jQuery UI.
var cell = coordinateGrid.cell(ev.pageX, ev.pageY);
// update states
isInBounds = !!cell;
if (isInBounds) {
isAllDay = getIsCellAllDay(cell);
// calculate column delta
colDelta = Math.round((ui.position.left - origPosition.left) / colWidth);
if (colDelta != prevColDelta) {
// calculate the day delta based off of the original clicked column and the column delta
var origDate = cellToDate(0, origCell.col);
var col = origCell.col + colDelta;
col = Math.max(0, col);
col = Math.min(colCnt-1, col);
var date = cellToDate(0, col);
dayDelta = dayDiff(date, origDate);
}
// calculate minute delta (only if over slots)
if (!isAllDay) {
minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes;
}
}
// any state changes?
if (
isInBounds != prevIsInBounds ||
isAllDay != prevIsAllDay ||
colDelta != prevColDelta ||
minuteDelta != prevMinuteDelta
) {
updateUI();
// update previous states for next time
prevIsInBounds = isInBounds;
prevIsAllDay = isAllDay;
prevColDelta = colDelta;
prevMinuteDelta = minuteDelta;
}
// if out-of-bounds, revert when done, and vice versa.
eventElement.draggable('option', 'revert', !isInBounds);
},
stop: function(ev, ui) {
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (isInBounds && (isAllDay || dayDelta || minuteDelta)) { // changed!
eventDrop(this, event, dayDelta, isAllDay ? 0 : minuteDelta, isAllDay, ev, ui);
}
else { // either no change or out-of-bounds (draggable has already reverted)
// reset states for next time, and for updateUI()
isInBounds = true;
isAllDay = false;
colDelta = 0;
dayDelta = 0;
minuteDelta = 0;
updateUI();
eventElement.css('filter', ''); // clear IE opacity side-effects
// sometimes fast drags make event revert to wrong position, so reset.
// also, if we dragged the element out of the area because of snapping,
// but the *mouse* is still in bounds, we need to reset the position.
eventElement.css(origPosition);
showEvents(event, eventElement);
}
}
});
function updateUI() {
clearOverlays();
if (isInBounds) {
if (isAllDay) {
timeElement.hide();
eventElement.draggable('option', 'grid', null); // disable grid snapping
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}
else {
updateTimeText(minuteDelta);
timeElement.css('display', ''); // show() was causing display=inline
eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping
}
}
}
function updateTimeText(minuteDelta) {
var newStart = addMinutes(cloneDate(event.start), minuteDelta);
var newEnd;
if (event.end) {
newEnd = addMinutes(cloneDate(event.end), minuteDelta);
}
timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
}
}
/* Resizing
--------------------------------------------------------------------------------------*/
function resizableSlotEvent(event, eventElement, timeElement) {
var snapDelta, prevSnapDelta;
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
eventElement.resizable({
handles: {
s: '.ui-resizable-handle'
},
grid: snapHeight,
start: function(ev, ui) {
snapDelta = prevSnapDelta = 0;
hideEvents(event, eventElement);
trigger('eventResizeStart', this, event, ev, ui);
},
resize: function(ev, ui) {
// don't rely on ui.size.height, doesn't take grid into account
snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
if (snapDelta != prevSnapDelta) {
timeElement.text(
formatDates(
event.start,
(!snapDelta && !event.end) ? null : // no change, so don't display time range
addMinutes(eventEnd(event), snapMinutes*snapDelta),
opt('timeFormat')
)
);
prevSnapDelta = snapDelta;
}
},
stop: function(ev, ui) {
trigger('eventResizeStop', this, event, ev, ui);
if (snapDelta) {
eventResize(this, event, 0, snapMinutes*snapDelta, ev, ui);
}else{
showEvents(event, eventElement);
// BUG: if event was really short, need to put title back in span
}
}
});
}
}
/* Agenda Event Segment Utilities
-----------------------------------------------------------------------------*/
// Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new
// list in the order they should be placed into the DOM (an implicit z-index).
function placeSlotSegs(segs) {
var levels = buildSlotSegLevels(segs);
var level0 = levels[0];
var i;
computeForwardSlotSegs(levels);
if (level0) {
for (i=0; i<level0.length; i++) {
computeSlotSegPressures(level0[i]);
}
for (i=0; i<level0.length; i++) {
computeSlotSegCoords(level0[i], 0, 0);
}
}
return flattenSlotSegLevels(levels);
}
// Builds an array of segments "levels". The first level will be the leftmost tier of segments
// if the calendar is left-to-right, or the rightmost if the calendar is right-to-left.
function buildSlotSegLevels(segs) {
var levels = [];
var i, seg;
var j;
for (i=0; i<segs.length; i++) {
seg = segs[i];
// go through all the levels and stop on the first level where there are no collisions
for (j=0; j<levels.length; j++) {
if (!computeSlotSegCollisions(seg, levels[j]).length) {
break;
}
}
(levels[j] || (levels[j] = [])).push(seg);
}
return levels;
}
// For every segment, figure out the other segments that are in subsequent
// levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
function computeForwardSlotSegs(levels) {
var i, level;
var j, seg;
var k;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.forwardSegs = [];
for (k=i+1; k<levels.length; k++) {
computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
}
}
}
}
// Figure out which path forward (via seg.forwardSegs) results in the longest path until
// the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
function computeSlotSegPressures(seg) {
var forwardSegs = seg.forwardSegs;
var forwardPressure = 0;
var i, forwardSeg;
if (seg.forwardPressure === undefined) { // not already computed
for (i=0; i<forwardSegs.length; i++) {
forwardSeg = forwardSegs[i];
// figure out the child's maximum forward path
computeSlotSegPressures(forwardSeg);
// either use the existing maximum, or use the child's forward pressure
// plus one (for the forwardSeg itself)
forwardPressure = Math.max(
forwardPressure,
1 + forwardSeg.forwardPressure
);
}
seg.forwardPressure = forwardPressure;
}
}
// Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
// from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
// seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
//
// The segment might be part of a "series", which means consecutive segments with the same pressure
// who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
// segments behind this one in the current series, and `seriesBackwardCoord` is the starting
// coordinate of the first segment in the series.
function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
var forwardSegs = seg.forwardSegs;
var i;
if (seg.forwardCoord === undefined) { // not already computed
if (!forwardSegs.length) {
// if there are no forward segments, this segment should butt up against the edge
seg.forwardCoord = 1;
}
else {
// sort highest pressure first
forwardSegs.sort(compareForwardSlotSegs);
// this segment's forwardCoord will be calculated from the backwardCoord of the
// highest-pressure forward segment.
computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
seg.forwardCoord = forwardSegs[0].backwardCoord;
}
// calculate the backwardCoord from the forwardCoord. consider the series
seg.backwardCoord = seg.forwardCoord -
(seg.forwardCoord - seriesBackwardCoord) / // available width for series
(seriesBackwardPressure + 1); // # of segments in the series
// use this segment's coordinates to computed the coordinates of the less-pressurized
// forward segments
for (i=0; i<forwardSegs.length; i++) {
computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
}
}
}
// Outputs a flat array of segments, from lowest to highest level
function flattenSlotSegLevels(levels) {
var segs = [];
var i, level;
var j;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
segs.push(level[j]);
}
}
return segs;
}
// Find all the segments in `otherSegs` that vertically collide with `seg`.
// Append into an optionally-supplied `results` array and return.
function computeSlotSegCollisions(seg, otherSegs, results) {
results = results || [];
for (var i=0; i<otherSegs.length; i++) {
if (isSlotSegCollision(seg, otherSegs[i])) {
results.push(otherSegs[i]);
}
}
return results;
}
// Do these segments occupy the same vertical space?
function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
}
// A cmp function for determining which forward segment to rely on more when computing coordinates.
function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
}
// A cmp function for determining which segment should be closer to the initial edge
// (the left edge on a left-to-right calendar).
function compareSlotSegs(seg1, seg2) {
return seg1.start - seg2.start || // earlier start time goes first
(seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first
(seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
}
;;
function View(element, calendar, viewName) {
var t = this;
// exports
t.element = element;
t.calendar = calendar;
t.name = viewName;
t.opt = opt;
t.trigger = trigger;
t.isEventDraggable = isEventDraggable;
t.isEventResizable = isEventResizable;
t.setEventData = setEventData;
t.clearEventData = clearEventData;
t.eventEnd = eventEnd;
t.reportEventElement = reportEventElement;
t.triggerEventDestroy = triggerEventDestroy;
t.eventElementHandlers = eventElementHandlers;
t.showEvents = showEvents;
t.hideEvents = hideEvents;
t.eventDrop = eventDrop;
t.eventResize = eventResize;
// t.title
// t.start, t.end
// t.visStart, t.visEnd
// imports
var defaultEventEnd = t.defaultEventEnd;
var normalizeEvent = calendar.normalizeEvent; // in EventManager
var reportEventChange = calendar.reportEventChange;
// locals
var eventsByID = {}; // eventID mapped to array of events (there can be multiple b/c of repeating events)
var eventElementsByID = {}; // eventID mapped to array of jQuery elements
var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system
var options = calendar.options;
function opt(name, viewNameOverride) {
var v = options[name];
if ($.isPlainObject(v)) {
return smartProperty(v, viewNameOverride || viewName);
}
return v;
}
function trigger(name, thisObj) {
return calendar.trigger.apply(
calendar,
[name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
);
}
/* Event Editable Boolean Calculations
------------------------------------------------------------------------------*/
function isEventDraggable(event) {
var source = event.source || {};
return firstDefined(
event.startEditable,
source.startEditable,
opt('eventStartEditable'),
event.editable,
source.editable,
opt('editable')
)
&& !opt('disableDragging'); // deprecated
}
function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
var source = event.source || {};
return firstDefined(
event.durationEditable,
source.durationEditable,
opt('eventDurationEditable'),
event.editable,
source.editable,
opt('editable')
)
&& !opt('disableResizing'); // deprecated
}
/* Event Data
------------------------------------------------------------------------------*/
function setEventData(events) { // events are already normalized at this point
eventsByID = {};
var i, len=events.length, event;
for (i=0; i<len; i++) {
event = events[i];
if (eventsByID[event._id]) {
eventsByID[event._id].push(event);
}else{
eventsByID[event._id] = [event];
}
}
}
function clearEventData() {
eventsByID = {};
eventElementsByID = {};
eventElementCouples = [];
}
// returns a Date object for an event's end
function eventEnd(event) {
return event.end ? cloneDate(event.end) : defaultEventEnd(event);
}
/* Event Elements
------------------------------------------------------------------------------*/
// report when view creates an element for an event
function reportEventElement(event, element) {
eventElementCouples.push({ event: event, element: element });
if (eventElementsByID[event._id]) {
eventElementsByID[event._id].push(element);
}else{
eventElementsByID[event._id] = [element];
}
}
function triggerEventDestroy() {
$.each(eventElementCouples, function(i, couple) {
t.trigger('eventDestroy', couple.event, couple.event, couple.element);
});
}
// attaches eventClick, eventMouseover, eventMouseout
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
function showEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'show');
}
function hideEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'hide');
}
function eachEventElement(event, exceptElement, funcName) {
// NOTE: there may be multiple events per ID (repeating events)
// and multiple segments per event
var elements = eventElementsByID[event._id],
i, len = elements.length;
for (i=0; i<len; i++) {
if (!exceptElement || elements[i][0] != exceptElement[0]) {
elements[i][funcName]();
}
}
}
/* Event Modification Reporting
---------------------------------------------------------------------------------*/
function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) {
var oldAllDay = event.allDay;
var eventId = event._id;
moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
trigger(
'eventDrop',
e,
event,
dayDelta,
minuteDelta,
allDay,
function() {
// TODO: investigate cases where this inverse technique might not work
moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
var eventId = event._id;
elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
trigger(
'eventResize',
e,
event,
dayDelta,
minuteDelta,
function() {
// TODO: investigate cases where this inverse technique might not work
elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
/* Event Modification Math
---------------------------------------------------------------------------------*/
function moveEvents(events, dayDelta, minuteDelta, allDay) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
if (allDay !== undefined) {
e.allDay = allDay;
}
addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
if (e.end) {
e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
}
normalizeEvent(e, options);
}
}
function elongateEvents(events, dayDelta, minuteDelta) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
normalizeEvent(e, options);
}
}
// ====================================================================================================
// Utilities for day "cells"
// ====================================================================================================
// The "basic" views are completely made up of day cells.
// The "agenda" views have day cells at the top "all day" slot.
// This was the obvious common place to put these utilities, but they should be abstracted out into
// a more meaningful class (like DayEventRenderer).
// ====================================================================================================
// For determining how a given "cell" translates into a "date":
//
// 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first).
// Keep in mind that column indices are inverted with isRTL. This is taken into account.
//
// 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view).
//
// 3. Convert the "day offset" into a "date" (a JavaScript Date object).
//
// The reverse transformation happens when transforming a date into a cell.
// exports
t.isHiddenDay = isHiddenDay;
t.skipHiddenDays = skipHiddenDays;
t.getCellsPerWeek = getCellsPerWeek;
t.dateToCell = dateToCell;
t.dateToDayOffset = dateToDayOffset;
t.dayOffsetToCellOffset = dayOffsetToCellOffset;
t.cellOffsetToCell = cellOffsetToCell;
t.cellToDate = cellToDate;
t.cellToCellOffset = cellToCellOffset;
t.cellOffsetToDayOffset = cellOffsetToDayOffset;
t.dayOffsetToDate = dayOffsetToDate;
t.rangeToSegments = rangeToSegments;
// internals
var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden
var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
var cellsPerWeek;
var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week
var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week
var isRTL = opt('isRTL');
// initialize important internal variables
(function() {
if (opt('weekends') === false) {
hiddenDays.push(0, 6); // 0=sunday, 6=saturday
}
// Loop through a hypothetical week and determine which
// days-of-week are hidden. Record in both hashes (one is the reverse of the other).
for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) {
dayToCellMap[dayIndex] = cellIndex;
isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1;
if (!isHiddenDayHash[dayIndex]) {
cellToDayMap[cellIndex] = dayIndex;
cellIndex++;
}
}
cellsPerWeek = cellIndex;
if (!cellsPerWeek) {
throw 'invalid hiddenDays'; // all days were hidden? bad.
}
})();
// Is the current day hidden?
// `day` is a day-of-week index (0-6), or a Date object
function isHiddenDay(day) {
if (typeof day == 'object') {
day = day.getDay();
}
return isHiddenDayHash[day];
}
function getCellsPerWeek() {
return cellsPerWeek;
}
// Keep incrementing the current day until it is no longer a hidden day.
// If the initial value of `date` is not a hidden day, don't do anything.
// Pass `isExclusive` as `true` if you are dealing with an end date.
// `inc` defaults to `1` (increment one day forward each time)
function skipHiddenDays(date, inc, isExclusive) {
inc = inc || 1;
while (
isHiddenDayHash[ ( date.getDay() + (isExclusive ? inc : 0) + 7 ) % 7 ]
) {
addDays(date, inc);
}
}
//
// TRANSFORMATIONS: cell -> cell offset -> day offset -> date
//
// cell -> date (combines all transformations)
// Possible arguments:
// - row, col
// - { row:#, col: # }
function cellToDate() {
var cellOffset = cellToCellOffset.apply(null, arguments);
var dayOffset = cellOffsetToDayOffset(cellOffset);
var date = dayOffsetToDate(dayOffset);
return date;
}
// cell -> cell offset
// Possible arguments:
// - row, col
// - { row:#, col:# }
function cellToCellOffset(row, col) {
var colCnt = t.getColCnt();
// rtl variables. wish we could pre-populate these. but where?
var dis = isRTL ? -1 : 1;
var dit = isRTL ? colCnt - 1 : 0;
if (typeof row == 'object') {
col = row.col;
row = row.row;
}
var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit)
return cellOffset;
}
// cell offset -> day offset
function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
}
// day offset -> date (JavaScript Date object)
function dayOffsetToDate(dayOffset) {
var date = cloneDate(t.visStart);
addDays(date, dayOffset);
return date;
}
//
// TRANSFORMATIONS: date -> day offset -> cell offset -> cell
//
// date -> cell (combines all transformations)
function dateToCell(date) {
var dayOffset = dateToDayOffset(date);
var cellOffset = dayOffsetToCellOffset(dayOffset);
var cell = cellOffsetToCell(cellOffset);
return cell;
}
// date -> day offset
function dateToDayOffset(date) {
return dayDiff(date, t.visStart);
}
// day offset -> cell offset
function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
}
// cell offset -> cell (object with row & col keys)
function cellOffsetToCell(cellOffset) {
var colCnt = t.getColCnt();
// rtl variables. wish we could pre-populate these. but where?
var dis = isRTL ? -1 : 1;
var dit = isRTL ? colCnt - 1 : 0;
var row = Math.floor(cellOffset / colCnt);
var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit)
return {
row: row,
col: col
};
}
//
// Converts a date range into an array of segment objects.
// "Segments" are horizontal stretches of time, sliced up by row.
// A segment object has the following properties:
// - row
// - cols
// - isStart
// - isEnd
//
function rangeToSegments(startDate, endDate) {
var rowCnt = t.getRowCnt();
var colCnt = t.getColCnt();
var segments = []; // array of segments to return
// day offset for given date range
var rangeDayOffsetStart = dateToDayOffset(startDate);
var rangeDayOffsetEnd = dateToDayOffset(endDate); // exclusive
// first and last cell offset for the given date range
// "last" implies inclusivity
var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart);
var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1;
// loop through all the rows in the view
for (var row=0; row<rowCnt; row++) {
// first and last cell offset for the row
var rowCellOffsetFirst = row * colCnt;
var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1;
// get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row
var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst);
var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast);
// make sure segment's offsets are valid and in view
if (segmentCellOffsetFirst <= segmentCellOffsetLast) {
// translate to cells
var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst);
var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast);
// view might be RTL, so order by leftmost column
var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort();
// Determine if segment's first/last cell is the beginning/end of the date range.
// We need to compare "day offset" because "cell offsets" are often ambiguous and
// can translate to multiple days, and an edge case reveals itself when we the
// range's first cell is hidden (we don't want isStart to be true).
var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart;
var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively
segments.push({
row: row,
leftCol: cols[0],
rightCol: cols[1],
isStart: isStart,
isEnd: isEnd
});
}
}
return segments;
}
}
;;
function DayEventRenderer() {
var t = this;
// exports
t.renderDayEvents = renderDayEvents;
t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override
t.resizableDayEvent = resizableDayEvent; // "
// imports
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var reportEventElement = t.reportEventElement;
var eventElementHandlers = t.eventElementHandlers;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var getRowCnt = t.getRowCnt;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var allDayRow = t.allDayRow; // TODO: rename
var colLeft = t.colLeft;
var colRight = t.colRight;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var dateToCell = t.dateToCell;
var getDaySegmentContainer = t.getDaySegmentContainer;
var formatDates = t.calendar.formatDates;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var clearSelection = t.clearSelection;
var getHoverListener = t.getHoverListener;
var rangeToSegments = t.rangeToSegments;
var cellToDate = t.cellToDate;
var cellToCellOffset = t.cellToCellOffset;
var cellOffsetToDayOffset = t.cellOffsetToDayOffset;
var dateToDayOffset = t.dateToDayOffset;
var dayOffsetToCellOffset = t.dayOffsetToCellOffset;
// Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each.
// Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`.
// Can only be called when the event container is empty (because it wipes out all innerHTML).
function renderDayEvents(events, modifiedEventId) {
// do the actual rendering. Receive the intermediate "segment" data structures.
var segments = _renderDayEvents(
events,
false, // don't append event elements
true // set the heights of the rows
);
// report the elements to the View, for general drag/resize utilities
segmentElementEach(segments, function(segment, element) {
reportEventElement(segment.event, element);
});
// attach mouse handlers
attachHandlers(segments, modifiedEventId);
// call `eventAfterRender` callback for each event
segmentElementEach(segments, function(segment, element) {
trigger('eventAfterRender', segment.event, segment.event, element);
});
}
// Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers.
// Append this event element to the event container, which might already be populated with events.
// If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`.
// This hack is used to maintain continuity when user is manually resizing an event.
// Returns an array of DOM elements for the event.
function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
}
// Render events onto the calendar. Only responsible for the VISUAL aspect.
// Not responsible for attaching handlers or calling callbacks.
// Set `doAppend` to `true` for rendering elements without clearing the existing container.
// Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
}
// Generate an array of "segments" for all events.
function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
}
// Generate an array of segments for a single event.
// A "segment" is the same data structure that View.rangeToSegments produces,
// with the addition of the `event` property being set to reference the original event.
function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
}
// Sets the `left` and `outerWidth` property of each segment.
// These values are the desired dimensions for the eventual DOM elements.
function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
}
// Build a concatenated HTML string for an array of segments
function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
}
// Build an HTML string for a single segment.
// Relies on the following properties:
// - `segment.event` (from `buildSegmentsForEvent`)
// - `segment.left` (from `calculateHorizontals`)
function buildHTMLForSegment(segment) {
var html = '';
var isRTL = opt('isRTL');
var event = segment.event;
var url = event.url;
// generate the list of CSS classNames
var classNames = [ 'fc-event', 'fc-event-hori' ];
if (isEventDraggable(event)) {
classNames.push('fc-event-draggable');
}
if (segment.isStart) {
classNames.push('fc-event-start');
}
if (segment.isEnd) {
classNames.push('fc-event-end');
}
// use the event's configured classNames
// guaranteed to be an array via `normalizeEvent`
classNames = classNames.concat(event.className);
if (event.source) {
// use the event's source's classNames, if specified
classNames = classNames.concat(event.source.className || []);
}
// generate a semicolon delimited CSS string for any of the "skin" properties
// of the event object (`backgroundColor`, `borderColor` and such)
var skinCss = getSkinCss(event, opt);
if (url) {
html += "<a href='" + htmlEscape(url) + "'";
}else{
html += "<div";
}
html +=
" class='" + classNames.join(' ') + "'" +
" style=" +
"'" +
"position:absolute;" +
"left:" + segment.left + "px;" +
skinCss +
"'" +
">" +
"<div class='fc-event-inner'>";
if (!event.allDay && segment.isStart) {
html +=
"<span class='fc-event-time'>" +
htmlEscape(
formatDates(event.start, event.end, opt('timeFormat'))
) +
"</span>";
}
html +=
"<span class='fc-event-title'>" +
htmlEscape(event.title || '') +
"</span>" +
"</div>";
if (segment.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
" " + // makes hit area a lot better for IE6/7
"</div>";
}
html += "</" + (url ? "a" : "div") + ">";
// TODO:
// When these elements are initially rendered, they will be briefly visibile on the screen,
// even though their widths/heights are not set.
// SOLUTION: initially set them as visibility:hidden ?
return html;
}
// Associate each segment (an object) with an element (a jQuery object),
// by setting each `segment.element`.
// Run each element through the `eventRender` filter, which allows developers to
// modify an existing element, supply a new one, or cancel rendering.
function resolveElements(segments, elements) {
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
var event = segment.event;
var element = elements.eq(i);
// call the trigger with the original element
var triggerRes = trigger('eventRender', event, event, element);
if (triggerRes === false) {
// if `false`, remove the event from the DOM and don't assign it to `segment.event`
element.remove();
}
else {
if (triggerRes && triggerRes !== true) {
// the trigger returned a new element, but not `true` (which means keep the existing element)
// re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment`
triggerRes = $(triggerRes)
.css({
position: 'absolute',
left: segment.left
});
element.replaceWith(triggerRes);
element = triggerRes;
}
segment.element = element;
}
}
}
/* Top-coordinate Methods
-------------------------------------------------------------------------------------------------*/
// Sets the "top" CSS property for each element.
// If `doRowHeights` is `true`, also sets each row's first cell to an explicit height,
// so that if elements vertically overflow, the cell expands vertically to compensate.
function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
}
// Calculate the "top" coordinate for each segment, relative to the "top" of the row.
// Also, return an array that contains the "content" height for each row
// (the height displaced by the vertically stacked events in the row).
// Requires segments to have their `outerHeight` property already set.
function calculateVerticals(segments) {
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var rowContentHeights = []; // content height for each row
var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row
for (var rowI=0; rowI<rowCnt; rowI++) {
var segmentRow = segmentRows[rowI];
// an array of running total heights for each column.
// initialize with all zeros.
var colHeights = [];
for (var colI=0; colI<colCnt; colI++) {
colHeights.push(0);
}
// loop through every segment
for (var segmentI=0; segmentI<segmentRow.length; segmentI++) {
var segment = segmentRow[segmentI];
// find the segment's top coordinate by looking at the max height
// of all the columns the segment will be in.
segment.top = arrayMax(
colHeights.slice(
segment.leftCol,
segment.rightCol + 1 // make exclusive for slice
)
);
// adjust the columns to account for the segment's height
for (var colI=segment.leftCol; colI<=segment.rightCol; colI++) {
colHeights[colI] = segment.top + segment.outerHeight;
}
}
// the tallest column in the row should be the "content height"
rowContentHeights.push(arrayMax(colHeights));
}
return rowContentHeights;
}
// Build an array of segment arrays, each representing the segments that will
// be in a row of the grid, sorted by which event should be closest to the top.
function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
}
// Sort an array of segments according to which segment should appear closest to the top
function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
}
// Take an array of segments, which are all assumed to be in the same row,
// and sort into subrows.
function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
}
// Return an array of jQuery objects for the placeholder content containers of each row.
// The content containers don't actually contain anything, but their dimensions should match
// the events that are overlaid on top.
function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
}
/* Mouse Handlers
---------------------------------------------------------------------------------------------------*/
// TODO: better documentation!
function attachHandlers(segments, modifiedEventId) {
var segmentContainer = getDaySegmentContainer();
segmentElementEach(segments, function(segment, element, i) {
var event = segment.event;
if (event._id === modifiedEventId) {
bindDaySeg(event, element, segment);
}else{
element[0]._fci = i; // for lazySegBind
}
});
lazySegBind(segmentContainer, segments, bindDaySeg);
}
function bindDaySeg(event, eventElement, segment) {
if (isEventDraggable(event)) {
t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
}
if (
segment.isEnd && // only allow resizing on the final segment for an event
isEventResizable(event)
) {
t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
}
// attach all other handlers.
// needs to be after, because resizableDayEvent might stopImmediatePropagation on click
eventElementHandlers(event, eventElement);
}
function draggableDayEvent(event, eventElement) {
var hoverListener = getHoverListener();
var dayDelta;
eventElement.draggable({
delay: 50,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
// INSTRUCTURE: Additional drag options to help with dragging to other calendars
helper: opt('dragHelper'),
appendTo: opt('dragAppendTo'),
zIndex: opt('dragZIndex'),
cursorAt: opt('dragCursorAt'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
clearOverlays();
if (cell) {
var origDate = cellToDate(origCell);
var date = cellToDate(cell);
dayDelta = dayDiff(date, origDate);
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}else{
dayDelta = 0;
}
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (dayDelta) {
eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
}else{
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}
}
});
}
function resizableDayEvent(event, element, segment) {
var isRTL = opt('isRTL');
var direction = isRTL ? 'w' : 'e';
var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
var isResizing = false;
// TODO: look into using jquery-ui mouse widget for this stuff
disableTextSelection(element); // prevent native <a> selection for IE
element
.mousedown(function(ev) { // prevent native <a> selection for others
ev.preventDefault();
})
.click(function(ev) {
if (isResizing) {
ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
// (eventElementHandlers needs to be bound after resizableDayEvent)
}
});
handle.mousedown(function(ev) {
if (ev.which != 1) {
return; // needs to be left mouse button
}
isResizing = true;
var hoverListener = getHoverListener();
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var elementTop = element.css('top');
var dayDelta;
var helpers;
var eventCopy = $.extend({}, event);
var minCellOffset = dayOffsetToCellOffset( dateToDayOffset(event.start) );
clearSelection();
$('body')
.css('cursor', direction + '-resize')
.one('mouseup', mouseup);
trigger('eventResizeStart', this, event, ev);
hoverListener.start(function(cell, origCell) {
if (cell) {
var origCellOffset = cellToCellOffset(origCell);
var cellOffset = cellToCellOffset(cell);
// don't let resizing move earlier than start date cell
cellOffset = Math.max(cellOffset, minCellOffset);
dayDelta =
cellOffsetToDayOffset(cellOffset) -
cellOffsetToDayOffset(origCellOffset);
if (dayDelta) {
eventCopy.end = addDays(eventEnd(event), dayDelta, true);
var oldHelpers = helpers;
helpers = renderTempDayEvent(eventCopy, segment.row, elementTop);
helpers = $(helpers); // turn array into a jQuery object
helpers.find('*').css('cursor', direction + '-resize');
if (oldHelpers) {
oldHelpers.remove();
}
hideEvents(event);
}
else {
if (helpers) {
showEvents(event);
helpers.remove();
helpers = null;
}
}
clearOverlays();
renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start()
event.start,
addDays( exclEndDay(event), dayDelta )
// TODO: instead of calling renderDayOverlay() with dates,
// call _renderDayOverlay (or whatever) with cell offsets.
);
}
}, ev);
function mouseup(ev) {
trigger('eventResizeStop', this, event, ev);
$('body').css('cursor', '');
hoverListener.stop();
clearOverlays();
if (dayDelta) {
eventResize(this, event, dayDelta, 0, ev);
// event redraw will clear helpers
}
// otherwise, the drag handler already restored the old events
setTimeout(function() { // make this happen after the element's click event
isResizing = false;
},0);
}
});
}
}
/* Generalized Segment Utilities
-------------------------------------------------------------------------------------------------*/
function isDaySegmentCollision(segment, otherSegments) {
for (var i=0; i<otherSegments.length; i++) {
var otherSegment = otherSegments[i];
if (
otherSegment.leftCol <= segment.rightCol &&
otherSegment.rightCol >= segment.leftCol
) {
return true;
}
}
return false;
}
function segmentElementEach(segments, callback) { // TODO: use in AgendaView?
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
var element = segment.element;
if (element) {
callback(segment, element, i);
}
}
}
// A cmp function for determining which segments should appear higher up
function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
}
;;
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigger;
var defaultSelectionEnd = t.defaultSelectionEnd;
var renderSelection = t.renderSelection;
var clearSelection = t.clearSelection;
// locals
var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
unselect(ev);
});
}
function select(startDate, endDate, allDay) {
unselect();
if (!endDate) {
endDate = defaultSelectionEnd(startDate, allDay);
}
renderSelection(startDate, endDate, allDay);
reportSelection(startDate, endDate, allDay);
}
function unselect(ev) {
if (selected) {
selected = false;
clearSelection();
trigger('unselect', null, ev);
}
}
function reportSelection(startDate, endDate, allDay, ev) {
selected = true;
trigger('select', null, startDate, endDate, allDay, ev);
}
function daySelectionMousedown(ev) { // not really a generic manager method, oh well
var cellToDate = t.cellToDate;
var getIsCellAllDay = t.getIsCellAllDay;
var hoverListener = t.getHoverListener();
var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
unselect(ev);
var _mousedownElement = this;
var dates;
hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
clearSelection();
if (cell && getIsCellAllDay(cell)) {
dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
renderSelection(dates[0], dates[1], true);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], true, ev);
}
reportSelection(dates[0], dates[1], true, ev);
}
});
}
}
}
;;
function OverlayManager() {
var t = this;
// exports
t.renderOverlay = renderOverlay;
t.clearOverlays = clearOverlays;
// locals
var usedOverlays = [];
var unusedOverlays = [];
function renderOverlay(rect, parent) {
var e = unusedOverlays.shift();
if (!e) {
e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
}
if (e[0].parentNode != parent[0]) {
e.appendTo(parent);
}
usedOverlays.push(e.css(rect).show());
return e;
}
function clearOverlays() {
var e;
while (e = usedOverlays.shift()) {
unusedOverlays.push(e.hide().unbind());
}
}
}
;;
function CoordinateGrid(buildFunc) {
var t = this;
var rows;
var cols;
t.build = function() {
rows = [];
cols = [];
buildFunc(rows, cols);
};
t.cell = function(x, y) {
var rowCnt = rows.length;
var colCnt = cols.length;
var i, r=-1, c=-1;
for (i=0; i<rowCnt; i++) {
if (y >= rows[i][0] && y < rows[i][1]) {
r = i;
break;
}
}
for (i=0; i<colCnt; i++) {
if (x >= cols[i][0] && x < cols[i][1]) {
c = i;
break;
}
}
return (r>=0 && c>=0) ? { row:r, col:c } : null;
};
t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
var origin = originElement.offset();
return {
top: rows[row0][0] - origin.top,
left: cols[col0][0] - origin.left,
width: cols[col1][1] - cols[col0][0],
height: rows[row1][1] - rows[row0][0]
};
};
}
;;
function HoverListener(coordinateGrid) {
var t = this;
var bindType;
var change;
var firstCell;
var cell;
t.start = function(_change, ev, _bindType) {
change = _change;
firstCell = cell = null;
coordinateGrid.build();
mouse(ev);
bindType = _bindType || 'mousemove';
$(document).bind(bindType, mouse);
};
function mouse(ev) {
_fixUIEvent(ev); // see below
var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) {
if (newCell) {
if (!firstCell) {
firstCell = newCell;
}
change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
}else{
change(newCell, firstCell);
}
cell = newCell;
}
}
t.stop = function() {
$(document).unbind(bindType, mouse);
return cell;
};
}
// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
// but keep this in here for 1.8.16 users
// and maybe remove it down the line
function _fixUIEvent(event) { // for issue 1168
if (event.pageX === undefined) {
event.pageX = event.originalEvent.pageX;
event.pageY = event.originalEvent.pageY;
}
}
;;
function HorizontalPositionCache(getElement) {
var t = this,
elements = {},
lefts = {},
rights = {};
function e(i) {
return elements[i] = elements[i] || getElement(i);
}
t.left = function(i) {
return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
};
t.right = function(i) {
return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
};
t.clear = function() {
elements = {};
lefts = {};
rights = {};
};
}
});
| usmschuck/canvas | public/javascripts/vendor/fullcalendar.js | JavaScript | agpl-3.0 | 152,783 |
ο»Ώ// Accord Math Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright Β© CΓ©sar Souza, 2009-2015
// cesarsouza at gmail.com
//
// Copyright Β© Diego Catalano, 2013
// diego.catalano at live.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Math
{
using System;
using AForge.Math;
/// <summary>
/// Discrete Sine Transform
/// </summary>
///
/// <remarks>
/// <para>
/// In mathematics, the discrete sine transform (DST) is a Fourier-related transform
/// similar to the discrete Fourier transform (DFT), but using a purely real matrix. It
/// is equivalent to the imaginary parts of a DFT of roughly twice the length, operating
/// on real data with odd symmetry (since the Fourier transform of a real and odd function
/// is imaginary and odd), where in some variants the input and/or output data are shifted
/// by half a sample.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description>
/// Wikipedia contributors, "Discrete sine transform," Wikipedia, The Free Encyclopedia,
/// available at: http://en.wikipedia.org/w/index.php?title=Discrete_sine_transform </description></item>
/// <item><description>
/// K. R. Castleman, Digital Image Processing. Chapter 13, p.288.
/// Prentice. Hall, 1998.</description></item>
/// </list></para>
/// </remarks>
///
public static class SineTransform
{
/// <summary>
/// Forward Discrete Sine Transform.
/// </summary>
///
public static void DST(double[] data)
{
double[] result = new double[data.Length];
for (int k = 1; k < result.Length + 1; k++)
{
double sum = 0;
for (int i = 1; i < data.Length + 1; i++)
sum += data[i - 1] * Math.Sin(Math.PI * ((k * i) / (data.Length + 1.0)));
result[k - 1] = sum;
}
for (int i = 0; i < data.Length; i++)
data[i] = result[i];
}
/// <summary>
/// Inverse Discrete Sine Transform.
/// </summary>
///
public static void IDST(double[] data)
{
double[] result = new double[data.Length];
double inverse = 2.0 / (data.Length + 1);
for (int k = 1; k < result.Length + 1; k++)
{
double sum = 0;
for (int i = 1; i < data.Length + 1; i++)
sum += data[i - 1] * Math.Sin(Math.PI * ((k * i) / (data.Length + 1.0)));
result[k - 1] = sum * inverse;
}
for (int i = 0; i < data.Length; i++)
data[i] = result[i];
}
/// <summary>
/// Forward Discrete Sine Transform.
/// </summary>
///
public static void DST(double[][] data)
{
int rows = data.Length;
int cols = data[0].Length;
double[] row = new double[cols];
double[] col = new double[rows];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < row.Length; j++)
row[j] = data[i][j];
DST(row);
for (int j = 0; j < row.Length; j++)
data[i][j] = row[j];
}
for (int j = 0; j < cols; j++)
{
for (int i = 0; i < col.Length; i++)
col[i] = data[i][j];
DST(col);
for (int i = 0; i < col.Length; i++)
data[i][j] = col[i];
}
}
/// <summary>
/// Inverse Discrete Sine Transform.
/// </summary>
///
public static void IDST(double[][] data)
{
int rows = data.Length;
int cols = data[0].Length;
double[] row = new double[cols];
double[] col = new double[rows];
for (int j = 0; j < cols; j++)
{
for (int i = 0; i < row.Length; i++)
col[i] = data[i][j];
IDST(col);
for (int i = 0; i < col.Length; i++)
data[i][j] = col[i];
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < row.Length; j++)
row[j] = data[i][j];
IDST(row);
for (int j = 0; j < row.Length; j++)
data[i][j] = row[j];
}
}
}
}
| lostmsu/framework | Sources/Accord.Math/Transforms/SineTransform.cs | C# | lgpl-2.1 | 5,429 |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 org.kuali.rice.kew.api.peopleflow;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.membership.MemberType;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.core.api.mo.ModelObjectUtils;
import org.kuali.rice.core.api.util.jaxb.MapStringStringAdapter;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@XmlRootElement(name = PeopleFlowDefinition.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = PeopleFlowDefinition.Constants.TYPE_NAME, propOrder = {
PeopleFlowDefinition.Elements.ID,
PeopleFlowDefinition.Elements.NAMESPACE_CODE,
PeopleFlowDefinition.Elements.NAME,
PeopleFlowDefinition.Elements.TYPE_ID,
PeopleFlowDefinition.Elements.DESCRIPTION,
PeopleFlowDefinition.Elements.MEMBERS,
PeopleFlowDefinition.Elements.ATTRIBUTES,
PeopleFlowDefinition.Elements.ACTIVE,
CoreConstants.CommonElements.VERSION_NUMBER,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class PeopleFlowDefinition extends AbstractDataTransferObject implements PeopleFlowContract {
@XmlElement(name = Elements.NAME, required = true)
private final String name;
@XmlElement(name = Elements.ATTRIBUTES, required = false)
@XmlJavaTypeAdapter(MapStringStringAdapter.class)
private final Map<String, String> attributes;
@XmlElement(name = Elements.NAMESPACE_CODE, required = true)
private final String namespaceCode;
@XmlElement(name = Elements.TYPE_ID, required = false)
private final String typeId;
@XmlElement(name = Elements.DESCRIPTION, required = false)
private final String description;
@XmlElementWrapper(name = Elements.MEMBERS, required = false)
@XmlElement(name = Elements.MEMBER, required = false)
private final List<PeopleFlowMember> members;
@XmlElement(name = Elements.ID, required = false)
private final String id;
@XmlElement(name = Elements.ACTIVE, required = false)
private final boolean active;
@XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false)
private final Long versionNumber;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*
*/
private PeopleFlowDefinition() {
this.name = null;
this.attributes = null;
this.namespaceCode = null;
this.typeId = null;
this.description = null;
this.members = null;
this.id = null;
this.active = false;
this.versionNumber = null;
}
private PeopleFlowDefinition(Builder builder) {
this.name = builder.getName();
this.attributes = builder.getAttributes();
this.namespaceCode = builder.getNamespaceCode();
this.typeId = builder.getTypeId();
this.description = builder.getDescription();
this.members = ModelObjectUtils.buildImmutableCopy(builder.getMembers());
this.id = builder.getId();
this.active = builder.isActive();
this.versionNumber = builder.getVersionNumber();
}
@Override
public String getName() {
return this.name;
}
@Override
public Map<String, String> getAttributes() {
return this.attributes;
}
@Override
public String getNamespaceCode() {
return this.namespaceCode;
}
@Override
public String getTypeId() {
return this.typeId;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public List<PeopleFlowMember> getMembers() {
return this.members;
}
@Override
public String getId() {
return this.id;
}
@Override
public boolean isActive() {
return this.active;
}
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
/**
* A builder which can be used to construct {@link PeopleFlowDefinition} instances. Enforces the constraints of the
* {@link PeopleFlowContract}.
*/
public final static class Builder implements Serializable, ModelBuilder, PeopleFlowContract {
private String name;
private Map<String, String> attributes;
private String namespaceCode;
private String typeId;
private String description;
private List<PeopleFlowMember.Builder> members;
private String id;
private boolean active;
private Long versionNumber;
private Builder(String namespaceCode, String name) {
setNamespaceCode(namespaceCode);
setName(name);
setActive(true);
setAttributes(new HashMap<String, String>());
setMembers(new ArrayList<PeopleFlowMember.Builder>());
}
public static Builder create(String namespaceCode, String name) {
return new Builder(namespaceCode, name);
}
public static Builder create(PeopleFlowContract contract) {
Builder builder = createCopy(contract);
builder.setVersionNumber(contract.getVersionNumber());
if (contract.getMembers() != null) {
for (PeopleFlowMemberContract member : contract.getMembers()) {
builder.getMembers().add(PeopleFlowMember.Builder.create(member));
}
}
return builder;
}
private static Builder createCopy(PeopleFlowContract contract) {
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
Builder builder = create(contract.getNamespaceCode(), contract.getName());
if (contract.getAttributes() != null) {
builder.getAttributes().putAll(contract.getAttributes());
}
if (StringUtils.isEmpty(contract.getTypeId())) {
// type_id is a foreign key, it needs to be either null or a real value, not empty String to avoid SQL Exception
builder.setTypeId(null);
} else {
builder.setTypeId(contract.getTypeId());
}
builder.setDescription(contract.getDescription());
builder.setId(contract.getId());
builder.setActive(contract.isActive());
return builder;
}
public static Builder createMaintenanceCopy(PeopleFlowContract contract) {
Builder builder = createCopy(contract);
if (contract.getMembers() != null) {
for (PeopleFlowMemberContract member : contract.getMembers()) {
builder.getMembers().add(PeopleFlowMember.Builder.createCopy(member));
}
}
return builder;
}
public PeopleFlowDefinition build() {
return new PeopleFlowDefinition(this);
}
@Override
public String getName() {
return this.name;
}
@Override
public Map<String, String> getAttributes() {
return this.attributes;
}
@Override
public String getNamespaceCode() {
return this.namespaceCode;
}
@Override
public String getTypeId() {
return this.typeId;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public List<PeopleFlowMember.Builder> getMembers() {
return this.members;
}
@Override
public String getId() {
return this.id;
}
@Override
public boolean isActive() {
return this.active;
}
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
public void setName(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("name was null or blank");
}
this.name = name;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public void setNamespaceCode(String namespaceCode) {
if (StringUtils.isBlank(namespaceCode)) {
throw new IllegalArgumentException("namespaceCode was null or blank");
}
this.namespaceCode = namespaceCode;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public void setDescription(String description) {
this.description = description;
}
public void setMembers(List<PeopleFlowMember.Builder> members) {
this.members = members;
}
public void setId(String id) {
this.id = id;
}
public void setActive(boolean active) {
this.active = active;
}
public void setVersionNumber(Long versionNumber) {
this.versionNumber = versionNumber;
}
public PeopleFlowMember.Builder addPrincipal(String principalId) {
PeopleFlowMember.Builder member = PeopleFlowMember.Builder.create(principalId, MemberType.PRINCIPAL);
getMembers().add(member);
return member;
}
public PeopleFlowMember.Builder addGroup(String groupId) {
PeopleFlowMember.Builder member = PeopleFlowMember.Builder.create(groupId, MemberType.GROUP);
getMembers().add(member);
return member;
}
public PeopleFlowMember.Builder addRole(String roleId) {
PeopleFlowMember.Builder member = PeopleFlowMember.Builder.create(roleId, MemberType.ROLE);
getMembers().add(member);
return member;
}
}
/**
* Defines some internal constants used on this class.
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "peopleFlowDefinition";
final static String TYPE_NAME = "PeopleFlowDefinitionType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*/
static class Elements {
final static String NAME = "name";
final static String ATTRIBUTES = "attributes";
final static String NAMESPACE_CODE = "namespaceCode";
final static String TYPE_ID = "typeId";
final static String DESCRIPTION = "description";
final static String MEMBERS = "members";
final static String MEMBER = "member";
final static String ID = "id";
final static String ACTIVE = "active";
}
}
| geothomasp/kualico-rice-kc | rice-middleware/kew/api/src/main/java/org/kuali/rice/kew/api/peopleflow/PeopleFlowDefinition.java | Java | apache-2.0 | 12,060 |
package com.querydsl.codegen;
import java.io.File;
import org.junit.Test;
public abstract class AbstractExporterTest {
@Test
public void test() {
GenericExporter exporter = new GenericExporter();
exporter.setTargetFolder(new File("target/" + getClass().getSimpleName()));
exporter.export(getClass().getClasses());
}
}
| kevinleturc/querydsl | querydsl-codegen/src/test/java/com/querydsl/codegen/AbstractExporterTest.java | Java | apache-2.0 | 359 |
ο»Ώ'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34011
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace TestResources.MetadataTests
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Public Class Invalid
Private Shared resourceMan As Global.System.Resources.ResourceManager
Private Shared resourceCulture As Global.System.Globalization.CultureInfo
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend Sub New()
MyBase.New
End Sub
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Public Shared ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Invalid", GetType(Invalid).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Public Shared Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property ClassLayout() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("ClassLayout", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property CustomAttributeTableDeclaredUnsorted() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("CustomAttributeTableDeclaredUnsorted", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property CustomAttributeTableUnsorted() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("CustomAttributeTableUnsorted", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property EmptyModuleTable() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("EmptyModuleTable", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property IncorrectCustomAssemblyTableSize_TooManyMethodSpecs() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("IncorrectCustomAssemblyTableSize_TooManyMethodSpecs", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property InvalidDynamicAttributeArgs() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("InvalidDynamicAttributeArgs", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property InvalidFuncDelegateName() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("InvalidFuncDelegateName", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property InvalidGenericType() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("InvalidGenericType", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property InvalidModuleName() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("InvalidModuleName", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property LongTypeFormInSignature() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("LongTypeFormInSignature", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized string similar to ' IncorrectCustomAssemblyTableSize_TooManyMethodSpecs.dll produced by compiling this file with erroneous metadata writer
'''
'''Imports System
'''Imports System.Linq.Expressions
'''Imports System.Text
'''
'''Namespace Global
'''
''' Public Class Clazz1
''' End Class
''' Public Class Clazz2
''' Inherits Clazz1
''' End Class
''' Public Structure Struct1
''' End Structure
'''
''' Public Enum E_Byte As Byte : Dummy : End Enum
''' Public Enum E_SByte As SByte : Dummy : End Enum
''' Public Enum E_UShort As UShort : [rest of string was truncated]";.
'''</summary>
Public Shared ReadOnly Property ManyMethodSpecs() As String
Get
Return ResourceManager.GetString("ManyMethodSpecs", resourceCulture)
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property Obfuscated() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("Obfuscated", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Public Shared ReadOnly Property Obfuscated2() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("Obfuscated2", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
End Class
End Namespace
| mono/roslyn | src/Compilers/Test/Resources/Core/MetadataTests/Invalid/Invalid.Designer.vb | Visual Basic | apache-2.0 | 8,703 |
/*
* 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.twitter.elephantbird.pig.piggybank;
import org.apache.pig.impl.logicalLayer.FrontendException;
/**
* @see GenericInvoker
*/
public class InvokeForFloat extends GenericInvoker<Float> {
public InvokeForFloat() {}
public InvokeForFloat(String fullName) throws FrontendException, SecurityException, ClassNotFoundException, NoSuchMethodException {
super(fullName);
}
public InvokeForFloat(String fullName, String paramSpecsStr) throws FrontendException, SecurityException, ClassNotFoundException, NoSuchMethodException {
super(fullName, paramSpecsStr);
}
public InvokeForFloat(String fullName, String paramSpecsStr, String isStatic)
throws ClassNotFoundException, FrontendException, SecurityException, NoSuchMethodException {
super(fullName, paramSpecsStr, isStatic);
}
} | 11xor6/elephant-bird | src/java/com/twitter/elephantbird/pig/piggybank/InvokeForFloat.java | Java | apache-2.0 | 1,664 |
/*
* 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 org.apache.wicket.properties;
/**
*/
public class MyApplication extends MyTesterApplication
{
}
| aldaris/wicket | wicket-core/src/test/java/org/apache/wicket/properties/MyApplication.java | Java | apache-2.0 | 910 |
/*
* 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 org.apache.flink.runtime.util.config.memory.jobmanager;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.runtime.util.config.memory.FlinkMemory;
import java.util.Objects;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* Flink internal memory components of Job Manager.
*
* <p>A Job Manager's internal Flink memory consists of the following components.
*
* <ul>
* <li>JVM Heap Memory
* <li>Off-Heap Memory (also JVM Direct Memory)
* </ul>
*
* <p>The relationships of Job Manager Flink memory components are shown below.
*
* <pre>
* β β β Total Flink Memory - β β β
* βββββββββββββββββββββββββββββ
* | β JVM Heap Memory β |
* βββββββββββββββββββββββββββββ
* β βββββββββββββββββββββββββββββ β
* | Off-heap Heap Memory β -β JVM Direct Memory
* β βββββββββββββββββββββββββββββ β
* β β β β β β β β β β β β β β β β β
* </pre>
*/
public class JobManagerFlinkMemory implements FlinkMemory {
private static final long serialVersionUID = 1L;
private final MemorySize jvmHeap;
private final MemorySize offHeapMemory;
@VisibleForTesting
public JobManagerFlinkMemory(MemorySize jvmHeap, MemorySize offHeapMemory) {
this.jvmHeap = checkNotNull(jvmHeap);
this.offHeapMemory = checkNotNull(offHeapMemory);
}
@Override
public MemorySize getJvmHeapMemorySize() {
return jvmHeap;
}
@Override
public MemorySize getJvmDirectMemorySize() {
return offHeapMemory;
}
@Override
public MemorySize getTotalFlinkMemorySize() {
return jvmHeap.add(offHeapMemory);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof JobManagerFlinkMemory) {
JobManagerFlinkMemory that = (JobManagerFlinkMemory) obj;
return Objects.equals(this.jvmHeap, that.jvmHeap)
&& Objects.equals(this.offHeapMemory, that.offHeapMemory);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(jvmHeap, offHeapMemory);
}
}
| apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/util/config/memory/jobmanager/JobManagerFlinkMemory.java | Java | apache-2.0 | 3,433 |
package com.commonsware.empublite;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import de.greenrobot.event.EventBus;
import retrofit.RestAdapter;
public class DownloadCheckService extends IntentService {
private static final String OUR_BOOK_DATE="20120418";
private static final String UPDATE_FILENAME="book.zip";
public static final String UPDATE_BASEDIR="updates";
public DownloadCheckService() {
super("DownloadCheckService");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
String url=getUpdateUrl();
if (url != null) {
File book=download(url);
File updateDir=new File(getFilesDir(), UPDATE_BASEDIR);
updateDir.mkdirs();
unzip(book, updateDir);
book.delete();
EventBus.getDefault().post(new BookUpdatedEvent());
}
}
catch (Exception e) {
Log.e(getClass().getSimpleName(),
"Exception downloading update", e);
}
}
private String getUpdateUrl() {
RestAdapter restAdapter=
new RestAdapter.Builder().setEndpoint("https://commonsware.com")
.build();
BookUpdateInterface updateInterface=
restAdapter.create(BookUpdateInterface.class);
BookUpdateInfo info=updateInterface.update();
if (info.updatedOn.compareTo(OUR_BOOK_DATE) > 0) {
return(info.updateUrl);
}
return(null);
}
private File download(String url) throws MalformedURLException,
IOException {
File output=new File(getFilesDir(), UPDATE_FILENAME);
if (output.exists()) {
output.delete();
}
HttpURLConnection c=
(HttpURLConnection)new URL(url).openConnection();
FileOutputStream fos=new FileOutputStream(output.getPath());
BufferedOutputStream out=new BufferedOutputStream(fos);
try {
InputStream in=c.getInputStream();
byte[] buffer=new byte[16384];
int len=0;
while ((len=in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
}
finally {
fos.getFD().sync();
out.close();
c.disconnect();
}
return(output);
}
private static void unzip(File src, File dest) throws IOException {
InputStream is=new FileInputStream(src);
ZipInputStream zis=new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
dest.mkdirs();
while ((ze=zis.getNextEntry()) != null) {
byte[] buffer=new byte[16384];
int count;
FileOutputStream fos=
new FileOutputStream(new File(dest, ze.getName()));
BufferedOutputStream out=new BufferedOutputStream(fos);
try {
while ((count=zis.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.flush();
}
finally {
fos.getFD().sync();
out.close();
}
zis.closeEntry();
}
zis.close();
}
} | AkechiNEET/cw-omnibus | EmPubLite-AndroidStudio/T16-Update/EmPubLite/app/src/main/java/com/commonsware/empublite/DownloadCheckService.java | Java | apache-2.0 | 3,286 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed 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.siyeh.ipp.trivialif;
import com.intellij.codeInsight.daemon.LightIntentionActionTestCase;
public class MergeIfAndIntentionTest extends LightIntentionActionTestCase {
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/mergeIfAnd";
}
}
| siosio/intellij-community | plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/trivialif/MergeIfAndIntentionTest.java | Java | apache-2.0 | 900 |
/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#pragma once
#include "library/io_state.h"
#include "api/expr.h"
#include "api/lean_ios.h"
namespace lean {
inline io_state * to_io_state(lean_ios n) { return reinterpret_cast<io_state *>(n); }
inline io_state const & to_io_state_ref(lean_ios n) { return *reinterpret_cast<io_state *>(n); }
inline lean_ios of_io_state(io_state * n) { return reinterpret_cast<lean_ios>(n); }
}
| eigengrau/lean | src/api/ios.h | C | apache-2.0 | 541 |
module Fog
module Rackspace
class BlockStorage
class Real
# Retrieves snapshot detail
# @param [String] snapshot_id
# @return [Excon::Response] response:
# * body [Hash]:
# * 'snapshot' [Hash]:
# * 'volume_id' [String]: - volume_id of the snapshot
# * 'display_description' [String]: - snapshot display description
# * 'status' [String]: - snapshot status
# * 'os-extended-snapshot-attributes:project_id' [String]: -
# * 'id' [String]: - snapshot id
# * 'size' [Fixnum]: - size of the snapshot in GB
# * 'os-extended-snapshot-attributes:progress' [String]: -
# * 'display_name' [String]: - display name of snapshot
# * 'created_at' [String]: - creation time of snapshot
# @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404
# @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400
# @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500
# @raise [Fog::Rackspace::BlockStorage::ServiceError]
# @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getSnapshot__v1__tenant_id__snapshots.html
def get_snapshot(snapshot_id)
request(
:expects => [200],
:method => 'GET',
:path => "snapshots/#{snapshot_id}"
)
end
end
class Mock
def get_snapshot(snapshot_id)
snapshot = self.data[:snapshots][snapshot_id]
if snapshot.nil?
raise Fog::Rackspace::BlockStorage::NotFound
else
response(:body => {"snapshot" => snapshot})
end
end
end
end
end
end
| jreichhold/chef-repo | vendor/ruby/2.0.0/gems/fog-1.20.0/lib/fog/rackspace/requests/block_storage/get_snapshot.rb | Ruby | apache-2.0 | 1,781 |
/*
* 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 description. -->
* Contains implementation of Stub for convergence checking.
* By this implementation gradient boosting will train new submodels until count of models achieving max value [count
* of iterations parameter].
*/
package org.apache.ignite.ml.composition.boosting.convergence.simple;
| samaitra/ignite | modules/ml/src/main/java/org/apache/ignite/ml/composition/boosting/convergence/simple/package-info.java | Java | apache-2.0 | 1,123 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed 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 e2e
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/api/resource"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/test/e2e/framework"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = framework.KubeDescribe("LimitRange", func() {
f := framework.NewDefaultFramework("limitrange")
It("should create a LimitRange with defaults and ensure pod has those defaults applied.", func() {
By("Creating a LimitRange")
min := getResourceList("50m", "100Mi")
max := getResourceList("500m", "500Mi")
defaultLimit := getResourceList("500m", "500Mi")
defaultRequest := getResourceList("100m", "200Mi")
maxLimitRequestRatio := v1.ResourceList{}
limitRange := newLimitRange("limit-range", v1.LimitTypeContainer,
min, max,
defaultLimit, defaultRequest,
maxLimitRequestRatio)
limitRange, err := f.ClientSet.Core().LimitRanges(f.Namespace.Name).Create(limitRange)
Expect(err).NotTo(HaveOccurred())
By("Fetching the LimitRange to ensure it has proper values")
limitRange, err = f.ClientSet.Core().LimitRanges(f.Namespace.Name).Get(limitRange.Name, metav1.GetOptions{})
expected := v1.ResourceRequirements{Requests: defaultRequest, Limits: defaultLimit}
actual := v1.ResourceRequirements{Requests: limitRange.Spec.Limits[0].DefaultRequest, Limits: limitRange.Spec.Limits[0].Default}
err = equalResourceRequirement(expected, actual)
Expect(err).NotTo(HaveOccurred())
By("Creating a Pod with no resource requirements")
pod := newTestPod(f, "pod-no-resources", v1.ResourceList{}, v1.ResourceList{})
pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod)
Expect(err).NotTo(HaveOccurred())
By("Ensuring Pod has resource requirements applied from LimitRange")
pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
for i := range pod.Spec.Containers {
err = equalResourceRequirement(expected, pod.Spec.Containers[i].Resources)
if err != nil {
// Print the pod to help in debugging.
framework.Logf("Pod %+v does not have the expected requirements", pod)
Expect(err).NotTo(HaveOccurred())
}
}
By("Creating a Pod with partial resource requirements")
pod = newTestPod(f, "pod-partial-resources", getResourceList("", "150Mi"), getResourceList("300m", ""))
pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod)
Expect(err).NotTo(HaveOccurred())
By("Ensuring Pod has merged resource requirements applied from LimitRange")
pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
// This is an interesting case, so it's worth a comment
// If you specify a Limit, and no Request, the Limit will default to the Request
// This means that the LimitRange.DefaultRequest will ONLY take affect if a container.resources.limit is not supplied
expected = v1.ResourceRequirements{Requests: getResourceList("300m", "150Mi"), Limits: getResourceList("300m", "500Mi")}
for i := range pod.Spec.Containers {
err = equalResourceRequirement(expected, pod.Spec.Containers[i].Resources)
if err != nil {
// Print the pod to help in debugging.
framework.Logf("Pod %+v does not have the expected requirements", pod)
Expect(err).NotTo(HaveOccurred())
}
}
By("Failing to create a Pod with less than min resources")
pod = newTestPod(f, podName, getResourceList("10m", "50Mi"), v1.ResourceList{})
pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod)
Expect(err).To(HaveOccurred())
By("Failing to create a Pod with more than max resources")
pod = newTestPod(f, podName, getResourceList("600m", "600Mi"), v1.ResourceList{})
pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod)
Expect(err).To(HaveOccurred())
})
})
func equalResourceRequirement(expected v1.ResourceRequirements, actual v1.ResourceRequirements) error {
framework.Logf("Verifying requests: expected %v with actual %v", expected.Requests, actual.Requests)
err := equalResourceList(expected.Requests, actual.Requests)
if err != nil {
return err
}
framework.Logf("Verifying limits: expected %v with actual %v", expected.Limits, actual.Limits)
err = equalResourceList(expected.Limits, actual.Limits)
if err != nil {
return err
}
return nil
}
func equalResourceList(expected v1.ResourceList, actual v1.ResourceList) error {
for k, v := range expected {
if actualValue, found := actual[k]; !found || (v.Cmp(actualValue) != 0) {
return fmt.Errorf("resource %v expected %v actual %v", k, v.String(), actualValue.String())
}
}
for k, v := range actual {
if expectedValue, found := expected[k]; !found || (v.Cmp(expectedValue) != 0) {
return fmt.Errorf("resource %v expected %v actual %v", k, expectedValue.String(), v.String())
}
}
return nil
}
func getResourceList(cpu, memory string) v1.ResourceList {
res := v1.ResourceList{}
if cpu != "" {
res[v1.ResourceCPU] = resource.MustParse(cpu)
}
if memory != "" {
res[v1.ResourceMemory] = resource.MustParse(memory)
}
return res
}
// newLimitRange returns a limit range with specified data
func newLimitRange(name string, limitType v1.LimitType,
min, max,
defaultLimit, defaultRequest,
maxLimitRequestRatio v1.ResourceList) *v1.LimitRange {
return &v1.LimitRange{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: v1.LimitRangeSpec{
Limits: []v1.LimitRangeItem{
{
Type: limitType,
Min: min,
Max: max,
Default: defaultLimit,
DefaultRequest: defaultRequest,
MaxLimitRequestRatio: maxLimitRequestRatio,
},
},
},
}
}
// newTestPod returns a pod that has the specified requests and limits
func newTestPod(f *framework.Framework, name string, requests v1.ResourceList, limits v1.ResourceList) *v1.Pod {
return &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "pause",
Image: framework.GetPauseImageName(f.ClientSet),
Resources: v1.ResourceRequirements{
Requests: requests,
Limits: limits,
},
},
},
},
}
}
| aweiteka/cri-o | vendor/k8s.io/kubernetes/test/e2e/limit_range.go | GO | apache-2.0 | 6,807 |
package securitygroup_test
import (
fakeSecurityGroup "github.com/cloudfoundry/cli/cf/api/security_groups/fakes"
"github.com/cloudfoundry/cli/cf/configuration/core_config"
"github.com/cloudfoundry/cli/cf/errors"
"github.com/cloudfoundry/cli/cf/models"
testcmd "github.com/cloudfoundry/cli/testhelpers/commands"
testconfig "github.com/cloudfoundry/cli/testhelpers/configuration"
testreq "github.com/cloudfoundry/cli/testhelpers/requirements"
testterm "github.com/cloudfoundry/cli/testhelpers/terminal"
"github.com/cloudfoundry/cli/cf/command_registry"
. "github.com/cloudfoundry/cli/testhelpers/matchers"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("security-group command", func() {
var (
ui *testterm.FakeUI
securityGroupRepo *fakeSecurityGroup.FakeSecurityGroupRepo
requirementsFactory *testreq.FakeReqFactory
configRepo core_config.Repository
deps command_registry.Dependency
)
updateCommandDependency := func(pluginCall bool) {
deps.Ui = ui
deps.RepoLocator = deps.RepoLocator.SetSecurityGroupRepository(securityGroupRepo)
deps.Config = configRepo
command_registry.Commands.SetCommand(command_registry.Commands.FindCommand("security-group").SetDependency(deps, pluginCall))
}
BeforeEach(func() {
ui = &testterm.FakeUI{}
requirementsFactory = &testreq.FakeReqFactory{}
securityGroupRepo = &fakeSecurityGroup.FakeSecurityGroupRepo{}
configRepo = testconfig.NewRepositoryWithDefaults()
})
runCommand := func(args ...string) bool {
return testcmd.RunCliCommand("security-group", args, requirementsFactory, updateCommandDependency, false)
}
Describe("requirements", func() {
It("should fail if not logged in", func() {
Expect(runCommand("my-group")).To(BeFalse())
})
It("should fail with usage when not provided a single argument", func() {
requirementsFactory.LoginSuccess = true
runCommand("whoops", "I can't believe", "I accidentally", "the whole thing")
Expect(ui.Outputs).To(ContainSubstrings(
[]string{"Incorrect Usage", "Requires an argument"},
))
})
})
Context("when logged in", func() {
BeforeEach(func() {
requirementsFactory.LoginSuccess = true
})
Context("when the group with the given name exists", func() {
BeforeEach(func() {
rulesMap := []map[string]interface{}{{"just-pretend": "that-this-is-correct"}}
securityGroup := models.SecurityGroup{
SecurityGroupFields: models.SecurityGroupFields{
Name: "my-group",
Guid: "group-guid",
Rules: rulesMap,
},
Spaces: []models.Space{
{
SpaceFields: models.SpaceFields{Guid: "my-space-guid-1", Name: "space-1"},
Organization: models.OrganizationFields{Guid: "my-org-guid-1", Name: "org-1"},
},
{
SpaceFields: models.SpaceFields{Guid: "my-space-guid", Name: "space-2"},
Organization: models.OrganizationFields{Guid: "my-org-guid-1", Name: "org-2"},
},
},
}
securityGroupRepo.ReadReturns(securityGroup, nil)
})
It("should fetch the security group from its repo", func() {
runCommand("my-group")
Expect(securityGroupRepo.ReadArgsForCall(0)).To(Equal("my-group"))
})
It("tells the user what it's about to do and then shows the group", func() {
runCommand("my-group")
Expect(ui.Outputs).To(ContainSubstrings(
[]string{"Getting", "security group", "my-group", "my-user"},
[]string{"OK"},
[]string{"Name", "my-group"},
[]string{"Rules"},
[]string{"["},
[]string{"{"},
[]string{"just-pretend", "that-this-is-correct"},
[]string{"}"},
[]string{"]"},
[]string{"#0", "org-1", "space-1"},
[]string{"#1", "org-2", "space-2"},
))
})
It("tells the user if no spaces are assigned", func() {
securityGroup := models.SecurityGroup{
SecurityGroupFields: models.SecurityGroupFields{
Name: "my-group",
Guid: "group-guid",
Rules: []map[string]interface{}{},
},
Spaces: []models.Space{},
}
securityGroupRepo.ReadReturns(securityGroup, nil)
runCommand("my-group")
Expect(ui.Outputs).To(ContainSubstrings(
[]string{"No spaces assigned"},
))
})
})
It("fails and warns the user if a group with that name could not be found", func() {
securityGroupRepo.ReadReturns(models.SecurityGroup{}, errors.New("half-past-tea-time"))
runCommand("im-late!")
Expect(ui.Outputs).To(ContainSubstrings([]string{"FAILED"}))
})
})
})
| TomG713/cli | cf/commands/securitygroup/security_group_test.go | GO | apache-2.0 | 4,509 |
/**
* Module dependencies
*/
var _ = require('lodash'),
utils = require('../utils/helpers'),
hasOwnProperty = utils.object.hasOwnProperty;
/**
* Transformation
*
* Allows for a Waterline Collection to have different
* attributes than what actually exist in an adater's representation.
*
* @param {Object} attributes
* @param {Object} tables
*/
var Transformation = module.exports = function(attributes, tables) {
// Hold an internal mapping of keys to transform
this._transformations = {};
// Initialize
this.initialize(attributes, tables);
return this;
};
/**
* Initial mapping of transformations.
*
* @param {Object} attributes
* @param {Object} tables
*/
Transformation.prototype.initialize = function(attributes, tables) {
var self = this;
Object.keys(attributes).forEach(function(attr) {
// Ignore Functions and Strings
if(['function', 'string'].indexOf(typeof attributes[attr]) > -1) return;
// If not an object, ignore
if(attributes[attr] !== Object(attributes[attr])) return;
// Loop through an attribute and check for transformation keys
Object.keys(attributes[attr]).forEach(function(key) {
// Currently just works with `columnName`, `collection`, `groupKey`
if(key !== 'columnName') return;
// Error if value is not a string
if(typeof attributes[attr][key] !== 'string') {
throw new Error('columnName transformation must be a string');
}
// Set transformation attr to new key
if(key === 'columnName') {
if(attr === attributes[attr][key]) return;
self._transformations[attr] = attributes[attr][key];
}
});
});
};
/**
* Transforms a set of attributes into a representation used
* in an adapter.
*
* @param {Object} attributes to transform
* @return {Object}
*/
Transformation.prototype.serialize = function(attributes,behavior) {
var self = this,
values = _.clone(attributes);
behavior = behavior || 'default';
function recursiveParse(obj) {
// Return if no object
if(!obj) return;
// Handle array of types for findOrCreateEach
if(typeof obj === 'string') {
if(hasOwnProperty(self._transformations, obj)) {
values = self._transformations[obj];
return;
}
return;
}
Object.keys(obj).forEach(function(property) {
// Just a double check to exit if hasOwnProperty fails
if(!hasOwnProperty(obj, property)) return;
// Schema must be serialized in first level only
if (behavior === 'schema') {
if(hasOwnProperty(self._transformations, property)) {
obj[self._transformations[property]] = _.clone(obj[property]);
delete obj[property];
}
return;
}
// Recursively parse `OR` criteria objects to transform keys
if(Array.isArray(obj[property]) && property === 'or') return recursiveParse(obj[property]);
// If Nested Object call function again passing the property as obj
if((toString.call(obj[property]) !== '[object Date]') && (_.isPlainObject(obj[property]))) {
// check if object key is in the transformations
if(hasOwnProperty(self._transformations, property)) {
obj[self._transformations[property]] = _.clone(obj[property]);
delete obj[property];
return recursiveParse(obj[self._transformations[property]]);
}
return recursiveParse(obj[property]);
}
// Check if property is a transformation key
if(hasOwnProperty(self._transformations, property)) {
obj[self._transformations[property]] = obj[property];
delete obj[property];
}
});
}
// Recursivly parse attributes to handle nested criteria
recursiveParse(values);
return values;
};
/**
* Transforms a set of attributes received from an adapter
* into a representation used in a collection.
*
* @param {Object} attributes to transform
* @return {Object}
*/
Transformation.prototype.unserialize = function(attributes) {
var self = this,
values = _.clone(attributes);
// Loop through the attributes and change them
Object.keys(this._transformations).forEach(function(key) {
var transformed = self._transformations[key];
if(!hasOwnProperty(attributes, transformed)) return;
values[key] = attributes[transformed];
if(transformed !== key) delete values[transformed];
});
return values;
};
| alexandruionascu/stocker | node_modules/waterline/lib/waterline/core/transformations.js | JavaScript | apache-2.0 | 4,453 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<p>
Before.
<!--comment--
>
After.
</p>
</body>
</html> | paplorinc/intellij-community | xml/tests/testData/psi/old/html/IDEADEV-13898.html | HTML | apache-2.0 | 225 |
// Copyright 2015 The Hugo Authors. All rights reserved.
//
// Licensed 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 source
import (
"bytes"
"fmt"
)
type ByteSource struct {
Name string
Content []byte
}
func (b *ByteSource) String() string {
return fmt.Sprintf("%s %s", b.Name, string(b.Content))
}
type InMemorySource struct {
ByteSource []ByteSource
}
func (i *InMemorySource) Files() (files []*File) {
files = make([]*File, len(i.ByteSource))
for i, fake := range i.ByteSource {
files[i] = NewFileWithContents(fake.Name, bytes.NewReader(fake.Content))
}
return
}
| vbatoufflet/hugo | source/inmemory.go | GO | apache-2.0 | 1,086 |
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8"/>
<title>CSS text, linebreaks: IN (strict,de)</title>
<link rel="author" title="Richard Ishida" href="mailto:[email protected]">
<link rel="help" href="https://drafts.csswg.org/css-text-3/#line-break-property">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<meta name="assert" content="When the language is neither Japanese nor Chinese, and line-break:strict, a browser will NOT allow a break before an inseparable character.">
<style type="text/css">
@font-face {
font-family: 'mplus-1p-regular';
src: url('/fonts/mplus-1p-regular.woff') format('woff');
}
#wrapper { position: relative; }
.test { color: red; }
.test, .ref { font-size: 30px; font-family: mplus-1p-regular, sans-serif; width: 185px; padding: 0; border: 1px solid orange; line-height: 1em; }
</style>
<style>
.test { line-break: strict; }
</style>
<script>
var charlist = `2024 ONE DOT LEADER
2025 TWO DOT LEADER
2026 HORIZONTAL ELLIPSIS
22EF MIDLINE HORIZONTAL ELLIPSIS
FE19 PRESENTATION FORM FOR VERTICAL HORIZONTAL ELLIPSIS`
</script>
</head>
<body>
<script>
var lines = charlist.split('\n')
var out = '<div id="log"></div>\n'
for (var i=0;i<lines.length;i++) {
// get the data
var firstSpace = lines[i].indexOf(' ')
var hex = lines[i].substr(0,firstSpace)
var name = lines[i].substr(firstSpace)
// make a test
out += '<div class="wrapper"><div>'+hex+'</div>' +
'<div class="test" id="test'+i+'" lang="de">ζζζζζζ&#x'+hex+';ε<span id="testSpan'+i+'">ε</span></div>' +
'<div class="ref" id="ref'+i+'" lang="de">ζζζζζ<br/>ζ&#x'+hex+';ε<span id="refSpan'+i+'">ε</span></div>' +
'</div>'
}
document.querySelector('body').innerHTML = out
setup({explicit_done: true});
document.fonts.ready.then(validate);
function validate() {
for (i=0;i<lines.length;i++) {
test(function() {
assert_approx_equals(
document.getElementById('testSpan'+i).getBoundingClientRect().left,
document.getElementById('refSpan'+i).getBoundingClientRect().left, 1);
// Hide successful tests.
document.getElementById('test'+i).parentNode.style.display = 'none';
}, lines[i]+' may NOT appear at line start if de and strict');
}
done();
}
</script>
<!--Notes:
The test creates a box with room for 6 characters, causing wrapping to occur either between the 6th and the 7th character, or before the 6th if the breaks after the 6th or before the 7th are prohibited.
It also creates the expected behaviour with a ref instance, using <br/>. Each line ends with a span. The test then checks whether the left edge of the span is in the same place in test and ref instance.
-->
</body>
</html>
| scheib/chromium | third_party/blink/web_tests/external/wpt/css/css-text/i18n/other-lang/css-text-line-break-de-in-strict.html | HTML | bsd-3-clause | 2,751 |
#!/bin/bash
# load java environment variables
source $IROOT/java7.installed
export JAVA_OPTS="-Xms2g -Xmx2g -XX:MaxPermSize=256m -XX:+UseG1GC -XX:MaxGCPauseMillis=25 -verbosegc -Xloggc:/tmp/wildfly_gc.log"
mvn clean initialize package -Pbenchmark -Ddatabase.host=${DBHOST}
target/wildfly-9.0.0.Beta2/bin/standalone.sh -b 0.0.0.0 & | hamiltont/FrameworkBenchmarks | frameworks/Java/wildfly-ee7/setup.sh | Shell | bsd-3-clause | 332 |
/*
* Copyright (c) 2016, The OpenThread Authors.
* 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.
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*/
#include "precomp.h"
#include "dllmain.tmh"
BOOL
__stdcall
DllMain(
HINSTANCE hinstDll,
DWORD dwReason,
LPVOID /* lpvReserved */
)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hinstDll);
WPP_INIT_TRACING(L"otNodeApi");
break;
case DLL_PROCESS_DETACH:
Unload();
WPP_CLEANUP();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
| mszczodrak/openthread | examples/drivers/windows/otNodeApi/dllmain.cpp | C++ | bsd-3-clause | 2,106 |
package com.xtremelabs.robolectric.shadows;
import java.lang.reflect.Field;
import android.content.ContentProviderResult;
import android.net.Uri;
import com.xtremelabs.robolectric.internal.Implements;
import com.xtremelabs.robolectric.internal.RealObject;
@Implements(ContentProviderResult.class)
public class ShadowContentProviderResult {
@RealObject ContentProviderResult realResult;
public void __constructor__(Uri uri) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = realResult.getClass().getField("uri");
field.setAccessible(true);
field.set(realResult, uri);
}
public void __constructor__(int count) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = realResult.getClass().getField("count");
field.setAccessible(true);
field.set(realResult, count);
}
} | BCGDV/robolectric | src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderResult.java | Java | mit | 967 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.