FTXUI 6.1.9
C++ functional terminal UI.
Loading...
Searching...
No Matches
catch_event.cpp
Go to the documentation of this file.
1// Copyright 2021 Arthur Sonzogni. 保留所有權利。
2// 此原始碼受 MIT 授權條款約束,詳情請參閱
3// LICENSE 檔案。
4#include <functional> // for function
5#include <utility> // for move
6
7#include "ftxui/component/component.hpp" // for Make, CatchEvent, ComponentDecorator
8#include "ftxui/component/component_base.hpp" // for Component, ComponentBase
9#include "ftxui/component/event.hpp" // for Event
10
11namespace ftxui {
12
13class CatchEventBase : public ComponentBase {
14 public:
15 // 建構函式。
16 explicit CatchEventBase(std::function<bool(Event)> on_event)
17 : on_event_(std::move(on_event)) {}
18
19 // 元件實作。
20 bool OnEvent(Event event) override {
21 if (on_event_(event)) {
22 return true;
23 } else {
24 return ComponentBase::OnEvent(event);
25 }
26 }
27
28 protected:
29 std::function<bool(Event)> on_event_;
30};
31
32/// @brief 傳回一個元件,使用 |on_event| 捕捉事件。當事件已處理時,此函式必須傳回 true,否則傳回 false。
33/// @param child 被包裝的元件。
34/// @param on_event 繪製介面的函式。
35/// @ingroup component
36///
37/// ### 範例
38///
39/// ```cpp
40/// auto screen = ScreenInteractive::TerminalOutput();
41/// auto renderer = Renderer([] {
42/// return text("My interface");
43/// });
44/// auto component = CatchEvent(renderer, [&](Event event) {
45/// if (event == Event::Character('q')) {
46/// screen.ExitLoopClosure()();
47/// return true;
48/// }
49/// return false;
50/// });
51/// screen.Loop(component);
52/// ```
54 std::function<bool(Event event)> on_event) {
55 auto out = Make<CatchEventBase>(std::move(on_event));
56 out->Add(std::move(child));
57 return out;
58}
59
60/// @brief 裝飾一個元件,使用 |on_event| 捕捉事件。當事件已處理時,此函式必須傳回 true,否則傳回 false。
61/// @param on_event 繪製介面的函式。
62/// @ingroup component
63///
64/// ### 範例
65///
66/// ```cpp
67/// auto screen = ScreenInteractive::TerminalOutput();
68/// auto renderer = Renderer([] { return text("Hello world"); });
69/// renderer |= CatchEvent([&](Event event) {
70/// if (event == Event::Character('q')) {
71/// screen.ExitLoopClosure()();
72/// return true;
73/// }
74/// return false;
75/// });
76/// screen.Loop(renderer);
77/// ```
78ComponentDecorator CatchEvent(std::function<bool(Event)> on_event) {
79 return [on_event = std::move(on_event)](Component child) {
80 return CatchEvent(std::move(child), [on_event = on_event](Event event) {
81 return on_event(std::move(event));
82 });
83 };
84}
85
86} // namespace ftxui
virtual bool OnEvent(Event)
回應事件時呼叫。
代表一個事件。它可以是按鍵事件、終端機大小調整,或更多...
Definition event.hpp:27
FTXUI 的 ftxui:: 命名空間
Definition animation.hpp:10
std::shared_ptr< T > Make(Args &&... args)
Definition component.hpp:26
std::function< Component(Component)> ComponentDecorator
Definition component.hpp:31
std::shared_ptr< ComponentBase > Component
Component CatchEvent(Component child, std::function< bool(Event)>)