Skip to content

Commit

Permalink
Implement center window function.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jordyfel committed Aug 26, 2023
1 parent 6da4ad1 commit b50ad2d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions doc/classes/Window.xml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@
Returns whether the window is being drawn to the screen.
</description>
</method>
<method name="move_to_center">
<return type="void" />
<description>
Centers a native window on the current screen and an embedded window on its embedder [Viewport].
</description>
</method>
<method name="child_controls_changed">
<return type="void" />
<description>
Expand Down
20 changes: 20 additions & 0 deletions scene/main/window.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,25 @@ Point2i Window::get_position() const {
return position;
}

void Window::move_to_center() {
ERR_MAIN_THREAD_GUARD;
ERR_FAIL_COND(!is_inside_tree());

Rect2 parent_rect;

if (is_embedded()) {
parent_rect = get_embedder()->get_visible_rect();
} else {
int parent_screen = DisplayServer::get_singleton()->window_get_current_screen(get_window_id());
parent_rect.position = DisplayServer::get_singleton()->screen_get_position(parent_screen);
parent_rect.size = DisplayServer::get_singleton()->screen_get_size(parent_screen);
}

if (parent_rect != Rect2()) {
set_position(parent_rect.position + (parent_rect.size - get_size()) / 2);
}
}

void Window::set_size(const Size2i &p_size) {
ERR_MAIN_THREAD_GUARD;

Expand Down Expand Up @@ -2602,6 +2621,7 @@ void Window::_bind_methods() {

ClassDB::bind_method(D_METHOD("set_position", "position"), &Window::set_position);
ClassDB::bind_method(D_METHOD("get_position"), &Window::get_position);
ClassDB::bind_method(D_METHOD("move_to_center"), &Window::move_to_center);

ClassDB::bind_method(D_METHOD("set_size", "size"), &Window::set_size);
ClassDB::bind_method(D_METHOD("get_size"), &Window::get_size);
Expand Down
1 change: 1 addition & 0 deletions scene/main/window.h
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ class Window : public Viewport {

void set_position(const Point2i &p_position);
Point2i get_position() const;
void move_to_center();

void set_size(const Size2i &p_size);
Size2i get_size() const;
Expand Down

0 comments on commit b50ad2d

Please sign in to comment.