8000 Find and keep layers inside layer groups by tomerkon · Pull Request #169 · gimp-mcp/gimp-mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ right command when the versions differ.
before writing files. Include `{index}` in `name_pattern` to give same-named
images distinct paths. If a destination refers to a file already written
by the batch, the later export is skipped and reported as an error (#161).
- Tools that take a `layer_name` now find layers inside layer groups; before, they
answered `Layer '<name>' not found`. `layer_index` still counts only the image's
top-level layers.
- `reorder_layer` keeps a layer inside its layer group, with `new_position` as its index
in that group. Before, it moved the layer out of the group to the top level.
- `duplicate_layer` puts the copy of a layer inside a group directly above it, in the same
group. Before, the copy went to the top of the image. If GIMP refuses to insert the copy,
the tool now returns an error instead of reporting success.
- `apply_drop_shadow` on a layer inside a group puts the shadow directly below it, in the
same group. Before, the shadow went to the top level, where it could cover the layer it
belongs to or end up hidden under other layers.

## [0.6.0] - 2026-11-21

Expand Down
39 changes: 30 additions & 9 deletions gimp-mcp-plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2459,8 +2459,9 @@ def _resolve_layer(self, image, layer_name, layer_index):
if layer_index is not None:
layer_index = self._index(layer_index, "layer_index")
if layer_name is not None:
layers = image.get_layers()
for layer in layers:
# The whole tree, so layers inside groups are found too. GIMP keeps
# item names unique within an image, so at most one layer matches.
for layer in self._walk_layers(image.get_layers()):
if layer.get_name() == layer_name:
return layer
raise RuntimeError(f"Layer '{layer_name}' not found")
Expand Down Expand Up @@ -4132,12 +4133,20 @@ def _duplicate_layer(self, params):
layer_name = params.get("layer_name", None)
image = self._get_image(image_index)
layer = self._resolve_layer(image, layer_name, None)
layers = image.get_layers()
position = layers.index(layer) if layer in layers else 0
# The copy goes directly above the source, in the source's group.
parent = layer.get_parent()
position = image.get_item_position(layer)
image.undo_group_start()
try:
new_layer = layer.copy()
image.insert_layer(new_layer, None, position)
try:
self._check_ok(image.insert_layer(new_layer, parent, position),
"Inserting the copy")
except Exception:
# Never in the image, so free it here (after _check_ok has
# read GIMP's error: delete() is a PDB call too).
new_layer.delete()
raise
finally:
image.undo_group_end()
Gimp.displays_flush()
Expand Down Expand Up @@ -4230,8 +4239,10 @@ def _reorder_layer(self, params):
image = self._get_image(image_index)
layer = self._resolve_layer(image, layer_name, layer_index)
# One call, so one undo step without an undo group; an empty group
# would mark the image dirty when GIMP refuses the move.
self._check_ok(image.reorder_item(layer, None, new_position), "Moving the layer")
# would mark the image dirty when GIMP refuses the move. The layer
# stays in its own group, and new_position is its index there.
self._check_ok(image.reorder_item(layer, layer.get_parent(), new_position),
"Moving the layer")
Gimp.displays_flush()
return {"status": "success", "results": {"status": "success"}}
except Exception as e:
Expand Down Expand Up @@ -5159,9 +5170,19 @@ def _apply_drop_shadow(self, params):
try:

# 1. Duplicate source layer to use as shadow base
shadow_layer = drawable.copy()
# Directly below the source, in the source's group: the
# position is an index within that group.
parent = drawable.get_parent()
src_pos = image.get_item_position(drawable)
image.insert_layer(shadow_layer, None, src_pos + 1)
shadow_layer = drawable.copy()
try:
self._check_ok(image.insert_layer(shadow_layer, parent, src_pos + 1),
"Inserting the shadow layer")
except Exception:
# Never in the image, so free it here (after _check_ok has
# read GIMP's error: delete() is a PDB call too).
shadow_layer.delete()
raise
try:
self._build_drop_shadow(image, shadow_layer, shadow_color,
offset_x, offset_y, blur_radius, opacity)
Expand Down
38 changes: 19 additions & 19 deletions gimp_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1818,8 +1818,7 @@ def create_layer(
above the highest if they are non-group layers with the same parent; at the
top inside a selected group if the others are non-group layers directly
inside it; otherwise, or with nothing selected, at the top of the image.
Other negative values are rejected. Prefer 0 or more: other tools can't find a
layer inside a group by layer_name.
Other negative values are rejected.
The new layer becomes the selected layer. If the image has a floating
selection (a user can make one in GIMP), anchor it first, with call_api:
Gimp.floating_sel_anchor(image.get_floating_sel()). Until then the new layer
Expand Down Expand Up @@ -1852,10 +1851,11 @@ def duplicate_layer(
layer_name: str | None = None,
image_index: int = 0
) -> dict:
"""Duplicate a layer and insert the copy above it.
"""Duplicate a layer and insert the copy directly above it, in the same layer group.

Parameters:
- layer_name: Name of the layer to duplicate; defaults to the selected layer, else the top layer
- layer_name: Name of the layer to duplicate, also inside a layer group; defaults to
the selected layer, else the top layer
- image_index: Target image index (default 0)

Returns: {layer_name, layer_id}
Expand Down Expand Up @@ -1884,7 +1884,7 @@ def delete_layer(
"""Delete a layer from an image.

Parameters:
- layer_name: Name of the layer to delete
- layer_name: Name of the layer to delete, also inside a layer group
- layer_index: Position of the layer among the image's top-level layers, 0 = top
(alternative to layer_name)
- image_index: Target image index (default 0)
Expand Down Expand Up @@ -1921,7 +1921,7 @@ def rename_layer(

Parameters:
- new_name: New name for the layer
- old_name: Current name of the layer to rename
- old_name: Current name of the layer to rename, also inside a layer group
- layer_index: Position of the layer among the image's top-level layers, 0 = top
(alternative to old_name)
- image_index: Target image index (default 0)
Expand Down Expand Up @@ -1957,8 +1957,9 @@ def set_layer_properties(
"""Set properties on an existing layer.

Parameters:
- layer_name / layer_index: Identify the layer; layer_index is its position among the
image's top-level layers, 0 = top (defaults to the selected layer, else the top layer)
- layer_name / layer_index: Identify the layer; layer_name also finds layers inside
groups, and layer_index is its position among the image's top-level layers, 0 = top
(defaults to the selected layer, else the top layer)
- opacity: New opacity 0-100 (omit to leave unchanged)
- blend_mode: NORMAL, MULTIPLY, SCREEN, OVERLAY, DARKEN, LIGHTEN, DODGE, BURN,
HARD_LIGHT, SOFT_LIGHT, DIFFERENCE, HUE, SATURATION, COLOR, LUMINOSITY, or
Expand Down Expand Up @@ -1995,18 +1996,17 @@ def reorder_layer(
"""Move a layer to a new stack position.

Parameters:
- new_position: Target stack index among the image's top-level layers, counted
from the top: 0 = top, 1 = second from the top, and so on; a value past the
bottom moves the layer to the bottom, and a negative value moves it to the top.
A layer inside a layer group is moved out of the group.
- new_position: Target stack index among the layer's siblings, counted from the
top: 0 = top, 1 = second from the top, and so on; a value past the bottom moves
the layer to the bottom, and a negative value moves it to the top. A layer inside
a layer group stays in that group, and new_position is its index there.
- layer_name / layer_index: Identify the layer (defaults to the selected layer;
if several are selected, any one of them, so select only one). Both find only
top-level layers. To move a grouped layer, select it and leave both out, e.g.
via call_api: image.set_selected_layers([layer]). A layer just made by
create_layer is already selected. But while the image has a floating
selection, that is always the selected layer, so leaving both out moves it.
Anchor it before calling create_layer: anchoring afterwards selects the layer
it was pasted on, not the new one.
if several are selected, any one of them, so select only one). layer_name also
finds layers inside groups; layer_index counts only the image's top-level
layers, 0 = top. A layer just made by create_layer is already selected. But
while the image has a floating selection, that is always the selected layer,
so leaving both out moves it. Anchor it before calling create_layer: anchoring
afterwards selects the layer it was pasted on, not the new one.
- image_index: Target image index (default 0)

Returns status dict.
Expand Down
154 changes: 154 additions & 0 deletions tests/test_grouped_layers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""Offline test: layers inside layer groups (#131).

Checks, with fake layers, that:
- layer_name finds a layer inside a group (also nested two levels deep), and a
missing name is still an error;
- layer_index still counts only top-level layers;
- reorder_layer moves a layer within its own group;
- duplicate_layer inserts the copy in the source's group, at the source's index,
and a refused insert is an error that frees the copy;
- apply_drop_shadow inserts the shadow directly below the source, in its group,
and a refused insert is an error that frees the shadow layer.

Exits 0 on pass, 1 on fail.
"""
import unittest
from unittest.mock import Mock, call, patch

from test_pdb_status import install_gi_stub, load_plugin


class FakeLayer:
def __init__(self, name, children=None):
self.name = name
self.parent = None
self.children = children
for child in children or []:
child.parent = self

def get_name(self):
return self.name

def get_parent(self):
return self.parent

def is_group_layer(self):
return self.children is not None

def get_children(self):
return list(self.children)


class GroupedLayersTests(unittest.TestCase):
def setUp(self):
install_gi_stub()
module = load_plugin()
self.plugin = module.MCPPlugin()
# top
# outer/ (group)
# inner/ (group)
# deep
# child
# bottom
self.deep = FakeLayer("deep")
self.inner = FakeLayer("inner", [self.deep])
self.child = FakeLayer("child")
self.outer = FakeLayer("outer", [self.inner, self.child])
self.top, self.bottom = FakeLayer("top"), FakeLayer("bottom")
self.by_name = {layer.name: layer for layer in (
self.top, self.outer, self.inner, self.deep, self.child, self.bottom)}
self.image = Mock()
self.image.get_layers.return_value = [self.top, self.outer, self.bottom]
self.image.get_selected_layers.return_value = []
self.plugin._get_image = Mock(return_value=self.image)
flush = patch.object(module.Gimp, "displays_flush", Mock(), create=True)
flush.start()
self.addCleanup(flush.stop)
last_error = patch.object(module.Gimp, "get_pdb", Mock(), create=True)
last_error.start().return_value.get_last_error.return_value = "refused"
self.addCleanup(last_error.stop)

def test_layer_name_finds_layers_inside_groups(self):
for name, layer in (("top", self.top), ("outer", self.outer), ("inner", self.inner),
("deep", self.deep), ("child", self.child),
("bottom", self.bottom)):
with self.subTest(name=name):
self.assertIs(self.plugin._resolve_layer(self.image, name, None), layer)

def test_missing_layer_name_is_still_an_error(self):
with self.assertRaisesRegex(RuntimeError, "Layer 'nope' not found"):
self.plugin._resolve_layer(self.image, "nope", None)

def test_layer_index_counts_only_top_level_layers(self):
self.assertIs(self.plugin._resolve_layer(self.image, None, 1), self.outer)
self.assertIs(self.plugin._resolve_layer(self.image, None, 2), self.bottom)
with self.assertRaisesRegex(RuntimeError, "layer_index 3 out of range"):
self.plugin._resolve_layer(self.image, None, 3)

def test_reorder_layer_keeps_a_grouped_layer_in_its_group(self):
for name, parent in (("child", self.outer), ("deep", self.inner), ("top", None)):
with self.subTest(name=name):
self.image.reset_mock()
self.image.reorder_item.return_value = True
result = self.plugin._reorder_layer({"layer_name": name, "new_position": 1})
self.assertEqual(result["status"], "success", result)
self.assertEqual(self.image.reorder_item.mock_calls,
[call(self.by_name[name], parent, 1)])

def test_duplicate_layer_inserts_the_copy_in_the_source_group(self):
for name, parent, position in (("child", self.outer, 1), ("deep", self.inner, 0),
("bottom", None, 2)):
with self.subTest(name=name):
self.image.reset_mock()
self.image.get_item_position.return_value = position
source = self.by_name[name]
copy = Mock()
source.copy = Mock(return_value=copy)
result = self.plugin._duplicate_layer({"layer_name": name})
self.assertEqual(result["status"], "success", result)
self.image.get_item_position.assert_called_once_with(source)
self.image.insert_layer.assert_called_once_with(copy, parent, position)

def test_duplicate_layer_frees_the_copy_when_the_insert_is_refused(self):
self.image.insert_layer.return_value = False
self.image.get_item_position.return_value = 1
copy = Mock()
self.child.copy = Mock(return_value=copy)
result = self.plugin._duplicate_layer({"layer_name": "child"})
self.assertEqual(result["status"], "error", result)
self.assertIn("Inserting the copy failed: refused", result["error"])
copy.delete.assert_called_once_with()
self.image.undo_group_end.assert_called_once_with()

def _drop_shadow(self, name, inserted=True):
"""Run apply_drop_shadow on a fake layer; return (result, shadow layer)."""
self.image.reset_mock()
self.image.get_item_position.return_value = 1
self.image.insert_layer.return_value = inserted
source = self.by_name[name]
source.is_group = Mock(return_value=False)
shadow = Mock()
source.copy = Mock(return_value=shadow)
self.plugin._color = Mock()
self.plugin._build_drop_shadow = Mock()
return self.plugin._apply_drop_shadow({"layer_name": name}), shadow

def test_apply_drop_shadow_inserts_the_shadow_in_the_source_group(self):
for name, parent in (("child", self.outer), ("deep", self.inner), ("top", None)):
with self.subTest(name=name):
result, shadow = self._drop_shadow(name)
self.assertEqual(result["status"], "success", result)
self.image.get_item_position.assert_called_once_with(self.by_name[name])
self.image.insert_layer.assert_called_once_with(shadow, parent, 2)

def test_apply_drop_shadow_frees_the_shadow_when_the_insert_is_refused(self):
result, shadow = self._drop_shadow("child", inserted=False)
self.assertEqual(result["status"], "error", result)
self.assertIn("Inserting the shadow layer failed: refused", result["error"])
shadow.delete.assert_called_once_with()
self.plugin._build_drop_shadow.assert_not_called()
self.image.undo_group_end.assert_called_once_with()


if __name__ == "__main__":
unittest.main()
Loading
0