FTXUI 6.1.9
C++ functional terminal UI.
载入中...
搜索中...
未找到
catch_event.cpp
浏览该文件的文档.
1// Copyright 2021 Arthur Sonzogni. All rights reserved.
2// Use of this source code is governed by the MIT license that can be found in
3// the LICENSE file.
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)
响应事件时调用。
代表一个事件。它可以是按键事件、终端大小调整等等...
#include "ftxui/component/component_base.hpp" // 用于 ComponentBase
std::shared_ptr< T > Make(Args &&... args)
std::function< Component(Component)> ComponentDecorator
std::shared_ptr< ComponentBase > Component
Component CatchEvent(Component child, std::function< bool(Event)>)