1# Native Window Development (C/C++)
2
3## When to Use
4
5The native window module is a local platform-based window that represents the producer of a graphics queue. It provides APIs for you to request and flush a buffer and configure buffer attributes.
6
7The following scenarios are common for native window development:
8
9* Request a graphics buffer by using the native window API, write the produced graphics content to the buffer, and flush the buffer to the graphics queue.
10* Request and flush a buffer when adapting to the **eglswapbuffer** interface at the EGL.
11
12## Available APIs
13
14| API| Description|
15| -------- | -------- |
16| OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests an **OHNativeWindowBuffer** through an **OHNativeWindow** instance for content production.|
17| OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the **OHNativeWindowBuffer** filled with the produced content to the buffer queue through an **OHNativeWindow** instance for content consumption.|
18| OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | Sets or obtains the attributes of an **OHNativeWindow** instance, including the width, height, and content format.|
19
20For details about the APIs, see [native_window](../reference/apis-arkgraphics2d/_native_window.md).
21
22## How to Develop
23
24The following describes how to use the native window APIs to request a graphics buffer, write the produced graphics content to the buffer, and flush the buffer to the graphics queue.
25
26**Adding Dynamic Link Libraries**
27
28Add the following libraries to **CMakeLists.txt**:
29```txt
30libace_ndk.z.so
31libnative_window.so
32```
33
34**Including Header Files**
35```c++
36#include <sys/poll.h>
37#include <sys/mman.h>
38#include <unistd.h>
39#include <ace/xcomponent/native_interface_xcomponent.h>
40#include <native_window/external_window.h>
41```
42
431. Obtain an **OHNativeWindow** instance.
44
45    You can call the APIs provided by [OH_NativeXComponent_Callback](../reference/apis-arkui/_o_h___native_x_component___callback.md) to obtain an **OHNativeWindow** instance. An example code snippet is provided below. For details about how to use the **XComponent**, see [XComponent Development](../ui/napi-xcomponent-guidelines.md).
46    1. Add an **XComponent** to the .ets file.
47        ```ts
48        XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'entry'})
49            .width(360)
50            .height(360)
51        ```
52    2. Obtain **NativeXComponent** at the native C++ layer.
53        ```c++
54        napi_value exportInstance = nullptr;
55        // Parse the attribute of the wrapped NativeXComponent pointer.
56        napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance);
57        OH_NativeXComponent *nativeXComponent = nullptr;
58        // Use the napi_unwrap API to parse the NativeXComponent instance pointer.
59        napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent));
60        // Obtain the XComponent ID.
61        char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
62        uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
63        OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize);
64        ```
65    3. Define **OH_NativeXComponent_Callback**.
66        ```c++
67        // Define the callback.
68        void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
69        {
70            // Obtain an OHNativeWindow instance.
71            OHNativeWindow* nativeWindow = static_cast<OHNativeWindow*>(window);
72            // After this callback is triggered, the reference count for the window is initialized to 1. If the window-related APIs and XComponent destructor are concurrently used,
73            // you must manually adjust the reference count by using OH_NativeWindow_NativeObjectReference to increase it and OH_NativeWindow_NativeObjectUnreference to decrease it.
74            // This manual management of the reference count by 1 helps to avoid issues with dangling or null pointers that could occur during concurrent calls to window APIs following the destruction of an XComponent.
75        }
76        void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window)
77        {
78            // Obtain an OHNativeWindow instance.
79            OHNativeWindow* nativeWindow = static_cast<OHNativeWindow*>(window);
80            // ...
81        }
82        void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window)
83        {
84            // Obtain an OHNativeWindow instance.
85            OHNativeWindow* nativeWindow = static_cast<OHNativeWindow*>(window);
86            // After this callback is triggered, the reference count for the window is decremented by 1. When the reference count reaches 0, the window is destructed.
87            // Once the window is destructed, no further API calls should be made through the window. This operation results in a crash caused by dangling or null pointers.
88        }
89        void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
90        {
91            // Obtain an OHNativeWindow instance.
92            OHNativeWindow* nativeWindow = static_cast<OHNativeWindow*>(window);
93            // ...
94        }
95        ```
96        ```c++
97        // Initialize OH_NativeXComponent_Callback.
98        OH_NativeXComponent_Callback callback;
99        callback.OnSurfaceCreated = OnSurfaceCreatedCB;
100        callback.OnSurfaceChanged = OnSurfaceChangedCB;
101        callback.OnSurfaceDestroyed = OnSurfaceDestroyedCB;
102        callback.DispatchTouchEvent = DispatchTouchEventCB;
103        ```
104   4. Register **OH_NativeXComponent_Callback** with **NativeXComponent**.
105        ```c++
106        // Register the callback.
107        OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback);
108        ```
109
1102. Set the attributes of an **OHNativeWindowBuffer** by using **OH_NativeWindow_NativeWindowHandleOpt**.
111    ```c++
112    // Set the width and height of the OHNativeWindowBuffer.
113    int32_t code = SET_BUFFER_GEOMETRY;
114    int32_t width = 0x100;
115    int32_t height = 0x100;
116    // The nativeWindow instance is obtained from the callback in the previous step.
117    int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height);
118    ```
119
1203. Request an **OHNativeWindowBuffer** from the graphics queue.
121    ```c++
122    OHNativeWindowBuffer* buffer = nullptr;
123    int releaseFenceFd = -1;
124    // Obtain the OHNativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer.
125    ret = OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow, &buffer, &releaseFenceFd);
126    if (ret != 0 || buffer == nullptr) {
127        return;
128    }
129    // Obtain the buffer handle by calling OH_NativeWindow_GetBufferHandleFromNative.
130    BufferHandle* bufferHandle = OH_NativeWindow_GetBufferHandleFromNative(buffer);
131    ```
132
1334. Map memory.
134    ```c++
135    #include <sys/mman.h>
136
137    // Use mmap() to map the shared memory allocated to the buffer handle to the user space. Image data can be written to the buffer handle by using the obtained virtual address.
138    // bufferHandle->virAddr indicates the start address of the buffer handle in the shared memory, and bufferHandle->size indicates the memory usage of the buffer handle in the shared memory.
139    void* mappedAddr = mmap(bufferHandle->virAddr, bufferHandle->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufferHandle->fd, 0);
140    if (mappedAddr == MAP_FAILED) {
141        // mmap failed
142    }
143    ```
144
1455. Write the produced content to the **OHNativeWindowBuffer**.
146
147   Before this operation, wait until **releaseFenceFd** is available. (Note that **poll** needs to be called only when **releaseFenceFd** is not **-1**.) If no data waiting for **releaseFenceFd** is available (POLLIN), problems such as artifacts, cracks, and High Efficiency Bandwidth Compression (HEBC) faults may occur. **releaseFenceFd** is a file handle created by the consumer process to indicate that the consumer has consumed the buffer, the buffer is readable, and the producer can start to fill in the buffer.
148    ```c++
149    int retCode = -1;
150    uint32_t timeout = 3000;
151    if (releaseFenceFd != -1) {
152        struct pollfd pollfds = {0};
153        pollfds.fd = releaseFenceFd;
154        pollfds.events = POLLIN;
155        do {
156            retCode = poll(&pollfds, 1, timeout);
157        } while (retCode == -1 && (errno == EINTR || errno == EAGAIN));
158        close(releaseFenceFd); // Prevent FD leakage.
159    }
160
161    static uint32_t value = 0x00;
162    value++;
163    uint32_t *pixel = static_cast<uint32_t *>(mappedAddr); // Use the address obtained by mmap() to access the memory.
164    for (uint32_t x = 0; x < width; x++) {
165        for (uint32_t y = 0;  y < height; y++) {
166            *pixel++ = value;
167        }
168    }
169    ```
170
1716. Flush the **OHNativeWindowBuffer** to the graphics queue.
172
173   Note that **acquireFenceFd** of **OH_NativeWindow_NativeWindowFlushBuffer** cannot be the same as **releaseFenceFd** obtained by **OH_NativeWindow_NativeWindowRequestBuffer**. **acquireFenceFd** is the file handle passed in by the producer, and the default value **-1** can be passed. Based on **acquireFenceFd**, the consumer, after obtaining the buffer, determines when to render and display the buffered content.
174    ```c++
175    // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the OHNativeWindowBuffer are changed.
176    Region region{nullptr, 0};
177    int acquireFenceFd = -1;
178    // Flush the buffer to the consumer through OH_NativeWindow_NativeWindowFlushBuffer, for example, by displaying it on the screen.
179    OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow, buffer, acquireFenceFd, region);
180    ```
1817. Unmap memory.
182    ```c++
183    // Unmap the memory when the memory is no longer required.
184    int result = munmap(mappedAddr, bufferHandle->size);
185    if (result == -1) {
186        // munmap failed
187    }
188    ```
189
190