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:
- 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:
- 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.
- get_topic_links_from_mindmap(mindmap, links, visited=None)¶
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:
- 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.
- class mindmap.mindmap.MindmapLink(text: str = '', url: str = '', guid: str = '')¶
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.
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.macos_access = macos_access
174 self.mindm = mm.Mindmanager(charttype, macos_access)
175
176 def get_mindmap(self, topic=None, mode='full'):
177 """
178 Retrieve the mind map structure from the currently open MindManager document.
179
180 Args:
181 topic: (Optional) A specific topic from which to start building the mindmap.
182 If not provided, the central topic is used.
183 mode (str): The mode to use to gather attributes (full=all attributes, content=text+rtf+notes, text=text only).
184
185 Returns:
186 bool: True if the mind map was successfully retrieved, otherwise False.
187 """
188 if self.macos_access == 'applescript' and self.mindm.platform == 'darwin':
189 # get whole mindmap
190 mindmap = self.mindm.get_central_topic()
191 else:
192 if topic is None:
193 topic = self.mindm.get_central_topic()
194
195 mindmap = self.get_mindmap_topic_from_topic(self.mindm.get_topic_by_id(topic.guid), mode=mode)
196
197 self.max_topic_level = self.get_max_topic_level(mindmap)
198 self.mindmap = mindmap
199 return True
200
201 def get_max_topic_level(self, mindmap_topic, max_topic_level=0, visited=None):
202 """
203 Recursively compute the maximum topic level within the mind map.
204
205 Args:
206 mindmap_topic (MindmapTopic): The current topic to evaluate.
207 max_topic_level (int): The current maximum level found.
208 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
209
210 Returns:
211 int: The highest topic level found in the mindmap.
212 """
213 if visited is None:
214 visited = set()
215 if mindmap_topic.guid in visited:
216 return max_topic_level
217 visited.add(mindmap_topic.guid)
218 for subtopic in mindmap_topic.subtopics:
219 if subtopic.level > max_topic_level:
220 max_topic_level = subtopic.level
221 max_topic_level = self.get_max_topic_level(subtopic, max_topic_level, visited)
222 return max_topic_level
223
224 def get_parent_topic(self, topic):
225 """
226 Retrieve the parent topic for a given MindManager topic.
227
228 Args:
229 topic: The current topic from which to get the parent.
230
231 Returns:
232 MindmapTopic or None: The parent topic wrapped as a MindmapTopic, or None if at the root.
233 """
234 topic_level = self.mindm.get_level_from_topic(topic)
235 if topic_level == 0:
236 return None
237 parent_topic = self.mindm.get_parent_from_topic(topic)
238 parent_mindmap_topic = MindmapTopic(
239 guid=self.mindm.get_guid_from_topic(parent_topic),
240 text=self.mindm.get_text_from_topic(parent_topic),
241 level=self.mindm.get_level_from_topic(parent_topic),
242 parent=self.get_parent_topic(parent_topic),
243 )
244 return parent_mindmap_topic
245
246 def get_selection(self):
247 """
248 Retrieve the currently selected topics in the MindManager document.
249
250 Returns:
251 list[MindmapTopic]: A list of MindmapTopic instances representing the selection.
252 """
253 selection = self.mindm.get_selection()
254 mindmap_topics = []
255 for topic in selection:
256 level = self.mindm.get_level_from_topic(topic)
257 mindmap_topic = MindmapTopic(
258 guid=self.mindm.get_guid_from_topic(topic),
259 text=self.mindm.get_text_from_topic(topic),
260 level=level,
261 parent=self.get_parent_topic(topic),
262 selected=True,
263 )
264 mindmap_topics.append(mindmap_topic)
265 self.get_topic_texts_from_selection(mindmap_topics)
266 return mindmap_topics
267
268 def get_mindmap_topic_from_topic(self, topic, parent_topic=None, mode='full'):
269 """
270 Recursively convert a MindManager topic into a MindmapTopic object.
271
272 Args:
273 topic: The current MindManager topic to convert.
274 parent_topic (MindmapTopic): The parent MindmapTopic, if any.
275 mode (str): The mode to use to gather attributes (full=all attributes, content=text+rtf+notes, text=text only).
276
277 Returns:
278 MindmapTopic: The converted topic with its subtopics.
279 """
280 if mode == 'full':
281 mindmap_topic = self.mindm.get_mindmaptopic_from_topic_full(topic)
282 mindmap_topic.parent = parent_topic
283 elif mode == 'content':
284 mindmap_topic = self.mindm.get_mindmaptopic_from_topic_content(topic)
285 else:
286 mindmap_topic = self.mindm.get_mindmaptopic_from_topic(topic)
287
288 subtopics = self.mindm.get_subtopics_from_topic(topic)
289 mindmap_subtopics = []
290 for subtopic in subtopics:
291 child = self.get_mindmap_topic_from_topic(subtopic, parent_topic=mindmap_topic, mode=mode)
292 mindmap_subtopics.append(child)
293 mindmap_topic.subtopics = mindmap_subtopics
294 return mindmap_topic
295
296 def get_relationships_from_mindmap(self, mindmap, references, visited=None):
297 """
298 Recursively extract relationships (references) from the mindmap.
299
300 Args:
301 mindmap (MindmapTopic): The current topic in the mindmap.
302 references (list[MindmapReference]): List to collect the relationships.
303 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
304 """
305 if visited is None:
306 visited = set()
307 if mindmap.guid in visited:
308 return
309 visited.add(mindmap.guid)
310 for reference in mindmap.references:
311 if reference.direction == 1:
312 references.append(MindmapReference(
313 guid_1=reference.guid_1,
314 guid_2=reference.guid_2,
315 direction=reference.direction,
316 label=reference.label
317 ))
318 for subtopic in mindmap.subtopics:
319 self.get_relationships_from_mindmap(subtopic, references, visited)
320
321 def get_topic_links_from_mindmap(self, mindmap, links, visited=None):
322 """
323 Recursively extract topic links from the mindmap.
324
325 Args:
326 mindmap (MindmapTopic): The current topic in the mindmap.
327 links (list[MindmapReference]): List to collect topic links as MindmapReference objects.
328 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
329 """
330 if visited is None:
331 visited = set()
332 if mindmap.guid in visited:
333 return
334 visited.add(mindmap.guid)
335 for link in mindmap.links:
336 if link.guid != '':
337 links.append(MindmapReference(
338 guid_1=mindmap.guid,
339 guid_2=link.guid,
340 direction=1,
341 label=link.text
342 ))
343 for subtopic in mindmap.subtopics:
344 self.get_topic_links_from_mindmap(subtopic, links, visited)
345
346 def get_tags_from_mindmap(self, mindmap, tags, visited=None):
347 """
348 Recursively collect unique tags from the mindmap.
349
350 Args:
351 mindmap (MindmapTopic): The current topic in the mindmap.
352 tags (list[str]): List to collect tag texts.
353 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
354 """
355 if visited is None:
356 visited = set()
357 if mindmap.guid in visited:
358 return
359 visited.add(mindmap.guid)
360 for tag in mindmap.tags:
361 if tag.text != '' and tag.text not in tags:
362 tags.append(tag.text)
363 for subtopic in mindmap.subtopics:
364 self.get_tags_from_mindmap(subtopic, tags, visited)
365
366 def get_parents_from_mindmap(self, mindmap, parents, visited=None):
367 """
368 Build a dictionary mapping subtopic GUIDs to their parent's GUID.
369
370 Args:
371 mindmap (MindmapTopic): The current topic in the mindmap.
372 parents (dict): Dictionary to store parent-child GUID mappings.
373 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
374 """
375 if visited is None:
376 visited = set()
377 if mindmap.guid in visited:
378 return
379 visited.add(mindmap.guid)
380 for subtopic in mindmap.subtopics:
381 if subtopic.guid not in parents:
382 parents[subtopic.guid] = mindmap.guid
383 self.get_parents_from_mindmap(subtopic, parents, visited)
384 return
385
386 def get_map_icons_and_fix_refs_from_mindmap(self, mindmap, map_icons: list['MindmapIcon'], visited=None):
387 """
388 Extract icons from mindmap topics and fix their references if needed.
389
390 Args:
391 mindmap (MindmapTopic): The current topic in the mindmap.
392 map_icons (list[MindmapIcon]): List to collect unique icons.
393 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
394 """
395 if visited is None:
396 visited = set()
397 if mindmap.guid in visited:
398 return
399 visited.add(mindmap.guid)
400
401 for i, topic_icon_ref in enumerate(mindmap.icons):
402 # Only process non-stock icons belonging to the 'Types' group
403 if not topic_icon_ref.is_stock_icon and topic_icon_ref.group == 'Types':
404 found = False
405 for map_icon in map_icons:
406 if map_icon.signature == topic_icon_ref.signature:
407 found = True
408 new_icon = map_icon
409 break
410 if not found:
411 new_icon = MindmapIcon(
412 text=topic_icon_ref.text,
413 index=topic_icon_ref.index,
414 is_stock_icon=topic_icon_ref.is_stock_icon,
415 path=topic_icon_ref.path,
416 signature=topic_icon_ref.signature,
417 group=topic_icon_ref.group)
418 map_icons.append(new_icon)
419 mindmap.icons[i] = new_icon
420 for subtopic in mindmap.subtopics:
421 self.get_map_icons_and_fix_refs_from_mindmap(subtopic, map_icons, visited)
422
423 def count_parent_and_child_occurrences(self, mindmap_topic, guid_counts, visited=None):
424 """
425 Recursively count the occurrences of parent and child relationships for each topic.
426
427 Args:
428 mindmap_topic (MindmapTopic): The current topic in the mindmap.
429 guid_counts (dict): Dictionary to store counts with topic GUID as keys.
430 visited (set): Set of visited topic GUIDs to avoid infinite recursion.
431 """
432 if visited is None:
433 visited = set()
434 if str(mindmap_topic.guid) == '':
435 mindmap_topic.guid = str(uuid.uuid4())
436 if mindmap_topic.guid not in visited:
437 visited.add(mindmap_topic.guid)
438 if mindmap_topic.guid not in guid_counts:
439 guid_counts[mindmap_topic.guid] = {'parent': 0, 'child': 0}
440 for subtopic in mindmap_topic.subtopics:
441 if mindmap_topic.guid:
442 guid_counts[mindmap_topic.guid]['parent'] += 1
443 if subtopic.guid:
444 if subtopic.guid not in guid_counts:
445 guid_counts[subtopic.guid] = {'parent': 0, 'child': 0}
446 guid_counts[subtopic.guid]['child'] += 1
447 self.count_parent_and_child_occurrences(subtopic, guid_counts, visited)
448
449 def get_topic_texts_from_selection(self, mindmap_topics):
450 """
451 Extract topic texts, levels, and GUIDs from selected topics.
452
453 Args:
454 mindmap_topics (list[MindmapTopic]): List of topics to process.
455 """
456 topic_texts = []
457 topic_levels = []
458 topic_ids = []
459 central_topic_selected = False
460 for topic in mindmap_topics:
461 if topic.selected:
462 if topic.level > 0:
463 topic_texts.append(topic.text)
464 topic_levels.append(topic.level)
465 topic_ids.append(topic.guid)
466 else:
467 central_topic_selected = True
468
469 self.central_topic_selected = central_topic_selected
470 self.selected_topic_texts = topic_texts
471 self.selected_topic_levels = topic_levels
472 self.selected_topic_ids = topic_ids
473
474 def clone_mindmap_topic(self, mindmap_topic, subtopics: list['MindmapTopic'] = None, parent=None):
475 """
476 Clone a MindmapTopic instance including its subtopics.
477
478 Args:
479 mindmap_topic (MindmapTopic): The topic to clone.
480 subtopics (list[MindmapTopic], optional): A list of subtopics to clone.
481 parent: The parent for the cloned topic.
482
483 Returns:
484 MindmapTopic: A new instance that is a clone of the given topic.
485 """
486 cloned_subtopics = []
487 if subtopics is not None:
488 for subtopic in subtopics:
489 cloned_subtopic = self.clone_mindmap_topic(subtopic)
490 cloned_subtopics.append(cloned_subtopic)
491 return MindmapTopic(
492 guid=mindmap_topic.guid,
493 text=mindmap_topic.text,
494 rtf=mindmap_topic.rtf,
495 level=mindmap_topic.level,
496 parent=parent,
497 links=mindmap_topic.links,
498 image=mindmap_topic.image,
499 icons=mindmap_topic.icons,
500 notes=mindmap_topic.notes,
501 tags=mindmap_topic.tags,
502 subtopics=cloned_subtopics
503 )
504
505 def update_done(self, topic_guid, mindmap_topic, level, done, done_global):
506 """
507 Update tracking dictionaries for processed topics and create duplicate links/tags.
508
509 Args:
510 topic_guid (str): The GUID of the current topic in MindManager.
511 mindmap_topic (MindmapTopic): The MindmapTopic being processed.
512 level (int): The current level in the topic hierarchy.
513 done (dict): Dictionary tracking topics processed at a given level.
514 done_global (dict): Global dictionary tracking processed topics for duplicate detection.
515 """
516 if mindmap_topic.guid == '':
517 return
518 if level <= 1:
519 done = {}
520 elif level >= 2:
521 done[mindmap_topic.guid] = [topic_guid] if mindmap_topic.guid not in done else done[mindmap_topic.guid] + [topic_guid]
522 if mindmap_topic.guid in done_global:
523 # Check for duplicate relationships and add links/tags accordingly.
524 if self.guid_counts[mindmap_topic.guid]['child'] < 11 and self.guid_counts[mindmap_topic.guid]['parent'] >= 0:
525 for i in range(len(done_global[mindmap_topic.guid])):
526 link_from = topic_guid
527 link_to = done_global[mindmap_topic.guid][i]
528 self.mindm.add_topic_link(link_from, link_to, DUPLICATE_LABEL)
529 self.mindm.add_topic_link(link_to, link_from, DUPLICATE_LABEL)
530 if len(done_global[mindmap_topic.guid]) == 1:
531 self.mindm.add_tag_to_topic(topic=None, tag_text=DUPLICATED_TAG, topic_guid=done_global[mindmap_topic.guid][0])
532 self.mindm.add_tag_to_topic(topic=None, tag_text=DUPLICATED_TAG, topic_guid=topic_guid)
533 done_global[mindmap_topic.guid] = done_global[mindmap_topic.guid] + [topic_guid]
534 else:
535 done_global[mindmap_topic.guid] = [topic_guid]
536
537 def set_topic_from_mindmap_topic(self, topic, mindmap_topic, map_icons, done=None, done_global=None, level=0):
538 """
539 Create or update a MindManager topic from a MindmapTopic instance recursively.
540
541 Args:
542 topic: The current MindManager topic to update.
543 mindmap_topic (MindmapTopic): The source MindmapTopic data.
544 map_icons (list[MindmapIcon]): List of map icons to use.
545 done (dict, optional): Dictionary tracking processed topics at current level.
546 done_global (dict, optional): Global dictionary for tracking duplicate processing.
547 level (int): Current hierarchical level.
548
549 Returns:
550 MindmapTopic: The processed MindmapTopic.
551 """
552 if done is None:
553 done = {}
554 if done_global is None:
555 done_global = {}
556 try:
557 if self.turbo_mode:
558 topic_guid = self.mindm.get_guid_from_topic(topic)
559 self.update_done(topic_guid, mindmap_topic, level, done, done_global)
560 for subtopic in mindmap_topic.subtopics:
561 try:
562 sub = self.mindm.add_subtopic_to_topic(topic, subtopic.text)
563 self.set_topic_from_mindmap_topic(sub, subtopic, map_icons, done, done_global, level + 1)
564 except Exception as e:
565 print(f"Error(1) processing topic/subtopic {mindmap_topic.guid}/{subtopic.guid}: {e}")
566 else:
567 topic, topic_guid = self.mindm.set_topic_from_mindmap_topic(topic, mindmap_topic, map_icons)
568 self.update_done(topic_guid, mindmap_topic, level, done, done_global)
569
570 if mindmap_topic.subtopics and len(mindmap_topic.subtopics) > 0:
571 # Sort subtopics alphabetically by text
572 mindmap_topic.subtopics.sort(key=lambda sub: sub.text)
573
574 for subtopic in mindmap_topic.subtopics:
575 try:
576 if subtopic.guid in done:
577 this_guid_as_parent_exists = self.check_parent_exists(topic_guid, subtopic.guid)
578 if not this_guid_as_parent_exists:
579 cloned_subtopic = self.clone_mindmap_topic(subtopic)
580 sub = self.mindm.add_subtopic_to_topic(topic, cloned_subtopic.text)
581 self.set_topic_from_mindmap_topic(sub, cloned_subtopic, map_icons, done, done_global, level + 1)
582 else:
583 sub = self.mindm.add_subtopic_to_topic(topic, subtopic.text)
584 self.set_topic_from_mindmap_topic(sub, subtopic, map_icons, done, done_global, level + 1)
585 except Exception as e:
586 print(f"Error(2) processing topic/subtopic {mindmap_topic.guid}/{subtopic.guid}: {e}")
587 return mindmap_topic
588 except Exception as e:
589 print(f"Error in set_topic_from_mindmap_topic at level {level} with topic {mindmap_topic.guid}: {e}")
590
591 def check_parent_exists(self, topic_guid, this_guid, visited=None):
592 """
593 Recursively check if a parent-child relationship exists between topics.
594
595 Args:
596 topic_guid (str): The GUID of the topic to check.
597 this_guid (str): The GUID that might be a parent of the topic.
598 visited (set, optional): Set of visited GUIDs to avoid infinite recursion.
599
600 Returns:
601 bool: True if the parent-child relationship exists, False otherwise.
602 """
603 if visited is None:
604 visited = set()
605 if topic_guid in visited:
606 return False
607 visited.add(topic_guid)
608
609 check = False
610 if topic_guid in self.parents:
611 parent_guid = self.parents[topic_guid]
612 if parent_guid == this_guid:
613 check = True
614 else:
615 check = self.check_parent_exists(parent_guid, this_guid, visited)
616 return check
617
618 def create_mindmap(self, verbose=False):
619 """
620 Create a MindManager mindmap document from the internal MindmapTopic structure.
621 This includes counting occurrences, extracting tags/icons, and setting up relationships and links.
622
623 Args:
624 verbose (bool): (Optional) Enable verbose output.
625 """
626 tags = []
627 map_icons = []
628 relationships = []
629 links = []
630
631 self.parents = {}
632 self.guid_counts = {}
633 self.count_parent_and_child_occurrences(self.mindmap, self.guid_counts)
634 self.get_parents_from_mindmap(self.mindmap, self.parents)
635
636 self.get_tags_from_mindmap(self.mindmap, tags)
637 self.get_map_icons_and_fix_refs_from_mindmap(self.mindmap, map_icons)
638 self.get_relationships_from_mindmap(self.mindmap, relationships)
639 self.get_topic_links_from_mindmap(self.mindmap, links)
640
641 self.mindm.add_document(0)
642 self.mindm.create_map_icons(map_icons)
643 self.mindm.create_tags(tags, DUPLICATED_TAG)
644
645 if self.mindm.platform == 'darwin' and self.macos_access == 'applescript':
646 self.mindm.set_topic_from_mindmap_topic(None, self.mindmap, map_icons)
647 self.get_mindmap()
648 else:
649 central_topic = self.mindm.get_central_topic()
650 self.mindm.set_text_to_topic(self.mindm.get_topic_by_id(central_topic.guid), self.mindmap.text)
651
652 done_global = {}
653 self.set_topic_from_mindmap_topic(
654 topic=self.mindm.get_topic_by_id(central_topic.guid),
655 mindmap_topic=self.mindmap,
656 map_icons=map_icons,
657 done={},
658 done_global=done_global)
659
660 # Create relationships between topics
661 for reference in relationships:
662 object1_guids = done_global[reference.guid_1]
663 object2_guids = done_global[reference.guid_2]
664 for object1_guid in object1_guids:
665 for object2_guid in object2_guids:
666 self.mindm.add_relationship(object1_guid, object2_guid, reference.label)
667
668 # Create topic links
669 for link in links:
670 object1_guids = done_global[link.guid_1]
671 object2_guids = done_global[link.guid_2]
672 for object1_guid in object1_guids:
673 for object2_guid in object2_guids:
674 self.mindm.add_topic_link(object1_guid, object2_guid, link.label)
675
676 def create_mindmap_and_finalize(self):
677 """
678 Create the mindmap document and finalize it.
679 """
680 self.create_mindmap()
681 self.finalize()
682
683 def finalize(self):
684 """
685 Finalize the mindmap document by ensuring the maximum topic level is set, then calling MindManager's finalize.
686 """
687 if self.max_topic_level == 0:
688 self.max_topic_level = self.get_max_topic_level(self.mindmap)
689 self.mindm.finalize(self.max_topic_level)
690
691 def set_background_image(self, image_path):
692 """
693 Set the background image for the MindManager document.
694
695 Args:
696 image_path (str): The file path to the background image.
697 """
698 self.mindm.set_document_background_image(image_path)
699
700 def get_library_folder(self):
701 """
702 Get the library folder used by MindManager.
703
704 Returns:
705 The path to the library folder.
706 """
707 return self.mindm.get_library_folder()
708
709 def get_grounding_information(self):
710 """
711 Extract grounding information from the mindmap, including the central topic and selected subtopics.
712
713 Returns:
714 tuple: (top_most_topic, subtopics) where top_most_topic is the central topic or a concatenated string
715 of non-selected topics, and subtopics is a comma-separated string of selected subtopics.
716 """
717 central_topic_text = self.mindmap.text
718 self.get_selection()
719 subtopics = ""
720 if len(self.selected_topic_texts) == 0:
721 top_most_topic = central_topic_text
722 else:
723 if self.central_topic_selected:
724 top_most_topic = central_topic_text
725 subtopics = ",".join(self.selected_topic_texts)
726 else:
727 min_level = min(self.selected_topic_levels)
728 max_level = max(self.selected_topic_levels)
729 if (min_level == max_level):
730 top_most_topic = central_topic_text
731 subtopics = ",".join(self.selected_topic_texts)
732 else:
733 top_most_topic = ""
734 for i in range(len(self.selected_topic_levels)):
735 if self.selected_topic_levels[i] != max_level:
736 top_most_topic += self.selected_topic_texts[i] + "/"
737 else:
738 subtopics += self.selected_topic_texts[i] + ","
739
740 if top_most_topic.endswith("/"):
741 top_most_topic = top_most_topic[:-1]
742 if subtopics.endswith(","):
743 subtopics = subtopics[:-1]
744 return top_most_topic, subtopics