mindmap.mindmap module

class mindmap.mindmap.MindmapDocument(charttype: str = 'auto', turbo_mode: bool = False, inline_editing_mode: bool = False, mermaid_mode: bool = True, macos_access: str = 'appscript')

Bases: object

__init__(charttype: str = 'auto', turbo_mode: bool = False, inline_editing_mode: bool = False, mermaid_mode: bool = True, macos_access: str = 'appscript')

Initialize a MindmapDocument instance which automates MindManager operations.

Parameters:
  • charttype (str) – The type of chart to be used (orgchart, radial, auto).

  • turbo_mode (bool) – Flag for enabling turbo mode -> use only text.

  • inline_editing_mode (bool) – Flag for enabling inline editing mode.

  • mermaid_mode (bool) – Flag for enabling mermaid mode.

  • macos_access (str) – Method for accessing macOS features (default is ‘appscript’, alternative is ‘applescript’).

check_parent_exists(topic_guid, this_guid, visited=None)

Recursively check if a parent-child relationship exists between topics.

Parameters:
  • topic_guid (str) – The GUID of the topic to check.

  • this_guid (str) – The GUID that might be a parent of the topic.

  • visited (set, optional) – Set of visited GUIDs to avoid infinite recursion.

Returns:

True if the parent-child relationship exists, False otherwise.

Return type:

bool

clone_mindmap_topic(mindmap_topic, subtopics: list[MindmapTopic] = None, parent=None)

Clone a MindmapTopic instance including its subtopics.

Parameters:
  • mindmap_topic (MindmapTopic) – The topic to clone.

  • subtopics (list[MindmapTopic], optional) – A list of subtopics to clone.

  • parent – The parent for the cloned topic.

Returns:

A new instance that is a clone of the given topic.

Return type:

MindmapTopic

count_parent_and_child_occurrences(mindmap_topic, guid_counts, visited=None)

Recursively count the occurrences of parent and child relationships for each topic.

Parameters:
  • mindmap_topic (MindmapTopic) – The current topic in the mindmap.

  • guid_counts (dict) – Dictionary to store counts with topic GUID as keys.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

create_mindmap(verbose=False)

Create a MindManager mindmap document from the internal MindmapTopic structure. This includes counting occurrences, extracting tags/icons, and setting up relationships and links.

Parameters:

verbose (bool) – (Optional) Enable verbose output.

create_mindmap_and_finalize()

Create the mindmap document and finalize it.

finalize()

Finalize the mindmap document by ensuring the maximum topic level is set, then calling MindManager’s finalize.

get_grounding_information()

Extract grounding information from the mindmap, including the central topic and selected subtopics.

Returns:

(top_most_topic, subtopics) where top_most_topic is the central topic or a concatenated string

of non-selected topics, and subtopics is a comma-separated string of selected subtopics.

Return type:

tuple

get_library_folder()

Get the library folder used by MindManager.

Returns:

The path to the library folder.

get_map_icons_and_fix_refs_from_mindmap(mindmap, map_icons: list[MindmapIcon], visited=None)

Extract icons from mindmap topics and fix their references if needed.

Parameters:
  • mindmap (MindmapTopic) – The current topic in the mindmap.

  • map_icons (list[MindmapIcon]) – List to collect unique icons.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

get_max_topic_level(mindmap_topic, max_topic_level=0, visited=None)

Recursively compute the maximum topic level within the mind map.

Parameters:
  • mindmap_topic (MindmapTopic) – The current topic to evaluate.

  • max_topic_level (int) – The current maximum level found.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

Returns:

The highest topic level found in the mindmap.

Return type:

int

get_mindmap(topic=None, mode='full')

Retrieve the mind map structure from the currently open MindManager document.

Parameters:
  • topic – (Optional) A specific topic from which to start building the mindmap. If not provided, the central topic is used.

  • mode (str) – The mode to use to gather attributes (full=all attributes, content=text+rtf+notes, text=text only).

Returns:

True if the mind map was successfully retrieved, otherwise False.

Return type:

bool

get_mindmap_topic_from_topic(topic, parent_topic=None, mode='full')

Recursively convert a MindManager topic into a MindmapTopic object.

Parameters:
  • topic – The current MindManager topic to convert.

  • parent_topic (MindmapTopic) – The parent MindmapTopic, if any.

  • mode (str) – The mode to use to gather attributes (full=all attributes, content=text+rtf+notes, text=text only).

Returns:

The converted topic with its subtopics.

Return type:

MindmapTopic

get_parent_topic(topic)

Retrieve the parent topic for a given MindManager topic.

Parameters:

topic – The current topic from which to get the parent.

Returns:

The parent topic wrapped as a MindmapTopic, or None if at the root.

Return type:

MindmapTopic or None

get_parents_from_mindmap(mindmap, parents, visited=None)

Build a dictionary mapping subtopic GUIDs to their parent’s GUID.

Parameters:
  • mindmap (MindmapTopic) – The current topic in the mindmap.

  • parents (dict) – Dictionary to store parent-child GUID mappings.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

get_relationships_from_mindmap(mindmap, references, visited=None)

Recursively extract relationships (references) from the mindmap.

Parameters:
  • mindmap (MindmapTopic) – The current topic in the mindmap.

  • references (list[MindmapReference]) – List to collect the relationships.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

get_selection()

Retrieve the currently selected topics in the MindManager document.

Returns:

A list of MindmapTopic instances representing the selection.

Return type:

list[MindmapTopic]

get_tags_from_mindmap(mindmap, tags, visited=None)

Recursively collect unique tags from the mindmap.

Parameters:
  • mindmap (MindmapTopic) – The current topic in the mindmap.

  • tags (list[str]) – List to collect tag texts.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

Recursively extract topic links from the mindmap.

Parameters:
  • mindmap (MindmapTopic) – The current topic in the mindmap.

  • links (list[MindmapReference]) – List to collect topic links as MindmapReference objects.

  • visited (set) – Set of visited topic GUIDs to avoid infinite recursion.

get_topic_texts_from_selection(mindmap_topics)

Extract topic texts, levels, and GUIDs from selected topics.

Parameters:

mindmap_topics (list[MindmapTopic]) – List of topics to process.

set_background_image(image_path)

Set the background image for the MindManager document.

Parameters:

image_path (str) – The file path to the background image.

set_topic_from_mindmap_topic(topic, mindmap_topic, map_icons, done=None, done_global=None, level=0)

Create or update a MindManager topic from a MindmapTopic instance recursively.

Parameters:
  • topic – The current MindManager topic to update.

  • mindmap_topic (MindmapTopic) – The source MindmapTopic data.

  • map_icons (list[MindmapIcon]) – List of map icons to use.

  • done (dict, optional) – Dictionary tracking processed topics at current level.

  • done_global (dict, optional) – Global dictionary for tracking duplicate processing.

  • level (int) – Current hierarchical level.

Returns:

The processed MindmapTopic.

Return type:

MindmapTopic

update_done(topic_guid, mindmap_topic, level, done, done_global)

Update tracking dictionaries for processed topics and create duplicate links/tags.

Parameters:
  • topic_guid (str) – The GUID of the current topic in MindManager.

  • mindmap_topic (MindmapTopic) – The MindmapTopic being processed.

  • level (int) – The current level in the topic hierarchy.

  • done (dict) – Dictionary tracking topics processed at a given level.

  • done_global (dict) – Global dictionary tracking processed topics for duplicate detection.

class mindmap.mindmap.MindmapIcon(text: str = '', is_stock_icon=True, index: int = 1, signature: str = '', path: str = '', group: str = '')

Bases: object

__init__(text: str = '', is_stock_icon=True, index: int = 1, signature: str = '', path: str = '', group: str = '')

Initialize a MindmapIcon instance.

Parameters:
  • text (str) – The display text for the icon.

  • is_stock_icon (bool) – Flag indicating if the icon is a stock icon.

  • index (int) – The index of a stock icon.

  • signature (str) – A unique signature for the icon.

  • path (str) – File path to the icon if it is custom.

  • group (str) – The group/category of the icon.

class mindmap.mindmap.MindmapImage(text: str = '')

Bases: object

__init__(text: str = '')

Initialize a MindmapImage instance.

Parameters:

text (str) – Path to the image.

Bases: object

__init__(text: str = '', url: str = '', guid: str = '')

Initialize a MindmapLink instance.

Parameters:
  • text (str) – The display text for the link.

  • url (str) – The URL that the link points to.

  • guid (str) – A unique identifier for the link.

class mindmap.mindmap.MindmapNotes(text: str = '', xhtml: str = '', rtf: str = '')

Bases: object

__init__(text: str = '', xhtml: str = '', rtf: str = '')

Initialize a MindmapNotes instance.

Parameters:
  • text (str) – Plain text version of the notes.

  • xhtml (str) – XHTML formatted notes.

  • rtf (str) – RTF formatted notes.

class mindmap.mindmap.MindmapReference(guid_1: str = '', guid_2: str = '', direction: int = 1, label: str = '')

Bases: object

__init__(guid_1: str = '', guid_2: str = '', direction: int = 1, label: str = '')

Initialize a MindmapReference (relationship) instance.

Parameters:
  • guid_1 (str) – The GUID of the first topic.

  • guid_2 (str) – The GUID of the second topic.

  • direction (int) – The direction of the reference (1 indicates a standard direction).

  • label (str) – A label for the relationship.

class mindmap.mindmap.MindmapTag(text: str = '')

Bases: object

__init__(text: str = '')

Initialize a MindmapTag instance.

Parameters:

text (str) – The text representing the tag.

class mindmap.mindmap.MindmapTopic(guid: str = '', text: str = '', rtf: str = '', level: int = 0, selected: bool = False, parent: MindmapTopic = None, subtopics: list[MindmapTopic] = None, links: list[MindmapLink] = None, image: MindmapImage = None, icons: list[MindmapIcon] = None, notes: MindmapNotes = None, tags: list[MindmapTag] = None, references: list[MindmapReference] = None)

Bases: object

__init__(guid: str = '', text: str = '', rtf: str = '', level: int = 0, selected: bool = False, parent: MindmapTopic = None, subtopics: list[MindmapTopic] = None, links: list[MindmapLink] = None, image: MindmapImage = None, icons: list[MindmapIcon] = None, notes: MindmapNotes = None, tags: list[MindmapTag] = None, references: list[MindmapReference] = None)

Initialize a MindmapTopic instance.

Parameters:
  • guid (str) – Unique identifier for the topic.

  • text (str) – The text content of the topic.

  • rtf (str) – RTF formatted text for the topic.

  • level (int) – The hierarchical level of the topic.

  • selected (bool) – Flag to indicate if the topic is selected.

  • parent (MindmapTopic) – The parent topic if any.

  • subtopics (list[MindmapTopic]) – List of subtopics.

  • links (list[MindmapLink]) – List of associated links.

  • image (MindmapImage) – Associated image object.

  • icons (list[MindmapIcon]) – List of associated icons.

  • notes (MindmapNotes) – Associated notes.

  • tags (list[MindmapTag]) – List of associated tags.

  • references (list[MindmapReference]) – List of associated relationships.

Source code for mindmap.py
  1import uuid
  2
  3import mindm.mindmanager as mm
  4
  5DUPLICATED_TAG = 'Duplicated'
  6DUPLICATE_LABEL = 'DUPLICATE'
  7
  8class MindmapLink:
  9    def __init__(self, text: str = '', url: str = '', guid: str = ''):
 10        """
 11        Initialize a MindmapLink instance.
 12
 13        Args:
 14            text (str): The display text for the link.
 15            url (str): The URL that the link points to.
 16            guid (str): A unique identifier for the link.
 17        """
 18        self.text = text
 19        self.url = url
 20        self.guid = guid
 21
 22class MindmapImage:
 23    def __init__(self, text: str = ''):
 24        """
 25        Initialize a MindmapImage instance.
 26
 27        Args:
 28            text (str): Path to the image.
 29        """
 30        self.text = text
 31
 32class MindmapNotes:
 33    def __init__(self, text: str = '', xhtml: str = '', rtf: str = ''):
 34        """
 35        Initialize a MindmapNotes instance.
 36
 37        Args:
 38            text (str): Plain text version of the notes.
 39            xhtml (str): XHTML formatted notes.
 40            rtf (str): RTF formatted notes.
 41        """
 42        self.text = text
 43        self.xhtml = xhtml
 44        self.rtf = rtf
 45
 46class MindmapIcon:
 47    def __init__(self, 
 48                 text: str = '', 
 49                 is_stock_icon=True, 
 50                 index: int = 1, 
 51                 signature: str = '', 
 52                 path: str = '',
 53                 group: str = ''):
 54        """
 55        Initialize a MindmapIcon instance.
 56
 57        Args:
 58            text (str): The display text for the icon.
 59            is_stock_icon (bool): Flag indicating if the icon is a stock icon.
 60            index (int): The index of a stock icon.
 61            signature (str): A unique signature for the icon.
 62            path (str): File path to the icon if it is custom.
 63            group (str): The group/category of the icon.
 64        """
 65        self.text = text
 66        self.is_stock_icon = is_stock_icon
 67        self.index = index
 68        self.signature = signature
 69        self.path = path
 70        self.group = group
 71
 72class MindmapTag:
 73    def __init__(self, text: str = ''):
 74        """
 75        Initialize a MindmapTag instance.
 76
 77        Args:
 78            text (str): The text representing the tag.
 79        """
 80        self.text = text
 81
 82class MindmapReference:
 83    def __init__(self, 
 84                 guid_1: str = '', 
 85                 guid_2: str = '', 
 86                 direction: int = 1, 
 87                 label: str = ''):
 88        """
 89        Initialize a MindmapReference (relationship) instance.
 90
 91        Args:
 92            guid_1 (str): The GUID of the first topic.
 93            guid_2 (str): The GUID of the second topic.
 94            direction (int): The direction of the reference (1 indicates a standard direction).
 95            label (str): A label for the relationship.
 96        """
 97        self.guid_1 = guid_1
 98        self.guid_2 = guid_2
 99        self.direction = direction
100        self.label = label
101
102class MindmapTopic:
103    def __init__(self,
104                 guid: str = '',
105                 text: str = '',
106                 rtf: str = '',
107                 level: int = 0,
108                 selected: bool = False,
109                 parent: 'MindmapTopic' = None,
110                 subtopics: list['MindmapTopic'] = None,
111                 links: list['MindmapLink'] = None,
112                 image: 'MindmapImage' = None,
113                 icons: list['MindmapIcon'] = None,
114                 notes: 'MindmapNotes' = None,
115                 tags: list['MindmapTag'] = None,
116                 references: list['MindmapReference'] = None):
117        """
118        Initialize a MindmapTopic instance.
119
120        Args:
121            guid (str): Unique identifier for the topic.
122            text (str): The text content of the topic.
123            rtf (str): RTF formatted text for the topic.
124            level (int): The hierarchical level of the topic.
125            selected (bool): Flag to indicate if the topic is selected.
126            parent (MindmapTopic): The parent topic if any.
127            subtopics (list[MindmapTopic]): List of subtopics.
128            links (list[MindmapLink]): List of associated links.
129            image (MindmapImage): Associated image object.
130            icons (list[MindmapIcon]): List of associated icons.
131            notes (MindmapNotes): Associated notes.
132            tags (list[MindmapTag]): List of associated tags.
133            references (list[MindmapReference]): List of associated relationships.
134        """
135        self.guid = guid
136        self.text = text.replace('"', '`').replace("'", "`").replace("\r", "").replace("\n", "")
137        self.rtf = rtf
138        self.level = level
139        self.selected = selected
140        self.parent = parent
141        self.links = links if links is not None else []
142        self.image = image
143        self.icons = icons if icons is not None else []
144        self.notes = notes
145        self.tags = tags if tags is not None else []
146        self.references = references if references is not None else []
147        self.subtopics = subtopics if subtopics is not None else []
148
149
150class MindmapDocument:
151    def __init__(self, charttype: str = 'auto', turbo_mode: bool = False, inline_editing_mode: bool = False, mermaid_mode: bool = True, macos_access: str = 'appscript'):
152        """
153        Initialize a MindmapDocument instance which automates MindManager operations.
154
155        Args:
156            charttype (str): The type of chart to be used (orgchart, radial, auto).
157            turbo_mode (bool): Flag for enabling turbo mode -> use only text.
158            inline_editing_mode (bool): Flag for enabling inline editing mode.
159            mermaid_mode (bool): Flag for enabling mermaid mode.
160            macos_access (str): Method for accessing macOS features (default is 'appscript', alternative is 'applescript').
161        """
162        self.charttype: str = charttype
163        self.turbo_mode: bool = turbo_mode
164        self.inline_editing_mode: bool = inline_editing_mode
165        self.mermaid_mode: bool = mermaid_mode
166        self.macos_access: str = macos_access
167        self.mindmap: 'MindmapTopic' = None
168        self.central_topic_selected: bool = False
169        self.selected_topic_texts: list[str] = []
170        self.selected_topic_levels: list[int] = []
171        self.selected_topic_ids: list[str] = []
172        self.max_topic_level: int = 0
173        self.mindm = mm.Mindmanager(charttype, macos_access)
174
175    def get_mindmap(self, topic=None, mode='full'):
176        """
177        Retrieve the mind map structure from the currently open MindManager document.
178
179        Args:
180            topic: (Optional) A specific topic from which to start building the mindmap.
181                   If not provided, the central topic is used.
182            mode (str): The mode to use to gather attributes (full=all attributes, content=text+rtf+notes, text=text only).
183
184        Returns:
185            bool: True if the mind map was successfully retrieved, otherwise False.
186        """
187        if not self.mindm.document_exists():
188            print("No document found. Please open MindManager with a document.")    
189            return False
190
191        if topic is None:
192            topic = self.mindm.get_central_topic()
193        
194        if len(topic.subtopics) > 0:
195            mindmap = topic
196        else:
197            mindmap = self.get_mindmap_topic_from_topic(self.mindm.get_topic_by_id(topic.guid), mode=mode)
198
199        self.max_topic_level = self.get_max_topic_level(mindmap)
200        self.mindmap = mindmap
201        return True
202    
203    def get_max_topic_level(self, mindmap_topic, max_topic_level=0, visited=None):
204        """
205        Recursively compute the maximum topic level within the mind map.
206
207        Args:
208            mindmap_topic (MindmapTopic): The current topic to evaluate.
209            max_topic_level (int): The current maximum level found.
210            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
211
212        Returns:
213            int: The highest topic level found in the mindmap.
214        """
215        if visited is None:
216            visited = set()
217        if mindmap_topic.guid in visited:
218            return max_topic_level
219        visited.add(mindmap_topic.guid)
220        for subtopic in mindmap_topic.subtopics:
221            if subtopic.level > max_topic_level:
222                max_topic_level = subtopic.level
223            max_topic_level = self.get_max_topic_level(subtopic, max_topic_level, visited)
224        return max_topic_level
225
226    def get_parent_topic(self, topic):
227        """
228        Retrieve the parent topic for a given MindManager topic.
229
230        Args:
231            topic: The current topic from which to get the parent.
232
233        Returns:
234            MindmapTopic or None: The parent topic wrapped as a MindmapTopic, or None if at the root.
235        """
236        topic_level = self.mindm.get_level_from_topic(topic)
237        if topic_level == 0:
238            return None
239        parent_topic = self.mindm.get_parent_from_topic(topic)
240        parent_mindmap_topic = MindmapTopic(
241            guid=self.mindm.get_guid_from_topic(parent_topic),
242            text=self.mindm.get_text_from_topic(parent_topic), 
243            level=self.mindm.get_level_from_topic(parent_topic),
244            parent=self.get_parent_topic(parent_topic),
245        )
246        return parent_mindmap_topic
247
248    def get_selection(self):
249        """
250        Retrieve the currently selected topics in the MindManager document.
251
252        Returns:
253            list[MindmapTopic]: A list of MindmapTopic instances representing the selection.
254        """
255        selection = self.mindm.get_selection()
256        mindmap_topics = []
257        for topic in selection:
258            level = self.mindm.get_level_from_topic(topic)
259            mindmap_topic = MindmapTopic(
260                guid=self.mindm.get_guid_from_topic(topic),
261                text=self.mindm.get_text_from_topic(topic), 
262                level=level,
263                parent=self.get_parent_topic(topic),
264                selected=True,
265            )
266            mindmap_topics.append(mindmap_topic)
267        self.get_topic_texts_from_selection(mindmap_topics)
268        return mindmap_topics
269
270    def get_mindmap_topic_from_topic(self, topic, parent_topic=None, mode='full'):
271        """
272        Recursively convert a MindManager topic into a MindmapTopic object.
273
274        Args:
275            topic: The current MindManager topic to convert.
276            parent_topic (MindmapTopic): The parent MindmapTopic, if any.
277            mode (str): The mode to use to gather attributes (full=all attributes, content=text+rtf+notes, text=text only).
278
279        Returns:
280            MindmapTopic: The converted topic with its subtopics.
281        """
282        if mode == 'full':
283            mindmap_topic = self.mindm.get_mindmaptopic_from_topic_full(topic)
284            mindmap_topic.parent = parent_topic
285        elif mode == 'content':
286            mindmap_topic = self.mindm.get_mindmaptopic_from_topic_content(topic)
287        else:
288            mindmap_topic = self.mindm.get_mindmaptopic_from_topic(topic)
289
290        subtopics = self.mindm.get_subtopics_from_topic(topic)
291        mindmap_subtopics = []
292        for subtopic in subtopics:
293            child = self.get_mindmap_topic_from_topic(subtopic, parent_topic=mindmap_topic, mode=mode)
294            mindmap_subtopics.append(child)
295        mindmap_topic.subtopics = mindmap_subtopics
296        return mindmap_topic 
297
298    def get_relationships_from_mindmap(self, mindmap, references, visited=None):
299        """
300        Recursively extract relationships (references) from the mindmap.
301
302        Args:
303            mindmap (MindmapTopic): The current topic in the mindmap.
304            references (list[MindmapReference]): List to collect the relationships.
305            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
306        """
307        if visited is None:
308            visited = set()
309        if mindmap.guid in visited:
310            return
311        visited.add(mindmap.guid)
312        for reference in mindmap.references:
313            if reference.direction == 1:
314                references.append(MindmapReference(
315                    guid_1=reference.guid_1,
316                    guid_2=reference.guid_2,
317                    direction=reference.direction,
318                    label=reference.label
319                ))
320        for subtopic in mindmap.subtopics:
321            self.get_relationships_from_mindmap(subtopic, references, visited)
322
323    def get_topic_links_from_mindmap(self, mindmap, links, visited=None):
324        """
325        Recursively extract topic links from the mindmap.
326
327        Args:
328            mindmap (MindmapTopic): The current topic in the mindmap.
329            links (list[MindmapReference]): List to collect topic links as MindmapReference objects.
330            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
331        """
332        if visited is None:
333            visited = set()
334        if mindmap.guid in visited:
335            return
336        visited.add(mindmap.guid)
337        for link in mindmap.links:
338            if link.guid != '':
339                links.append(MindmapReference(
340                    guid_1=mindmap.guid, 
341                    guid_2=link.guid, 
342                    direction=1, 
343                    label=link.text
344                ))
345        for subtopic in mindmap.subtopics:
346            self.get_topic_links_from_mindmap(subtopic, links, visited)
347
348    def get_tags_from_mindmap(self, mindmap, tags, visited=None):
349        """
350        Recursively collect unique tags from the mindmap.
351
352        Args:
353            mindmap (MindmapTopic): The current topic in the mindmap.
354            tags (list[str]): List to collect tag texts.
355            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
356        """
357        if visited is None:
358            visited = set()
359        if mindmap.guid in visited:
360            return
361        visited.add(mindmap.guid)
362        for tag in mindmap.tags:
363            if tag.text != '' and tag.text not in tags:
364                tags.append(tag.text)
365        for subtopic in mindmap.subtopics:
366            self.get_tags_from_mindmap(subtopic, tags, visited)
367
368    def get_parents_from_mindmap(self, mindmap, parents, visited=None):
369        """
370        Build a dictionary mapping subtopic GUIDs to their parent's GUID.
371
372        Args:
373            mindmap (MindmapTopic): The current topic in the mindmap.
374            parents (dict): Dictionary to store parent-child GUID mappings.
375            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
376        """
377        if visited is None:
378            visited = set()
379        if mindmap.guid in visited:
380            return
381        visited.add(mindmap.guid)
382        for subtopic in mindmap.subtopics:
383            if subtopic.guid not in parents:
384                parents[subtopic.guid] = mindmap.guid
385                self.get_parents_from_mindmap(subtopic, parents, visited)
386        return
387
388    def get_map_icons_and_fix_refs_from_mindmap(self, mindmap, map_icons: list['MindmapIcon'], visited=None):
389        """
390        Extract icons from mindmap topics and fix their references if needed.
391
392        Args:
393            mindmap (MindmapTopic): The current topic in the mindmap.
394            map_icons (list[MindmapIcon]): List to collect unique icons.
395            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
396        """
397        if visited is None:
398            visited = set()
399        if mindmap.guid in visited:
400            return
401        visited.add(mindmap.guid)
402        
403        for i, topic_icon_ref in enumerate(mindmap.icons):
404            # Only process non-stock icons belonging to the 'Types' group
405            if not topic_icon_ref.is_stock_icon and topic_icon_ref.group == 'Types':
406                found = False
407                for map_icon in map_icons:
408                    if map_icon.signature == topic_icon_ref.signature:
409                        found = True
410                        new_icon = map_icon
411                        break
412                if not found:
413                    new_icon = MindmapIcon(
414                        text=topic_icon_ref.text, 
415                        index=topic_icon_ref.index,
416                        is_stock_icon=topic_icon_ref.is_stock_icon, 
417                        path=topic_icon_ref.path,
418                        signature=topic_icon_ref.signature,
419                        group=topic_icon_ref.group)                
420                    map_icons.append(new_icon)
421                mindmap.icons[i] = new_icon
422        for subtopic in mindmap.subtopics:
423            self.get_map_icons_and_fix_refs_from_mindmap(subtopic, map_icons, visited)
424
425    def count_parent_and_child_occurrences(self, mindmap_topic, guid_counts, visited=None):
426        """
427        Recursively count the occurrences of parent and child relationships for each topic.
428
429        Args:
430            mindmap_topic (MindmapTopic): The current topic in the mindmap.
431            guid_counts (dict): Dictionary to store counts with topic GUID as keys.
432            visited (set): Set of visited topic GUIDs to avoid infinite recursion.
433        """
434        if visited is None:
435            visited = set()
436        if str(mindmap_topic.guid) == '':
437            mindmap_topic.guid = str(uuid.uuid4())
438        if mindmap_topic.guid not in visited:
439            visited.add(mindmap_topic.guid)
440            if mindmap_topic.guid not in guid_counts:
441                guid_counts[mindmap_topic.guid] = {'parent': 0, 'child': 0}
442            for subtopic in mindmap_topic.subtopics:
443                if mindmap_topic.guid:
444                    guid_counts[mindmap_topic.guid]['parent'] += 1
445                if subtopic.guid:
446                    if subtopic.guid not in guid_counts:
447                        guid_counts[subtopic.guid] = {'parent': 0, 'child': 0}
448                    guid_counts[subtopic.guid]['child'] += 1
449                self.count_parent_and_child_occurrences(subtopic, guid_counts, visited)
450
451    def get_topic_texts_from_selection(self, mindmap_topics):
452        """
453        Extract topic texts, levels, and GUIDs from selected topics.
454
455        Args:
456            mindmap_topics (list[MindmapTopic]): List of topics to process.
457        """
458        topic_texts = []
459        topic_levels = []
460        topic_ids = []
461        central_topic_selected = False
462        for topic in mindmap_topics:
463            if topic.selected:
464                if topic.level > 0:
465                    topic_texts.append(topic.text)
466                    topic_levels.append(topic.level)
467                    topic_ids.append(topic.guid)
468                else:
469                    central_topic_selected = True
470
471        self.central_topic_selected = central_topic_selected
472        self.selected_topic_texts = topic_texts
473        self.selected_topic_levels = topic_levels
474        self.selected_topic_ids = topic_ids
475            
476    def clone_mindmap_topic(self, mindmap_topic, subtopics: list['MindmapTopic'] = None, parent=None):
477        """
478        Clone a MindmapTopic instance including its subtopics.
479
480        Args:
481            mindmap_topic (MindmapTopic): The topic to clone.
482            subtopics (list[MindmapTopic], optional): A list of subtopics to clone.
483            parent: The parent for the cloned topic.
484
485        Returns:
486            MindmapTopic: A new instance that is a clone of the given topic.
487        """
488        cloned_subtopics = []
489        if subtopics is not None:
490            for subtopic in subtopics:
491                cloned_subtopic = self.clone_mindmap_topic(subtopic)
492                cloned_subtopics.append(cloned_subtopic)
493        return MindmapTopic(
494            guid=mindmap_topic.guid,
495            text=mindmap_topic.text, 
496            rtf=mindmap_topic.rtf,
497            level=mindmap_topic.level,
498            parent=parent,
499            links=mindmap_topic.links,
500            image=mindmap_topic.image,
501            icons=mindmap_topic.icons,
502            notes=mindmap_topic.notes,
503            tags=mindmap_topic.tags,
504            subtopics=cloned_subtopics
505        )
506
507    def update_done(self, topic_guid, mindmap_topic, level, done, done_global):
508        """
509        Update tracking dictionaries for processed topics and create duplicate links/tags.
510
511        Args:
512            topic_guid (str): The GUID of the current topic in MindManager.
513            mindmap_topic (MindmapTopic): The MindmapTopic being processed.
514            level (int): The current level in the topic hierarchy.
515            done (dict): Dictionary tracking topics processed at a given level.
516            done_global (dict): Global dictionary tracking processed topics for duplicate detection.
517        """
518        if mindmap_topic.guid == '':
519            return
520        if level <= 1:
521            done = {}
522        elif level >= 2: 
523            done[mindmap_topic.guid] = [topic_guid] if mindmap_topic.guid not in done else done[mindmap_topic.guid] + [topic_guid]
524        if mindmap_topic.guid in done_global:
525            # Check for duplicate relationships and add links/tags accordingly.
526            if self.guid_counts[mindmap_topic.guid]['child'] < 11 and self.guid_counts[mindmap_topic.guid]['parent'] >= 0:
527                for i in range(len(done_global[mindmap_topic.guid])):
528                    link_from = topic_guid
529                    link_to = done_global[mindmap_topic.guid][i]
530                    self.mindm.add_topic_link(link_from, link_to, DUPLICATE_LABEL)
531                    self.mindm.add_topic_link(link_to, link_from, DUPLICATE_LABEL)
532                if len(done_global[mindmap_topic.guid]) == 1:
533                    self.mindm.add_tag_to_topic(topic=None, tag_text=DUPLICATED_TAG, topic_guid=done_global[mindmap_topic.guid][0])
534            self.mindm.add_tag_to_topic(topic=None, tag_text=DUPLICATED_TAG, topic_guid=topic_guid)
535            done_global[mindmap_topic.guid] = done_global[mindmap_topic.guid] + [topic_guid]
536        else:
537            done_global[mindmap_topic.guid] = [topic_guid]
538
539    def set_topic_from_mindmap_topic(self, topic, mindmap_topic, map_icons, done=None, done_global=None, level=0):
540        """
541        Create or update a MindManager topic from a MindmapTopic instance recursively.
542
543        Args:
544            topic: The current MindManager topic to update.
545            mindmap_topic (MindmapTopic): The source MindmapTopic data.
546            map_icons (list[MindmapIcon]): List of map icons to use.
547            done (dict, optional): Dictionary tracking processed topics at current level.
548            done_global (dict, optional): Global dictionary for tracking duplicate processing.
549            level (int): Current hierarchical level.
550            
551        Returns:
552            MindmapTopic: The processed MindmapTopic.
553        """
554        if done is None:
555            done = {}
556        if done_global is None:
557            done_global = {}
558        try:
559            if self.turbo_mode:
560                topic_guid = self.mindm.get_guid_from_topic(topic)
561                self.update_done(topic_guid, mindmap_topic, level, done, done_global)
562                for subtopic in mindmap_topic.subtopics:
563                    try:
564                        sub = self.mindm.add_subtopic_to_topic(topic, subtopic.text)
565                        self.set_topic_from_mindmap_topic(sub, subtopic, map_icons, done, done_global, level + 1)
566                    except Exception as e:
567                        print(f"Error(1) processing topic/subtopic {mindmap_topic.guid}/{subtopic.guid}: {e}")
568            else:
569                topic, topic_guid = self.mindm.set_topic_from_mindmap_topic(topic, mindmap_topic, map_icons)
570                self.update_done(topic_guid, mindmap_topic, level, done, done_global)
571
572                if mindmap_topic.subtopics and len(mindmap_topic.subtopics) > 0:
573                    # Sort subtopics alphabetically by text
574                    mindmap_topic.subtopics.sort(key=lambda sub: sub.text)
575
576                for subtopic in mindmap_topic.subtopics:
577                    try:
578                        if subtopic.guid in done:
579                            this_guid_as_parent_exists = self.check_parent_exists(topic_guid, subtopic.guid)
580                            if not this_guid_as_parent_exists:
581                                cloned_subtopic = self.clone_mindmap_topic(subtopic)
582                                sub = self.mindm.add_subtopic_to_topic(topic, cloned_subtopic.text)
583                                self.set_topic_from_mindmap_topic(sub, cloned_subtopic, map_icons, done, done_global, level + 1)
584                        else:
585                            sub = self.mindm.add_subtopic_to_topic(topic, subtopic.text)
586                            self.set_topic_from_mindmap_topic(sub, subtopic, map_icons, done, done_global, level + 1)
587                    except Exception as e:
588                        print(f"Error(2) processing topic/subtopic {mindmap_topic.guid}/{subtopic.guid}: {e}")
589            return mindmap_topic
590        except Exception as e:
591            print(f"Error in set_topic_from_mindmap_topic at level {level} with topic {mindmap_topic.guid}: {e}")
592
593    def check_parent_exists(self, topic_guid, this_guid, visited=None):
594        """
595        Recursively check if a parent-child relationship exists between topics.
596
597        Args:
598            topic_guid (str): The GUID of the topic to check.
599            this_guid (str): The GUID that might be a parent of the topic.
600            visited (set, optional): Set of visited GUIDs to avoid infinite recursion.
601
602        Returns:
603            bool: True if the parent-child relationship exists, False otherwise.
604        """
605        if visited is None:
606            visited = set()
607        if topic_guid in visited:
608            return False
609        visited.add(topic_guid)
610        
611        check = False
612        if topic_guid in self.parents:
613            parent_guid = self.parents[topic_guid]
614            if parent_guid == this_guid:
615                check = True
616            else:
617                check = self.check_parent_exists(parent_guid, this_guid, visited)
618        return check
619
620    def create_mindmap(self, verbose=False):
621        """
622        Create a MindManager mindmap document from the internal MindmapTopic structure.
623        This includes counting occurrences, extracting tags/icons, and setting up relationships and links.
624
625        Args:
626            verbose (bool): (Optional) Enable verbose output.
627        """
628        tags = []
629        map_icons = []
630        relationships = []
631        links = []
632
633        self.parents = {}
634        self.guid_counts = {}
635        self.count_parent_and_child_occurrences(self.mindmap, self.guid_counts)
636        self.get_parents_from_mindmap(self.mindmap, self.parents)
637
638        self.get_tags_from_mindmap(self.mindmap, tags)
639        self.get_map_icons_and_fix_refs_from_mindmap(self.mindmap, map_icons)
640        self.get_relationships_from_mindmap(self.mindmap, relationships)
641        self.get_topic_links_from_mindmap(self.mindmap, links)
642
643        self.mindm.add_document(0)
644        self.mindm.create_map_icons(map_icons)
645        self.mindm.create_tags(tags, DUPLICATED_TAG)
646
647        central_topic = self.mindm.get_central_topic()
648        self.mindm.set_text_to_topic(self.mindm.get_topic_by_id(central_topic.guid), self.mindmap.text)
649
650        done_global = {}
651        self.set_topic_from_mindmap_topic(
652            topic=self.mindm.get_topic_by_id(central_topic.guid),
653            mindmap_topic=self.mindmap,
654            map_icons=map_icons,
655            done={},
656            done_global=done_global)
657
658        # Create relationships between topics
659        for reference in relationships:
660            object1_guids = done_global[reference.guid_1]
661            object2_guids = done_global[reference.guid_2]
662            for object1_guid in object1_guids:
663                for object2_guid in object2_guids:
664                    self.mindm.add_relationship(object1_guid, object2_guid, reference.label)
665
666        # Create topic links
667        for link in links:
668            object1_guids = done_global[link.guid_1]
669            object2_guids = done_global[link.guid_2]
670            for object1_guid in object1_guids:
671                for object2_guid in object2_guids:
672                    self.mindm.add_topic_link(object1_guid, object2_guid, link.label)
673
674    def create_mindmap_and_finalize(self):
675        """
676        Create the mindmap document and finalize it.
677        """
678        self.create_mindmap()
679        self.finalize()
680
681    def finalize(self):
682        """
683        Finalize the mindmap document by ensuring the maximum topic level is set, then calling MindManager's finalize.
684        """
685        if self.max_topic_level == 0:
686            self.max_topic_level = self.get_max_topic_level(self.mindmap)
687        self.mindm.finalize(self.max_topic_level)
688    
689    def set_background_image(self, image_path):
690        """
691        Set the background image for the MindManager document.
692
693        Args:
694            image_path (str): The file path to the background image.
695        """
696        self.mindm.set_document_background_image(image_path)
697    
698    def get_library_folder(self):
699        """
700        Get the library folder used by MindManager.
701
702        Returns:
703            The path to the library folder.
704        """
705        return self.mindm.get_library_folder()
706    
707    def get_grounding_information(self):
708        """
709        Extract grounding information from the mindmap, including the central topic and selected subtopics.
710
711        Returns:
712            tuple: (top_most_topic, subtopics) where top_most_topic is the central topic or a concatenated string
713                   of non-selected topics, and subtopics is a comma-separated string of selected subtopics.
714        """
715        central_topic_text = self.mindmap.text
716        subtopics = ""
717        if len(self.selected_topic_texts) == 0: 
718            top_most_topic = central_topic_text
719        else:
720            if self.central_topic_selected:
721                top_most_topic = central_topic_text
722                subtopics =  ",".join(self.selected_topic_texts)
723            else:
724                min_level = min(self.selected_topic_levels)
725                max_level = max(self.selected_topic_levels)
726                if (min_level == max_level):
727                    top_most_topic = central_topic_text
728                    subtopics =  ",".join(self.selected_topic_texts)
729                else:
730                    top_most_topic = ""
731                    for i in range(len(self.selected_topic_levels)):
732                        if self.selected_topic_levels[i] != max_level:
733                            top_most_topic += self.selected_topic_texts[i] + "/"
734                        else:
735                            subtopics += self.selected_topic_texts[i] + ","
736
737                    if top_most_topic.endswith("/"):
738                        top_most_topic = top_most_topic[:-1]
739                    if subtopics.endswith(","):
740                        subtopics = subtopics[:-1]        
741        return top_most_topic, subtopics