code
stringlengths
73
34.1k
label
stringclasses
1 value
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); }
java
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); } }
java
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); } }
java
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(); }
java
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; }
java
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; } }
java
public void error(final String msg) { errors++; if (!suppressOutput) { out.println("ERROR: " + msg); } if (stopOnError) { throw new IllegalArgumentException(msg); } }
java
public void warning(final String msg) { warnings++; if (!suppressOutput) { out.println("WARNING: " + msg); } if (warningsFatal && stopOnError) { throw new IllegalArgumentException(msg); } }
java
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 ""; } }
java
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; }
java
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); }
java
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"); }
java
public static void append(final StringBuilder builder, final String indent, final String line) { builder.append(indent).append(line).append('\n'); }
java
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 + '\n' + indent + " */\n"; }
java
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 + '\n' + indent + " *\n" + indent + " * @param value true if " + optionToken.name() + " is set or false if not\n" + indent + " */\n"; }
java
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 + '\n' + indent + " *\n" + indent + " * @return " + typeName + " : " + description + "\n" + indent + " */\n"; }
java
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; }
java
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); } }
java
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); } }
java
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(); }
java
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(); }
java
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); } }
java
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; }
java
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; } } }
java
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())))); }
java
public static String formatScopedName(final CharSequence[] scope, final String value) { return String.join("_", scope).toLowerCase() + "_" + formatName(value); }
java
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(); } } } }
java
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()); } }
java
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(); }
java
public void makeDataFieldCompositeType() { final EncodedDataType edt = (EncodedDataType)containedTypeByNameMap.get("varData"); if (edt != null) { edt.variableLength(true); } }
java
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)); } } } }
java
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\""); } }
java
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); }
java
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(); } }
java
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); }
java
public int getTemplateId(final DirectBuffer buffer, final int bufferOffset) { return Types.getInt(buffer, bufferOffset + templateIdOffset, templateIdType, templateIdByteOrder); }
java
public int getSchemaId(final DirectBuffer buffer, final int bufferOffset) { return Types.getInt(buffer, bufferOffset + schemaIdOffset, schemaIdType, schemaIdByteOrder); }
java
public int getSchemaVersion(final DirectBuffer buffer, final int bufferOffset) { return Types.getInt(buffer, bufferOffset + schemaVersionOffset, schemaVersionType, schemaVersionByteOrder); }
java
public int getBlockLength(final DirectBuffer buffer, final int bufferOffset) { return Types.getInt(buffer, bufferOffset + blockLengthOffset, blockLengthType, blockLengthByteOrder); }
java
public static void initialize(AlbumConfig albumConfig) { if (sAlbumConfig == null) sAlbumConfig = albumConfig; else Log.w("Album", new IllegalStateException("Illegal operation, only allowed to configure once.")); }
java
public static AlbumConfig getAlbumConfig() { if (sAlbumConfig == null) { sAlbumConfig = AlbumConfig.newBuilder(null).build(); } return sAlbumConfig; }
java
public static Camera<ImageCameraWrapper, VideoCameraWrapper> camera(android.support.v4.app.Fragment fragment) { return new AlbumCamera(fragment.getContext()); }
java
public static Choice<ImageMultipleWrapper, ImageSingleWrapper> image(android.support.v4.app.Fragment fragment) { return new ImageChoice(fragment.getContext()); }
java
public static Choice<VideoMultipleWrapper, VideoSingleWrapper> video(android.support.v4.app.Fragment fragment) { return new VideoChoice(fragment.getContext()); }
java
public static Choice<AlbumMultipleWrapper, AlbumSingleWrapper> album(android.support.v4.app.Fragment fragment) { return new AlbumChoice(fragment.getContext()); }
java
@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; }
java
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()); } }
java
public Returner currentPosition(@IntRange(from = 0, to = Integer.MAX_VALUE) int currentPosition) { this.mCurrentPosition = currentPosition; return (Returner) this; }
java
@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); }
java
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); } }
java
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); } } }
java
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(); }
java
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(); }
java
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."); } } }
java
private void showFolderAlbumFiles(int position) { this.mCurrentFolder = position; AlbumFolder albumFolder = mAlbumFolders.get(position); mView.bindAlbumFolder(albumFolder); }
java
private void showLoadingDialog() { if (mLoadingDialog == null) { mLoadingDialog = new LoadingDialog(this); mLoadingDialog.setupViews(mWidget); } if (!mLoadingDialog.isShowing()) { mLoadingDialog.show(); } }
java
public VideoMultipleWrapper selectCount(@IntRange(from = 1, to = Integer.MAX_VALUE) int count) { this.mLimitCount = count; return this; }
java
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); } }
java
@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; } }
java
@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; } }
java
@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; }
java
@NonNull public static File getAlbumRootPath(Context context) { if (sdCardIsAvailable()) { return new File(Environment.getExternalStorageDirectory(), CACHE_DIRECTORY); } else { return new File(context.getFilesDir(), CACHE_DIRECTORY); } }
java
public static boolean sdCardIsAvailable() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return Environment.getExternalStorageDirectory().canWrite(); } else return false; }
java
@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(); }
java
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; }
java
public static String getExtension(String url) { url = TextUtils.isEmpty(url) ? "" : url.toLowerCase(); String extension = MimeTypeMap.getFileExtensionFromUrl(url); return TextUtils.isEmpty(extension) ? "" : extension; }
java
@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; }
java
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(); }
java
@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); } }); } }
java
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); } }
java
private void queueUpload(String key, File file) { if (mUploadQueue == null) mUploadQueue = new ArrayDeque<>(); mUploadQueue.add(new Pair<>(key, file)); }
java
private void submitQueuedUploadsToS3() { if (mUploadQueue == null) return; for (Pair<String, File> pair : mUploadQueue) { submitUpload(pair.first, pair.second); } }
java
public void applyFilter(int filter) { Filters.checkFilterArgument(filter); mDisplayRenderer.changeFilterMode(filter); synchronized (mReadyForFrameFence) { mNewFilter = filter; } }
java
public void handleCameraPreviewTouchEvent(MotionEvent ev) { if (mFullScreen != null) mFullScreen.handleTouchEvent(ev); if (mDisplayRenderer != null) mDisplayRenderer.handleTouchEvent(ev); }
java
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; } }
java
@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)); }
java
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; }
java
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; }
java
private void releaseCamera() { if (mDisplayView != null) releaseDisplayView(); if (mCamera != null) { if (VERBOSE) Log.d(TAG, "releasing camera"); mCamera.stopPreview(); mCamera.release(); mCamera = null; } }
java
private void configureDisplayView() { if (mDisplayView instanceof GLCameraEncoderView) ((GLCameraEncoderView) mDisplayView).setCameraEncoder(this); else if (mDisplayView instanceof GLCameraView) ((GLCameraView) mDisplayView).setCamera(mCamera); }
java
private void releaseDisplayView() { if (mDisplayView instanceof GLCameraEncoderView) { ((GLCameraEncoderView) mDisplayView).releaseCamera(); } else if (mDisplayView instanceof GLCameraView) ((GLCameraView) mDisplayView).releaseCamera(); }
java
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; }
java
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; }
java
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); } }
java
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; }
java
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); } } }
java
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]; }
java
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; }
java
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; }
java
public void makeCurrent(EGLSurface eglSurface) { if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) { // called makeCurrent() before create? Log.d(TAG, "NOTE: makeCurrent w/o display"); } if (!EGL14.eglMakeCurrent(mEGLDisplay, eglSurface, eglSurface, mEGLContext)) { throw new RuntimeException("eglMakeCurrent failed"); } }
java
public void makeCurrent(EGLSurface drawSurface, EGLSurface readSurface) { if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) { // called makeCurrent() before create? Log.d(TAG, "NOTE: makeCurrent w/o display"); } if (!EGL14.eglMakeCurrent(mEGLDisplay, drawSurface, readSurface, mEGLContext)) { throw new RuntimeException("eglMakeCurrent(draw,read) failed"); } }
java
public void makeNothingCurrent() { if (!EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)) { throw new RuntimeException("eglMakeCurrent failed"); } }
java
public boolean isCurrent(EGLSurface eglSurface) { return mEGLContext.equals(EGL14.eglGetCurrentContext()) && eglSurface.equals(EGL14.eglGetCurrentSurface(EGL14.EGL_DRAW)); }
java
public int querySurface(EGLSurface eglSurface, int what) { int[] value = new int[1]; EGL14.eglQuerySurface(mEGLDisplay, eglSurface, what, value, 0); return value[0]; }
java
public static void logCurrent(String msg) { EGLDisplay display; EGLContext context; EGLSurface surface; display = EGL14.eglGetCurrentDisplay(); context = EGL14.eglGetCurrentContext(); surface = EGL14.eglGetCurrentSurface(EGL14.EGL_DRAW); Log.i(TAG, "Current EGL (" + msg + "): display=" + display + ", context=" + context + ", surface=" + surface); }
java
private void checkEglError(String msg) { int error; if ((error = EGL14.eglGetError()) != EGL14.EGL_SUCCESS) { throw new RuntimeException(msg + ": EGL error: 0x" + Integer.toHexString(error)); } }
java
private long getJitterFreePTS(long bufferPts, long bufferSamplesNum) { long correctedPts = 0; long bufferDuration = (1000000 * bufferSamplesNum) / (mEncoderCore.mSampleRate); bufferPts -= bufferDuration; // accounts for the delay of acquiring the audio buffer if (totalSamplesNum == 0) { // reset startPTS = bufferPts; totalSamplesNum = 0; } correctedPts = startPTS + (1000000 * totalSamplesNum) / (mEncoderCore.mSampleRate); if(bufferPts - correctedPts >= 2*bufferDuration) { // reset startPTS = bufferPts; totalSamplesNum = 0; correctedPts = startPTS; } totalSamplesNum += bufferSamplesNum; return correctedPts; }
java
public void adjustForVerticalVideo(SCREEN_ROTATION orientation, boolean scaleToFit) { synchronized (mDrawLock) { mCorrectVerticalVideo = true; mScaleToFit = scaleToFit; requestedOrientation = orientation; Matrix.setIdentityM(IDENTITY_MATRIX, 0); switch (orientation) { case VERTICAL: if (scaleToFit) { Matrix.rotateM(IDENTITY_MATRIX, 0, -90, 0f, 0f, 1f); Matrix.scaleM(IDENTITY_MATRIX, 0, 3.16f, 1.0f, 1f); } else { Matrix.scaleM(IDENTITY_MATRIX, 0, 0.316f, 1f, 1f); } break; case UPSIDEDOWN_LANDSCAPE: if (scaleToFit) { Matrix.rotateM(IDENTITY_MATRIX, 0, -180, 0f, 0f, 1f); } break; case UPSIDEDOWN_VERTICAL: if (scaleToFit) { Matrix.rotateM(IDENTITY_MATRIX, 0, 90, 0f, 0f, 1f); Matrix.scaleM(IDENTITY_MATRIX, 0, 3.16f, 1.0f, 1f); } else { Matrix.scaleM(IDENTITY_MATRIX, 0, 0.316f, 1f, 1f); } break; } } }
java
public void drawFrame(int textureId, float[] texMatrix) { // Use the identity matrix for MVP so our 2x2 FULL_RECTANGLE covers the viewport. synchronized (mDrawLock) { if (mCorrectVerticalVideo && !mScaleToFit && (requestedOrientation == SCREEN_ROTATION.VERTICAL || requestedOrientation == SCREEN_ROTATION.UPSIDEDOWN_VERTICAL)) { Matrix.scaleM(texMatrix, 0, 0.316f, 1.0f, 1f); } mProgram.draw(IDENTITY_MATRIX, mRectDrawable.getVertexArray(), 0, mRectDrawable.getVertexCount(), mRectDrawable.getCoordsPerVertex(), mRectDrawable.getVertexStride(), texMatrix, TEX_COORDS_BUF, textureId, TEX_COORDS_STRIDE); } }
java
public void stopBroadcasting() { if (mBroadcaster.isRecording()) { mBroadcaster.stopRecording(); mBroadcaster.release(); } else { Log.e(TAG, "stopBroadcasting called but mBroadcaster not broadcasting"); } }
java