Skip to content

Commit

Permalink
Return null instead of throwing of Widget.child does not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
whitebyte authored and GrimMaple committed Nov 26, 2024
1 parent 3c38f32 commit a22f2aa
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
17 changes: 14 additions & 3 deletions src/dlangui/core/collections.d
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ module dlangui.core.collections;

import std.algorithm;

/**
/**
Array based collection of items.
Retains item order when during add/remove operations.
Expand All @@ -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)) {
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/dlangui/widgets/tree.d
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/dlangui/widgets/widget.d
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit a22f2aa

Please sign in to comment.