| 707 | } |
| 708 | |
| 709 | bool DataStorageBridge::UpdateNode(const std::string& uid, const Json& updates) |
| 710 | { |
| 711 | std::lock_guard<std::mutex> lock(m_Mutex); |
| 712 | return this->DispatchTask<bool>([this, uid, updates]() |
| 713 | { |
| 714 | auto dataStorage = m_DataStorage.Lock(); |
| 715 | if (dataStorage.IsNull()) |
| 716 | { |
| 717 | return false; |
| 718 | } |
| 719 | |
| 720 | mitk::DataNode::Pointer node = m_UidMapper->FindNodeByUid(uid); |
| 721 | if (node == nullptr) |
| 722 | { |
| 723 | return false; |
| 724 | } |
| 725 | |
| 726 | // Handle parent_uid for reparenting |
| 727 | if (!updates.contains("parent_uid")) |
| 728 | { |
| 729 | return false; |
| 730 | } |
| 731 | |
| 732 | DataNode::Pointer newParent; |
| 733 | if (!updates["parent_uid"].is_null()) |
| 734 | { |
| 735 | std::string newParentUid = updates["parent_uid"].get<std::string>(); |
| 736 | newParent = m_UidMapper->FindNodeByUid(newParentUid); |
| 737 | } |
| 738 | |
| 739 | if (newParent == node) |
| 740 | { // Prevent circular references: new parent cannot be the node itself or a descendant |
| 741 | return false; |
| 742 | } |
| 743 | |
| 744 | // Check if newParent is a descendant of node |
| 745 | auto descendants = dataStorage->GetDerivations(node, nullptr, true); |
| 746 | for (auto it = descendants->Begin(); it != descendants->End(); ++it) |
| 747 | { |
| 748 | if (it->Value() == newParent) |
| 749 | { |
| 750 | return false; // Would create circular reference |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | // Reparent: remove and re-add under new parent |
| 755 | // This is the same approach used by QmitkDataStorageTreeModel |
| 756 | // |
| 757 | // Important: Preserve the UID across reparenting operation. |
| 758 | // The NodeUidMapper clears mappings when a node is removed from DataStorage, |
| 759 | // so we save the UID and restore the mapping after re-adding. |
| 760 | const std::string preservedUid = uid; |
| 761 | |
| 762 | dataStorage->Remove(node); |
| 763 | if (newParent != nullptr) |
| 764 | { |
| 765 | dataStorage->Add(node, newParent); |
| 766 | } |