< turn >ios event processing mechanism and image rendering process

Source: Internet
Author: User

Original: http://mp.weixin.qq.com/s?__biz=MjM5OTM0MzIwMQ==&mid=401383686&idx=1&sn= 1613dfa8fa762a0efee4bc4af496fddf&scene=0#wechat_redirectWhat did IOS Runloop do?

Runloop is a loop that receives the processing of an asynchronous message event, in a loop: waits for an event to occur, and then sends the event to where it can be handled.

1-1, describes a simple process in which a touch event is routed from the operating system layer to the main runloop in the application.


Figure 1-1

Simply put, Runloop is a large loop of event-driven, as shown in the following code

int main(int argc, char * argv[]) {     //程序一直运行状态     while (AppIsRunning) {          //睡眠状态,等待唤醒事件          id whoWakesMe = SleepForWakingU  p();          //得到唤醒事件          id event = GetEvent(whoWakesMe);          //开始处理事件          HandleEvent(event);     }     return 0;}

Runloop mainly handles the following 6 types of events:

  static void __cfrunloop_is_calling_out_to_an_observer_callback_function__ (); static void __cfrunloop_is_ Calling_out_to_a_block__ (); static void __cfrunloop_is_servicing_the_main_dispatch_queue__ (); static void __ CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ (); static void __cfrunloop_is_calling_out_to_a_source0_ PERFORM_FUNCTION__ (); static void __cfrunloop_is_calling_out_to_a_source1_perform_function__ ();  
    1. Observer event, notify when status changes in Runloop. (Lag monitoring is to use this event notification to record the most recent main runloop activity time, in another check thread with the timer to detect the current time distance of the last active time to determine the main thread processing logic time and the main thread of the card). It is also important to note that Caanimation is redrawn by the Runloopobserver trigger callback, which is described next.

    2. Block event, non-deferred nsobject performselector immediate call, Dispatch_after immediate call, Block callback.

    3. Main_dispatch_queue event: Block in GCD Dispatch to main queue will be executed by Dispatch to main loop.

    4. Timer event: Delayed NSObject performselector, deferred Dispatch_after,timer event.

    5. Source0 Event: Handles events such as Uievent,cfsocket. Manual triggering is required. A touch event is actually a source0,source0 triggered after a Source1 receive system event in the callback __iohideventsystemclientqueuecallback () Uiapplicationhandleeventqueue (). Source0 must be to wake up the runloop in a timely response and execute, if runloop at this time in hibernation waiting for the system's Mach_msg event, then source1 to wake up runloop execution.

    6. Source1 Event: The Mach_msg event that handles the system kernel. (presumably Cadisplaylink is also triggered here).

Runloop pseudo-code for execution order

Setupthisrunloopruntimeouttimer (); By GCD timer//Notice is about to enter runloop__cfrunllop_is_calling_out_to_an_observer_callback_function__ (KCFRunLoopEntry);d O {_     _cfrunloopdoobservers (kcfrunloopbeforetimers);     __cfrunloopdoobservers (kcfrunloopbeforesources);  __cfrunloopdoblocks (); A loop is called two times to ensure that non-deferred nsobject Performselector calls and non-deferred dispatch_after calls are performed at the current runloop. There is also a callback block __cfrunloopdosource0 (); For example, the Uievent event Checkifexistmessagesinmaindispatchqueue () handled by Uikit; GCD Dispatch main queue __cfrunloopdoobservers (kcfrunloopbeforewaiting);     Going into hibernation, will redraw the interface var wakeupport = Sleepandwaitforwakingupports ();     Mach_msg_trap, trapped kernel waiting for matching kernel mach_msg event//Zzz ...     Received mach_msg, Wake up __cfrunloopdoobservers (kcfrunloopafterwaiting);     Handle msgs if (wakeupport = = Timerport) {__cfrunloopdotimers (); } else if (Wakeupport = = Maindispatchqueueport) {//GCD when calling Dispatch_async (Dispatch_get_main_queue (), block), Libdis Patches are sent to the runloop of the main thread mach_msgThe message wakes up Runloop and executes here.          This is limited to performing dispatch to the main thread of the task, dispatch to other threads is still libdispatch to handle.  __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()} else {__cfrunloopdosource1 ();     Cadisplaylink is Source1 's mach_msg trigger? } __cfrunloopdoblocks ();} while (!stop &&!timeout);//notification observers, imminent exit Runloop__cfrunloop_is_calling_out_to_an_oberver_callback_ FUNCTION__ (Cfrunloopexit);

Combining the above Runloop event execution order, consider why the following code logic can identify whether TableView is reload complete

dispatch_async(dispatch_get_main_queue(), ^{    _isReloadDone = NO;    [tableView reload]; //会自动设置tableView layoutIfNeeded为YES,意味着将会在runloop结束时重绘table    dispatch_async(dispatch_get_main_queue(),^{        _isReloadDone = YES;    });});

tip: Here are two tasks inserted in the GCD dispatch main queue, once runloop have two opportunities to perform the tasks in GCD dispatch main queue, respectively, before and after hibernation.

Why IOS must operate the UI in the main thread

because Uikit is not thread-safe . Consider the following scenarios:

    1. Two threads set the same background image at the same time, it is possible that the application crashes because the current picture is released twice.

    2. Two threads set the same UIView background color at the same time, it is very likely that the rendering is displayed in color A, while the background color property on the UIView logical tree is b.

    3. Two threads manipulate the tree of view at the same time: the For loop in thread a iterates over and operates on all the subview of the current view, and then a subview is deleted directly at this point, causing confusion and possibly causing the app to crash.
      After IOS4, Apple has rewritten most of the drawing methods and classes such as Uicolor and Uifont for thread-safe usability, but it is still strongly recommended that UI operations be performed in the main thread.

Incident response

Apple has registered a Source1 (Mach Port-based) to receive system events with a callback function of __iohideventsystemclientqueuecallback ().

When a hardware event (Touch/Lock screen/shake, etc.) occurs, a Iohidevent event is first generated by Iokit.framework and received by springboard.

Springboard only receives keystrokes (lock screen/mute, etc.), touches, accelerates, approaches sensors, etc., and then forwards it to the desired app process using Mach port. Then the apple-registered SOURCE1 triggers the callback and calls _uiapplicationhandleeventqueue () to distribute the app internally.

_uiapplicationhandleeventqueue () iohidevent processed and packaged as uievent for processing or distribution, including identification uigesture/processing screen rotation/sending to UIWindow, etc. Usually events such as UIButton clicks and touchesbegin/move/end/cancel events are done in this callback.

Calayer

In iOS, all views derive from a base class called UIView, UIView can handle touch events, support a core graphics drawing, perform affine transformations (such as rotation or zooming), or simply resemble a sliding or gradient animation.

The Calayer class is conceptually similar to UIView and is also a rectangular block managed by a hierarchical tree, and can also contain some content (like pictures, text, or background colors) to manage the placement of sublayers. They have some methods and properties for animating and transforming. The biggest difference from UIView is that Calayer does not handle user interaction. Calayer does not know the specific response chain.

UIView and Calayer are a parallel hierarchical relationship, and each uiview has a layer attribute for the Calayer instance, the so-called backing layer, and the view's responsibility is to create and manage the layer. To make sure that when a child view is added to or removed from a hierarchical relationship, the layers they are associated with also correspond to the same actions in the hierarchy tree. In fact, the layer layers behind these are the ones that are really used to display and animate on the screen, and UIView is just one package for it, providing some of the specific features of iOS that are similar to touch, as well as the advanced interface of the core animation approach.

The UIView Layer is maintained within the system with three identical tree data structures, namely:

    1. The layer tree (here is what the code can manipulate, and the final value of the Set property will be updated here immediately);

    2. The rendering tree (which is an intermediate layer in which the system changes properties for various rendering operations.) For example an animation is to change the alpha value from 0 to 1, then on the logical tree this property will be immediately updated to the final attribute 1, and the animation tree will be set according to the animation time from 0 to 1);

    3. The rendering tree (whose attribute value is the property value currently being displayed on the screen);

Cadisplaylink and Nstimer

Nstimer is actually cfrunlooptimerref. After a nstimer is registered with Runloop, Runloop registers good events for its repeated points in time.

Runloop to conserve resources, it does not callback the timer at a very accurate point in time. The Timer has a property called tolerance (latitude), which indicates how much maximum error is allowed when the point is reached. If a point in time is missed, such as a long task, then the callback at that point in time skips over and does not postpone execution.

Runloop is a Timer implemented with the dispatch_source_t of GCD. When you call NSObject's performselecter:afterdelay:, it actually creates a Timer inside it and adds it to the runloop of the current thread. So if the current thread does not have Runloop, then this method will fail. When calling Performselector:onthread:, it will actually create a Timer to add to the corresponding thread, similarly, if the corresponding thread does not runloop the method will also be invalidated.

Cadisplaylink is a timer that is consistent with the screen refresh rate (refresh 60 times per second) (but the actual implementation principle is more complex, and the Nstimer is not the same, the inside is actually manipulating a Source). If a long task is performed between two screen refreshes, one frame is skipped, causing the interface to stutter.

IOS Rendering Process


Figure 2-1


In general, the CPU, GPU, and monitor in a computer system work together in this way. The CPU calculates the display content submitted to the GPU,GPU render results into the frame buffer after rendering, then the video controller will follow the VSync signal as shown in 1-4, read the data of the frame buffer row by line, passing through the possible digital-to-analog conversion to display the display.


Figure 2-2

After the VSync signal arrives, the system graphics Service notifies the App,app main thread to start computing the display content in the CPU, such as view creation, layout calculation, picture decoding, text drawing, etc. through Cadisplaylink mechanism. The CPU then submits the computed content to the GPU, which is transformed, synthesized, and rendered by the GPU. The GPU then submits the rendered result to the frame buffer, waiting for the next VSync signal to appear on the screen. Due to the mechanism of vertical synchronization, if the CPU or GPU does not complete the content submission within a VSync time, the frame will be discarded, waiting for the next opportunity to display again, and the display will remain unchanged. This is the reason for the interface lag. As you can see, the CPU and GPU, regardless of which block the display process, will cause a drop frame phenomenon. Therefore, it is also necessary to evaluate and optimize the CPU and GPU pressure separately during development.

The IOS display system is driven by the VSync signal, and the VSync signal is generated by the hardware clock, which is emitted 60 times per second (this value depends on the device hardware, such as the iPhone is usually 59.97 on a real machine). After the IOS graphics service receives the VSYNC signal, it is notified via IPC to the App. The app's runloop will register the corresponding Cfrunloopsource through Mach_port to receive the clock signal notification, then the Source callback will drive the entire app animation and display.

Core Animation registered a Observer in runloop and monitored the beforewaiting and Exit events. When a touch event arrives, the Runloop is awakened, and the code in the APP performs some actions, such as creating and resizing the view hierarchy, setting the frame of the UIView, modifying the transparency of the Calayer, adding an animation to the view, which will eventually be Calayer tagged and passed Catransaction submits to an intermediate state to go. When all of the above operations are completed, Runloop is about to enter hibernation (or exit), the Observer that is concerned about the event will be notified. At this point the Core Animation registered Observer will be in the callback, all the intermediate state is submitted to the GPU to display, if there is animation, through the DisplayLink stable refresh mechanism will continue to wake up Runloop, This makes it possible for the observer callback to be triggered continuously, thus updating the property value of the animation and drawing it according to the time.

In order not to block the main thread, core Animation is an abstraction of OpenGL ES, so most of the rendering is directly submitted to the GPU for processing. Most of the drawing operations of the core Graphics/quartz 2D are done synchronously on the main thread and CPU, such as in the custom UIView drawrect with Cgcontext to draw.

Render Time

As mentioned above: Core Animation registers a Observer monitoring beforewaiting (going into hibernation) and exit (impending exit Loop) events in Runloop. When manipulating the UI, such as changing the Frame, updating the Uiview/calayer hierarchy, or manually invoking the Uiview/calayer Setneedslayout/setneedsdisplay method, this uiview/ The Calayer is marked for processing and is committed to a global container. When the Oberver listener event arrives, the callback execution function iterates through all the pending uiview/calayer to perform the actual drawing and adjustment, and updates the UI interface.

The call stack inside this function is probably the same:

_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv()    QuartzCore:CA::Transaction::observer_callback:        CA::Transaction::commit();            CA::Context::commit_transaction();                CA::Layer::layout_and_display_if_needed();                    CA::Layer::layout_if_needed();                          [CALayer layoutSublayers];                          [UIView layoutSubviews];                    CA::Layer::display_if_needed();                          [CALayer display];                          [UIView drawRect];
CPU and GPU rendering

In OpenGL, GPU screen rendering is available in the following two ways:

    1. On-Screen Rendering
      means the current screen rendering, which refers to the rendering operation of the GPU in the screen buffer currently used for display.

    2. Off-screen Rendering
      Off-screen rendering means that the GPU creates a new buffer outside the current screen buffer for rendering operations.
      In this way, if rendering in the current screen buffer that is not in the GPU is called off-screen rendering, there is another special "off-screen Rendering" method: CPU Rendering. If we rewrite the DrawRect method and draw using any of the core graphics techniques, CPU rendering is involved. The entire rendering process is done synchronously by the CPU in the app, and the rendered bitmap is finally used by the GPU for display.

Compared to the current screen rendering, the cost of off-screen rendering is very high, mainly reflected in two aspects:

    1. Create a new buffer
      To perform off-screen rendering, you first create a new buffer.

    2. Context Switches
      The entire process of off-screen rendering requires multiple switching of the context: first switching from the current screen (on-screen) to off-screen (off-screen), and when the off-screen rendering is finished, the rendering of the off-screen buffer is displayed on the screen with the need to switch the context from off-screen to the current screen. And the context of the switch is to pay a great price.

When the following properties are set, off-screen drawing is triggered:

    1. Shouldrasterize (rasterization)

    2. Masks (matte)

    3. Shadows (Shadow)

    4. Edge antialiasing (anti-aliasing)

    5. Group Opacity (opaque)
      It is important to note that if Shouldrasterize is set to Yes, the rasterized content will be cached when the off-screen drawing is triggered, and if the corresponding layer and its sublayers are not changed, the next frame can be reused directly. This will improve rendering performance to a large extent.
      If the other properties are turned on, there will be no cache, and the off-screen drawing will occur at each frame.

In the development, we need to choose the optimal implementation method according to the actual situation, and use on-screen Rendering as far as possible. Simple off-screen rendering can consider using the core graphics to render the CPU.

Core Animation

1. Implicit animations

Implicit animation is the automatic completion of the system framework. Core animation automatically starts a new transaction in each Runloop cycle, even if you do not explicitly start a transaction with [Catransaction begin], any changes to the properties in a Runloop loop will be concentrated. Then do a 0.25-second animation.
In IOS4, Apple added a block-based animation method to UIView: +animatewithduration:animations:.
It's easier to write a bunch of property animations in this way, but in essence they're doing the same thing.
Catransaction's +begin and +commit methods are automatically called inside the +animatewithduration:animations: so that changes to all properties in the block are included in the transaction.

Core animation usually animates all properties of Calayer (animated properties), but how does UIView close the feature of the layer it is associated with?
Each uiview has a delegate to its associated layers, and provides a way to implement-actionforlayer:forkey. When not in the implementation of an animation block, UIView returns nil for all layer behavior, but within the animation block range, it returns a non-null value.

@interface ViewController ()@property (nonatomic, weak) IBOutlet UIView *layerView;@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    //test layer action when outside of animation block    NSLog(@"Outside: %@", [self.layerView actionForLayer:self.layerView.layer forKey:@"backgroundColor"]);    //begin animation block    [UIView beginAnimations:nil context:nil];    //test layer action when inside of animation block    NSLog(@"Inside: %@", [self.layerView actionForLayer:self.layerView.layer forKey:@"backgroundColor"]);    //end animation block    [UIView commitAnimations];}@end$ LayerTest[21215:c07] Outside: <null>$ LayerTest[21215:c07] Inside: <CABasicAnimation: 0x757f090>

2. Explicit animations

Core Animation provides an explicit animation type that can animate a fallback property directly, or override the default layer behavior.
The cabasicanimation,cakeyframeanimation,catransitionanimation,caanimationgroup that we often use are all explicit animation types, These caanimation types can be submitted directly to the Calayer.

Whether it is an implicit animation or an explicit animation, after being submitted to the layer, after a series of processing, and finally after the painting process described above is finally rendered.

Facebook Pop Introduction

In the world of computers, there is no absolute continuous animation, you can see the animation on the screen is essentially discrete, but in a second time the discrete frame more than a certain number of people's eyes feel is continuous,

In iOS, the maximum frame rate is 60 frames per second. iOS provides a core animation framework that requires only the developer to provide keyframe information, such as providing key frame information for the end of a animatable attribute, and then the median value is interpolated by a certain algorithm to achieve tweened animation. The time curve on which interpolation is calculated in Core aniamtion is provided by Camediatimingfunction.

Pop animation in use and core animation very similar, all involve the concept of animation object and animation carrier, the difference is that the core animation carrier can only be calayer, and pop The animation can be any NSObject-based object. Of course, most of the cases animation is the visual effect displayed on the interface, so the vector of the animation execution is generally direct or indirect is uiview or calayer.

But if you just want to study the change curve of pop animation, you can also apply it to a normal data object. When Pop animation is applied to Calayer, the related property values of the layer and its presentationlayer are always consistent at any point in the animation run, and the core animation cannot. Pop animation can apply any NSObject object, and the core aniamtion must be calayer.

The following example is Custom pop Readblock and WriteBlock handling Custom Animation properties:

prop = [POPAnimatableProperty propertyWithName:@"com.foo.radio.volume" initializer:^(POPMutableAnimatableProperty *prop) {    // read value    prop.readBlock = ^(id obj, CGFloat values[]) {        values[0] = [obj volume];    };    // write value    prop.writeBlock = ^(id obj, const CGFloat values[]) {        [obj setVolume:values[0]];    };    // dynamics threshold    prop.threshold = 0.01;}];POPSpringAnimation *anim = [POPSpringAnimation animation];anim.property = prop;

The core of pop implementation dependence is Cadisplaylink.

Finally, attach an article on how Facebook Pop is used, "introducing Facebook pop"

Asyncdisplay Introduction

The main task of the blocking main thread is the three major categories: Layout calculation view layouts text width, rendering text rendering picture decoding picture drawing, Uikit object creation update release. In addition to the Uikit and coreanimation related operations must be done in the main thread, others can be moved to the background thread asynchronous execution.

Asyncdisplay creates the Asdisplaynode class through an abstract UIView relationship, Asdisplaynode is thread-safe and can be created and modified in a background thread. When Node was first created, it does not create a new UIView and Calayer internally, until the first time the view or Layer property is accessed on the main thread, it generates the corresponding object internally. When its properties (such as Frame/transform) are changed, it does not immediately synchronize to the view or layer it holds, but instead saves the changed attribute to an internal intermediate variable, which is then set to the internal view or layer at a time, if necessary, by a mechanism. This allows asynchronous concurrency operations to be implemented.

The Asyncdisplay implementation relies on triggering as the core animation registers observer events in Runloop.
Also attached is a good article on Asyncdisplay, "iOS keep the interface fluent and Asyncdisplay introduction"

Reference articles
    • Runloop principle (Https://github.com/ming1016/study/wiki/CFRunLoop)

    • In-depth understanding of runloop (http://blog.ibireme.com/2015/05/18/runloop/)

    • Design of thread-safe classes (http://objccn.io/issue-2-4/)

    • iOS keeps the interface flowing with tips and asyncdisplay introduction (http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/)

      • Off-screen rendering (http://foggry.com/blog/2015/05/06/chi-ping-xuan-ran-xue-xi-bi-ji/)

      • Advanced iOS Core Animation tips (https://zsisme.gitbooks.io/ios-/content/index.html)

< turn >ios event processing mechanism and image rendering process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.