idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
153,600
|
static String pullFontPathFromView ( Context context , AttributeSet attrs , int [ ] attributeId ) { if ( attributeId == null || attrs == null ) return null ; final String attributeName ; try { attributeName = context . getResources ( ) . getResourceEntryName ( attributeId [ 0 ] ) ; } catch ( Resources . NotFoundException e ) { // invalid attribute ID return null ; } final int stringResourceId = attrs . getAttributeResourceValue ( null , attributeName , - 1 ) ; return stringResourceId > 0 ? context . getString ( stringResourceId ) : attrs . getAttributeValue ( null , attributeName ) ; }
|
Tries to pull the Custom Attribute directly from the TextView .
| 141
| 14
|
153,601
|
static String pullFontPathFromStyle ( Context context , AttributeSet attrs , int [ ] attributeId ) { if ( attributeId == null || attrs == null ) return null ; final TypedArray typedArray = context . obtainStyledAttributes ( attrs , attributeId ) ; if ( typedArray != null ) { try { // First defined attribute String fontFromAttribute = typedArray . getString ( 0 ) ; if ( ! TextUtils . isEmpty ( fontFromAttribute ) ) { return fontFromAttribute ; } } catch ( Exception ignore ) { // Failed for some reason. } finally { typedArray . recycle ( ) ; } } return null ; }
|
Tries to pull the Font Path from the View Style as this is the next decendent after being defined in the View s xml .
| 139
| 28
|
153,602
|
static String pullFontPathFromTextAppearance ( final Context context , AttributeSet attrs , int [ ] attributeId ) { if ( attributeId == null || attrs == null ) { return null ; } int textAppearanceId = - 1 ; final TypedArray typedArrayAttr = context . obtainStyledAttributes ( attrs , ANDROID_ATTR_TEXT_APPEARANCE ) ; if ( typedArrayAttr != null ) { try { textAppearanceId = typedArrayAttr . getResourceId ( 0 , - 1 ) ; } catch ( Exception ignored ) { // Failed for some reason return null ; } finally { typedArrayAttr . recycle ( ) ; } } final TypedArray textAppearanceAttrs = context . obtainStyledAttributes ( textAppearanceId , attributeId ) ; if ( textAppearanceAttrs != null ) { try { return textAppearanceAttrs . getString ( 0 ) ; } catch ( Exception ignore ) { // Failed for some reason. return null ; } finally { textAppearanceAttrs . recycle ( ) ; } } return null ; }
|
Tries to pull the Font Path from the Text Appearance .
| 227
| 12
|
153,603
|
static boolean canCheckForV7Toolbar ( ) { if ( sToolbarCheck == null ) { try { Class . forName ( "android.support.v7.widget.Toolbar" ) ; sToolbarCheck = Boolean . TRUE ; } catch ( ClassNotFoundException e ) { sToolbarCheck = Boolean . FALSE ; } } return sToolbarCheck ; }
|
See if the user has added appcompat - v7 this is done at runtime so we only check once .
| 81
| 23
|
153,604
|
static boolean canAddV7AppCompatViews ( ) { if ( sAppCompatViewCheck == null ) { try { Class . forName ( "android.support.v7.widget.AppCompatTextView" ) ; sAppCompatViewCheck = Boolean . TRUE ; } catch ( ClassNotFoundException e ) { sAppCompatViewCheck = Boolean . FALSE ; } } return sAppCompatViewCheck ; }
|
See if the user has added appcompat - v7 with AppCompatViews
| 88
| 17
|
153,605
|
private static void addAppCompatViews ( ) { DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatTextView . class , android . R . attr . textViewStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatButton . class , android . R . attr . buttonStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatEditText . class , android . R . attr . editTextStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatAutoCompleteTextView . class , android . R . attr . autoCompleteTextViewStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatMultiAutoCompleteTextView . class , android . R . attr . autoCompleteTextViewStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatCheckBox . class , android . R . attr . checkboxStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatRadioButton . class , android . R . attr . radioButtonStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatCheckedTextView . class , android . R . attr . checkedTextViewStyle ) ; }
|
AppCompat will inflate special versions of views for Material tinting etc this adds those classes to the style lookup map
| 318
| 23
|
153,606
|
static CalligraphyActivityFactory get ( Activity activity ) { if ( ! ( activity . getLayoutInflater ( ) instanceof CalligraphyLayoutInflater ) ) { throw new RuntimeException ( "This activity does not wrap the Base Context! See CalligraphyContextWrapper.wrap(Context)" ) ; } return ( CalligraphyActivityFactory ) activity . getLayoutInflater ( ) ; }
|
Get the Calligraphy Activity Fragment Instance to allow callbacks for when views are created .
| 86
| 20
|
153,607
|
protected static int [ ] getStyleForTextView ( TextView view ) { final int [ ] styleIds = new int [ ] { - 1 , - 1 } ; // Try to find the specific actionbar styles if ( isActionBarTitle ( view ) ) { styleIds [ 0 ] = android . R . attr . actionBarStyle ; styleIds [ 1 ] = android . R . attr . titleTextStyle ; } else if ( isActionBarSubTitle ( view ) ) { styleIds [ 0 ] = android . R . attr . actionBarStyle ; styleIds [ 1 ] = android . R . attr . subtitleTextStyle ; } if ( styleIds [ 0 ] == - 1 ) { // Use TextAppearance as default style styleIds [ 0 ] = CalligraphyConfig . get ( ) . getClassStyles ( ) . containsKey ( view . getClass ( ) ) ? CalligraphyConfig . get ( ) . getClassStyles ( ) . get ( view . getClass ( ) ) : android . R . attr . textAppearance ; } return styleIds ; }
|
Some styles are in sub styles such as actionBarTextStyle etc ..
| 240
| 14
|
153,608
|
protected static boolean matchesResourceIdName ( View view , String matches ) { if ( view . getId ( ) == View . NO_ID ) return false ; final String resourceEntryName = view . getResources ( ) . getResourceEntryName ( view . getId ( ) ) ; return resourceEntryName . equalsIgnoreCase ( matches ) ; }
|
Use to match a view against a potential view id . Such as ActionBar title etc .
| 73
| 18
|
153,609
|
public View onViewCreated ( View view , Context context , AttributeSet attrs ) { if ( view != null && view . getTag ( R . id . calligraphy_tag_id ) != Boolean . TRUE ) { onViewCreatedInternal ( view , context , attrs ) ; view . setTag ( R . id . calligraphy_tag_id , Boolean . TRUE ) ; } return view ; }
|
Handle the created view
| 88
| 4
|
153,610
|
private String resolveFontPath ( Context context , AttributeSet attrs ) { // Try view xml attributes String textViewFont = CalligraphyUtils . pullFontPathFromView ( context , attrs , mAttributeId ) ; // Try view style attributes if ( TextUtils . isEmpty ( textViewFont ) ) { textViewFont = CalligraphyUtils . pullFontPathFromStyle ( context , attrs , mAttributeId ) ; } // Try View TextAppearance if ( TextUtils . isEmpty ( textViewFont ) ) { textViewFont = CalligraphyUtils . pullFontPathFromTextAppearance ( context , attrs , mAttributeId ) ; } return textViewFont ; }
|
Resolving font path from xml attrs style attrs or text appearance
| 149
| 14
|
153,611
|
private void applyFontToToolbar ( final Toolbar view ) { final CharSequence previousTitle = view . getTitle ( ) ; final CharSequence previousSubtitle = view . getSubtitle ( ) ; // The toolbar inflates both the title and the subtitle views lazily but luckily they do it // synchronously when you set a title and a subtitle programmatically. // So we set a title and a subtitle to something, then get the views, then revert. view . setTitle ( "uk.co.chrisjenx.calligraphy:toolbar_title" ) ; view . setSubtitle ( "uk.co.chrisjenx.calligraphy:toolbar_subtitle" ) ; // Iterate through the children to run post inflation on them final int childCount = view . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { onViewCreated ( view . getChildAt ( i ) , view . getContext ( ) , null ) ; } // Remove views from view if they didn't have copy set. view . setTitle ( previousTitle ) ; view . setSubtitle ( previousSubtitle ) ; }
|
Will forcibly set text on the views then remove ones that didn t have copy .
| 250
| 16
|
153,612
|
public static Typeface load ( final AssetManager assetManager , final String filePath ) { synchronized ( sCachedFonts ) { try { if ( ! sCachedFonts . containsKey ( filePath ) ) { final Typeface typeface = Typeface . createFromAsset ( assetManager , filePath ) ; sCachedFonts . put ( filePath , typeface ) ; return typeface ; } } catch ( Exception e ) { Log . w ( "Calligraphy" , "Can't create asset from " + filePath + ". Make sure you have passed in the correct path and file name." , e ) ; sCachedFonts . put ( filePath , null ) ; return null ; } return sCachedFonts . get ( filePath ) ; } }
|
A helper loading a custom font .
| 165
| 7
|
153,613
|
public static CalligraphyTypefaceSpan getSpan ( final Typeface typeface ) { if ( typeface == null ) return null ; synchronized ( sCachedSpans ) { if ( ! sCachedSpans . containsKey ( typeface ) ) { final CalligraphyTypefaceSpan span = new CalligraphyTypefaceSpan ( typeface ) ; sCachedSpans . put ( typeface , span ) ; return span ; } return sCachedSpans . get ( typeface ) ; } }
|
A helper loading custom spans so we don t have to keep creating hundreds of spans .
| 112
| 17
|
153,614
|
public static String getScript ( String path ) { StringBuilder sb = new StringBuilder ( ) ; InputStream stream = ScriptUtil . class . getClassLoader ( ) . getResourceAsStream ( path ) ; try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( stream ) ) ) { String str ; while ( ( str = br . readLine ( ) ) != null ) { sb . append ( str ) . append ( System . lineSeparator ( ) ) ; } } catch ( IOException e ) { System . err . println ( e . getStackTrace ( ) ) ; } return sb . toString ( ) ; }
|
return lua script String
| 142
| 5
|
153,615
|
private Object getConnection ( ) { Object connection ; if ( type == RedisToolsConstant . SINGLE ) { RedisConnection redisConnection = jedisConnectionFactory . getConnection ( ) ; connection = redisConnection . getNativeConnection ( ) ; } else { RedisClusterConnection clusterConnection = jedisConnectionFactory . getClusterConnection ( ) ; connection = clusterConnection . getNativeConnection ( ) ; } return connection ; }
|
get Redis connection
| 95
| 4
|
153,616
|
public boolean tryLock ( String key , String request ) { //get connection Object connection = getConnection ( ) ; String result ; if ( connection instanceof Jedis ) { result = ( ( Jedis ) connection ) . set ( lockPrefix + key , request , SET_IF_NOT_EXIST , SET_WITH_EXPIRE_TIME , 10 * TIME ) ; ( ( Jedis ) connection ) . close ( ) ; } else { result = ( ( JedisCluster ) connection ) . set ( lockPrefix + key , request , SET_IF_NOT_EXIST , SET_WITH_EXPIRE_TIME , 10 * TIME ) ; } if ( LOCK_MSG . equals ( result ) ) { return true ; } else { return false ; } }
|
Non - blocking lock
| 168
| 4
|
153,617
|
public void error ( final String msg ) { errors ++ ; if ( ! suppressOutput ) { out . println ( "ERROR: " + msg ) ; } if ( stopOnError ) { throw new IllegalArgumentException ( msg ) ; } }
|
Record a message signifying an error condition .
| 51
| 9
|
153,618
|
public void warning ( final String msg ) { warnings ++ ; if ( ! suppressOutput ) { out . println ( "WARNING: " + msg ) ; } if ( warningsFatal && stopOnError ) { throw new IllegalArgumentException ( msg ) ; } }
|
Record a message signifying an warning condition .
| 55
| 9
|
153,619
|
public static String formatByteOrderEncoding ( final ByteOrder byteOrder , final PrimitiveType primitiveType ) { switch ( primitiveType . size ( ) ) { case 2 : return "SBE_" + byteOrder + "_ENCODE_16" ; case 4 : return "SBE_" + byteOrder + "_ENCODE_32" ; case 8 : return "SBE_" + byteOrder + "_ENCODE_64" ; default : return "" ; } }
|
Return the Cpp98 formatted byte order encoding string to use for a given byte order and primitiveType
| 100
| 20
|
153,620
|
public static String formatPropertyName ( final String value ) { String formattedValue = toUpperFirstChar ( value ) ; if ( ValidationUtil . isGolangKeyword ( formattedValue ) ) { final String keywordAppendToken = System . getProperty ( SbeTool . KEYWORD_APPEND_TOKEN ) ; if ( null == keywordAppendToken ) { throw new IllegalStateException ( "Invalid property name='" + formattedValue + "' please correct the schema or consider setting system property: " + SbeTool . KEYWORD_APPEND_TOKEN ) ; } formattedValue += keywordAppendToken ; } return formattedValue ; }
|
Format a String as a property name .
| 140
| 8
|
153,621
|
public static PrimitiveValue parse ( final String value , final int length , final String characterEncoding ) { if ( value . length ( ) > length ) { throw new IllegalStateException ( "value.length=" + value . length ( ) + " greater than length=" + length ) ; } byte [ ] bytes = value . getBytes ( forName ( characterEncoding ) ) ; if ( bytes . length < length ) { bytes = Arrays . copyOf ( bytes , length ) ; } return new PrimitiveValue ( bytes , characterEncoding , length ) ; }
|
Parse constant value string and set representation based on type length and characterEncoding
| 119
| 16
|
153,622
|
public byte [ ] byteArrayValue ( final PrimitiveType type ) { if ( representation == Representation . BYTE_ARRAY ) { return byteArrayValue ; } else if ( representation == Representation . LONG && size == 1 && type == PrimitiveType . CHAR ) { byteArrayValueForLong [ 0 ] = ( byte ) longValue ; return byteArrayValueForLong ; } throw new IllegalStateException ( "PrimitiveValue is not a byte[] representation" ) ; }
|
Return byte array value for this PrimitiveValue given a particular type
| 101
| 13
|
153,623
|
public static void append ( final StringBuilder builder , final String indent , final String line ) { builder . append ( indent ) . append ( line ) . append ( ' ' ) ; }
|
Shortcut to append a line of generated code
| 38
| 9
|
153,624
|
public static String generateTypeJavadoc ( final String indent , final Token typeToken ) { final String description = typeToken . description ( ) ; if ( null == description || description . isEmpty ( ) ) { return "" ; } return indent + "/**\n" + indent + " * " + description + ' ' + indent + " */\n" ; }
|
Generate the Javadoc comment header for a type .
| 78
| 12
|
153,625
|
public static String generateOptionEncodeJavadoc ( final String indent , final Token optionToken ) { final String description = optionToken . description ( ) ; if ( null == description || description . isEmpty ( ) ) { return "" ; } return indent + "/**\n" + indent + " * " + description + ' ' + indent + " *\n" + indent + " * @param value true if " + optionToken . name ( ) + " is set or false if not\n" + indent + " */\n" ; }
|
Generate the Javadoc comment header for a bitset choice option encode method .
| 117
| 17
|
153,626
|
public static String generateFlyweightPropertyJavadoc ( final String indent , final Token propertyToken , final String typeName ) { final String description = propertyToken . description ( ) ; if ( null == description || description . isEmpty ( ) ) { return "" ; } return indent + "/**\n" + indent + " * " + description + ' ' + indent + " *\n" + indent + " * @return " + typeName + " : " + description + "\n" + indent + " */\n" ; }
|
Generate the Javadoc comment header for flyweight property .
| 114
| 13
|
153,627
|
public static Map < Long , Message > findMessages ( final Document document , final XPath xPath , final Map < String , Type > typeByNameMap ) throws Exception { final Map < Long , Message > messageByIdMap = new HashMap <> ( ) ; final ObjectHashSet < String > distinctNames = new ObjectHashSet <> ( ) ; forEach ( ( NodeList ) xPath . compile ( MESSAGE_XPATH_EXPR ) . evaluate ( document , XPathConstants . NODESET ) , ( node ) - > addMessageWithIdCheck ( distinctNames , messageByIdMap , new Message ( node , typeByNameMap ) , node ) ) ; return messageByIdMap ; }
|
Scan XML for all message definitions and save in map
| 153
| 10
|
153,628
|
public static void handleError ( final Node node , final String msg ) { final ErrorHandler handler = ( ErrorHandler ) node . getOwnerDocument ( ) . getUserData ( ERROR_HANDLER_KEY ) ; if ( handler == null ) { throw new IllegalStateException ( "ERROR: " + formatLocationInfo ( node ) + msg ) ; } else { handler . error ( formatLocationInfo ( node ) + msg ) ; } }
|
Handle an error condition as consequence of parsing .
| 92
| 9
|
153,629
|
public static void handleWarning ( final Node node , final String msg ) { final ErrorHandler handler = ( ErrorHandler ) node . getOwnerDocument ( ) . getUserData ( ERROR_HANDLER_KEY ) ; if ( handler == null ) { throw new IllegalStateException ( "WARNING: " + formatLocationInfo ( node ) + msg ) ; } else { handler . warning ( formatLocationInfo ( node ) + msg ) ; } }
|
Handle a warning condition as a consequence of parsing .
| 92
| 10
|
153,630
|
public static String getAttributeValue ( final Node elementNode , final String attrName ) { final Node attrNode = elementNode . getAttributes ( ) . getNamedItemNS ( null , attrName ) ; if ( attrNode == null || "" . equals ( attrNode . getNodeValue ( ) ) ) { throw new IllegalStateException ( "Element '" + elementNode . getNodeName ( ) + "' has empty or missing attribute: " + attrName ) ; } return attrNode . getNodeValue ( ) ; }
|
Helper function that throws an exception when the attribute is not set .
| 117
| 13
|
153,631
|
public static String getAttributeValue ( final Node elementNode , final String attrName , final String defValue ) { final Node attrNode = elementNode . getAttributes ( ) . getNamedItemNS ( null , attrName ) ; if ( attrNode == null ) { return defValue ; } return attrNode . getNodeValue ( ) ; }
|
Helper function that uses a default value when value not set .
| 77
| 12
|
153,632
|
public static void checkForValidName ( final Node node , final String name ) { if ( ! ValidationUtil . isSbeCppName ( name ) ) { handleWarning ( node , "name is not valid for C++: " + name ) ; } if ( ! ValidationUtil . isSbeJavaName ( name ) ) { handleWarning ( node , "name is not valid for Java: " + name ) ; } if ( ! ValidationUtil . isSbeGolangName ( name ) ) { handleWarning ( node , "name is not valid for Golang: " + name ) ; } if ( ! ValidationUtil . isSbeCSharpName ( name ) ) { handleWarning ( node , "name is not valid for C#: " + name ) ; } }
|
Check name against validity for C ++ and Java naming . Warning if not valid .
| 173
| 16
|
153,633
|
private int generateFieldEncodeDecode ( final List < Token > tokens , final char varName , final int currentOffset , final StringBuilder encode , final StringBuilder decode , final StringBuilder rc , final StringBuilder init ) { final Token signalToken = tokens . get ( 0 ) ; final Token encodingToken = tokens . get ( 1 ) ; final String propertyName = formatPropertyName ( signalToken . name ( ) ) ; int gap = 0 ; // for offset calculations switch ( encodingToken . signal ( ) ) { case BEGIN_COMPOSITE : case BEGIN_ENUM : case BEGIN_SET : gap = signalToken . offset ( ) - currentOffset ; encode . append ( generateEncodeOffset ( gap , "" ) ) ; decode . append ( generateDecodeOffset ( gap , "" ) ) ; // Encode of a constant is a nullop, decode is assignment if ( signalToken . isConstantEncoding ( ) ) { decode . append ( String . format ( "\t%1$s.%2$s = %3$s\n" , varName , propertyName , signalToken . encoding ( ) . constValue ( ) ) ) ; init . append ( String . format ( "\t%1$s.%2$s = %3$s\n" , varName , propertyName , signalToken . encoding ( ) . constValue ( ) ) ) ; } else { encode . append ( String . format ( "\tif err := %1$s.%2$s.Encode(_m, _w); err != nil {\n" + "\t\treturn err\n" + "\t}\n" , varName , propertyName ) ) ; decode . append ( String . format ( "\tif %1$s.%2$sInActingVersion(actingVersion) {\n" + "\t\tif err := %1$s.%2$s.Decode(_m, _r, actingVersion); err != nil {\n" + "\t\t\treturn err\n" + "\t\t}\n" + "\t}\n" , varName , propertyName ) ) ; } if ( encodingToken . signal ( ) == Signal . BEGIN_ENUM ) { rc . append ( String . format ( "\tif err := %1$s.%2$s.RangeCheck(actingVersion, schemaVersion); err != nil {\n" + "\t\treturn err\n" + "\t}\n" , varName , propertyName ) ) ; } break ; case ENCODING : gap = encodingToken . offset ( ) - currentOffset ; encode . append ( generateEncodeOffset ( gap , "" ) ) ; decode . append ( generateDecodeOffset ( gap , "" ) ) ; final String primitive = varName + "." + propertyName ; // Encode of a constant is a nullop and we want to // initialize constant values. // (note: constancy is determined by the type's token) if ( encodingToken . isConstantEncoding ( ) ) { generateConstantInitPrimitive ( init , primitive , encodingToken ) ; } else { generateEncodePrimitive ( encode , varName , formatPropertyName ( signalToken . name ( ) ) , encodingToken ) ; } // Optional tokens get initialized to NullValue // (note: optionality is determined by the field's token) if ( signalToken . isOptionalEncoding ( ) ) { generateOptionalInitPrimitive ( init , primitive , encodingToken ) ; } generateDecodePrimitive ( decode , primitive , encodingToken ) ; generateRangeCheckPrimitive ( rc , primitive , encodingToken , signalToken . isOptionalEncoding ( ) ) ; break ; } return encodingToken . encodedLength ( ) + gap ; }
|
Returns how many extra tokens to skip over
| 798
| 8
|
153,634
|
private void generateGroupProperties ( final StringBuilder sb , final List < Token > tokens , final String prefix ) { for ( int i = 0 , size = tokens . size ( ) ; i < size ; i ++ ) { final Token token = tokens . get ( i ) ; if ( token . signal ( ) == Signal . BEGIN_GROUP ) { final String propertyName = formatPropertyName ( token . name ( ) ) ; generateId ( sb , prefix , propertyName , token ) ; generateSinceActingDeprecated ( sb , prefix , propertyName , token ) ; generateExtensibilityMethods ( sb , prefix + propertyName , token ) ; // Look inside for nested groups with extra prefix generateGroupProperties ( sb , tokens . subList ( i + 1 , i + token . componentTokenCount ( ) - 1 ) , prefix + propertyName ) ; i += token . componentTokenCount ( ) - 1 ; } } }
|
Recursively traverse groups to create the group properties
| 200
| 10
|
153,635
|
private void generateExtensibilityMethods ( final StringBuilder sb , final String typeName , final Token token ) { sb . append ( String . format ( "\nfunc (*%1$s) SbeBlockLength() (blockLength uint) {\n" + "\treturn %2$s\n" + "}\n" + "\nfunc (*%1$s) SbeSchemaVersion() (schemaVersion %3$s) {\n" + "\treturn %4$s\n" + "}\n" , typeName , generateLiteral ( ir . headerStructure ( ) . blockLengthType ( ) , Integer . toString ( token . encodedLength ( ) ) ) , golangTypeName ( ir . headerStructure ( ) . schemaVersionType ( ) ) , generateLiteral ( ir . headerStructure ( ) . schemaVersionType ( ) , Integer . toString ( ir . version ( ) ) ) ) ) ; }
|
of block length and version to check for extensions
| 207
| 9
|
153,636
|
public static String formatScopedName ( final CharSequence [ ] scope , final String value ) { return String . join ( "_" , scope ) . toLowerCase ( ) + "_" + formatName ( value ) ; }
|
Format a String as a struct name prepended with a scope .
| 48
| 13
|
153,637
|
public static void main ( final String [ ] args ) throws Exception { if ( args . length == 0 ) { System . err . format ( "Usage: %s <filenames>...%n" , SbeTool . class . getName ( ) ) ; System . exit ( - 1 ) ; } for ( final String fileName : args ) { final Ir ir ; if ( fileName . endsWith ( ".xml" ) ) { final String xsdFilename = System . getProperty ( SbeTool . VALIDATION_XSD ) ; if ( xsdFilename != null ) { validateAgainstSchema ( fileName , xsdFilename ) ; } ir = new IrGenerator ( ) . generate ( parseSchema ( fileName ) , System . getProperty ( TARGET_NAMESPACE ) ) ; } else if ( fileName . endsWith ( ".sbeir" ) ) { ir = new IrDecoder ( fileName ) . decode ( ) ; } else { System . err . println ( "Input file format not supported: " + fileName ) ; System . exit ( - 1 ) ; return ; } final String outputDirName = System . getProperty ( OUTPUT_DIR , "." ) ; if ( Boolean . parseBoolean ( System . getProperty ( GENERATE_STUBS , "true" ) ) ) { final String targetLanguage = System . getProperty ( TARGET_LANGUAGE , "Java" ) ; generate ( ir , outputDirName , targetLanguage ) ; } if ( Boolean . parseBoolean ( System . getProperty ( GENERATE_IR , "false" ) ) ) { final File inputFile = new File ( fileName ) ; final String inputFilename = inputFile . getName ( ) ; final int nameEnd = inputFilename . lastIndexOf ( ' ' ) ; final String namePart = inputFilename . substring ( 0 , nameEnd ) ; final File fullPath = new File ( outputDirName , namePart + ".sbeir" ) ; try ( IrEncoder irEncoder = new IrEncoder ( fullPath . getAbsolutePath ( ) , ir ) ) { irEncoder . encode ( ) ; } } } }
|
Main entry point for the SBE Tool .
| 469
| 9
|
153,638
|
public static void validateAgainstSchema ( final String sbeSchemaFilename , final String xsdFilename ) throws Exception { final ParserOptions . Builder optionsBuilder = ParserOptions . builder ( ) . xsdFilename ( System . getProperty ( VALIDATION_XSD ) ) . xIncludeAware ( Boolean . parseBoolean ( System . getProperty ( XINCLUDE_AWARE ) ) ) . stopOnError ( Boolean . parseBoolean ( System . getProperty ( VALIDATION_STOP_ON_ERROR ) ) ) . warningsFatal ( Boolean . parseBoolean ( System . getProperty ( VALIDATION_WARNINGS_FATAL ) ) ) . suppressOutput ( Boolean . parseBoolean ( System . getProperty ( VALIDATION_SUPPRESS_OUTPUT ) ) ) ; final Path path = Paths . get ( sbeSchemaFilename ) ; try ( InputStream in = new BufferedInputStream ( Files . newInputStream ( path ) ) ) { final InputSource inputSource = new InputSource ( in ) ; if ( path . toAbsolutePath ( ) . getParent ( ) != null ) { inputSource . setSystemId ( path . toUri ( ) . toString ( ) ) ; } XmlSchemaParser . validate ( xsdFilename , inputSource , optionsBuilder . build ( ) ) ; } }
|
Validate the SBE Schema against the XSD .
| 293
| 12
|
153,639
|
public static void generate ( final Ir ir , final String outputDirName , final String targetLanguage ) throws Exception { final TargetCodeGenerator targetCodeGenerator = TargetCodeGeneratorLoader . get ( targetLanguage ) ; final CodeGenerator codeGenerator = targetCodeGenerator . newInstance ( ir , outputDirName ) ; codeGenerator . generate ( ) ; }
|
Generate SBE encoding and decoding stubs for a target language .
| 77
| 14
|
153,640
|
public void makeDataFieldCompositeType ( ) { final EncodedDataType edt = ( EncodedDataType ) containedTypeByNameMap . get ( "varData" ) ; if ( edt != null ) { edt . variableLength ( true ) ; } }
|
Make this composite type if it has a varData member variable length by making the EncodedDataType with the name varData be variable length .
| 59
| 29
|
153,641
|
public void checkForWellFormedGroupSizeEncoding ( final Node node ) { final EncodedDataType blockLengthType = ( EncodedDataType ) containedTypeByNameMap . get ( "blockLength" ) ; final EncodedDataType numInGroupType = ( EncodedDataType ) containedTypeByNameMap . get ( "numInGroup" ) ; if ( blockLengthType == null ) { XmlSchemaParser . handleError ( node , "composite for group encodedLength encoding must have \"blockLength\"" ) ; } else if ( ! isUnsigned ( blockLengthType . primitiveType ( ) ) ) { XmlSchemaParser . handleError ( node , "\"blockLength\" must be unsigned type" ) ; } else { if ( blockLengthType . primitiveType ( ) != UINT8 && blockLengthType . primitiveType ( ) != UINT16 ) { XmlSchemaParser . handleWarning ( node , "\"blockLength\" should be UINT8 or UINT16" ) ; } final PrimitiveValue blockLengthTypeMaxValue = blockLengthType . maxValue ( ) ; validateGroupMaxValue ( node , blockLengthType . primitiveType ( ) , blockLengthTypeMaxValue ) ; } if ( numInGroupType == null ) { XmlSchemaParser . handleError ( node , "composite for group encodedLength encoding must have \"numInGroup\"" ) ; } else if ( ! isUnsigned ( numInGroupType . primitiveType ( ) ) ) { XmlSchemaParser . handleWarning ( node , "\"numInGroup\" should be unsigned type" ) ; final PrimitiveValue numInGroupMinValue = numInGroupType . minValue ( ) ; if ( null == numInGroupMinValue ) { XmlSchemaParser . handleError ( node , "\"numInGroup\" minValue must be set for signed types" ) ; } else if ( numInGroupMinValue . longValue ( ) < 0 ) { XmlSchemaParser . handleError ( node , String . format ( "\"numInGroup\" minValue=%s must be greater than zero " + "for signed \"numInGroup\" types" , numInGroupMinValue ) ) ; } } else { if ( numInGroupType . primitiveType ( ) != UINT8 && numInGroupType . primitiveType ( ) != UINT16 ) { XmlSchemaParser . handleWarning ( node , "\"numInGroup\" should be UINT8 or UINT16" ) ; } final PrimitiveValue numInGroupMaxValue = numInGroupType . maxValue ( ) ; validateGroupMaxValue ( node , numInGroupType . primitiveType ( ) , numInGroupMaxValue ) ; final PrimitiveValue numInGroupMinValue = numInGroupType . minValue ( ) ; if ( null != numInGroupMinValue ) { final long max = numInGroupMaxValue != null ? numInGroupMaxValue . longValue ( ) : numInGroupType . primitiveType ( ) . maxValue ( ) . longValue ( ) ; if ( numInGroupMinValue . longValue ( ) > max ) { XmlSchemaParser . handleError ( node , String . format ( "\"numInGroup\" minValue=%s greater than maxValue=%d" , numInGroupMinValue , max ) ) ; } } } }
|
Check the composite for being a well formed group encodedLength encoding . This means that there are the fields blockLength and numInGroup present .
| 724
| 28
|
153,642
|
public void checkForWellFormedVariableLengthDataEncoding ( final Node node ) { final EncodedDataType lengthType = ( EncodedDataType ) containedTypeByNameMap . get ( "length" ) ; if ( lengthType == null ) { XmlSchemaParser . handleError ( node , "composite for variable length data encoding must have \"length\"" ) ; } else { final PrimitiveType primitiveType = lengthType . primitiveType ( ) ; if ( ! isUnsigned ( primitiveType ) ) { XmlSchemaParser . handleError ( node , "\"length\" must be unsigned type" ) ; } else if ( primitiveType != UINT8 && primitiveType != UINT16 && primitiveType != UINT32 ) { XmlSchemaParser . handleWarning ( node , "\"length\" should be UINT8, UINT16, or UINT32" ) ; } validateGroupMaxValue ( node , primitiveType , lengthType . maxValue ( ) ) ; } if ( "optional" . equals ( getAttributeValueOrNull ( node , "presence" ) ) ) { XmlSchemaParser . handleError ( node , "composite for variable length data encoding cannot have presence=\"optional\"" ) ; } if ( containedTypeByNameMap . get ( "varData" ) == null ) { XmlSchemaParser . handleError ( node , "composite for variable length data encoding must have \"varData\"" ) ; } }
|
Check the composite for being a well formed variable length data encoding . This means that there are the fields length and varData present .
| 316
| 26
|
153,643
|
public void checkForWellFormedMessageHeader ( final Node node ) { final boolean shouldGenerateInterfaces = Boolean . getBoolean ( JAVA_GENERATE_INTERFACES ) ; final EncodedDataType blockLengthType = ( EncodedDataType ) containedTypeByNameMap . get ( "blockLength" ) ; final EncodedDataType templateIdType = ( EncodedDataType ) containedTypeByNameMap . get ( "templateId" ) ; final EncodedDataType schemaIdType = ( EncodedDataType ) containedTypeByNameMap . get ( "schemaId" ) ; final EncodedDataType versionType = ( EncodedDataType ) containedTypeByNameMap . get ( "version" ) ; if ( blockLengthType == null ) { XmlSchemaParser . handleError ( node , "composite for message header must have \"blockLength\"" ) ; } else if ( ! isUnsigned ( blockLengthType . primitiveType ( ) ) ) { XmlSchemaParser . handleError ( node , "\"blockLength\" must be unsigned" ) ; } validateHeaderField ( node , "blockLength" , blockLengthType , UINT16 , shouldGenerateInterfaces ) ; validateHeaderField ( node , "templateId" , templateIdType , UINT16 , shouldGenerateInterfaces ) ; validateHeaderField ( node , "schemaId" , schemaIdType , UINT16 , shouldGenerateInterfaces ) ; validateHeaderField ( node , "version" , versionType , UINT16 , shouldGenerateInterfaces ) ; }
|
Check the composite for being a well formed message headerStructure encoding . This means that there are the fields blockLength templateId and version present .
| 341
| 29
|
153,644
|
public void checkForValidOffsets ( final Node node ) { int offset = 0 ; for ( final Type edt : containedTypeByNameMap . values ( ) ) { final int offsetAttribute = edt . offsetAttribute ( ) ; if ( - 1 != offsetAttribute ) { if ( offsetAttribute < offset ) { XmlSchemaParser . handleError ( node , String . format ( "composite element \"%s\" has incorrect offset specified" , edt . name ( ) ) ) ; } offset = offsetAttribute ; } offset += edt . encodedLength ( ) ; } }
|
Check the composite for any specified offsets and validate they are correctly specified .
| 124
| 14
|
153,645
|
public static Token findFirst ( final String name , final List < Token > tokens , final int index ) { for ( int i = index , size = tokens . size ( ) ; i < size ; i ++ ) { final Token token = tokens . get ( i ) ; if ( token . name ( ) . equals ( name ) ) { return token ; } } throw new IllegalStateException ( "name not found: " + name ) ; }
|
Find the first token with a given name from an index inclusive .
| 92
| 13
|
153,646
|
public int getTemplateId ( final DirectBuffer buffer , final int bufferOffset ) { return Types . getInt ( buffer , bufferOffset + templateIdOffset , templateIdType , templateIdByteOrder ) ; }
|
Get the template id from the message header .
| 43
| 9
|
153,647
|
public int getSchemaId ( final DirectBuffer buffer , final int bufferOffset ) { return Types . getInt ( buffer , bufferOffset + schemaIdOffset , schemaIdType , schemaIdByteOrder ) ; }
|
Get the schema id number from the message header .
| 44
| 10
|
153,648
|
public int getSchemaVersion ( final DirectBuffer buffer , final int bufferOffset ) { return Types . getInt ( buffer , bufferOffset + schemaVersionOffset , schemaVersionType , schemaVersionByteOrder ) ; }
|
Get the schema version number from the message header .
| 44
| 10
|
153,649
|
public int getBlockLength ( final DirectBuffer buffer , final int bufferOffset ) { return Types . getInt ( buffer , bufferOffset + blockLengthOffset , blockLengthType , blockLengthByteOrder ) ; }
|
Get the block length of the root block in the message .
| 43
| 12
|
153,650
|
public static void initialize ( AlbumConfig albumConfig ) { if ( sAlbumConfig == null ) sAlbumConfig = albumConfig ; else Log . w ( "Album" , new IllegalStateException ( "Illegal operation, only allowed to configure once." ) ) ; }
|
Initialize Album .
| 58
| 4
|
153,651
|
public static AlbumConfig getAlbumConfig ( ) { if ( sAlbumConfig == null ) { sAlbumConfig = AlbumConfig . newBuilder ( null ) . build ( ) ; } return sAlbumConfig ; }
|
Get the album configuration .
| 47
| 5
|
153,652
|
public static Camera < ImageCameraWrapper , VideoCameraWrapper > camera ( android . support . v4 . app . Fragment fragment ) { return new AlbumCamera ( fragment . getContext ( ) ) ; }
|
Open the camera from the activity .
| 44
| 7
|
153,653
|
public static Choice < ImageMultipleWrapper , ImageSingleWrapper > image ( android . support . v4 . app . Fragment fragment ) { return new ImageChoice ( fragment . getContext ( ) ) ; }
|
Select images .
| 44
| 3
|
153,654
|
public static Choice < VideoMultipleWrapper , VideoSingleWrapper > video ( android . support . v4 . app . Fragment fragment ) { return new VideoChoice ( fragment . getContext ( ) ) ; }
|
Select videos .
| 44
| 3
|
153,655
|
public static Choice < AlbumMultipleWrapper , AlbumSingleWrapper > album ( android . support . v4 . app . Fragment fragment ) { return new AlbumChoice ( fragment . getContext ( ) ) ; }
|
Select images and videos .
| 44
| 5
|
153,656
|
@ WorkerThread public ArrayList < AlbumFolder > getAllVideo ( ) { Map < String , AlbumFolder > albumFolderMap = new HashMap <> ( ) ; AlbumFolder allFileFolder = new AlbumFolder ( ) ; allFileFolder . setChecked ( true ) ; allFileFolder . setName ( mContext . getString ( R . string . album_all_videos ) ) ; scanVideoFile ( albumFolderMap , allFileFolder ) ; ArrayList < AlbumFolder > albumFolders = new ArrayList <> ( ) ; Collections . sort ( allFileFolder . getAlbumFiles ( ) ) ; albumFolders . add ( allFileFolder ) ; for ( Map . Entry < String , AlbumFolder > folderEntry : albumFolderMap . entrySet ( ) ) { AlbumFolder albumFolder = folderEntry . getValue ( ) ; Collections . sort ( albumFolder . getAlbumFiles ( ) ) ; albumFolders . add ( albumFolder ) ; } return albumFolders ; }
|
Scan the list of videos in the library .
| 214
| 9
|
153,657
|
public void setupViews ( Widget widget ) { if ( widget . getUiStyle ( ) == Widget . STYLE_LIGHT ) { int color = ContextCompat . getColor ( getContext ( ) , R . color . albumLoadingDark ) ; mProgressBar . setColorFilter ( color ) ; } else { mProgressBar . setColorFilter ( widget . getToolBarColor ( ) ) ; } }
|
Set some properties of the view .
| 90
| 7
|
153,658
|
public Returner currentPosition ( @ IntRange ( from = 0 , to = Integer . MAX_VALUE ) int currentPosition ) { this . mCurrentPosition = currentPosition ; return ( Returner ) this ; }
|
Set the show position of List .
| 44
| 7
|
153,659
|
@ RequiresApi ( api = Build . VERSION_CODES . LOLLIPOP ) public static void invasionStatusBar ( Window window ) { View decorView = window . getDecorView ( ) ; decorView . setSystemUiVisibility ( decorView . getSystemUiVisibility ( ) | View . SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View . SYSTEM_UI_FLAG_LAYOUT_STABLE ) ; window . setStatusBarColor ( Color . TRANSPARENT ) ; }
|
Set the content layout full the StatusBar but do not hide StatusBar .
| 117
| 15
|
153,660
|
public static boolean setStatusBarDarkFont ( Window window , boolean darkFont ) { if ( setMIUIStatusBarFont ( window , darkFont ) ) { setDefaultStatusBarFont ( window , darkFont ) ; return true ; } else if ( setMeizuStatusBarFont ( window , darkFont ) ) { setDefaultStatusBarFont ( window , darkFont ) ; return true ; } else { return setDefaultStatusBarFont ( window , darkFont ) ; } }
|
Set the status bar to dark .
| 99
| 7
|
153,661
|
private static void setImageViewScaleTypeMatrix ( ImageView imageView ) { /** * PhotoView sets its own ScaleType to Matrix, then diverts all calls * setScaleType to this.setScaleType automatically. */ if ( null != imageView && ! ( imageView instanceof IPhotoView ) ) { if ( ! ScaleType . MATRIX . equals ( imageView . getScaleType ( ) ) ) { imageView . setScaleType ( ScaleType . MATRIX ) ; } } }
|
Sets the ImageView s ScaleType to Matrix .
| 106
| 11
|
153,662
|
private void updateBaseMatrix ( Drawable d ) { ImageView imageView = getImageView ( ) ; if ( null == imageView || null == d ) { return ; } final float viewWidth = getImageViewWidth ( imageView ) ; final float viewHeight = getImageViewHeight ( imageView ) ; final int drawableWidth = d . getIntrinsicWidth ( ) ; final int drawableHeight = d . getIntrinsicHeight ( ) ; mBaseMatrix . reset ( ) ; final float widthScale = viewWidth / drawableWidth ; final float heightScale = viewHeight / drawableHeight ; if ( mScaleType == ScaleType . CENTER ) { mBaseMatrix . postTranslate ( ( viewWidth - drawableWidth ) / 2F , ( viewHeight - drawableHeight ) / 2F ) ; } else if ( mScaleType == ScaleType . CENTER_CROP ) { float scale = Math . max ( widthScale , heightScale ) ; mBaseMatrix . postScale ( scale , scale ) ; mBaseMatrix . postTranslate ( ( viewWidth - drawableWidth * scale ) / 2F , ( viewHeight - drawableHeight * scale ) / 2F ) ; } else if ( mScaleType == ScaleType . CENTER_INSIDE ) { float scale = Math . min ( 1.0f , Math . min ( widthScale , heightScale ) ) ; mBaseMatrix . postScale ( scale , scale ) ; mBaseMatrix . postTranslate ( ( viewWidth - drawableWidth * scale ) / 2F , ( viewHeight - drawableHeight * scale ) / 2F ) ; } else { RectF mTempSrc = new RectF ( 0 , 0 , drawableWidth , drawableHeight ) ; RectF mTempDst = new RectF ( 0 , 0 , viewWidth , viewHeight ) ; if ( ( int ) mBaseRotation % 180 != 0 ) { mTempSrc = new RectF ( 0 , 0 , drawableHeight , drawableWidth ) ; } switch ( mScaleType ) { case FIT_CENTER : mBaseMatrix . setRectToRect ( mTempSrc , mTempDst , ScaleToFit . CENTER ) ; break ; case FIT_START : mBaseMatrix . setRectToRect ( mTempSrc , mTempDst , ScaleToFit . START ) ; break ; case FIT_END : mBaseMatrix . setRectToRect ( mTempSrc , mTempDst , ScaleToFit . END ) ; break ; case FIT_XY : mBaseMatrix . setRectToRect ( mTempSrc , mTempDst , ScaleToFit . FILL ) ; break ; default : break ; } } resetMatrix ( ) ; }
|
Calculate Matrix for FIT_CENTER
| 595
| 10
|
153,663
|
public static Widget getDefaultWidget ( Context context ) { return Widget . newDarkBuilder ( context ) . statusBarColor ( ContextCompat . getColor ( context , R . color . albumColorPrimaryDark ) ) . toolBarColor ( ContextCompat . getColor ( context , R . color . albumColorPrimary ) ) . navigationBarColor ( ContextCompat . getColor ( context , R . color . albumColorPrimaryBlack ) ) . title ( R . string . album_title ) . mediaItemCheckSelector ( ContextCompat . getColor ( context , R . color . albumSelectorNormal ) , ContextCompat . getColor ( context , R . color . albumColorPrimary ) ) . bucketItemCheckSelector ( ContextCompat . getColor ( context , R . color . albumSelectorNormal ) , ContextCompat . getColor ( context , R . color . albumColorPrimary ) ) . buttonStyle ( ButtonStyle . newDarkBuilder ( context ) . setButtonSelector ( ContextCompat . getColor ( context , R . color . albumColorPrimary ) , ContextCompat . getColor ( context , R . color . albumColorPrimaryDark ) ) . build ( ) ) . build ( ) ; }
|
Create default widget .
| 250
| 4
|
153,664
|
private int createView ( ) { switch ( mWidget . getUiStyle ( ) ) { case Widget . STYLE_DARK : { return R . layout . album_activity_album_dark ; } case Widget . STYLE_LIGHT : { return R . layout . album_activity_album_light ; } default : { throw new AssertionError ( "This should not be the case." ) ; } } }
|
Use different layouts depending on the style .
| 95
| 8
|
153,665
|
private void showFolderAlbumFiles ( int position ) { this . mCurrentFolder = position ; AlbumFolder albumFolder = mAlbumFolders . get ( position ) ; mView . bindAlbumFolder ( albumFolder ) ; }
|
Update data source .
| 50
| 4
|
153,666
|
private void showLoadingDialog ( ) { if ( mLoadingDialog == null ) { mLoadingDialog = new LoadingDialog ( this ) ; mLoadingDialog . setupViews ( mWidget ) ; } if ( ! mLoadingDialog . isShowing ( ) ) { mLoadingDialog . show ( ) ; } }
|
Display loading dialog .
| 65
| 4
|
153,667
|
public VideoMultipleWrapper selectCount ( @ IntRange ( from = 1 , to = Integer . MAX_VALUE ) int count ) { this . mLimitCount = count ; return this ; }
|
Set the maximum number to be selected .
| 40
| 8
|
153,668
|
protected void requestPermission ( String [ ] permissions , int code ) { if ( Build . VERSION . SDK_INT >= 23 ) { List < String > deniedPermissions = getDeniedPermissions ( this , permissions ) ; if ( deniedPermissions . isEmpty ( ) ) { onPermissionGranted ( code ) ; } else { permissions = new String [ deniedPermissions . size ( ) ] ; deniedPermissions . toArray ( permissions ) ; ActivityCompat . requestPermissions ( this , permissions , code ) ; } } else { onPermissionGranted ( code ) ; } }
|
Request permission .
| 125
| 3
|
153,669
|
@ WorkerThread @ Nullable public String createThumbnailForImage ( String imagePath ) { if ( TextUtils . isEmpty ( imagePath ) ) return null ; File inFile = new File ( imagePath ) ; if ( ! inFile . exists ( ) ) return null ; File thumbnailFile = randomPath ( imagePath ) ; if ( thumbnailFile . exists ( ) ) return thumbnailFile . getAbsolutePath ( ) ; Bitmap inBitmap = readImageFromPath ( imagePath , THUMBNAIL_SIZE , THUMBNAIL_SIZE ) ; if ( inBitmap == null ) return null ; ByteArrayOutputStream compressStream = new ByteArrayOutputStream ( ) ; inBitmap . compress ( Bitmap . CompressFormat . JPEG , THUMBNAIL_QUALITY , compressStream ) ; try { compressStream . close ( ) ; thumbnailFile . createNewFile ( ) ; FileOutputStream writeStream = new FileOutputStream ( thumbnailFile ) ; writeStream . write ( compressStream . toByteArray ( ) ) ; writeStream . flush ( ) ; writeStream . close ( ) ; return thumbnailFile . getAbsolutePath ( ) ; } catch ( Exception ignored ) { return null ; } }
|
Create a thumbnail for the image .
| 260
| 7
|
153,670
|
@ WorkerThread @ Nullable public String createThumbnailForVideo ( String videoPath ) { if ( TextUtils . isEmpty ( videoPath ) ) return null ; File thumbnailFile = randomPath ( videoPath ) ; if ( thumbnailFile . exists ( ) ) return thumbnailFile . getAbsolutePath ( ) ; try { MediaMetadataRetriever retriever = new MediaMetadataRetriever ( ) ; if ( URLUtil . isNetworkUrl ( videoPath ) ) { retriever . setDataSource ( videoPath , new HashMap < String , String > ( ) ) ; } else { retriever . setDataSource ( videoPath ) ; } Bitmap bitmap = retriever . getFrameAtTime ( ) ; thumbnailFile . createNewFile ( ) ; bitmap . compress ( Bitmap . CompressFormat . JPEG , THUMBNAIL_QUALITY , new FileOutputStream ( thumbnailFile ) ) ; return thumbnailFile . getAbsolutePath ( ) ; } catch ( Exception ignored ) { return null ; } }
|
Create a thumbnail for the video .
| 219
| 7
|
153,671
|
@ Nullable public static Bitmap readImageFromPath ( String imagePath , int width , int height ) { File imageFile = new File ( imagePath ) ; if ( imageFile . exists ( ) ) { try { BufferedInputStream inputStream = new BufferedInputStream ( new FileInputStream ( imageFile ) ) ; BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; BitmapFactory . decodeStream ( inputStream , null , options ) ; inputStream . close ( ) ; options . inJustDecodeBounds = false ; options . inSampleSize = computeSampleSize ( options , width , height ) ; Bitmap sampledBitmap = null ; boolean attemptSuccess = false ; while ( ! attemptSuccess ) { inputStream = new BufferedInputStream ( new FileInputStream ( imageFile ) ) ; try { sampledBitmap = BitmapFactory . decodeStream ( inputStream , null , options ) ; attemptSuccess = true ; } catch ( Exception e ) { options . inSampleSize *= 2 ; } inputStream . close ( ) ; } String lowerPath = imagePath . toLowerCase ( ) ; if ( lowerPath . endsWith ( ".jpg" ) || lowerPath . endsWith ( ".jpeg" ) ) { int degrees = computeDegree ( imagePath ) ; if ( degrees > 0 ) { Matrix matrix = new Matrix ( ) ; matrix . setRotate ( degrees ) ; Bitmap newBitmap = Bitmap . createBitmap ( sampledBitmap , 0 , 0 , sampledBitmap . getWidth ( ) , sampledBitmap . getHeight ( ) , matrix , true ) ; if ( newBitmap != sampledBitmap ) { sampledBitmap . recycle ( ) ; sampledBitmap = newBitmap ; } } } return sampledBitmap ; } catch ( Exception ignored ) { } } return null ; }
|
Deposit in the province read images mViewWidth is high the greater the picture clearer but also the memory .
| 404
| 22
|
153,672
|
@ NonNull public static File getAlbumRootPath ( Context context ) { if ( sdCardIsAvailable ( ) ) { return new File ( Environment . getExternalStorageDirectory ( ) , CACHE_DIRECTORY ) ; } else { return new File ( context . getFilesDir ( ) , CACHE_DIRECTORY ) ; } }
|
Get a writable root directory .
| 74
| 7
|
153,673
|
public static boolean sdCardIsAvailable ( ) { if ( Environment . getExternalStorageState ( ) . equals ( Environment . MEDIA_MOUNTED ) ) { return Environment . getExternalStorageDirectory ( ) . canWrite ( ) ; } else return false ; }
|
SD card is available .
| 55
| 5
|
153,674
|
@ NonNull private static String randomMediaPath ( File bucket , String extension ) { if ( bucket . exists ( ) && bucket . isFile ( ) ) bucket . delete ( ) ; if ( ! bucket . exists ( ) ) bucket . mkdirs ( ) ; String outFilePath = AlbumUtils . getNowDateTime ( "yyyyMMdd_HHmmssSSS" ) + "_" + getMD5ForString ( UUID . randomUUID ( ) . toString ( ) ) + extension ; File file = new File ( bucket , outFilePath ) ; return file . getAbsolutePath ( ) ; }
|
Generates a random file path using the specified suffix name in the specified directory .
| 133
| 16
|
153,675
|
public static String getMimeType ( String url ) { String extension = getExtension ( url ) ; if ( ! MimeTypeMap . getSingleton ( ) . hasExtension ( extension ) ) return "" ; String mimeType = MimeTypeMap . getSingleton ( ) . getMimeTypeFromExtension ( extension ) ; return TextUtils . isEmpty ( mimeType ) ? "" : mimeType ; }
|
Get the mime type of the file in the url .
| 93
| 12
|
153,676
|
public static String getExtension ( String url ) { url = TextUtils . isEmpty ( url ) ? "" : url . toLowerCase ( ) ; String extension = MimeTypeMap . getFileExtensionFromUrl ( url ) ; return TextUtils . isEmpty ( extension ) ? "" : extension ; }
|
Get the file extension in url .
| 67
| 7
|
153,677
|
@ NonNull public static String convertDuration ( @ IntRange ( from = 1 ) long duration ) { duration /= 1000 ; int hour = ( int ) ( duration / 3600 ) ; int minute = ( int ) ( ( duration - hour * 3600 ) / 60 ) ; int second = ( int ) ( duration - hour * 3600 - minute * 60 ) ; String hourValue = "" ; String minuteValue ; String secondValue ; if ( hour > 0 ) { if ( hour >= 10 ) { hourValue = Integer . toString ( hour ) ; } else { hourValue = "0" + hour ; } hourValue += ":" ; } if ( minute > 0 ) { if ( minute >= 10 ) { minuteValue = Integer . toString ( minute ) ; } else { minuteValue = "0" + minute ; } } else { minuteValue = "00" ; } minuteValue += ":" ; if ( second > 0 ) { if ( second >= 10 ) { secondValue = Integer . toString ( second ) ; } else { secondValue = "0" + second ; } } else { secondValue = "00" ; } return hourValue + minuteValue + secondValue ; }
|
Time conversion .
| 251
| 3
|
153,678
|
public static String getMD5ForString ( String content ) { StringBuilder md5Buffer = new StringBuilder ( ) ; try { MessageDigest digest = MessageDigest . getInstance ( "MD5" ) ; byte [ ] tempBytes = digest . digest ( content . getBytes ( ) ) ; int digital ; for ( int i = 0 ; i < tempBytes . length ; i ++ ) { digital = tempBytes [ i ] ; if ( digital < 0 ) { digital += 256 ; } if ( digital < 16 ) { md5Buffer . append ( "0" ) ; } md5Buffer . append ( Integer . toHexString ( digital ) ) ; } } catch ( Exception ignored ) { return Integer . toString ( content . hashCode ( ) ) ; } return md5Buffer . toString ( ) ; }
|
Get the MD5 value of string .
| 174
| 8
|
153,679
|
@ Override public void stopRecording ( ) { super . stopRecording ( ) ; mSentBroadcastLiveEvent = false ; if ( mStream != null ) { if ( VERBOSE ) Log . i ( TAG , "Stopping Stream" ) ; mKickflip . stopStream ( mStream , new KickflipCallback ( ) { @ Override public void onSuccess ( Response response ) { if ( VERBOSE ) Log . i ( TAG , "Got stop stream response " + response ) ; } @ Override public void onError ( KickflipException error ) { Log . w ( TAG , "Error getting stop stream response! " + error ) ; } } ) ; } }
|
Stop broadcasting and release resources . After this call this Broadcaster can no longer be used .
| 148
| 18
|
153,680
|
private void queueOrSubmitUpload ( String key , File file ) { if ( mReadyToBroadcast ) { submitUpload ( key , file ) ; } else { if ( VERBOSE ) Log . i ( TAG , "queueing " + key + " until S3 Credentials available" ) ; queueUpload ( key , file ) ; } }
|
Handle an upload either submitting to the S3 client or queueing for submission once credentials are ready
| 74
| 19
|
153,681
|
private void queueUpload ( String key , File file ) { if ( mUploadQueue == null ) mUploadQueue = new ArrayDeque <> ( ) ; mUploadQueue . add ( new Pair <> ( key , file ) ) ; }
|
Queue an upload for later submission to S3
| 51
| 9
|
153,682
|
private void submitQueuedUploadsToS3 ( ) { if ( mUploadQueue == null ) return ; for ( Pair < String , File > pair : mUploadQueue ) { submitUpload ( pair . first , pair . second ) ; } }
|
Submit all queued uploads to the S3 client
| 52
| 11
|
153,683
|
public void applyFilter ( int filter ) { Filters . checkFilterArgument ( filter ) ; mDisplayRenderer . changeFilterMode ( filter ) ; synchronized ( mReadyForFrameFence ) { mNewFilter = filter ; } }
|
Apply a filter to the camera input
| 51
| 7
|
153,684
|
public void handleCameraPreviewTouchEvent ( MotionEvent ev ) { if ( mFullScreen != null ) mFullScreen . handleTouchEvent ( ev ) ; if ( mDisplayRenderer != null ) mDisplayRenderer . handleTouchEvent ( ev ) ; }
|
Notify the preview and encoder programs of a touch event . Used by GLCameraEncoderView
| 56
| 21
|
153,685
|
public void startRecording ( ) { if ( mState != STATE . INITIALIZED ) { Log . e ( TAG , "startRecording called in invalid state. Ignoring" ) ; return ; } synchronized ( mReadyForFrameFence ) { mFrameNum = 0 ; mRecording = true ; mState = STATE . RECORDING ; } }
|
Called from UI thread
| 78
| 5
|
153,686
|
@ Override public void onFrameAvailable ( SurfaceTexture surfaceTexture ) { // Pass SurfaceTexture to Encoding thread via Handler // Then Encode and display frame mHandler . sendMessage ( mHandler . obtainMessage ( MSG_FRAME_AVAILABLE , surfaceTexture ) ) ; }
|
Called on an arbitrary thread
| 60
| 6
|
153,687
|
private void prepareEncoder ( EGLContext sharedContext , int width , int height , int bitRate , Muxer muxer ) throws IOException { mVideoEncoder = new VideoEncoderCore ( width , height , bitRate , muxer ) ; if ( mEglCore == null ) { // This is the first prepare called for this CameraEncoder instance mEglCore = new EglCore ( sharedContext , EglCore . FLAG_RECORDABLE ) ; } if ( mInputWindowSurface != null ) mInputWindowSurface . release ( ) ; mInputWindowSurface = new WindowSurface ( mEglCore , mVideoEncoder . getInputSurface ( ) ) ; mInputWindowSurface . makeCurrent ( ) ; if ( mFullScreen != null ) mFullScreen . release ( ) ; mFullScreen = new FullFrameRect ( new Texture2dProgram ( Texture2dProgram . ProgramType . TEXTURE_EXT ) ) ; mFullScreen . getProgram ( ) . setTexSize ( width , height ) ; mIncomingSizeUpdated = true ; }
|
Called with the display EGLContext current on Encoder thread
| 239
| 13
|
153,688
|
private void releaseEglResources ( ) { mReadyForFrames = false ; if ( mInputWindowSurface != null ) { mInputWindowSurface . release ( ) ; mInputWindowSurface = null ; } if ( mFullScreen != null ) { mFullScreen . release ( ) ; mFullScreen = null ; } if ( mEglCore != null ) { mEglCore . release ( ) ; mEglCore = null ; } mSurfaceTexture = null ; }
|
Release all recording - specific resources . The Encoder EGLCore and FullFrameRect are tied to capture resolution and other parameters .
| 105
| 26
|
153,689
|
private void releaseCamera ( ) { if ( mDisplayView != null ) releaseDisplayView ( ) ; if ( mCamera != null ) { if ( VERBOSE ) Log . d ( TAG , "releasing camera" ) ; mCamera . stopPreview ( ) ; mCamera . release ( ) ; mCamera = null ; } }
|
Stops camera preview and releases the camera to the system .
| 70
| 12
|
153,690
|
private void configureDisplayView ( ) { if ( mDisplayView instanceof GLCameraEncoderView ) ( ( GLCameraEncoderView ) mDisplayView ) . setCameraEncoder ( this ) ; else if ( mDisplayView instanceof GLCameraView ) ( ( GLCameraView ) mDisplayView ) . setCamera ( mCamera ) ; }
|
Communicate camera - ready state to our display view . This method allows us to handle custom subclasses
| 77
| 20
|
153,691
|
private void releaseDisplayView ( ) { if ( mDisplayView instanceof GLCameraEncoderView ) { ( ( GLCameraEncoderView ) mDisplayView ) . releaseCamera ( ) ; } else if ( mDisplayView instanceof GLCameraView ) ( ( GLCameraView ) mDisplayView ) . releaseCamera ( ) ; }
|
Communicate camera - released state to our display view .
| 74
| 11
|
153,692
|
public static int createProgram ( String vertexSource , String fragmentSource ) { int vertexShader = loadShader ( GLES20 . GL_VERTEX_SHADER , vertexSource ) ; if ( vertexShader == 0 ) { return 0 ; } int pixelShader = loadShader ( GLES20 . GL_FRAGMENT_SHADER , fragmentSource ) ; if ( pixelShader == 0 ) { return 0 ; } int program = GLES20 . glCreateProgram ( ) ; checkGlError ( "glCreateProgram" ) ; if ( program == 0 ) { Log . e ( TAG , "Could not create program" ) ; } GLES20 . glAttachShader ( program , vertexShader ) ; checkGlError ( "glAttachShader" ) ; GLES20 . glAttachShader ( program , pixelShader ) ; checkGlError ( "glAttachShader" ) ; GLES20 . glLinkProgram ( program ) ; int [ ] linkStatus = new int [ 1 ] ; GLES20 . glGetProgramiv ( program , GLES20 . GL_LINK_STATUS , linkStatus , 0 ) ; if ( linkStatus [ 0 ] != GLES20 . GL_TRUE ) { Log . e ( TAG , "Could not link program: " ) ; Log . e ( TAG , GLES20 . glGetProgramInfoLog ( program ) ) ; GLES20 . glDeleteProgram ( program ) ; program = 0 ; } return program ; }
|
Creates a new program from the supplied vertex and fragment shaders .
| 321
| 14
|
153,693
|
public static int loadShader ( int shaderType , String source ) { int shader = GLES20 . glCreateShader ( shaderType ) ; checkGlError ( "glCreateShader type=" + shaderType ) ; GLES20 . glShaderSource ( shader , source ) ; GLES20 . glCompileShader ( shader ) ; int [ ] compiled = new int [ 1 ] ; GLES20 . glGetShaderiv ( shader , GLES20 . GL_COMPILE_STATUS , compiled , 0 ) ; if ( compiled [ 0 ] == 0 ) { Log . e ( TAG , "Could not compile shader " + shaderType + ":" ) ; Log . e ( TAG , " " + GLES20 . glGetShaderInfoLog ( shader ) ) ; GLES20 . glDeleteShader ( shader ) ; shader = 0 ; } return shader ; }
|
Compiles the provided shader source .
| 190
| 7
|
153,694
|
public static void checkGlError ( String op ) { int error = GLES20 . glGetError ( ) ; if ( error != GLES20 . GL_NO_ERROR ) { String msg = op + ": glError 0x" + Integer . toHexString ( error ) ; Log . e ( TAG , msg ) ; throw new RuntimeException ( msg ) ; } }
|
Checks to see if a GLES error has been raised .
| 81
| 13
|
153,695
|
public static FloatBuffer createFloatBuffer ( float [ ] coords ) { // Allocate a direct ByteBuffer, using 4 bytes per float, and copy coords into it. ByteBuffer bb = ByteBuffer . allocateDirect ( coords . length * SIZEOF_FLOAT ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; FloatBuffer fb = bb . asFloatBuffer ( ) ; fb . put ( coords ) ; fb . position ( 0 ) ; return fb ; }
|
Allocates a direct float buffer and populates it with the float array data .
| 112
| 17
|
153,696
|
public static void logVersionInfo ( ) { Log . i ( TAG , "vendor : " + GLES20 . glGetString ( GLES20 . GL_VENDOR ) ) ; Log . i ( TAG , "renderer: " + GLES20 . glGetString ( GLES20 . GL_RENDERER ) ) ; Log . i ( TAG , "version : " + GLES20 . glGetString ( GLES20 . GL_VERSION ) ) ; if ( false ) { int [ ] values = new int [ 1 ] ; GLES30 . glGetIntegerv ( GLES30 . GL_MAJOR_VERSION , values , 0 ) ; int majorVersion = values [ 0 ] ; GLES30 . glGetIntegerv ( GLES30 . GL_MINOR_VERSION , values , 0 ) ; int minorVersion = values [ 0 ] ; if ( GLES30 . glGetError ( ) == GLES30 . GL_NO_ERROR ) { Log . i ( TAG , "iversion: " + majorVersion + "." + minorVersion ) ; } } }
|
Writes GL version info to the log .
| 236
| 9
|
153,697
|
private EGLConfig getConfig ( int flags , int version ) { int renderableType = EGL14 . EGL_OPENGL_ES2_BIT ; if ( version >= 3 ) { renderableType |= EGLExt . EGL_OPENGL_ES3_BIT_KHR ; } // The actual surface is generally RGBA or RGBX, so situationally omitting alpha // doesn't really help. It can also lead to a huge performance hit on glReadPixels() // when reading into a GL_RGBA buffer. int [ ] attribList = { EGL14 . EGL_RED_SIZE , 8 , EGL14 . EGL_GREEN_SIZE , 8 , EGL14 . EGL_BLUE_SIZE , 8 , EGL14 . EGL_ALPHA_SIZE , 8 , //EGL14.EGL_DEPTH_SIZE, 16, //EGL14.EGL_STENCIL_SIZE, 8, EGL14 . EGL_RENDERABLE_TYPE , renderableType , EGL14 . EGL_NONE , 0 , // placeholder for recordable [@-3] EGL14 . EGL_NONE } ; if ( ( flags & FLAG_RECORDABLE ) != 0 ) { attribList [ attribList . length - 3 ] = EGL_RECORDABLE_ANDROID ; attribList [ attribList . length - 2 ] = 1 ; } EGLConfig [ ] configs = new EGLConfig [ 1 ] ; int [ ] numConfigs = new int [ 1 ] ; if ( ! EGL14 . eglChooseConfig ( mEGLDisplay , attribList , 0 , configs , 0 , configs . length , numConfigs , 0 ) ) { Log . w ( TAG , "unable to find RGB8888 / " + version + " EGLConfig" ) ; return null ; } return configs [ 0 ] ; }
|
Finds a suitable EGLConfig .
| 428
| 8
|
153,698
|
public void release ( ) { if ( mEGLDisplay != EGL14 . EGL_NO_DISPLAY ) { // Android is unusual in that it uses a reference-counted EGLDisplay. So for // every eglInitialize() we need an eglTerminate(). EGL14 . eglMakeCurrent ( mEGLDisplay , EGL14 . EGL_NO_SURFACE , EGL14 . EGL_NO_SURFACE , EGL14 . EGL_NO_CONTEXT ) ; EGL14 . eglDestroyContext ( mEGLDisplay , mEGLContext ) ; EGL14 . eglReleaseThread ( ) ; EGL14 . eglTerminate ( mEGLDisplay ) ; } mEGLDisplay = EGL14 . EGL_NO_DISPLAY ; mEGLContext = EGL14 . EGL_NO_CONTEXT ; mEGLConfig = null ; }
|
Discard all resources held by this class notably the EGL context .
| 202
| 14
|
153,699
|
public EGLSurface createOffscreenSurface ( int width , int height ) { int [ ] surfaceAttribs = { EGL14 . EGL_WIDTH , width , EGL14 . EGL_HEIGHT , height , EGL14 . EGL_NONE } ; EGLSurface eglSurface = EGL14 . eglCreatePbufferSurface ( mEGLDisplay , mEGLConfig , surfaceAttribs , 0 ) ; checkEglError ( "eglCreatePbufferSurface" ) ; if ( eglSurface == null ) { throw new RuntimeException ( "surface was null" ) ; } return eglSurface ; }
|
Creates an EGL surface associated with an offscreen buffer .
| 148
| 13
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.