下面列出了com.squareup.okhttp.CacheControl#com.facebook.common.logging.FLog 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Zooms to the desired scale and positions the image so that the given image point corresponds
* to the given view point.
* <p>
* <p>If this method is called while an animation or gesture is already in progress,
* the current animation or gesture will be stopped first.
*
* @param scale desired scale, will be limited to {min, max} scale factor
* @param imagePoint 2D point in image's relative coordinate system (i.e. 0 <= x, y <= 1)
* @param viewPoint 2D point in view's absolute coordinate system
* @param limitFlags whether to limit translation and/or scale.
* @param durationMs length of animation of the zoom, or 0 if no animation desired
* @param onAnimationComplete code to run when the animation completes. Ignored if durationMs=0
*/
public void zoomToPoint(
float scale,
PointF imagePoint,
PointF viewPoint,
@LimitFlag int limitFlags,
long durationMs,
@Nullable Runnable onAnimationComplete) {
FLog.v(getLogTag(), "zoomToPoint: duration %d ms", durationMs);
calculateZoomToPointTransform(
mNewTransform,
scale,
imagePoint,
viewPoint,
limitFlags);
setTransform(mNewTransform, durationMs, onAnimationComplete);
}
/** Callback used to notify about top-level-drawable being drawn. */
@Override
public void onDraw() {
// draw is only expected if the controller is attached
if (mIsControllerAttached) {
return;
}
// something went wrong here; controller is not attached, yet the hierarchy has to be drawn
// log error and attach the controller
FLog.w(
DraweeEventTracker.class,
"%x: Draw requested for a non-attached controller %x. %s",
System.identityHashCode(this),
System.identityHashCode(mController),
toString());
mIsHolderAttached = true;
mIsVisible = true;
attachOrDetachController();
}
/**
* Get image width and height from jpeg header
* @param is the input stream of jpeg image
* @return dimensions of the image in form of Rect
*/
public static Rect getDimensions(InputStream is) {
try {
if (moveToMarker(is, MARKER_SOFn)) {
// read block length
// subtract 2 as length contain SIZE field we just read
int length = StreamProcessor.readPackedInt(is, 2, false) - 2;
if (length > 6) {
// SOFn structure: 0xFFCn|length(2)|bitDepth(1)|height(2)|width(2)|...
int bitDepth = StreamProcessor.readPackedInt(is, 1, false);
int height = StreamProcessor.readPackedInt(is, 2, false);
int width = StreamProcessor.readPackedInt(is, 2, false);
return new Rect(0, 0, width, height);
}
}
} catch (IOException ioe) {
FLog.e(TAG, ioe, "%x: getDimensions", is.hashCode());
// log and return null.
}
return null;
}
private void onFailureInternal(String id,
DataSource<CloseableReference<CloseableImage>> dataSource,
Throwable throwable, boolean isFinished) {
if (FLog.isLoggable(Log.WARN)) {
FLog.w(DraweeSpan.class, id + " load failure", throwable);
}
// ignored this result
if (!getId().equals(id)
|| dataSource != mDataSource
|| !mIsRequestSubmitted) {
dataSource.close();
return;
}
if (isFinished) {
mDataSource = null;
// Set the previously available image if available.
setDrawableInner(mDrawable);
}
}
@Override
protected void finalize() throws Throwable {
try {
// We put synchronized here so that lint doesn't warn about accessing mIsClosed, which is
// guarded by this. Lint isn't aware of finalize semantics.
synchronized (this) {
if (mIsClosed) {
return;
}
}
FLog.w(TAG, "Finalized without closing: %x %x (type = %s)",
System.identityHashCode(this),
System.identityHashCode(mSharedReference),
mSharedReference.get().getClass().getSimpleName());
close();
} finally {
super.finalize();
}
}
public void setFpsDebugViewVisible(final boolean fpsDebugViewVisible) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (fpsDebugViewVisible && mFPSDebugViewContainer == null) {
if (!permissionCheck(mReactContext)) {
FLog.d(ReactConstants.TAG, "Wait for overlay permission to be set");
return;
}
mFPSDebugViewContainer = new FpsView(mReactContext);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowOverlayCompat.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
mWindowManager.addView(mFPSDebugViewContainer, params);
} else if (!fpsDebugViewVisible && mFPSDebugViewContainer != null) {
mFPSDebugViewContainer.removeAllViews();
mWindowManager.removeView(mFPSDebugViewContainer);
mFPSDebugViewContainer = null;
}
}
});
}
public void init(Context context, ImagePipelineConfig config) {
if(config == null) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ImagePipelineConfig.Builder builder = ImagePipelineConfig.newBuilder(context)
.setResizeAndRotateEnabledForNetwork(true)
.setBitmapsConfig(Bitmap.Config.ARGB_8888)
.setBitmapMemoryCacheParamsSupplier(new MyBitmapMemoryCacheParamsSupplier(activityManager))
.setDownsampleEnabled(true);
if (isVLoggable || isDLoggable) {
Set<RequestListener> requestListeners = new HashSet<>();
requestListeners.add(new RequestLoggingListener());
builder.setRequestListeners(requestListeners);
int level = isVLoggable ? FLog.VERBOSE : FLog.DEBUG;
FLog.setMinimumLoggingLevel(level);
}
config = builder.build();
}
context.getApplicationContext().registerComponentCallbacks(this);
Fresco.initialize(context, config);
}
/**
* An in-place iterative box blur algorithm that runs faster than a traditional box blur.
*
* <p>The individual box blurs are split up in vertical and horizontal direction. That allows us
* to use a moving average implementation for blurring individual rows and columns.
*
* <p>The runtime is: O(iterations * width * height) and therefore linear in the number of pixels
*
* <p>The required memory is: 2 * radius * 256 * 4 Bytes + max(width, height) * 4 Bytes + width *
* height * 4 Bytes (+constant)
*
* @param bitmap The {@link Bitmap} containing the image. The bitmap dimension need to be smaller
* than {@link BitmapUtil#MAX_BITMAP_SIZE}
* @param iterations The number of iterations of the blurring algorithm > 0.
* @param radius The radius of the blur with a supported range 0 < radius <= {@link
* RenderScriptBlurFilter#BLUR_MAX_RADIUS}
*/
public static void boxBlurBitmapInPlace(
final Bitmap bitmap, final int iterations, final int radius) {
Preconditions.checkNotNull(bitmap);
Preconditions.checkArgument(bitmap.isMutable());
Preconditions.checkArgument(bitmap.getHeight() <= BitmapUtil.MAX_BITMAP_SIZE);
Preconditions.checkArgument(bitmap.getWidth() <= BitmapUtil.MAX_BITMAP_SIZE);
Preconditions.checkArgument(radius > 0 && radius <= RenderScriptBlurFilter.BLUR_MAX_RADIUS);
Preconditions.checkArgument(iterations > 0);
try {
fastBoxBlur(bitmap, iterations, radius);
} catch (OutOfMemoryError oom) {
FLog.e(
TAG,
String.format(
(Locale) null,
"OOM: %d iterations on %dx%d with %d radius",
iterations,
bitmap.getWidth(),
bitmap.getHeight(),
radius));
throw oom;
}
}
public void linkBridge() {
if (messagingEnabled) {
if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// See isNative in lodash
String testPostMessageNative = "String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage')";
evaluateJavascript(testPostMessageNative, new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
if (value.equals("true")) {
FLog.w(ReactConstants.TAG, "Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
}
}
});
}
evaluateJavascriptWithFallback("(" +
"window.originalPostMessage = window.postMessage," +
"window.postMessage = function(data) {" +
BRIDGE_NAME + ".postMessage(String(data));" +
"}" +
")");
}
}
/**
* Close a database (in another thread).
*
* @param dbname The name of the database file
*/
private void closeDatabase(String dbname, CallbackContext cbc) {
DBRunner r = dbrmap.get(dbname);
if (r != null) {
try {
r.q.put(new DBQuery(false, cbc));
} catch(Exception ex) {
if (cbc != null) {
cbc.error("couldn't close database" + ex);
}
FLog.e(TAG, "couldn't close database", ex);
}
} else {
if (cbc != null) {
cbc.success("couldn't close database");
}
}
}
/**
* Submit a task to be executed in the future.
* @param runnable The task to be executed.
*/
@Override
public void execute(Runnable runnable) {
if (runnable == null) {
throw new NullPointerException("runnable parameter is null");
}
if (!mWorkQueue.offer(runnable)) {
throw new RejectedExecutionException(
mName + " queue is full, size=" + mWorkQueue.size());
}
final int queueSize = mWorkQueue.size();
final int maxSize = mMaxQueueSize.get();
if ((queueSize > maxSize) && mMaxQueueSize.compareAndSet(maxSize, queueSize)) {
FLog.v(TAG, "%s: max pending work in queue = %d", mName, queueSize);
} // else, there was a race and another thread updated and logged the max queue size
startWorkerIfNeeded();
}
@Override
public void onAttach() {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("AbstractDraweeController#onAttach");
}
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"controller %x %s: onAttach: %s",
System.identityHashCode(this),
mId,
mIsRequestSubmitted ? "request already submitted" : "request needs submit");
}
mEventTracker.recordEvent(Event.ON_ATTACH_CONTROLLER);
Preconditions.checkNotNull(mSettableDraweeHierarchy);
mDeferredReleaser.cancelDeferredRelease(this);
mIsAttached = true;
if (!mIsRequestSubmitted) {
submitRequest();
}
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
/**
* Releases a value to this bucket and decrements the inUse count
*
* @param value the value to release
*/
public void release(V value) {
Preconditions.checkNotNull(value);
if (mFixBucketsReinitialization) {
// Proper way
Preconditions.checkState(mInUseLength > 0);
mInUseLength--;
addToFreeList(value);
} else {
// Keep using previous adhoc
if (mInUseLength > 0) {
mInUseLength--;
addToFreeList(value);
} else {
FLog.e(TAG, "Tried to release value %s from an empty bucket!", value);
}
}
}
/**
* Close a database (in another thread).
*
* @param dbName - The name of the database file
* @param cbc - JS callback
*/
private void closeDatabase(String dbName, CallbackContext cbc) {
DBRunner r = dbrmap.get(dbName);
if (r != null) {
try {
r.q.put(new DBQuery(false, cbc));
} catch(Exception ex) {
if (cbc != null) {
cbc.error("couldn't close database" + ex);
}
FLog.e(TAG, "couldn't close database", ex);
}
} else {
if (cbc != null) {
cbc.success("database closed");
}
}
}
public void callFunction(PendingJSCall function) {
if (mDestroyed) {
final String call = function.toString();
FLog.w(ReactConstants.TAG, "Calling JS function after bridge has been destroyed: " + call);
return;
}
if (!mAcceptCalls) {
// Most of the time the instance is initialized and we don't need to acquire the lock
synchronized (mJSCallsPendingInitLock) {
if (!mAcceptCalls) {
mJSCallsPendingInit.add(function);
return;
}
}
}
function.call(this);
}
private void updateStats() {
final Runtime runtime = Runtime.getRuntime();
final long heapMemory = runtime.totalMemory() - runtime.freeMemory();
final StringBuilder sb = new StringBuilder(DEFAULT_MESSAGE_SIZE);
// When changing format of output below, make sure to sync "run_comparison.py" as well
sb.append("Heap: ");
appendSize(sb, heapMemory);
sb.append(" Java ");
appendSize(sb, Debug.getNativeHeapSize());
sb.append(" native\n");
appendTime(sb, "Avg wait time: ", mPerfListener.getAverageWaitTime(), "\n");
appendNumber(sb, "Requests: ", mPerfListener.getOutstandingRequests(), " outsdng ");
appendNumber(sb, "", mPerfListener.getCancelledRequests(), " cncld\n");
final String message = sb.toString();
mStatsDisplay.setText(message);
FLog.i(TAG, message);
}
/**
* @return a clone of the {@link ReactShadowNode} received by parameter. The cloned
* ReactShadowNode will contain a copy of all the internal data of the original node, but its
* props will be overridden with the {@link ReadableMap} received by parameter and its
* children set will be empty.
*/
@Nullable
@DoNotStrip
public ReactShadowNode cloneNodeWithNewChildrenAndProps(
ReactShadowNode node, ReadableNativeMap newProps) {
if (DEBUG) {
FLog.d(TAG, "cloneNodeWithNewChildrenAndProps \n\tnode: " + node + "\n\tnewProps: " + newProps);
}
SystraceMessage.beginSection(
Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
"FabricUIManager.cloneNodeWithNewChildrenAndProps")
.flush();
try {
ReactShadowNode clone =
node.mutableCopyWithNewChildrenAndProps(node.getInstanceHandle(),
newProps == null ? null : new ReactStylesDiffMap(newProps));
assertReactShadowNodeCopy(node, clone);
return clone;
} catch (Throwable t) {
handleException(node, t);
return null;
} finally{
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
@Override
public synchronized void onProducerFinishWithSuccess(
String requestId, String producerName, @Nullable Map<String, String> extraMap) {
if (FLog.isLoggable(FLog.VERBOSE)) {
Pair<String, String> mapKey = Pair.create(requestId, producerName);
Long startTime = mProducerStartTimeMap.remove(mapKey);
long currentTime = getTime();
FLog.v(
TAG,
"time %d: onProducerFinishWithSuccess: "
+ "{requestId: %s, producer: %s, elapsedTime: %d ms, extraMap: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap);
}
}
/**
* Updates the root view size and re-render the RN surface.
*
* //TODO: change synchronization to integrate with new #render loop.
*/
private synchronized void updateRootSize(int rootTag, int newWidth, int newHeight) {
ReactShadowNode rootNode = getRootNode(rootTag);
if (rootNode == null) {
FLog.w(
ReactConstants.TAG,
"Tried to update size of non-existent tag: " + rootTag);
return;
}
ReactShadowNode newRootNode = rootNode.mutableCopy(rootNode.getInstanceHandle());
int newWidthSpec = View.MeasureSpec.makeMeasureSpec(newWidth, View.MeasureSpec.EXACTLY);
int newHeightSpec = View.MeasureSpec.makeMeasureSpec(newHeight, View.MeasureSpec.EXACTLY);
updateRootView(newRootNode, newWidthSpec, newHeightSpec);
completeRoot(rootTag, newRootNode.getChildrenList());
}
public CloseableReferenceFactory(
final CloseableReferenceLeakTracker closeableReferenceLeakTracker) {
mLeakHandler =
new CloseableReference.LeakHandler() {
@Override
public void reportLeak(
SharedReference<Object> reference, @Nullable Throwable stacktrace) {
closeableReferenceLeakTracker.trackCloseableReferenceLeak(reference, stacktrace);
FLog.w(
"Fresco",
"Finalized without closing: %x %x (type = %s).\nStack:\n%s",
System.identityHashCode(this),
System.identityHashCode(reference),
reference.get().getClass().getName(),
getStackTraceString(stacktrace));
}
@Override
public boolean requiresStacktrace() {
return closeableReferenceLeakTracker.isSet();
}
};
}
private void enableLayoutCalculation() {
if (mReactInstanceManager == null) {
FLog.w(
ReactConstants.TAG,
"Unable to enable layout calculation for uninitialized ReactInstanceManager");
return;
}
final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext();
if (reactApplicationContext != null) {
reactApplicationContext
.getCatalystInstance()
.getNativeModule(UIManagerModule.class)
.getUIImplementation()
.enableLayoutCalculationForRootNode(getRootViewTag());
}
}
DBRunner(final String dbname, ReadableMap options, CallbackContext cbc) {
this.dbname = dbname;
int openFlags = SQLiteOpenFlags.CREATE | SQLiteOpenFlags.READWRITE;
try {
this.assetFilename = SQLitePluginConverter.getString(options,"assetFilename",null);
if (this.assetFilename != null && this.assetFilename.length() > 0) {
boolean readOnly = SQLitePluginConverter.getBoolean(options,"readOnly",false);
openFlags = readOnly ? SQLiteOpenFlags.READONLY : openFlags;
}
} catch (Exception ex){
FLog.e(TAG,"Error retrieving assetFilename or mode from options:",ex);
}
this.openFlags = openFlags;
this.oldImpl = SQLitePluginConverter.getBoolean(options,"androidOldDatabaseImplementation",false);
FLog.v(TAG, "Android db implementation: " + (oldImpl ? "OLD" : "sqlite4java (NDK)"));
this.androidLockWorkaround = this.oldImpl && SQLitePluginConverter.getBoolean(options,"androidLockWorkaround",false);
if (this.androidLockWorkaround)
FLog.i(TAG, "Android db closing/locking workaround applied");
this.q = new LinkedBlockingQueue<>();
this.openCbc = cbc;
}
/**
* Interface for fast tracking the initial adding of views. Children view tags are assumed to be
* in order
*
* @param viewTag the view tag of the parent view
* @param childrenTags An array of tags to add to the parent in order
*/
@ReactMethod
public void setChildren(
int viewTag,
ReadableArray childrenTags) {
if (DEBUG) {
String message = "(UIManager.setChildren) tag: " + viewTag + ", children: " + childrenTags;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
mUIImplementation.setChildren(viewTag, childrenTags);
}
@Override
public void onGestureUpdate(TransformGestureDetector detector) {
FLog.v(getLogTag(), "onGestureUpdate %s", isAnimating() ? "(ignored)" : "");
if (isAnimating()) {
return;
}
super.onGestureUpdate(detector);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(TAG, "controller %x %s: onTouchEvent %s", System.identityHashCode(this), mId, event);
}
if (mGestureDetector == null) {
return false;
}
if (mGestureDetector.isCapturingGesture() || shouldHandleGesture()) {
mGestureDetector.onTouchEvent(event);
return true;
}
return false;
}
private void logMessageAndImage(String messageAndMethod, T image) {
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"controller %x %s: %s: image: %s %x",
System.identityHashCode(this),
mId,
messageAndMethod,
getImageClass(image),
getImageHash(image));
}
}
/** Initializes {@link ImagePipelineFactory} with the specified config. */
public static synchronized void initialize(
ImagePipelineConfig imagePipelineConfig, boolean forceSinglePipelineInstance) {
if (sInstance != null) {
FLog.w(
TAG,
"ImagePipelineFactory has already been initialized! `ImagePipelineFactory.initialize(...)` should only be called once to avoid unexpected behavior.");
}
sForceSinglePipelineInstance = forceSinglePipelineInstance;
sInstance = new ImagePipelineFactory(imagePipelineConfig);
}
/**
* Rests the controller.
*/
public void reset() {
FLog.v(TAG, "reset");
mGestureDetector.reset();
mPreviousTransform.reset();
mActiveTransform.reset();
onTransformChanged();
}
@Override
public void onStartMethodEnd() {
long elapsedMs = SystemClock.elapsedRealtime() - mLastTimeStamp;
if (elapsedMs > 3) {
FLog.v(TAG, "onStart took %d", elapsedMs);
}
}
@Override
public void dropCaches() {
FLog.v(TAG, "(%s) Dropping caches", mLogId);
if (mLastDrawnFrame != null) {
mLastDrawnFrame.close();
mLastDrawnFrame = null;
mLastDrawnFrameNumber = -1;
mLastDrawnFrameMonotonicNumber = -1;
}
mAnimatedDrawableBackend.dropCaches();
}