aboutsummaryrefslogtreecommitdiff
path: root/src/ui/controls/Window.cpp
blob: f4714efa08dd38bde3b0260772ce2105d61cf07a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "cru/ui/controls/Window.h"
#include "cru/platform/gui/UiApplication.h"
#include "cru/platform/gui/Window.h"
#include "cru/ui/Base.h"
#include "cru/ui/controls/Control.h"
#include "cru/ui/controls/ControlHost.h"

#include <cassert>

namespace cru::ui::controls {
Window::Window()
    : LayoutControl<render::StackLayoutRenderObject>(kControlName),
      control_host_(new ControlHost(this)),
      attached_control_(nullptr) {
  GetContainerRenderObject()->SetDefaultHorizontalAlignment(Alignment::Stretch);
  GetContainerRenderObject()->SetDefaultVerticalAlignment(Alignment::Stretch);
}

Window* Window::CreatePopup(Control* attached_control) {
  auto window = new Window();
  window->GetNativeWindow()->SetStyleFlag(
      platform::gui::WindowStyleFlags::NoCaptionAndBorder);
  window->SetAttachedControl(attached_control);
  window->SetGainFocusOnCreateAndDestroyWhenLoseFocus(true);
  return window;
}

Control* Window::GetAttachedControl() { return attached_control_; }

void Window::SetAttachedControl(Control* control) {
  attached_control_ = control;
  if (control) {
    if (auto control_host = control->GetControlHost()) {
      control_host_->GetNativeWindow()->SetParent(
          control_host->GetNativeWindow());
    }
    parent_window_guard_.Reset(control->ControlHostChangeEvent()->AddHandler(
        [this](const ControlHostChangeEventArgs& args) {
          control_host_->GetNativeWindow()->SetParent(
              args.new_host ? args.new_host->GetNativeWindow() : nullptr);
        }));
  } else {
    control_host_->GetNativeWindow()->SetParent(nullptr);
    parent_window_guard_.Reset();
  }
}

platform::gui::INativeWindow* Window::GetNativeWindow() {
  return control_host_->GetNativeWindow();
}

void Window::SetGainFocusOnCreateAndDestroyWhenLoseFocus(bool value) {
  gain_focus_on_create_and_destroy_when_lose_focus_event_guard_.Clear();
  if (value) {
    gain_focus_on_create_and_destroy_when_lose_focus_event_guard_ +=
        GetNativeWindow()->VisibilityChangeEvent()->AddHandler(
            [this](platform::gui::WindowVisibilityType type) {
              if (type == platform::gui::WindowVisibilityType::Show) {
                GetNativeWindow()->RequestFocus();
              }
            });

    gain_focus_on_create_and_destroy_when_lose_focus_event_guard_ +=
        GetNativeWindow()->FocusEvent()->AddHandler(
            [this](platform::gui::FocusChangeType type) {
              if (type == platform::gui::FocusChangeType::Lose) {
                GetNativeWindow()->Close();
              }
            });
  }
}
}  // namespace cru::ui::controls