From a22f2aabd097510bd74fa8e0c5db894fbbd9fe57 Mon Sep 17 00:00:00 2001 From: Anton Pastukhov Date: Mon, 18 Nov 2024 21:51:00 +0200 Subject: [PATCH] Return null instead of throwing of Widget.child does not exist --- src/dlangui/core/collections.d | 17 ++++++++++++++--- src/dlangui/widgets/tree.d | 2 +- src/dlangui/widgets/widget.d | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/dlangui/core/collections.d b/src/dlangui/core/collections.d index 8b95b062..b62191ef 100644 --- a/src/dlangui/core/collections.d +++ b/src/dlangui/core/collections.d @@ -42,7 +42,7 @@ module dlangui.core.collections; import std.algorithm; -/** +/** Array based collection of items. Retains item order when during add/remove operations. @@ -62,10 +62,10 @@ struct Collection(T, bool ownItems = false) { @property void size(size_t newSize) { if (_len > newSize) length = newSize; // shrink - _items.length = newSize; + _items.length = newSize; } /// returns number of items in collection - @property void length(size_t newSize) { + @property void length(size_t newSize) { if (newSize < _len) { // shrink static if (is(T == class) || is(T == struct)) { @@ -248,6 +248,17 @@ struct ObjectList(T) { assert(index >= 0 && index < _count, "child index out of range"); return _list[index]; } + /// get item by index. Returns null if item not found + inout(T) tryGet(int index) @safe inout nothrow { + try { + if (index < 0 || index >= _count) { + return null; + } + return _list[index]; + } catch (Exception e) { + return null; + } + } /// get item by index T opIndex(int index) @safe { return get(index); diff --git a/src/dlangui/widgets/tree.d b/src/dlangui/widgets/tree.d index 0a089c49..bcfac847 100644 --- a/src/dlangui/widgets/tree.d +++ b/src/dlangui/widgets/tree.d @@ -279,7 +279,7 @@ class TreeItem { /// returns number of children of this widget @property int childCount() { return _children.count; } /// returns child by index - TreeItem child(int index) { return _children.get(index); } + TreeItem child(int index) { return _children.tryGet(index); } /// adds child, returns added item TreeItem addChild(TreeItem item, int index = -1) { TreeItem res = _children.insert(item, index).parent(this).level(_level + 1); diff --git a/src/dlangui/widgets/widget.d b/src/dlangui/widgets/widget.d index 2e760f60..8dc97685 100644 --- a/src/dlangui/widgets/widget.d +++ b/src/dlangui/widgets/widget.d @@ -1821,7 +1821,7 @@ class WidgetGroup : Widget { /// returns number of children of this widget @property override int childCount() const { return _children.count; } /// returns child by index - override inout(Widget) child(int index) inout { return _children.get(index); } + override inout(Widget) child(int index) inout { return _children.tryGet(index); } /// adds child, returns added item override Widget addChild(Widget item) { return _children.add(item).parent(this); } /// inserts child at given index, returns inserted item