If We Were a Child Again


Description

The Problem

 

The first project for the poor student was to make a calculator that can just perform the basic arithmetic operations.

 


But like many other university students he doesn’t like to do any project by himself. He just wants to collect programs from here and there. As you are a friend of him, he asks you to write the program. But, you are also intelligent enough to tackle this kind of people. You agreed to write only the (integer) division and mod (% in C/C++) operations for him.

Input

Input is a sequence of lines. Each line will contain an input number. One or more spaces. A sign (division or mod). Again spaces. And another input number. Both the input numbers are non-negative integer. The first one may be arbitrarily long. The second number n will be in the range (0 < n < 231).

Output

A line for each input, each containing an integer. See the sample input and output. Output should not contain any extra space.

Sample Input

110 / 100
99 % 10
2147483647 / 2147483647
2147483646 % 2147483647

Sample Output

1
9
1
2147483646

HINT

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
	char str[1000],a[100],b[100],c;
	int t,i,j,x,y;
    int	 num,s,d[1000],e,m;
	while(gets(str))
	{
		t=0;
		for(i=0;str[i];i++)
		{
			if(str[i]=='/'||str[i]=='%')
			{
				c=str[i];
				a[t-1]='\0';
				break;
			}
			else
				a[t++]=str[i];
		}
		a[t]='\0';
		t=0;
		for(j=i+2;str[j];j++)
			b[t++]=str[j];
		b[t]='\0';
		x=strlen(a);
		y=strlen(b);
		s=0;
		if(strcmp(a,b)<0&&x<y)
		{
			if(c=='/')
				cout<<"0"<<endl;
			else if(c=='%')
			{
				cout<<a<<endl;
			}
		}
		else if(strcmp(a,b)==0)
		{
			if(c=='/')
				cout<<"1"<<endl;
			else if(c=='%')
			{
				cout<<"0"<<endl;
			}
		}	
		else
		{
			for(i=0;i<y;i++)
				s=s*10+(b[i]-'0');
			num=0;
			if(c=='/')
			{
				e=0;
				for(i=0;i<x;i++)
				{
					num=num*10+(a[i]-'0');//从高位向低位逐渐的除(例子123/5,1/5=0,* 1%5=1 * ,(1*10+2)/5=2,* 12%5=2 *  ,(2*10+3)/5=4)所以为024
					m=num/s;
					d[e++]=m;
					num%=s;
				}
				for(i=0;i<e;i++)
				{
					if(d[i]!=0)
						break;
				}
				for(j=i;j<e;j++)
					cout<<d[j];
					//printf("%I64d",d[j]);
				cout<<endl;
			}
			else if(c=='%')
			{
				for(i=0;i<x;i++)
				{
					num=num*10+(a[i]-'0');//从高位向低位逐渐的取余(例子123%5, 1%5=1 ,(1*10+2)%5=2,(2*10+3)%5=3)所以为余数3
					num%=s;
				}
				cout<<num<<endl;
				//printf("%I64d\n",num);
			}
			
		//	cout<<s<<endl;
		}
		//cout<<a<<endl<<x<<endl;
		//cout<<b<<endl<<y<<endl;		
	}
	return 0;
}


另一种方法更简洁

#include<stdio.h>
#include<string.h>
int main()
{
	int b,t,len,i,j,k;
	char a[1000],flag;
	while(scanf("%s %c %d",a,&flag,&b)!=EOF)
	{
		len=strlen(a);
		if(flag=='/')
			t=0; //标志作用
		else if(flag=='%')
			t=1;
		k=0;
		j=0;
		for(i=0;i<len;i++)
		{
			k=k*10+(a[i]-'0');
			if((k/b)!=0||(j!=0))
			{
				if(t==0)
					printf("%d",k/b);
				k%=b;
				j=1;//标志除了第一次整除的零不输出外,其余均输出,例如100/5输出的是20而不是020
			}
		}
		if(j==0&&t==0) printf("0");//整除的特殊情况例如2/5的值是零
		if(t!=0) printf("%d",k);
		printf("\n");
	}
	return 0;
}




 

private void performTraversals() { 3295 mLastPerformTraversalsSkipDrawReason = null; 3296 3297 // cache mView since it is used so much below... 3298 final View host = mView; 3299 if (DBG) { 3300 System.out.println("======================================"); 3301 System.out.println("performTraversals"); 3302 host.debug(); 3303 } 3304 3305 if (host == null || !mAdded) { 3306 mLastPerformTraversalsSkipDrawReason = host == null ? "no_host" : "not_added"; 3307 return; 3308 } 3309 3310 if (mNumPausedForSync > 0) { 3311 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 3312 Trace.instant(Trace.TRACE_TAG_VIEW, 3313 TextUtils.formatSimple("performTraversals#mNumPausedForSync=%d", 3314 mNumPausedForSync)); 3315 } 3316 3317 Log.d(mTag, "Skipping traversal due to sync " + mNumPausedForSync); 3318 mLastPerformTraversalsSkipDrawReason = "paused_for_sync"; 3319 return; 3320 } 3321 3322 // #ifdef OPLUS_FEATURE_VIEW_DEBUG 3323 // Bard.Zhang@Android.UIFramework 2023-01-28 Add for : view debug 3324 mViewRootImplExt.markOnPerformTraversalsStart(host, mFirst); 3325 // #endif /* OPLUS_FEATURE_VIEW_DEBUG */ 3326 3327 mIsInTraversal = true; 3328 mWillDrawSoon = true; 3329 boolean cancelDraw = false; 3330 String cancelReason = null; 3331 boolean isSyncRequest = false; 3332 3333 boolean windowSizeMayChange = false; 3334 WindowManager.LayoutParams lp = mWindowAttributes; 3335 3336 int desiredWindowWidth; 3337 int desiredWindowHeight; 3338 3339 final int viewVisibility = getHostVisibility(); 3340 final boolean viewVisibilityChanged = !mFirst 3341 && (mViewVisibility != viewVisibility || mNewSurfaceNeeded 3342 // Also check for possible double visibility update, which will make current 3343 // viewVisibility value equal to mViewVisibility and we may miss it. 3344 || mAppVisibilityChanged); 3345 mAppVisibilityChanged = false; 3346 final boolean viewUserVisibilityChanged = !mFirst && 3347 ((mViewVisibility == View.VISIBLE) != (viewVisibility == View.VISIBLE)); 3348 final boolean shouldOptimizeMeasure = shouldOptimizeMeasure(lp); 3349 3350 WindowManager.LayoutParams params = null; 3351 CompatibilityInfo compatibilityInfo = 3352 mDisplay.getDisplayAdjustments().getCompatibilityInfo(); 3353 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 3354 params = lp; 3355 mFullRedrawNeeded = true; 3356 mLayoutRequested = true; 3357 if (mLastInCompatMode) { 3358 params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW; 3359 mLastInCompatMode = false; 3360 } else { 3361 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW; 3362 mLastInCompatMode = true; 3363 } 3364 } 3365 3366 Rect frame = mWinFrame; 3367 if (mFirst) { 3368 mFullRedrawNeeded = true; 3369 mLayoutRequested = true; 3370 3371 final Configuration config = getConfiguration(); 3372 if (shouldUseDisplaySize(lp)) { 3373 // NOTE -- system code, won't try to do compat mode. 3374 Point size = new Point(); 3375 mDisplay.getRealSize(size); 3376 desiredWindowWidth = size.x; 3377 desiredWindowHeight = size.y; 3378 } else if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 3379 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 3380 // For wrap content, we have to remeasure later on anyways. Use size consistent with 3381 // below so we get best use of the measure cache. 3382 final Rect bounds = getWindowBoundsInsetSystemBars(); 3383 desiredWindowWidth = bounds.width(); 3384 desiredWindowHeight = bounds.height(); 3385 } else { 3386 // After addToDisplay, the frame contains the frameHint from window manager, which 3387 // for most windows is going to be the same size as the result of relayoutWindow. 3388 // Using this here allows us to avoid remeasuring after relayoutWindow 3389 desiredWindowWidth = frame.width(); 3390 desiredWindowHeight = frame.height(); 3391 } 3392 3393 // We used to use the following condition to choose 32 bits drawing caches: 3394 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 3395 // However, windows are now always 32 bits by default, so choose 32 bits 3396 mAttachInfo.mUse32BitDrawingCache = true; 3397 mAttachInfo.mWindowVisibility = viewVisibility; 3398 mAttachInfo.mRecomputeGlobalAttributes = false; 3399 mLastConfigurationFromResources.setTo(config); 3400 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 3401 // Set the layout direction if it has not been set before (inherit is the default) 3402 if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 3403 host.setLayoutDirection(config.getLayoutDirection()); 3404 } 3405 //#ifdef OPLUS_FEATURE_BRACKETMODE_2_0 3406 //wenguangyu@ANDROID.WMS, 2022/10/02, add for bracket mode 3407 mViewRootImplExt.attachToWindow(); 3408 //#endif /*OPLUS_FEATURE_BRACKETMODE_2_0*/ 3409 host.dispatchAttachedToWindow(mAttachInfo, 0); 3410 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true); 3411 dispatchApplyInsets(host); 3412 if (!mOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled()) { 3413 // For apps requesting legacy back behavior, we add a compat callback that 3414 // dispatches {@link KeyEvent#KEYCODE_BACK} to their root views. 3415 // This way from system point of view, these apps are providing custom 3416 // {@link OnBackInvokedCallback}s, and will not play system back animations 3417 // for them. 3418 registerCompatOnBackInvokedCallback(); 3419 } 3420 } else { 3421 desiredWindowWidth = frame.width(); 3422 desiredWindowHeight = frame.height(); 3423 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) { 3424 if (DEBUG_ORIENTATION) Log.v(mTag, "View " + host + " resized to: " + frame); 3425 mFullRedrawNeeded = true; 3426 mLayoutRequested = true; 3427 windowSizeMayChange = true; 3428 } 3429 } 3430 3431 if (viewVisibilityChanged) { 3432 mAttachInfo.mWindowVisibility = viewVisibility; 3433 host.dispatchWindowVisibilityChanged(viewVisibility); 3434 mAttachInfo.mTreeObserver.dispatchOnWindowVisibilityChange(viewVisibility); 3435 if (viewUserVisibilityChanged) { 3436 host.dispatchVisibilityAggregated(viewVisibility == View.VISIBLE); 3437 } 3438 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) { 3439 endDragResizing(); 3440 destroyHardwareResources(); 3441 } 3442 } 3443 3444 // Non-visible windows can't hold accessibility focus. 3445 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 3446 host.clearAccessibilityFocus(); 3447 } 3448 3449 // Execute enqueued actions on every traversal in case a detached view enqueued an action 3450 getRunQueue().executeActions(mAttachInfo.mHandler); 3451 3452 if (mFirst) { 3453 // make sure touch mode code executes by setting cached value 3454 // to opposite of the added touch mode. 3455 mAttachInfo.mInTouchMode = !mAddedTouchMode; 3456 ensureTouchModeLocally(mAddedTouchMode); 3457 } 3458 3459 boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw); 3460 if (layoutRequested) { 3461 if (!mFirst) { 3462 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 3463 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 3464 windowSizeMayChange = true; 3465 3466 if (shouldUseDisplaySize(lp)) { 3467 // NOTE -- system code, won't try to do compat mode. 3468 Point size = new Point(); 3469 mDisplay.getRealSize(size); 3470 desiredWindowWidth = size.x; 3471 desiredWindowHeight = size.y; 3472 } else { 3473 final Rect bounds = getWindowBoundsInsetSystemBars(); 3474 desiredWindowWidth = bounds.width(); 3475 desiredWindowHeight = bounds.height(); 3476 } 3477 } 3478 } 3479 3480 // Ask host how big it wants to be 3481 windowSizeMayChange |= measureHierarchy(host, lp, mView.getContext().getResources(), 3482 desiredWindowWidth, desiredWindowHeight, shouldOptimizeMeasure); 3483 } 3484 3485 if (collectViewAttributes()) { 3486 params = lp; 3487 } 3488 if (mAttachInfo.mForceReportNewAttributes) { 3489 mAttachInfo.mForceReportNewAttributes = false; 3490 params = lp; 3491 } 3492 3493 if (mFirst || mAttachInfo.mViewVisibilityChanged) { 3494 mAttachInfo.mViewVisibilityChanged = false; 3495 int resizeMode = mSoftInputMode & SOFT_INPUT_MASK_ADJUST; 3496 // If we are in auto resize mode, then we need to determine 3497 // what mode to use now. 3498 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 3499 final int N = mAttachInfo.mScrollContainers.size(); 3500 for (int i=0; i<N; i++) { 3501 if (mAttachInfo.mScrollContainers.get(i).isShown()) { 3502 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; 3503 } 3504 } 3505 if (resizeMode == 0) { 3506 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN; 3507 } 3508 if ((lp.softInputMode & SOFT_INPUT_MASK_ADJUST) != resizeMode) { 3509 lp.softInputMode = (lp.softInputMode & ~SOFT_INPUT_MASK_ADJUST) | resizeMode; 3510 params = lp; 3511 } 3512 } 3513 } 3514 3515 if (mApplyInsetsRequested) { 3516 dispatchApplyInsets(host); 3517 if (mLayoutRequested) { 3518 // Short-circuit catching a new layout request here, so 3519 // we don't need to go through two layout passes when things 3520 // change due to fitting system windows, which can happen a lot. 3521 windowSizeMayChange |= measureHierarchy(host, lp, 3522 mView.getContext().getResources(), desiredWindowWidth, desiredWindowHeight, 3523 shouldOptimizeMeasure); 3524 } 3525 } 3526 3527 if (layoutRequested) { 3528 // Clear this now, so that if anything requests a layout in the 3529 // rest of this function we will catch it and re-run a full 3530 // layout pass. 3531 mLayoutRequested = false; 3532 } 3533 3534 boolean windowShouldResize = layoutRequested && windowSizeMayChange 3535 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) 3536 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT && 3537 frame.width() < desiredWindowWidth && frame.width() != mWidth) 3538 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT && 3539 frame.height() < desiredWindowHeight && frame.height() != mHeight)); 3540 windowShouldResize |= mDragResizing && mPendingDragResizing; 3541 3542 // Determine whether to compute insets. 3543 // If there are no inset listeners remaining then we may still need to compute 3544 // insets in case the old insets were non-empty and must be reset. 3545 final boolean computesInternalInsets = 3546 mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners() 3547 || mAttachInfo.mHasNonEmptyGivenInternalInsets; 3548 3549 boolean insetsPending = false; 3550 int relayoutResult = 0; 3551 boolean updatedConfiguration = false; 3552 3553 final int surfaceGenerationId = mSurface.getGenerationId(); 3554 3555 final boolean isViewVisible = viewVisibility == View.VISIBLE; 3556 boolean surfaceSizeChanged = false; 3557 boolean surfaceCreated = false; 3558 boolean surfaceDestroyed = false; 3559 // True if surface generation id changes or relayout result is RELAYOUT_RES_SURFACE_CHANGED. 3560 boolean surfaceReplaced = false; 3561 3562 final boolean windowAttributesChanged = mWindowAttributesChanged; 3563 if (windowAttributesChanged) { 3564 mWindowAttributesChanged = false; 3565 params = lp; 3566 } 3567 3568 if (params != null) { 3569 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0 3570 && !PixelFormat.formatHasAlpha(params.format)) { 3571 params.format = PixelFormat.TRANSLUCENT; 3572 } 3573 adjustLayoutParamsForCompatibility(params); 3574 controlInsetsForCompatibility(params); 3575 if (mDispatchedSystemBarAppearance != params.insetsFlags.appearance) { 3576 mDispatchedSystemBarAppearance = params.insetsFlags.appearance; 3577 mView.onSystemBarAppearanceChanged(mDispatchedSystemBarAppearance); 3578 } 3579 } 3580 3581 if (mFirst || windowShouldResize || viewVisibilityChanged || params != null 3582 || mForceNextWindowRelayout) { 3583 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 3584 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 3585 TextUtils.formatSimple("relayoutWindow#" 3586 + "first=%b/resize=%b/vis=%b/params=%b/force=%b", 3587 mFirst, windowShouldResize, viewVisibilityChanged, params != null, 3588 mForceNextWindowRelayout)); 3589 } 3590 3591 mForceNextWindowRelayout = false; 3592 3593 // If this window is giving internal insets to the window manager, then we want to first 3594 // make the provided insets unchanged during layout. This avoids it briefly causing 3595 // other windows to resize/move based on the raw frame of the window, waiting until we 3596 // can finish laying out this window and get back to the window manager with the 3597 // ultimately computed insets. 3598 insetsPending = computesInternalInsets; 3599 3600 if (mSurfaceHolder != null) { 3601 mSurfaceHolder.mSurfaceLock.lock(); 3602 mDrawingAllowed = true; 3603 } 3604 3605 boolean hwInitialized = false; 3606 boolean dispatchApplyInsets = false; 3607 boolean hadSurface = mSurface.isValid(); 3608 3609 try { 3610 if (DEBUG_LAYOUT) { 3611 Log.i(mTag, "host=w:" + host.getMeasuredWidth() + ", h:" + 3612 host.getMeasuredHeight() + ", params=" + params); 3613 } 3614 3615 if (mFirst || viewVisibilityChanged) { 3616 mViewFrameInfo.flags |= FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED; 3617 } 3618 //#ifdef OPLUS_FEATURE_JANK_TRACKER 3619 //wangwei11@oppo.com, 2021/11/28, Add for janktracker 3620 mChoreographer.mChoreographerExt.markRelayout(); 3621 //#endif /*OPLUS_FEATURE_JANK_TRACKER*/ 3622 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending); 3623 cancelDraw = (relayoutResult & RELAYOUT_RES_CANCEL_AND_REDRAW) 3624 == RELAYOUT_RES_CANCEL_AND_REDRAW; 3625 cancelReason = "relayout"; 3626 final boolean dragResizing = mPendingDragResizing; 3627 if (mSyncSeqId > mLastSyncSeqId) { 3628 mLastSyncSeqId = mSyncSeqId; 3629 if (DEBUG_BLAST) { 3630 Log.d(mTag, "Relayout called with blastSync"); 3631 } 3632 reportNextDraw("relayout"); 3633 mSyncBuffer = true; 3634 isSyncRequest = true; 3635 if (!cancelDraw) { 3636 mDrewOnceForSync = false; 3637 } 3638 } 3639 3640 final boolean surfaceControlChanged = 3641 (relayoutResult & RELAYOUT_RES_SURFACE_CHANGED) 3642 == RELAYOUT_RES_SURFACE_CHANGED; 3643 3644 if (mSurfaceControl.isValid()) { 3645 updateOpacity(mWindowAttributes, dragResizing, 3646 surfaceControlChanged /*forceUpdate */); 3647 // No need to updateDisplayDecoration if it's a new SurfaceControl and 3648 // mDisplayDecorationCached is false, since that's the default for a new 3649 // SurfaceControl. 3650 if (surfaceControlChanged && mDisplayDecorationCached) { 3651 updateDisplayDecoration(); 3652 } 3653 if (surfaceControlChanged 3654 && mWindowAttributes.type 3655 == WindowManager.LayoutParams.TYPE_STATUS_BAR) { 3656 mTransaction.setDefaultFrameRateCompatibility(mSurfaceControl, 3657 Surface.FRAME_RATE_COMPATIBILITY_NO_VOTE).apply(); 3658 } 3659 } 3660 3661 if (DEBUG_LAYOUT) Log.v(mTag, "relayout: frame=" + frame.toShortString() 3662 + " surface=" + mSurface); 3663 3664 // If the pending {@link MergedConfiguration} handed back from 3665 // {@link #relayoutWindow} does not match the one last reported, 3666 // WindowManagerService has reported back a frame from a configuration not yet 3667 // handled by the client. In this case, we need to accept the configuration so we 3668 // do not lay out and draw with the wrong configuration. 3669 if (mRelayoutRequested 3670 && !mPendingMergedConfiguration.equals(mLastReportedMergedConfiguration)) { 3671 if (DEBUG_CONFIGURATION) Log.v(mTag, "Visible with new config: " 3672 + mPendingMergedConfiguration.getMergedConfiguration()); 3673 performConfigurationChange(new MergedConfiguration(mPendingMergedConfiguration), 3674 !mFirst, INVALID_DISPLAY /* same display */); 3675 updatedConfiguration = true; 3676 } 3677 final boolean updateSurfaceNeeded = mUpdateSurfaceNeeded; 3678 mUpdateSurfaceNeeded = false; 3679 3680 surfaceSizeChanged = false; 3681 if (!mLastSurfaceSize.equals(mSurfaceSize)) { 3682 surfaceSizeChanged = true; 3683 mLastSurfaceSize.set(mSurfaceSize.x, mSurfaceSize.y); 3684 } 3685 final boolean alwaysConsumeSystemBarsChanged = 3686 mPendingAlwaysConsumeSystemBars != mAttachInfo.mAlwaysConsumeSystemBars; 3687 updateColorModeIfNeeded(lp.getColorMode()); 3688 surfaceCreated = !hadSurface && mSurface.isValid(); 3689 surfaceDestroyed = hadSurface && !mSurface.isValid(); 3690 3691 // When using Blast, the surface generation id may not change when there's a new 3692 // SurfaceControl. In that case, we also check relayout flag 3693 // RELAYOUT_RES_SURFACE_CHANGED since it should indicate that WMS created a new 3694 // SurfaceControl. 3695 surfaceReplaced = (surfaceGenerationId != mSurface.getGenerationId() 3696 || surfaceControlChanged) && mSurface.isValid(); 3697 if (surfaceReplaced) { 3698 mSurfaceSequenceId++; 3699 } 3700 if (alwaysConsumeSystemBarsChanged) { 3701 mAttachInfo.mAlwaysConsumeSystemBars = mPendingAlwaysConsumeSystemBars; 3702 dispatchApplyInsets = true; 3703 } 3704 if (updateCaptionInsets()) { 3705 dispatchApplyInsets = true; 3706 } 3707 if (dispatchApplyInsets || mLastSystemUiVisibility != 3708 mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested) { 3709 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 3710 dispatchApplyInsets(host); 3711 // We applied insets so force contentInsetsChanged to ensure the 3712 // hierarchy is measured below. 3713 dispatchApplyInsets = true; 3714 } 3715 3716 if (surfaceCreated) { 3717 // If we are creating a new surface, then we need to 3718 // completely redraw it. 3719 mFullRedrawNeeded = true; 3720 mPreviousTransparentRegion.setEmpty(); 3721 3722 // Only initialize up-front if transparent regions are not 3723 // requested, otherwise defer to see if the entire window 3724 // will be transparent 3725 if (mAttachInfo.mThreadedRenderer != null) { 3726 try { 3727 hwInitialized = mAttachInfo.mThreadedRenderer.initialize(mSurface); 3728 // #ifdef OPLUS_EXTENSION_HOOK 3729 // yanliang@Android.Performance 2023-02-13 Add for Optimize sliding effect 3730 mViewRootImplExt.setPendingBufferCountSetting(true); 3731 // #endif /*OPLUS_EXTENSION_HOOK*/ 3732 if (hwInitialized && (host.mPrivateFlags 3733 //#ifndef OPLUS_BUG_STABILITY 3734 //Weitao.Chen@ANDROID.STABILITY.2742412, 2020/01/02, Add for null pointer exp 3735 //& View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0) { 3736 //#else 3737 & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0 && mAttachInfo.mThreadedRenderer != null) { 3738 //#endif /*OPLUS_BUG_STABILITY*/ 3739 // Don't pre-allocate if transparent regions 3740 // are requested as they may not be needed 3741 mAttachInfo.mThreadedRenderer.allocateBuffers(); 3742 } 3743 } catch (OutOfResourcesException e) { 3744 handleOutOfResourcesException(e); 3745 mLastPerformTraversalsSkipDrawReason = "oom_initialize_renderer"; 3746 return; 3747 } 3748 } 3749 } else if (surfaceDestroyed) { 3750 // If the surface has been removed, then reset the scroll 3751 // positions. 3752 if (mLastScrolledFocus != null) { 3753 mLastScrolledFocus.clear(); 3754 } 3755 mScrollY = mCurScrollY = 0; 3756 if (mView instanceof RootViewSurfaceTaker) { 3757 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY); 3758 } 3759 if (mScroller != null) { 3760 mScroller.abortAnimation(); 3761 } 3762 // Our surface is gone 3763 if (isHardwareEnabled()) { 3764 mAttachInfo.mThreadedRenderer.destroy(); 3765 } 3766 } else if ((surfaceReplaced || surfaceSizeChanged || updateSurfaceNeeded) 3767 && mSurfaceHolder == null 3768 && mAttachInfo.mThreadedRenderer != null 3769 && mSurface.isValid()) { 3770 mFullRedrawNeeded = true; 3771 try { 3772 // Need to do updateSurface (which leads to CanvasContext::setSurface and 3773 // re-create the EGLSurface) if either the Surface changed (as indicated by 3774 // generation id), or WindowManager changed the surface size. The latter is 3775 // because on some chips, changing the consumer side's BufferQueue size may 3776 // not take effect immediately unless we create a new EGLSurface. 3777 // Note that frame size change doesn't always imply surface size change (eg. 3778 // drag resizing uses fullscreen surface), need to check surfaceSizeChanged 3779 // flag from WindowManager. 3780 mAttachInfo.mThreadedRenderer.updateSurface(mSurface); 3781 } catch (OutOfResourcesException e) { 3782 handleOutOfResourcesException(e); 3783 mLastPerformTraversalsSkipDrawReason = "oom_update_surface"; 3784 return; 3785 } 3786 } 3787 3788 if (mDragResizing != dragResizing) { 3789 if (dragResizing) { 3790 final boolean backdropSizeMatchesFrame = 3791 mWinFrame.width() == mPendingBackDropFrame.width() 3792 && mWinFrame.height() == mPendingBackDropFrame.height(); 3793 // TODO: Need cutout? 3794 startDragResizing(mPendingBackDropFrame, !backdropSizeMatchesFrame, 3795 mAttachInfo.mContentInsets, mAttachInfo.mStableInsets); 3796 } else { 3797 // We shouldn't come here, but if we come we should end the resize. 3798 endDragResizing(); 3799 } 3800 } 3801 if (!mUseMTRenderer) { 3802 if (dragResizing) { 3803 mCanvasOffsetX = mWinFrame.left; 3804 mCanvasOffsetY = mWinFrame.top; 3805 } else { 3806 mCanvasOffsetX = mCanvasOffsetY = 0; 3807 } 3808 } 3809 } catch (RemoteException e) { 3810 } finally { 3811 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 3812 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3813 } 3814 } 3815 3816 if (DEBUG_ORIENTATION) Log.v( 3817 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 3818 3819 mAttachInfo.mWindowLeft = frame.left; 3820 mAttachInfo.mWindowTop = frame.top; 3821 3822 // !!FIXME!! This next section handles the case where we did not get the 3823 // window size we asked for. We should avoid this by getting a maximum size from 3824 // the window session beforehand. 3825 if (mWidth != frame.width() || mHeight != frame.height()) { 3826 mWidth = frame.width(); 3827 mHeight = frame.height(); 3828 } 3829 3830 if (mSurfaceHolder != null) { 3831 // The app owns the surface; tell it about what is going on. 3832 if (mSurface.isValid()) { 3833 // XXX .copyFrom() doesn't work! 3834 //mSurfaceHolder.mSurface.copyFrom(mSurface); 3835 mSurfaceHolder.mSurface = mSurface; 3836 } 3837 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 3838 mSurfaceHolder.mSurfaceLock.unlock(); 3839 if (surfaceCreated) { 3840 mSurfaceHolder.ungetCallbacks(); 3841 3842 mIsCreating = true; 3843 SurfaceHolder.Callback[] callbacks = mSurfaceHolder.getCallbacks(); 3844 if (callbacks != null) { 3845 for (SurfaceHolder.Callback c : callbacks) { 3846 c.surfaceCreated(mSurfaceHolder); 3847 } 3848 } 3849 } 3850 3851 if ((surfaceCreated || surfaceReplaced || surfaceSizeChanged 3852 || windowAttributesChanged) && mSurface.isValid()) { 3853 SurfaceHolder.Callback[] callbacks = mSurfaceHolder.getCallbacks(); 3854 if (callbacks != null) { 3855 for (SurfaceHolder.Callback c : callbacks) { 3856 c.surfaceChanged(mSurfaceHolder, lp.format, 3857 mWidth, mHeight); 3858 } 3859 } 3860 mIsCreating = false; 3861 } 3862 3863 if (surfaceDestroyed) { 3864 notifyHolderSurfaceDestroyed(); 3865 mSurfaceHolder.mSurfaceLock.lock(); 3866 try { 3867 mSurfaceHolder.mSurface = new Surface(); 3868 } finally { 3869 mSurfaceHolder.mSurfaceLock.unlock(); 3870 } 3871 } 3872 } 3873 3874 final ThreadedRenderer threadedRenderer = mAttachInfo.mThreadedRenderer; 3875 if (threadedRenderer != null && threadedRenderer.isEnabled()) { 3876 if (hwInitialized 3877 || mWidth != threadedRenderer.getWidth() 3878 || mHeight != threadedRenderer.getHeight() 3879 || mNeedsRendererSetup) { 3880 threadedRenderer.setup(mWidth, mHeight, mAttachInfo, 3881 mWindowAttributes.surfaceInsets); 3882 mNeedsRendererSetup = false; 3883 } 3884 } 3885 3886 // TODO: In the CL "ViewRootImpl: Fix issue with early draw report in 3887 // seamless rotation". We moved processing of RELAYOUT_RES_BLAST_SYNC 3888 // earlier in the function, potentially triggering a call to 3889 // reportNextDraw(). That same CL changed this and the next reference 3890 // to wasReportNextDraw, such that this logic would remain undisturbed 3891 // (it continues to operate as if the code was never moved). This was 3892 // done to achieve a more hermetic fix for S, but it's entirely 3893 // possible that checking the most recent value is actually more 3894 // correct here. 3895 if (!mStopped || mReportNextDraw) { 3896 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight() 3897 || dispatchApplyInsets || updatedConfiguration) { 3898 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width, 3899 lp.privateFlags); 3900 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height, 3901 lp.privateFlags); 3902 3903 if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed! mWidth=" 3904 + mWidth + " measuredWidth=" + host.getMeasuredWidth() 3905 + " mHeight=" + mHeight 3906 + " measuredHeight=" + host.getMeasuredHeight() 3907 + " dispatchApplyInsets=" + dispatchApplyInsets); 3908 3909 // #ifdef OPLUS_FEATURE_VIEW_DEBUG 3910 // Bard.Zhang@Android.UIFramework 2023-01-19 Add for : view debug 3911 String measureReason = "Measure reason mFirst " + mFirst 3912 + " windowShouldResize " + windowShouldResize 3913 + " viewVisibilityChanged " + viewVisibilityChanged 3914 + " params != null " + (params != null) 3915 + " mForceNextWindowRelayout " + mForceNextWindowRelayout 3916 + " mStopped " + mStopped + " mReportNextDraw " + mReportNextDraw 3917 + " mWidth " + mWidth + " host.getMeasuredWidth " + host.getMeasuredWidth() 3918 + " mHeight " + mHeight + " host.getMeasuredHeight " + host.getMeasuredHeight() 3919 + " dispatchApplyInsets " + dispatchApplyInsets 3920 + " updateConfiguration " + updatedConfiguration; 3921 mViewRootImplExt.markPerformMeasureReason(measureReason); 3922 // #endif /* OPLUS_FEATURE_VIEW_DEBUG */ 3923 // #ifdef OPLUS_BUG_COMPATIBILITY 3924 //Qian.Jiang@Android.Wms, 2023/05/19: fix bug-5573936 3925 int heightMesure = MeasureSpec.getSize(childHeightMeasureSpec); 3926 int widthMesure = MeasureSpec.getSize(childWidthMeasureSpec); 3927 if (PANIC_DEBUG && (heightMesure > LIMIT || widthMesure > LIMIT)) { 3928 Log.d(mTag, "performMeasure heightMesure = " + heightMesure + ",widthMesure = " + widthMesure); 3929 } 3930 //#endif /* OPLUS_BUG_COMPATIBILITY */ 3931 // Ask host how big it wants to be 3932 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 3933 3934 // Implementation of weights from WindowManager.LayoutParams 3935 // We just grow the dimensions as needed and re-measure if 3936 // needs be 3937 int width = host.getMeasuredWidth(); 3938 int height = host.getMeasuredHeight(); 3939 boolean measureAgain = false; 3940 3941 if (lp.horizontalWeight > 0.0f) { 3942 width += (int) ((mWidth - width) * lp.horizontalWeight); 3943 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, 3944 MeasureSpec.EXACTLY); 3945 measureAgain = true; 3946 } 3947 if (lp.verticalWeight > 0.0f) { 3948 height += (int) ((mHeight - height) * lp.verticalWeight); 3949 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 3950 MeasureSpec.EXACTLY); 3951 measureAgain = true; 3952 } 3953 3954 if (measureAgain) { 3955 if (DEBUG_LAYOUT) Log.v(mTag, 3956 "And hey let's measure once more: width=" + width 3957 + " height=" + height); 3958 3959 // #ifdef OPLUS_FEATURE_VIEW_DEBUG 3960 // Bard.Zhang@Android.UIFramework 2023-01-19 Add for : view debug 3961 mMeasureReason = "3"; 3962 String measureAgainReason = "Measure again lp.horizontalWeight " + lp.horizontalWeight 3963 + " lp.verticalWeight " + lp.verticalWeight; 3964 mViewRootImplExt.markPerformMeasureReason(measureAgainReason); 3965 // #endif /* OPLUS_FEATURE_VIEW_DEBUG */ 3966 3967 // #ifdef OPLUS_BUG_COMPATIBILITY 3968 //Qian.Jiang@Android.Wms, 2023/05/19: fix bug-5573936 3969 int heightAgain = MeasureSpec.getSize(childHeightMeasureSpec); 3970 int widthAgain = MeasureSpec.getSize(childWidthMeasureSpec); 3971 if (PANIC_DEBUG && (heightAgain > LIMIT || widthAgain > LIMIT)) { 3972 Log.d(mTag, "measureAgain performMeasure heightAgain = " + heightAgain + ",widthAgain = " + widthAgain); 3973 } 3974 //#endif /* OPLUS_BUG_COMPATIBILITY */ 3975 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 3976 } 3977 3978 layoutRequested = true; 3979 } 3980 } 3981 } else { 3982 // Not the first pass and no window/insets/visibility change but the window 3983 // may have moved and we need check that and if so to update the left and right 3984 // in the attach info. We translate only the window frame since on window move 3985 // the window manager tells us only for the new frame but the insets are the 3986 // same and we do not want to translate them more than once. 3987 maybeHandleWindowMove(frame); 3988 } 3989 3990 if (mViewMeasureDeferred) { 3991 // It's time to measure the views since we are going to layout them. 3992 performMeasure( 3993 MeasureSpec.makeMeasureSpec(frame.width(), MeasureSpec.EXACTLY), 3994 MeasureSpec.makeMeasureSpec(frame.height(), MeasureSpec.EXACTLY)); 3995 } 3996 3997 if (!mRelayoutRequested && mCheckIfCanDraw) { 3998 // We had a sync previously, but we didn't call IWindowSession#relayout in this 3999 // traversal. So we don't know if the sync is complete that we can continue to draw. 4000 // Here invokes cancelDraw to obtain the information. 4001 try { 4002 cancelDraw = mWindowSession.cancelDraw(mWindow); 4003 cancelReason = "wm_sync"; 4004 Log.d(mTag, "cancelDraw returned " + cancelDraw); 4005 } catch (RemoteException e) { 4006 } 4007 } 4008 4009 if (surfaceSizeChanged || surfaceReplaced || surfaceCreated || 4010 windowAttributesChanged || mChildBoundingInsetsChanged) { 4011 // If the surface has been replaced, there's a chance the bounds layer is not parented 4012 // to the new layer. When updating bounds layer, also reparent to the main VRI 4013 // SurfaceControl to ensure it's correctly placed in the hierarchy. 4014 // 4015 // This needs to be done on the client side since WMS won't reparent the children to the 4016 // new surface if it thinks the app is closing. WMS gets the signal that the app is 4017 // stopping, but on the client side it doesn't get stopped since it's restarted quick 4018 // enough. WMS doesn't want to keep around old children since they will leak when the 4019 // client creates new children. 4020 prepareSurfaces(); 4021 mChildBoundingInsetsChanged = false; 4022 } 4023 4024 final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw); 4025 boolean triggerGlobalLayoutListener = didLayout 4026 || mAttachInfo.mRecomputeGlobalAttributes; 4027 if (didLayout) { 4028 //#ifdef OPLUS_EXTENSION_HOOK 4029 //Jie.Zhang@ANDROID.PERFORMANCE, 2021/12/14, Add for quality information update 4030 final long startTime = SystemClock.uptimeMillis(); 4031 performLayout(lp, mWidth, mHeight); 4032 ExtLoader.type(IOplusJankMonitorExt.class).create().setLaunchStageTime(ActivityThread.currentProcessName(), "performLayout", startTime); 4033 //#endif /* OPLUS_EXTENSION_HOOK */ 4034 // #ifdef OPLUS_EXTENSION_HOOK 4035 // Guofu.Yang@ANDROID.WMS, 2018/02/23, [OSP-1634] add for Screen mode. 4036 mViewRootImplExt.setRefreshRateIfNeed((mView instanceof ViewGroup), mContext, 4037 mView, mWindow); 4038 // #endif /* OPLUS_EXTENSION_HOOK */ 4039 4040 // By this point all views have been sized and positioned 4041 // We can compute the transparent area 4042 4043 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 4044 // start out transparent 4045 // TODO: AVOID THAT CALL BY CACHING THE RESULT? 4046 host.getLocationInWindow(mTmpLocation); 4047 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1], 4048 mTmpLocation[0] + host.mRight - host.mLeft, 4049 mTmpLocation[1] + host.mBottom - host.mTop); 4050 4051 host.gatherTransparentRegion(mTransparentRegion); 4052 if (mTranslator != null) { 4053 mTranslator.translateRegionInWindowToScreen(mTransparentRegion); 4054 } 4055 4056 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) { 4057 mPreviousTransparentRegion.set(mTransparentRegion); 4058 mFullRedrawNeeded = true; 4059 // TODO: Ideally we would do this in prepareSurfaces, 4060 // but prepareSurfaces is currently working under 4061 // the assumption that we paused the render thread 4062 // via the WM relayout code path. We probably eventually 4063 // want to synchronize transparent region hint changes 4064 // with draws. 4065 SurfaceControl sc = getSurfaceControl(); 4066 if (sc.isValid()) { 4067 mTransaction.setTransparentRegionHint(sc, mTransparentRegion).apply(); 4068 } 4069 } 4070 } 4071 4072 if (DBG) { 4073 System.out.println("======================================"); 4074 System.out.println("performTraversals -- after setFrame"); 4075 host.debug(); 4076 } 4077 } 4078 4079 boolean didUseTransaction = false; 4080 // These callbacks will trigger SurfaceView SurfaceHolder.Callbacks and must be invoked 4081 // after the measure pass. If its invoked before the measure pass and the app modifies 4082 // the view hierarchy in the callbacks, we could leave the views in a broken state. 4083 if (surfaceCreated) { 4084 notifySurfaceCreated(mTransaction); 4085 didUseTransaction = true; 4086 } else if (surfaceReplaced) { 4087 notifySurfaceReplaced(mTransaction); 4088 didUseTransaction = true; 4089 } else if (surfaceDestroyed) { 4090 notifySurfaceDestroyed(); 4091 } 4092 4093 if (didUseTransaction) { 4094 applyTransactionOnDraw(mTransaction); 4095 } 4096 4097 if (triggerGlobalLayoutListener) { 4098 mAttachInfo.mRecomputeGlobalAttributes = false; 4099 mAttachInfo.mTreeObserver.dispatchOnGlobalLayout(); 4100 } 4101 4102 Rect contentInsets = null; 4103 Rect visibleInsets = null; 4104 Region touchableRegion = null; 4105 int touchableInsetMode = TOUCHABLE_INSETS_REGION; 4106 boolean computedInternalInsets = false; 4107 if (computesInternalInsets) { 4108 final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets; 4109 4110 // Clear the original insets. 4111 insets.reset(); 4112 4113 // Compute new insets in place. 4114 mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 4115 mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty(); 4116 4117 // Tell the window manager. 4118 if (insetsPending || !mLastGivenInsets.equals(insets)) { 4119 mLastGivenInsets.set(insets); 4120 4121 // Translate insets to screen coordinates if needed. 4122 if (mTranslator != null) { 4123 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 4124 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 4125 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 4126 } else { 4127 contentInsets = insets.contentInsets; 4128 visibleInsets = insets.visibleInsets; 4129 touchableRegion = insets.touchableRegion; 4130 } 4131 computedInternalInsets = true; 4132 } 4133 touchableInsetMode = insets.mTouchableInsets; 4134 } 4135 boolean needsSetInsets = computedInternalInsets; 4136 needsSetInsets |= !Objects.equals(mPreviousTouchableRegion, mTouchableRegion) && 4137 (mTouchableRegion != null); 4138 if (needsSetInsets) { 4139 if (mTouchableRegion != null) { 4140 if (mPreviousTouchableRegion == null) { 4141 mPreviousTouchableRegion = new Region(); 4142 } 4143 mPreviousTouchableRegion.set(mTouchableRegion); 4144 if (touchableInsetMode != TOUCHABLE_INSETS_REGION) { 4145 Log.e(mTag, "Setting touchableInsetMode to non TOUCHABLE_INSETS_REGION" + 4146 " from OnComputeInternalInsets, while also using setTouchableRegion" + 4147 " causes setTouchableRegion to be ignored"); 4148 } 4149 } else { 4150 mPreviousTouchableRegion = null; 4151 } 4152 if (contentInsets == null) contentInsets = new Rect(0,0,0,0); 4153 if (visibleInsets == null) visibleInsets = new Rect(0,0,0,0); 4154 if (touchableRegion == null) { 4155 touchableRegion = mTouchableRegion; 4156 } else if (touchableRegion != null && mTouchableRegion != null) { 4157 touchableRegion.op(touchableRegion, mTouchableRegion, Region.Op.UNION); 4158 } 4159 try { 4160 mWindowSession.setInsets(mWindow, touchableInsetMode, 4161 contentInsets, visibleInsets, touchableRegion); 4162 } catch (RemoteException e) { 4163 throw e.rethrowFromSystemServer(); 4164 } 4165 } else if (mTouchableRegion == null && mPreviousTouchableRegion != null) { 4166 mPreviousTouchableRegion = null; 4167 try { 4168 mWindowSession.clearTouchableRegion(mWindow); 4169 } catch (RemoteException e) { 4170 throw e.rethrowFromSystemServer(); 4171 } 4172 } 4173 4174 if (mFirst) { 4175 if (sAlwaysAssignFocus || !isInTouchMode()) { 4176 // handle first focus request 4177 if (DEBUG_INPUT_RESIZE) { 4178 Log.v(mTag, "First: mView.hasFocus()=" + mView.hasFocus()); 4179 } 4180 if (mView != null) { 4181 if (!mView.hasFocus()) { 4182 mView.restoreDefaultFocus(); 4183 if (DEBUG_INPUT_RESIZE) { 4184 Log.v(mTag, "First: requested focused view=" + mView.findFocus()); 4185 } 4186 } else { 4187 if (DEBUG_INPUT_RESIZE) { 4188 Log.v(mTag, "First: existing focused view=" + mView.findFocus()); 4189 } 4190 } 4191 } 4192 } else { 4193 // Some views (like ScrollView) won't hand focus to descendants that aren't within 4194 // their viewport. Before layout, there's a good change these views are size 0 4195 // which means no children can get focus. After layout, this view now has size, but 4196 // is not guaranteed to hand-off focus to a focusable child (specifically, the edge- 4197 // case where the child has a size prior to layout and thus won't trigger 4198 // focusableViewAvailable). 4199 View focused = mView.findFocus(); 4200 if (focused instanceof ViewGroup 4201 && ((ViewGroup) focused).getDescendantFocusability() 4202 == ViewGroup.FOCUS_AFTER_DESCENDANTS) { 4203 focused.restoreDefaultFocus(); 4204 } 4205 } 4206 //#ifdef OPLUS_EXTENSION_HOOK 4207 //Honzhu@ANDROID.VIEW, 2020/07/20, add for Optimize app startup speed 4208 mViewRootImplExt.checkIsFragmentAnimUI(); 4209 //#endif /* OPLUS_EXTENSION_HOOK */ 4210 } 4211 4212 final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible; 4213 if (changedVisibility) { 4214 maybeFireAccessibilityWindowStateChangedEvent(); 4215 } 4216 4217 mFirst = false; 4218 mWillDrawSoon = false; 4219 mNewSurfaceNeeded = false; 4220 mViewVisibility = viewVisibility; 4221 4222 final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible; 4223 mImeFocusController.onTraversal(hasWindowFocus, mWindowAttributes); 4224 4225 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 4226 reportNextDraw("first_relayout"); 4227 } 4228 4229 mCheckIfCanDraw = isSyncRequest || cancelDraw; 4230 4231 boolean cancelDueToPreDrawListener = mAttachInfo.mTreeObserver.dispatchOnPreDraw(); 4232 boolean cancelAndRedraw = cancelDueToPreDrawListener 4233 || (cancelDraw && mDrewOnceForSync); 4234 //#ifdef OPLUS_EXTENSION_HOOK 4235 //Guofu.Yang@@ANDROID.WMS 2023/03/14,Add for fixed bug 5268134,5132324 4236 cancelAndRedraw = mViewRootImplExt.cancelAndRedraw(mTag,cancelAndRedraw,isViewVisible,mSyncBuffer); 4237 //#endif // OPLUS_EXTENSION_HOOK 4238 4239 if (!cancelAndRedraw) { 4240 // A sync was already requested before the WMS requested sync. This means we need to 4241 // sync the buffer, regardless if WMS wants to sync the buffer. 4242 if (mActiveSurfaceSyncGroup != null) { 4243 mSyncBuffer = true; 4244 } 4245 4246 createSyncIfNeeded(); 4247 notifyDrawStarted(isInWMSRequestedSync()); 4248 mDrewOnceForSync = true; 4249 4250 // If the active SSG is also requesting to sync a buffer, the following needs to happen 4251 // 1. Ensure we keep track of the number of active syncs to know when to disable RT 4252 // RT animations that conflict with syncing a buffer. 4253 // 2. Add a safeguard SSG to prevent multiple SSG that sync buffers from being submitted 4254 // out of order. 4255 if (mActiveSurfaceSyncGroup != null && mSyncBuffer) { 4256 updateSyncInProgressCount(mActiveSurfaceSyncGroup); 4257 safeguardOverlappingSyncs(mActiveSurfaceSyncGroup); 4258 } 4259 } 4260 // #ifdef OPLUS_FEATURE_EXTENSION_HOOKS 4261 // Bard.Zhang@Android.UIFramework 2023-10-30 Add for : debug 6429918 4262 else { 4263 Log.w(TAG, "cancelAndRedraw cancelDueToPreDrawListener " + cancelDueToPreDrawListener 4264 + " cancelDraw " + cancelDraw 4265 + " mDrewOnceForSync " + mDrewOnceForSync 4266 + " isSyncRequest " + isSyncRequest); 4267 } 4268 // #endif /* OPLUS_FEATURE_EXTENSION_HOOKS */ 4269 4270 if (!isViewVisible) { 4271 mLastPerformTraversalsSkipDrawReason = "view_not_visible"; 4272 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 4273 for (int i = 0; i < mPendingTransitions.size(); ++i) { 4274 mPendingTransitions.get(i).endChangingAnimations(); 4275 } 4276 mPendingTransitions.clear(); 4277 } 4278 4279 if (mActiveSurfaceSyncGroup != null) { 4280 mActiveSurfaceSyncGroup.markSyncReady(); 4281 } 4282 } else if (cancelAndRedraw) { 4283 mLastPerformTraversalsSkipDrawReason = cancelDueToPreDrawListener 4284 ? "predraw_" + mAttachInfo.mTreeObserver.getLastDispatchOnPreDrawCanceledReason() 4285 : "cancel_" + cancelReason; 4286 // Try again 4287 scheduleTraversals(); 4288 } else { 4289 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 4290 for (int i = 0; i < mPendingTransitions.size(); ++i) { 4291 mPendingTransitions.get(i).startChangingAnimations(); 4292 } 4293 mPendingTransitions.clear(); 4294 } 4295 if (!performDraw(mActiveSurfaceSyncGroup) && mActiveSurfaceSyncGroup != null) { 4296 mActiveSurfaceSyncGroup.markSyncReady(); 4297 } 4298 } 4299 4300 if (mAttachInfo.mContentCaptureEvents != null) { 4301 notifyContentCaptureEvents(); 4302 } 4303 mIsInTraversal = false; 4304 mRelayoutRequested = false; 4305 4306 if (!cancelAndRedraw) { 4307 mReportNextDraw = false; 4308 mLastReportNextDrawReason = null; 4309 mActiveSurfaceSyncGroup = null; 4310 mSyncBuffer = false; 4311 if (isInWMSRequestedSync()) { 4312 mWmsRequestSyncGroup.markSyncReady(); 4313 mWmsRequestSyncGroup = null; 4314 mWmsRequestSyncGroupState = WMS_SYNC_NONE; 4315 } 4316 } 4317 4318 // #ifdef OPLUS_FEATURE_VIEW_DEBUG 4319 // Bard.Zhang@Android.UIFramework 2023-01-28 Add for : view debug 4320 mViewRootImplExt.markOnPerformTraversalsEnd(host); 4321 // #endif /* OPLUS_FEATURE_VIEW_DEBUG */ 4322 4323 // #ifdef OPLUS_EXTENSION_HOOK 4324 // yanliang@Android.Performance 2023-02-13 Add for Optimize sliding effect 4325 mViewRootImplExt.checkPendingBufferCountSetting(mSurface); 4326 // #endif /*OPLUS_EXTENSION_HOOK*/ 4327 } 4328 解释里面的每行代码
最新发布
09-24
protected-mode no port 6379 tcp-backlog 511 timeout 0 tcp-keepalive 300 daemonize no pidfile /var/run/redis_6379.pid loglevel notice logfile "" databases 16 always-show-logo no set-proc-title yes proc-title-template "{title} {listen-addr} {server-mode}" stop-writes-on-bgsave-error yes rdbcompression yes rdbchecksum yes dbfilename dump.rdb rdb-del-sync-files no dir ./ replica-serve-stale-data yes replica-read-only yes repl-diskless-sync no repl-diskless-sync-delay 5 repl-diskless-load disabled repl-disable-tcp-nodelay no replica-priority 100 acllog-max-len 128 requirepass Guyuan@2021 # New users are initialized with restrictive permissions by default, via the # equivalent of this ACL rule 'off resetkeys -@all'. Starting with Redis 6.2, it # is possible to manage access to Pub/Sub channels with ACL rules as well. The # default Pub/Sub channels permission if new users is controlled by the # acl-pubsub-default configuration directive, which accepts one of these values: # # allchannels: grants access to all Pub/Sub channels # resetchannels: revokes access to all Pub/Sub channels # # To ensure backward compatibility while upgrading Redis 6.0, acl-pubsub-default # defaults to the 'allchannels' permission. # # Future compatibility note: it is very likely that in a future version of Redis # the directive's default of 'allchannels' will be changed to 'resetchannels' in # order to provide better out-of-the-box Pub/Sub security. Therefore, it is # recommended that you explicitly define Pub/Sub permissions for all users # rather then rely on implicit default values. Once you've set explicit # Pub/Sub for all existing users, you should uncomment the following line. # # acl-pubsub-default resetchannels # Command renaming (DEPRECATED). # # ------------------------------------------------------------------------ # WARNING: avoid using this option if possible. Instead use ACLs to remove # commands from the default user, and put them only in some admin user you # create for administrative purposes. # ------------------------------------------------------------------------ # # It is possible to change the name of dangerous commands in a shared # environment. For instance the CONFIG command may be renamed into something # hard to guess so that it will still be available for internal-use tools # but not available for general clients. # # Example: # # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 # # It is also possible to completely kill a command by renaming it into # an empty string: # # rename-command CONFIG "" # # Please note that changing the name of commands that are logged into the # AOF file or transmitted to replicas may cause problems. ################################### CLIENTS #################################### # Set the max number of connected clients at the same time. By default # this limit is set to 10000 clients, however if the Redis server is not # able to configure the process file limit to allow for the specified limit # the max number of allowed clients is set to the current file limit # minus 32 (as Redis reserves a few file descriptors for internal uses). # # Once the limit is reached Redis will close all the new connections sending # an error 'max number of clients reached'. # # IMPORTANT: When Redis Cluster is used, the max number of connections is also # shared with the cluster bus: every node in the cluster will use two # connections, one incoming and another outgoing. It is important to size the # limit accordingly in case of very large clusters. # # maxclients 10000 ############################## MEMORY MANAGEMENT ################################ # Set a memory usage limit to the specified amount of bytes. # When the memory limit is reached Redis will try to remove keys # according to the eviction policy selected (see maxmemory-policy). # # If Redis can't remove keys according to the policy, or if the policy is # set to 'noeviction', Redis will start to reply with errors to commands # that would use more memory, like SET, LPUSH, and so on, and will continue # to reply to read-only commands like GET. # # This option is usually useful when using Redis as an LRU or LFU cache, or to # set a hard memory limit for an instance (using the 'noeviction' policy). # # WARNING: If you have replicas attached to an instance with maxmemory on, # the size of the output buffers needed to feed the replicas are subtracted # from the used memory count, so that network problems / resyncs will # not trigger a loop where keys are evicted, and in turn the output # buffer of replicas is full with DELs of keys evicted triggering the deletion # of more keys, and so forth until the database is completely emptied. # # In short... if you have replicas attached it is suggested that you set a lower # limit for maxmemory so that there is some free RAM on the system for replica # output buffers (but this is not needed if the policy is 'noeviction'). # # maxmemory <bytes> # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory # is reached. You can select one from the following behaviors: # # volatile-lru -> Evict using approximated LRU, only keys with an expire set. # allkeys-lru -> Evict any key using approximated LRU. # volatile-lfu -> Evict using approximated LFU, only keys with an expire set. # allkeys-lfu -> Evict any key using approximated LFU. # volatile-random -> Remove a random key having an expire set. # allkeys-random -> Remove a random key, any key. # volatile-ttl -> Remove the key with the nearest expire time (minor TTL) # noeviction -> Don't evict anything, just return an error on write operations. # # LRU means Least Recently Used # LFU means Least Frequently Used # # Both LRU, LFU and volatile-ttl are implemented using approximated # randomized algorithms. # # Note: with any of the above policies, when there are no suitable keys for # eviction, Redis will return an error on write operations that require # more memory. These are usually commands that create new keys, add data or # modify existing keys. A few examples are: SET, INCR, HSET, LPUSH, SUNIONSTORE, # SORT (due to the STORE argument), and EXEC (if the transaction includes any # command that requires memory). # # The default is: # # maxmemory-policy noeviction # LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated # algorithms (in order to save memory), so you can tune it for speed or # accuracy. By default Redis will check five keys and pick the one that was # used least recently, you can change the sample size using the following # configuration directive. # # The default of 5 produces good enough results. 10 Approximates very closely # true LRU but costs more CPU. 3 is faster but not very accurate. # # maxmemory-samples 5 # Eviction processing is designed to function well with the default setting. # If there is an unusually large amount of write traffic, this value may need to # be increased. Decreasing this value may reduce latency at the risk of # eviction processing effectiveness # 0 = minimum latency, 10 = default, 100 = process without regard to latency # # maxmemory-eviction-tenacity 10 # Starting from Redis 5, by default a replica will ignore its maxmemory setting # (unless it is promoted to master after a failover or manually). It means # that the eviction of keys will be just handled by the master, sending the # DEL commands to the replica as keys evict in the master side. # # This behavior ensures that masters and replicas stay consistent, and is usually # what you want, however if your replica is writable, or you want the replica # to have a different memory setting, and you are sure all the writes performed # to the replica are idempotent, then you may change this default (but be sure # to understand what you are doing). # # Note that since the replica by default does not evict, it may end using more # memory than the one set via maxmemory (there are certain buffers that may # be larger on the replica, or data structures may sometimes take more memory # and so forth). So make sure you monitor your replicas and make sure they # have enough memory to never hit a real out-of-memory condition before the # master hits the configured maxmemory setting. # # replica-ignore-maxmemory yes # Redis reclaims expired keys in two ways: upon access when those keys are # found to be expired, and also in background, in what is called the # "active expire key". The key space is slowly and interactively scanned # looking for expired keys to reclaim, so that it is possible to free memory # of keys that are expired and will never be accessed again in a short time. # # The default effort of the expire cycle will try to avoid having more than # ten percent of expired keys still in memory, and will try to avoid consuming # more than 25% of total memory and to add latency to the system. However # it is possible to increase the expire "effort" that is normally set to # "1", to a greater value, up to the value "10". At its maximum value the # system will use more CPU, longer cycles (and technically may introduce # more latency), and will tolerate less already expired keys still present # in the system. It's a tradeoff between memory, CPU and latency. # # active-expire-effort 1 ############################# LAZY FREEING #################################### # Redis has two primitives to delete keys. One is called DEL and is a blocking # deletion of the object. It means that the server stops processing new commands # in order to reclaim all the memory associated with an object in a synchronous # way. If the key deleted is associated with a small object, the time needed # in order to execute the DEL command is very small and comparable to most other # O(1) or O(log_N) commands in Redis. However if the key is associated with an # aggregated value containing millions of elements, the server can block for # a long time (even seconds) in order to complete the operation. # # For the above reasons Redis also offers non blocking deletion primitives # such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and # FLUSHDB commands, in order to reclaim memory in background. Those commands # are executed in constant time. Another thread will incrementally free the # object in the background as fast as possible. # # DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled. # It's up to the design of the application to understand when it is a good # idea to use one or the other. However the Redis server sometimes has to # delete keys or flush the whole database as a side effect of other operations. # Specifically Redis deletes objects independently of a user call in the # following scenarios: # # 1) On eviction, because of the maxmemory and maxmemory policy configurations, # in order to make room for new data, without going over the specified # memory limit. # 2) Because of expire: when a key with an associated time to live (see the # EXPIRE command) must be deleted from memory. # 3) Because of a side effect of a command that stores data on a key that may # already exist. For example the RENAME command may delete the old key # content when it is replaced with another one. Similarly SUNIONSTORE # or SORT with STORE option may delete existing keys. The SET command # itself removes any old content of the specified key in order to replace # it with the specified string. # 4) During replication, when a replica performs a full resynchronization with # its master, the content of the whole database is removed in order to # load the RDB file just transferred. # # In all the above cases the default is to delete objects in a blocking way, # like if DEL was called. However you can configure each case specifically # in order to instead release memory in a non-blocking way like if UNLINK # was called, using the following configuration directives. lazyfree-lazy-eviction no lazyfree-lazy-expire no lazyfree-lazy-server-del no replica-lazy-flush no # It is also possible, for the case when to replace the user code DEL calls # with UNLINK calls is not easy, to modify the default behavior of the DEL # command to act exactly like UNLINK, using the following configuration # directive: lazyfree-lazy-user-del no # FLUSHDB, FLUSHALL, and SCRIPT FLUSH support both asynchronous and synchronous # deletion, which can be controlled by passing the [SYNC|ASYNC] flags into the # commands. When neither flag is passed, this directive will be used to determine # if the data should be deleted asynchronously. lazyfree-lazy-user-flush no ################################ THREADED I/O ################################# # Redis is mostly single threaded, however there are certain threaded # operations such as UNLINK, slow I/O accesses and other things that are # performed on side threads. # # Now it is also possible to handle Redis clients socket reads and writes # in different I/O threads. Since especially writing is so slow, normally # Redis users use pipelining in order to speed up the Redis performances per # core, and spawn multiple instances in order to scale more. Using I/O # threads it is possible to easily speedup two times Redis without resorting # to pipelining nor sharding of the instance. # # By default threading is disabled, we suggest enabling it only in machines # that have at least 4 or more cores, leaving at least one spare core. # Using more than 8 threads is unlikely to help much. We also recommend using # threaded I/O only if you actually have performance problems, with Redis # instances being able to use a quite big percentage of CPU time, otherwise # there is no point in using this feature. # # So for instance if you have a four cores boxes, try to use 2 or 3 I/O # threads, if you have a 8 cores, try to use 6 threads. In order to # enable I/O threads use the following configuration directive: # # io-threads 4 # # Setting io-threads to 1 will just use the main thread as usual. # When I/O threads are enabled, we only use threads for writes, that is # to thread the write(2) syscall and transfer the client buffers to the # socket. However it is also possible to enable threading of reads and # protocol parsing using the following configuration directive, by setting # it to yes: # # io-threads-do-reads no # # Usually threading reads doesn't help much. # # NOTE 1: This configuration directive cannot be changed at runtime via # CONFIG SET. Aso this feature currently does not work when SSL is # enabled. # # NOTE 2: If you want to test the Redis speedup using redis-benchmark, make # sure you also run the benchmark itself in threaded mode, using the # --threads option to match the number of Redis threads, otherwise you'll not # be able to notice the improvements. ############################ KERNEL OOM CONTROL ############################## # On Linux, it is possible to hint the kernel OOM killer on what processes # should be killed first when out of memory. # # Enabling this feature makes Redis actively control the oom_score_adj value # for all its processes, depending on their role. The default scores will # attempt to have background child processes killed before all others, and # replicas killed before masters. # # Redis supports three options: # # no: Don't make changes to oom-score-adj (default). # yes: Alias to "relative" see below. # absolute: Values in oom-score-adj-values are written as is to the kernel. # relative: Values are used relative to the initial value of oom_score_adj when # the server starts and are then clamped to a range of -1000 to 1000. # Because typically the initial value is 0, they will often match the # absolute values. oom-score-adj no # When oom-score-adj is used, this directive controls the specific values used # for master, replica and background child processes. Values range -2000 to # 2000 (higher means more likely to be killed). # # Unprivileged processes (not root, and without CAP_SYS_RESOURCE capabilities) # can freely increase their value, but not decrease it below its initial # settings. This means that setting oom-score-adj to "relative" and setting the # oom-score-adj-values to positive values will always succeed. oom-score-adj-values 0 200 800 #################### KERNEL transparent hugepage CONTROL ###################### # Usually the kernel Transparent Huge Pages control is set to "madvise" or # or "never" by default (/sys/kernel/mm/transparent_hugepage/enabled), in which # case this config has no effect. On systems in which it is set to "always", # redis will attempt to disable it specifically for the redis process in order # to avoid latency problems specifically with fork(2) and CoW. # If for some reason you prefer to keep it enabled, you can set this config to # "no" and the kernel global to "always". disable-thp yes ############################## APPEND ONLY MODE ############################### # By default Redis asynchronously dumps the dataset on disk. This mode is # good enough in many applications, but an issue with the Redis process or # a power outage may result into a few minutes of writes lost (depending on # the configured save points). # # The Append Only File is an alternative persistence mode that provides # much better durability. For instance using the default data fsync policy # (see later in the config file) Redis can lose just one second of writes in a # dramatic event like a server power outage, or a single write if something # wrong with the Redis process itself happens, but the operating system is # still running correctly. # # AOF and RDB persistence can be enabled at the same time without problems. # If the AOF is enabled on startup Redis will load the AOF, that is the file # with the better durability guarantees. # # Please check https://redis.io/topics/persistence for more information. appendonly yes # The name of the append only file (default: "appendonly.aof") appendfilename "appendonly.aof" # The fsync() call tells the Operating System to actually write data on disk # instead of waiting for more data in the output buffer. Some OS will really flush # data on disk, some other OS will just try to do it ASAP. # # Redis supports three different modes: # # no: don't fsync, just let the OS flush the data when it wants. Faster. # always: fsync after every write to the append only log. Slow, Safest. # everysec: fsync only one time every second. Compromise. # # The default is "everysec", as that's usually the right compromise between # speed and data safety. It's up to you to understand if you can relax this to # "no" that will let the operating system flush the output buffer when # it wants, for better performances (but if you can live with the idea of # some data loss consider the default persistence mode that's snapshotting), # or on the contrary, use "always" that's very slow but a bit safer than # everysec. # # More details please check the following article: # http://antirez.com/post/redis-persistence-demystified.html # # If unsure, use "everysec". # appendfsync always appendfsync everysec # appendfsync no # When the AOF fsync policy is set to always or everysec, and a background # saving process (a background save or AOF log background rewriting) is # performing a lot of I/O against the disk, in some Linux configurations # Redis may block too long on the fsync() call. Note that there is no fix for # this currently, as even performing fsync in a different thread will block # our synchronous write(2) call. # # In order to mitigate this problem it's possible to use the following option # that will prevent fsync() from being called in the main process while a # BGSAVE or BGREWRITEAOF is in progress. # # This means that while another child is saving, the durability of Redis is # the same as "appendfsync none". In practical terms, this means that it is # possible to lose up to 30 seconds of log in the worst scenario (with the # default Linux settings). # # If you have latency problems turn this to "yes". Otherwise leave it as # "no" that is the safest pick from the point of view of durability. no-appendfsync-on-rewrite no # Automatic rewrite of the append only file. # Redis is able to automatically rewrite the log file implicitly calling # BGREWRITEAOF when the AOF log size grows by the specified percentage. # # This is how it works: Redis remembers the size of the AOF file after the # latest rewrite (if no rewrite has happened since the restart, the size of # the AOF at startup is used). # # This base size is compared to the current size. If the current size is # bigger than the specified percentage, the rewrite is triggered. Also # you need to specify a minimal size for the AOF file to be rewritten, this # is useful to avoid rewriting the AOF file even if the percentage increase # is reached but it is still pretty small. # # Specify a percentage of zero in order to disable the automatic AOF # rewrite feature. auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb # An AOF file may be found to be truncated at the end during the Redis # startup process, when the AOF data gets loaded back into memory. # This may happen when the system where Redis is running # crashes, especially when an ext4 filesystem is mounted without the # data=ordered option (however this can't happen when Redis itself # crashes or aborts but the operating system still works correctly). # # Redis can either exit with an error when this happens, or load as much # data as possible (the default now) and start if the AOF file is found # to be truncated at the end. The following option controls this behavior. # # If aof-load-truncated is set to yes, a truncated AOF file is loaded and # the Redis server starts emitting a log to inform the user of the event. # Otherwise if the option is set to no, the server aborts with an error # and refuses to start. When the option is set to no, the user requires # to fix the AOF file using the "redis-check-aof" utility before to restart # the server. # # Note that if the AOF file will be found to be corrupted in the middle # the server will still exit with an error. This option only applies when # Redis will try to read more data from the AOF file but not enough bytes # will be found. aof-load-truncated yes # When rewriting the AOF file, Redis is able to use an RDB preamble in the # AOF file for faster rewrites and recoveries. When this option is turned # on the rewritten AOF file is composed of two different stanzas: # # [RDB file][AOF tail] # # When loading, Redis recognizes that the AOF file starts with the "REDIS" # string and loads the prefixed RDB file, then continues loading the AOF # tail. aof-use-rdb-preamble yes ################################ LUA SCRIPTING ############################### # Max execution time of a Lua script in milliseconds. # # If the maximum execution time is reached Redis will log that a script is # still in execution after the maximum allowed time and will start to # reply to queries with an error. # # When a long running script exceeds the maximum execution time only the # SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be # used to stop a script that did not yet call any write commands. The second # is the only way to shut down the server in the case a write command was # already issued by the script but the user doesn't want to wait for the natural # termination of the script. # # Set it to 0 or a negative value for unlimited execution without warnings. lua-time-limit 5000 ################################ REDIS CLUSTER ############################### # Normal Redis instances can't be part of a Redis Cluster; only nodes that are # started as cluster nodes can. In order to start a Redis instance as a # cluster node enable the cluster support uncommenting the following: # # cluster-enabled yes # Every cluster node has a cluster configuration file. This file is not # intended to be edited by hand. It is created and updated by Redis nodes. # Every Redis Cluster node requires a different cluster configuration file. # Make sure that instances running in the same system do not have # overlapping cluster configuration file names. # # cluster-config-file nodes-6379.conf # Cluster node timeout is the amount of milliseconds a node must be unreachable # for it to be considered in failure state. # Most other internal time limits are a multiple of the node timeout. # # cluster-node-timeout 15000 # A replica of a failing master will avoid to start a failover if its data # looks too old. # # There is no simple way for a replica to actually have an exact measure of # its "data age", so the following two checks are performed: # # 1) If there are multiple replicas able to failover, they exchange messages # in order to try to give an advantage to the replica with the best # replication offset (more data from the master processed). # Replicas will try to get their rank by offset, and apply to the start # of the failover a delay proportional to their rank. # # 2) Every single replica computes the time of the last interaction with # its master. This can be the last ping or command received (if the master # is still in the "connected" state), or the time that elapsed since the # disconnection with the master (if the replication link is currently down). # If the last interaction is too old, the replica will not try to failover # at all. # # The point "2" can be tuned by user. Specifically a replica will not perform # the failover if, since the last interaction with the master, the time # elapsed is greater than: # # (node-timeout * cluster-replica-validity-factor) + repl-ping-replica-period # # So for example if node-timeout is 30 seconds, and the cluster-replica-validity-factor # is 10, and assuming a default repl-ping-replica-period of 10 seconds, the # replica will not try to failover if it was not able to talk with the master # for longer than 310 seconds. # # A large cluster-replica-validity-factor may allow replicas with too old data to failover # a master, while a too small value may prevent the cluster from being able to # elect a replica at all. # # For maximum availability, it is possible to set the cluster-replica-validity-factor # to a value of 0, which means, that replicas will always try to failover the # master regardless of the last time they interacted with the master. # (However they'll always try to apply a delay proportional to their # offset rank). # # Zero is the only value able to guarantee that when all the partitions heal # the cluster will always be able to continue. # # cluster-replica-validity-factor 10 # Cluster replicas are able to migrate to orphaned masters, that are masters # that are left without working replicas. This improves the cluster ability # to resist to failures as otherwise an orphaned master can't be failed over # in case of failure if it has no working replicas. # # Replicas migrate to orphaned masters only if there are still at least a # given number of other working replicas for their old master. This number # is the "migration barrier". A migration barrier of 1 means that a replica # will migrate only if there is at least 1 other working replica for its master # and so forth. It usually reflects the number of replicas you want for every # master in your cluster. # # Default is 1 (replicas migrate only if their masters remain with at least # one replica). To disable migration just set it to a very large value or # set cluster-allow-replica-migration to 'no'. # A value of 0 can be set but is useful only for debugging and dangerous # in production. # # cluster-migration-barrier 1 # Turning off this option allows to use less automatic cluster configuration. # It both disables migration to orphaned masters and migration from masters # that became empty. # # Default is 'yes' (allow automatic migrations). # # cluster-allow-replica-migration yes # By default Redis Cluster nodes stop accepting queries if they detect there # is at least a hash slot uncovered (no available node is serving it). # This way if the cluster is partially down (for example a range of hash slots # are no longer covered) all the cluster becomes, eventually, unavailable. # It automatically returns available as soon as all the slots are covered again. # # However sometimes you want the subset of the cluster which is working, # to continue to accept queries for the part of the key space that is still # covered. In order to do so, just set the cluster-require-full-coverage # option to no. # # cluster-require-full-coverage yes # This option, when set to yes, prevents replicas from trying to failover its # master during master failures. However the replica can still perform a # manual failover, if forced to do so. # # This is useful in different scenarios, especially in the case of multiple # data center operations, where we want one side to never be promoted if not # in the case of a total DC failure. # # cluster-replica-no-failover no # This option, when set to yes, allows nodes to serve read traffic while the # the cluster is in a down state, as long as it believes it owns the slots. # # This is useful for two cases. The first case is for when an application # doesn't require consistency of data during node failures or network partitions. # One example of this is a cache, where as long as the node has the data it # should be able to serve it. # # The second use case is for configurations that don't meet the recommended # three shards but want to enable cluster mode and scale later. A # master outage in a 1 or 2 shard configuration causes a read/write outage to the # entire cluster without this option set, with it set there is only a write outage. # Without a quorum of masters, slot ownership will not change automatically. # # cluster-allow-reads-when-down no # In order to setup your cluster make sure to read the documentation # available at https://redis.io web site. ########################## CLUSTER DOCKER/NAT support ######################## # In certain deployments, Redis Cluster nodes address discovery fails, because # addresses are NAT-ted or because ports are forwarded (the typical case is # Docker and other containers). # # In order to make Redis Cluster working in such environments, a static # configuration where each node knows its public address is needed. The # following four options are used for this scope, and are: # # * cluster-announce-ip # * cluster-announce-port # * cluster-announce-tls-port # * cluster-announce-bus-port # # Each instructs the node about its address, client ports (for connections # without and with TLS) and cluster message bus port. The information is then # published in the header of the bus packets so that other nodes will be able to # correctly map the address of the node publishing the information. # # If cluster-tls is set to yes and cluster-announce-tls-port is omitted or set # to zero, then cluster-announce-port refers to the TLS port. Note also that # cluster-announce-tls-port has no effect if cluster-tls is set to no. # # If the above options are not used, the normal Redis Cluster auto-detection # will be used instead. # # Note that when remapped, the bus port may not be at the fixed offset of # clients port + 10000, so you can specify any port and bus-port depending # on how they get remapped. If the bus-port is not set, a fixed offset of # 10000 will be used as usual. # # Example: # # cluster-announce-ip 10.1.1.5 # cluster-announce-tls-port 6379 # cluster-announce-port 0 # cluster-announce-bus-port 6380 ################################## SLOW LOG ################################### # The Redis Slow Log is a system to log queries that exceeded a specified # execution time. The execution time does not include the I/O operations # like talking with the client, sending the reply and so forth, # but just the time needed to actually execute the command (this is the only # stage of command execution where the thread is blocked and can not serve # other requests in the meantime). # # You can configure the slow log with two parameters: one tells Redis # what is the execution time, in microseconds, to exceed in order for the # command to get logged, and the other parameter is the length of the # slow log. When a new command is logged the oldest one is removed from the # queue of logged commands. # The following time is expressed in microseconds, so 1000000 is equivalent # to one second. Note that a negative number disables the slow log, while # a value of zero forces the logging of every command. slowlog-log-slower-than 10000 # There is no limit to this length. Just be aware that it will consume memory. # You can reclaim memory used by the slow log with SLOWLOG RESET. slowlog-max-len 128 ################################ LATENCY MONITOR ############################## # The Redis latency monitoring subsystem samples different operations # at runtime in order to collect data related to possible sources of # latency of a Redis instance. # # Via the LATENCY command this information is available to the user that can # print graphs and obtain reports. # # The system only logs operations that were performed in a time equal or # greater than the amount of milliseconds specified via the # latency-monitor-threshold configuration directive. When its value is set # to zero, the latency monitor is turned off. # # By default latency monitoring is disabled since it is mostly not needed # if you don't have latency issues, and collecting data has a performance # impact, that while very small, can be measured under big load. Latency # monitoring can easily be enabled at runtime using the command # "CONFIG SET latency-monitor-threshold <milliseconds>" if needed. latency-monitor-threshold 0 ############################# EVENT NOTIFICATION ############################## # Redis can notify Pub/Sub clients about events happening in the key space. # This feature is documented at https://redis.io/topics/notifications # # For instance if keyspace events notification is enabled, and a client # performs a DEL operation on key "foo" stored in the Database 0, two # messages will be published via Pub/Sub: # # PUBLISH __keyspace@0__:foo del # PUBLISH __keyevent@0__:del foo # # It is possible to select the events that Redis will notify among a set # of classes. Every class is identified by a single character: # # K Keyspace events, published with __keyspace@<db>__ prefix. # E Keyevent events, published with __keyevent@<db>__ prefix. # g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... # $ String commands # l List commands # s Set commands # h Hash commands # z Sorted set commands # x Expired events (events generated every time a key expires) # e Evicted events (events generated when a key is evicted for maxmemory) # t Stream commands # d Module key type events # m Key-miss events (Note: It is not included in the 'A' class) # A Alias for g$lshzxetd, so that the "AKE" string means all the events # (Except key-miss events which are excluded from 'A' due to their # unique nature). # # The "notify-keyspace-events" takes as argument a string that is composed # of zero or multiple characters. The empty string means that notifications # are disabled. # # Example: to enable list and generic events, from the point of view of the # event name, use: # # notify-keyspace-events Elg # # Example 2: to get the stream of the expired keys subscribing to channel # name __keyevent@0__:expired use: # # notify-keyspace-events Ex # # By default all notifications are disabled because most users don't need # this feature and the feature has some overhead. Note that if you don't # specify at least one of K or E, no events will be delivered. notify-keyspace-events "" ############################### GOPHER SERVER ################################# # Redis contains an implementation of the Gopher protocol, as specified in # the RFC 1436 (https://www.ietf.org/rfc/rfc1436.txt). # # The Gopher protocol was very popular in the late '90s. It is an alternative # to the web, and the implementation both server and client side is so simple # that the Redis server has just 100 lines of code in order to implement this # support. # # What do you do with Gopher nowadays? Well Gopher never *really* died, and # lately there is a movement in order for the Gopher more hierarchical content # composed of just plain text documents to be resurrected. Some want a simpler # internet, others believe that the mainstream internet became too much # controlled, and it's cool to create an alternative space for people that # want a bit of fresh air. # # Anyway for the 10nth birthday of the Redis, we gave it the Gopher protocol # as a gift. # # --- HOW IT WORKS? --- # # The Redis Gopher support uses the inline protocol of Redis, and specifically # two kind of inline requests that were anyway illegal: an empty request # or any request that starts with "/" (there are no Redis commands starting # with such a slash). Normal RESP2/RESP3 requests are completely out of the # path of the Gopher protocol implementation and are served as usual as well. # # If you open a connection to Redis when Gopher is enabled and send it # a string like "/foo", if there is a key named "/foo" it is served via the # Gopher protocol. # # In order to create a real Gopher "hole" (the name of a Gopher site in Gopher # talking), you likely need a script like the following: # # https://github.com/antirez/gopher2redis # # --- SECURITY WARNING --- # # If you plan to put Redis on the internet in a publicly accessible address # to server Gopher pages MAKE SURE TO SET A PASSWORD to the instance. # Once a password is set: # # 1. The Gopher server (when enabled, not by default) will still serve # content via Gopher. # 2. However other commands cannot be called before the client will # authenticate. # # So use the 'requirepass' option to protect your instance. # # Note that Gopher is not currently supported when 'io-threads-do-reads' # is enabled. # # To enable Gopher support, uncomment the following line and set the option # from no (the default) to yes. # # gopher-enabled no ############################### ADVANCED CONFIG ############################### # Hashes are encoded using a memory efficient data structure when they have a # small number of entries, and the biggest entry does not exceed a given # threshold. These thresholds can be configured using the following directives. hash-max-ziplist-entries 512 hash-max-ziplist-value 64 # Lists are also encoded in a special way to save a lot of space. # The number of entries allowed per internal list node can be specified # as a fixed maximum size or a maximum number of elements. # For a fixed maximum size, use -5 through -1, meaning: # -5: max size: 64 Kb <-- not recommended for normal workloads # -4: max size: 32 Kb <-- not recommended # -3: max size: 16 Kb <-- probably not recommended # -2: max size: 8 Kb <-- good # -1: max size: 4 Kb <-- good # Positive numbers mean store up to _exactly_ that number of elements # per list node. # The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size), # but if your use case is unique, adjust the settings as necessary. list-max-ziplist-size -2 # Lists may also be compressed. # Compress depth is the number of quicklist ziplist nodes from *each* side of # the list to *exclude* from compression. The head and tail of the list # are always uncompressed for fast push/pop operations. Settings are: # 0: disable all list compression # 1: depth 1 means "don't start compressing until after 1 node into the list, # going from either the head or tail" # So: [head]->node->node->...->node->[tail] # [head], [tail] will always be uncompressed; inner nodes will compress. # 2: [head]->[next]->node->node->...->node->[prev]->[tail] # 2 here means: don't compress head or head->next or tail->prev or tail, # but compress all nodes between them. # 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail] # etc. list-compress-depth 0 # Sets have a special encoding in just one case: when a set is composed # of just strings that happen to be integers in radix 10 in the range # of 64 bit signed integers. # The following configuration setting sets the limit in the size of the # set in order to use this special memory saving encoding. set-max-intset-entries 512 # Similarly to hashes and lists, sorted sets are also specially encoded in # order to save a lot of space. This encoding is only used when the length and # elements of a sorted set are below the following limits: zset-max-ziplist-entries 128 zset-max-ziplist-value 64 # HyperLogLog sparse representation bytes limit. The limit includes the # 16 bytes header. When an HyperLogLog using the sparse representation crosses # this limit, it is converted into the dense representation. # # A value greater than 16000 is totally useless, since at that point the # dense representation is more memory efficient. # # The suggested value is ~ 3000 in order to have the benefits of # the space efficient encoding without slowing down too much PFADD, # which is O(N) with the sparse encoding. The value can be raised to # ~ 10000 when CPU is not a concern, but space is, and the data set is # composed of many HyperLogLogs with cardinality in the 0 - 15000 range. hll-sparse-max-bytes 3000 # Streams macro node max size / items. The stream data structure is a radix # tree of big nodes that encode multiple items inside. Using this configuration # it is possible to configure how big a single node can be in bytes, and the # maximum number of items it may contain before switching to a new node when # appending new stream entries. If any of the following settings are set to # zero, the limit is ignored, so for instance it is possible to set just a # max entries limit by setting max-bytes to 0 and max-entries to the desired # value. stream-node-max-bytes 4096 stream-node-max-entries 100 # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in # order to help rehashing the main Redis hash table (the one mapping top-level # keys to values). The hash table implementation Redis uses (see dict.c) # performs a lazy rehashing: the more operation you run into a hash table # that is rehashing, the more rehashing "steps" are performed, so if the # server is idle the rehashing is never complete and some more memory is used # by the hash table. # # The default is to use this millisecond 10 times every second in order to # actively rehash the main dictionaries, freeing memory when possible. # # If unsure: # use "activerehashing no" if you have hard latency requirements and it is # not a good thing in your environment that Redis can reply from time to time # to queries with 2 milliseconds delay. # # use "activerehashing yes" if you don't have such hard requirements but # want to free memory asap when possible. activerehashing yes # The client output buffer limits can be used to force disconnection of clients # that are not reading data from the server fast enough for some reason (a # common reason is that a Pub/Sub client can't consume messages as fast as the # publisher can produce them). # # The limit can be set differently for the three different classes of clients: # # normal -> normal clients including MONITOR clients # replica -> replica clients # pubsub -> clients subscribed to at least one pubsub channel or pattern # # The syntax of every client-output-buffer-limit directive is the following: # # client-output-buffer-limit <class> <hard limit> <soft limit> <soft seconds> # # A client is immediately disconnected once the hard limit is reached, or if # the soft limit is reached and remains reached for the specified number of # seconds (continuously). # So for instance if the hard limit is 32 megabytes and the soft limit is # 16 megabytes / 10 seconds, the client will get disconnected immediately # if the size of the output buffers reach 32 megabytes, but will also get # disconnected if the client reaches 16 megabytes and continuously overcomes # the limit for 10 seconds. # # By default normal clients are not limited because they don't receive data # without asking (in a push way), but just after a request, so only # asynchronous clients may create a scenario where data is requested faster # than it can read. # # Instead there is a default limit for pubsub and replica clients, since # subscribers and replicas receive data in a push fashion. # # Both the hard or the soft limit can be disabled by setting them to zero. client-output-buffer-limit normal 0 0 0 client-output-buffer-limit replica 256mb 64mb 60 client-output-buffer-limit pubsub 32mb 8mb 60 # Client query buffers accumulate new commands. They are limited to a fixed # amount by default in order to avoid that a protocol desynchronization (for # instance due to a bug in the client) will lead to unbound memory usage in # the query buffer. However you can configure it here if you have very special # needs, such us huge multi/exec requests or alike. # # client-query-buffer-limit 1gb # In the Redis protocol, bulk requests, that are, elements representing single # strings, are normally limited to 512 mb. However you can change this limit # here, but must be 1mb or greater # # proto-max-bulk-len 512mb # Redis calls an internal function to perform many background tasks, like # closing connections of clients in timeout, purging expired keys that are # never requested, and so forth. # # Not all tasks are performed with the same frequency, but Redis checks for # tasks to perform according to the specified "hz" value. # # By default "hz" is set to 10. Raising the value will use more CPU when # Redis is idle, but at the same time will make Redis more responsive when # there are many keys expiring at the same time, and timeouts may be # handled with more precision. # # The range is between 1 and 500, however a value over 100 is usually not # a good idea. Most users should use the default of 10 and raise this up to # 100 only in environments where very low latency is required. hz 10 # Normally it is useful to have an HZ value which is proportional to the # number of clients connected. This is useful in order, for instance, to # avoid too many clients are processed for each background task invocation # in order to avoid latency spikes. # # Since the default HZ value by default is conservatively set to 10, Redis # offers, and enables by default, the ability to use an adaptive HZ value # which will temporarily raise when there are many connected clients. # # When dynamic HZ is enabled, the actual configured HZ will be used # as a baseline, but multiples of the configured HZ value will be actually # used as needed once more clients are connected. In this way an idle # instance will use very little CPU time while a busy instance will be # more responsive. dynamic-hz yes # When a child rewrites the AOF file, if the following option is enabled # the file will be fsync-ed every 32 MB of data generated. This is useful # in order to commit the file to the disk more incrementally and avoid # big latency spikes. aof-rewrite-incremental-fsync yes # When redis saves RDB file, if the following option is enabled # the file will be fsync-ed every 32 MB of data generated. This is useful # in order to commit the file to the disk more incrementally and avoid # big latency spikes. rdb-save-incremental-fsync yes # Redis LFU eviction (see maxmemory setting) can be tuned. However it is a good # idea to start with the default settings and only change them after investigating # how to improve the performances and how the keys LFU change over time, which # is possible to inspect via the OBJECT FREQ command. # # There are two tunable parameters in the Redis LFU implementation: the # counter logarithm factor and the counter decay time. It is important to # understand what the two parameters mean before changing them. # # The LFU counter is just 8 bits per key, it's maximum value is 255, so Redis # uses a probabilistic increment with logarithmic behavior. Given the value # of the old counter, when a key is accessed, the counter is incremented in # this way: # # 1. A random number R between 0 and 1 is extracted. # 2. A probability P is calculated as 1/(old_value*lfu_log_factor+1). # 3. The counter is incremented only if R < P. # # The default lfu-log-factor is 10. This is a table of how the frequency # counter changes with a different number of accesses with different # logarithmic factors: # # +--------+------------+------------+------------+------------+------------+ # | factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits | # +--------+------------+------------+------------+------------+------------+ # | 0 | 104 | 255 | 255 | 255 | 255 | # +--------+------------+------------+------------+------------+------------+ # | 1 | 18 | 49 | 255 | 255 | 255 | # +--------+------------+------------+------------+------------+------------+ # | 10 | 10 | 18 | 142 | 255 | 255 | # +--------+------------+------------+------------+------------+------------+ # | 100 | 8 | 11 | 49 | 143 | 255 | # +--------+------------+------------+------------+------------+------------+ # # NOTE: The above table was obtained by running the following commands: # # redis-benchmark -n 1000000 incr foo # redis-cli object freq foo # # NOTE 2: The counter initial value is 5 in order to give new objects a chance # to accumulate hits. # # The counter decay time is the time, in minutes, that must elapse in order # for the key counter to be divided by two (or decremented if it has a value # less <= 10). # # The default value for the lfu-decay-time is 1. A special value of 0 means to # decay the counter every time it happens to be scanned. # # lfu-log-factor 10 # lfu-decay-time 1 ########################### ACTIVE DEFRAGMENTATION ####################### # # What is active defragmentation? # ------------------------------- # # Active (online) defragmentation allows a Redis server to compact the # spaces left between small allocations and deallocations of data in memory, # thus allowing to reclaim back memory. # # Fragmentation is a natural process that happens with every allocator (but # less so with Jemalloc, fortunately) and certain workloads. Normally a server # restart is needed in order to lower the fragmentation, or at least to flush # away all the data and create it again. However thanks to this feature # implemented by Oran Agra for Redis 4.0 this process can happen at runtime # in a "hot" way, while the server is running. # # Basically when the fragmentation is over a certain level (see the # configuration options below) Redis will start to create new copies of the # values in contiguous memory regions by exploiting certain specific Jemalloc # features (in order to understand if an allocation is causing fragmentation # and to allocate it in a better place), and at the same time, will release the # old copies of the data. This process, repeated incrementally for all the keys # will cause the fragmentation to drop back to normal values. # # Important things to understand: # # 1. This feature is disabled by default, and only works if you compiled Redis # to use the copy of Jemalloc we ship with the source code of Redis. # This is the default with Linux builds. # # 2. You never need to enable this feature if you don't have fragmentation # issues. # # 3. Once you experience fragmentation, you can enable this feature when # needed with the command "CONFIG SET activedefrag yes". # # The configuration parameters are able to fine tune the behavior of the # defragmentation process. If you are not sure about what they mean it is # a good idea to leave the defaults untouched. # Enabled active defragmentation # activedefrag no # Minimum amount of fragmentation waste to start active defrag # active-defrag-ignore-bytes 100mb # Minimum percentage of fragmentation to start active defrag # active-defrag-threshold-lower 10 # Maximum percentage of fragmentation at which we use maximum effort # active-defrag-threshold-upper 100 # Minimal effort for defrag in CPU percentage, to be used when the lower # threshold is reached # active-defrag-cycle-min 1 # Maximal effort for defrag in CPU percentage, to be used when the upper # threshold is reached # active-defrag-cycle-max 25 # Maximum number of set/hash/zset/list fields that will be processed from # the main dictionary scan # active-defrag-max-scan-fields 1000 # Jemalloc background thread for purging will be enabled by default jemalloc-bg-thread yes # It is possible to pin different threads and processes of Redis to specific # CPUs in your system, in order to maximize the performances of the server. # This is useful both in order to pin different Redis threads in different # CPUs, but also in order to make sure that multiple Redis instances running # in the same host will be pinned to different CPUs. # # Normally you can do this using the "taskset" command, however it is also # possible to this via Redis configuration directly, both in Linux and FreeBSD. # # You can pin the server/IO threads, bio threads, aof rewrite child process, and # the bgsave child process. The syntax to specify the cpu list is the same as # the taskset command: # # Set redis server/io threads to cpu affinity 0,2,4,6: # server_cpulist 0-7:2 # # Set bio threads to cpu affinity 1,3: # bio_cpulist 1,3 # # Set aof rewrite child process to cpu affinity 8,9,10,11: # aof_rewrite_cpulist 8-11 # # Set bgsave child process to cpu affinity 1,10,11 # bgsave_cpulist 1,10-11 # In some cases redis will emit warnings and even refuse to start if it detects # that the system is in bad state, it is possible to suppress these warnings # by setting the following config which takes a space delimited list of warnings # to suppress # # ignore-warnings ARM64-COW-BUG 在里面那边加上bind 0.0.0.0
05-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值