| 1 | // Copyright (C) 2016 The Qt Company Ltd. |
|---|---|
| 2 | // Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | // |
| 4 | // SPDX-License-Identifier: MIT |
| 5 | |
| 6 | #include "event.h" |
| 7 | #include <atomic> |
| 8 | #include <memory> |
| 9 | |
| 10 | QT_YOGA_NAMESPACE_BEGIN |
| 11 | |
| 12 | namespace facebook { |
| 13 | namespace yoga { |
| 14 | |
| 15 | const char* LayoutPassReasonToString(const LayoutPassReason value) { |
| 16 | switch (value) { |
| 17 | case LayoutPassReason::kInitial: |
| 18 | return "initial"; |
| 19 | case LayoutPassReason::kAbsLayout: |
| 20 | return "abs_layout"; |
| 21 | case LayoutPassReason::kStretch: |
| 22 | return "stretch"; |
| 23 | case LayoutPassReason::kMultilineStretch: |
| 24 | return "multiline_stretch"; |
| 25 | case LayoutPassReason::kFlexLayout: |
| 26 | return "flex_layout"; |
| 27 | case LayoutPassReason::kMeasureChild: |
| 28 | return "measure"; |
| 29 | case LayoutPassReason::kAbsMeasureChild: |
| 30 | return "abs_measure"; |
| 31 | case LayoutPassReason::kFlexMeasure: |
| 32 | return "flex_measure"; |
| 33 | default: |
| 34 | return "unknown"; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | namespace { |
| 39 | |
| 40 | struct Node { |
| 41 | std::function<Event::Subscriber> subscriber = nullptr; |
| 42 | Node* next = nullptr; |
| 43 | |
| 44 | Node(std::function<Event::Subscriber>&& subscriber) |
| 45 | : subscriber{std::move(subscriber)} {} |
| 46 | }; |
| 47 | |
| 48 | std::atomic<Node*> subscribers{nullptr}; |
| 49 | |
| 50 | Node* push(Node* newHead) { |
| 51 | Node* oldHead; |
| 52 | do { |
| 53 | oldHead = subscribers.load(m: std::memory_order_relaxed); |
| 54 | if (newHead != nullptr) { |
| 55 | newHead->next = oldHead; |
| 56 | } |
| 57 | } while (!subscribers.compare_exchange_weak( |
| 58 | p1&: oldHead, p2: newHead, m1: std::memory_order_release, m2: std::memory_order_relaxed)); |
| 59 | return oldHead; |
| 60 | } |
| 61 | |
| 62 | } // namespace |
| 63 | |
| 64 | void Event::reset() { |
| 65 | auto head = push(newHead: nullptr); |
| 66 | while (head != nullptr) { |
| 67 | auto current = head; |
| 68 | head = head->next; |
| 69 | delete current; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | void Event::subscribe(std::function<Subscriber>&& subscriber) { |
| 74 | push(newHead: new Node{std::move(subscriber)}); |
| 75 | } |
| 76 | |
| 77 | void Event::publish(const YGNode& node, Type eventType, const Data& eventData) { |
| 78 | for (auto subscriber = subscribers.load(m: std::memory_order_relaxed); |
| 79 | subscriber != nullptr; |
| 80 | subscriber = subscriber->next) { |
| 81 | subscriber->subscriber(node, eventType, eventData); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | } // namespace yoga |
| 86 | } // namespace facebook |
| 87 | |
| 88 | QT_YOGA_NAMESPACE_END |
| 89 |
