1 /* praat_actions.cpp
2  *
3  * Copyright (C) 1992-2018,2020,2021 Paul Boersma
4  *
5  * This code is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at
8  * your option) any later version.
9  *
10  * This code is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13  * See the GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this work. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "praatP.h"
20 #include "praat_script.h"
21 #include "praat_version.h"
22 #include "../kar/longchar.h"
23 #include "machine.h"
24 #include "GuiP.h"
25 
26 #define BUTTON_LEFT  -240
27 #define BUTTON_RIGHT -5
28 
29 static OrderedOf <structPraat_Command> theActions;
praat_actions_exit_optimizeByLeaking()30 void praat_actions_exit_optimizeByLeaking () { theActions. _ownItems = false; }
31 static GuiMenu praat_writeMenu;
32 static GuiMenuItem praat_writeMenuSeparator;
33 static GuiForm praat_form;
34 static bool actionsInvisible = false;
35 
fixSelectionSpecification(ClassInfo * class1,integer * n1,ClassInfo * class2,integer * n2,ClassInfo * class3,integer * n3)36 static void fixSelectionSpecification (ClassInfo *class1, integer *n1, ClassInfo *class2, integer *n2, ClassInfo *class3, integer *n3) {
37 /*
38  * Function:
39  *	sort the specification pairs *class(i), *n(i) according to class name, with null classes at the end.
40  * Postconditions:
41  *	if (*class2) !! *class1;
42  *	if (*class3) !! *class2;
43  *	(*class1) -> className <= (*class2) -> className <= (*class3) -> className;
44  * Usage:
45  *	Called by praat_addAction () and praat_removeAction ().
46  */
47 
48 	/* Fix unusual input bubblewise. */
49 
50 	if (! *class1 && *class2) { *class1 = *class2; *n1 = *n2; *class2 = nullptr; *n2 = 0; }
51 	if (! *class2 && *class3) { *class2 = *class3; *n2 = *n3; *class3 = nullptr; *n3 = 0;
52 		if (! *class1 && *class2) { *class1 = *class2; *n1 = *n2; *class2 = nullptr; *n2 = 0; } }
53 
54 	/* Now: if *class3, then *class2, and if *class2, then *class1.
55 	 * Bubble-sort the input by class name.
56 	 */
57 	if (*class2 && str32cmp ((*class1) -> className, (*class2) -> className) > 0) {
58 		ClassInfo helpClass1 = *class1; *class1 = *class2; *class2 = helpClass1;
59 		integer helpN1 = *n1; *n1 = *n2; *n2 = helpN1;
60 	}
61 	if (*class3 && str32cmp ((*class2) -> className, (*class3) -> className) > 0) {
62 		ClassInfo helpClass2 = *class2; *class2 = *class3; *class3 = helpClass2;
63 		integer helpN2 = *n2; *n2 = *n3; *n3 = helpN2;
64 		if (str32cmp ((*class1) -> className, (*class2) -> className) > 0) {
65 			ClassInfo helpClass1 = *class1; *class1 = *class2; *class2 = helpClass1;
66 			integer helpN1 = *n1; *n1 = *n2; *n2 = helpN1;
67 		}
68 	}
69 }
70 
lookUpMatchingAction(ClassInfo class1,ClassInfo class2,ClassInfo class3,ClassInfo class4,conststring32 title)71 static integer lookUpMatchingAction (ClassInfo class1, ClassInfo class2, ClassInfo class3, ClassInfo class4, conststring32 title) {
72 /*
73  * An action command is fully specified by its environment (the selected classes) and its title.
74  * Precondition:
75  *	class1, class2, and class3 must be in sorted order.
76  */
77 	for (integer i = 1; i <= theActions.size; i ++) {
78 		Praat_Command action = theActions.at [i];
79 		if (class1 == action -> class1 && class2 == action -> class2 &&
80 		    class3 == action -> class3 && class4 == action -> class4 &&
81 		    title && action -> title && str32equ (action -> title.get(), title)) return i;
82 	}
83 	return 0;   // not found
84 }
85 
praat_addAction1_(ClassInfo class1,integer n1,conststring32 title,conststring32 after,uint32 flags,UiCallback callback,conststring32 nameOfCallback)86 void praat_addAction1_ (ClassInfo class1, integer n1,
87 	conststring32 title, conststring32 after, uint32 flags, UiCallback callback, conststring32 nameOfCallback)
88 { praat_addAction4_ (class1, n1, nullptr, 0, nullptr, 0, nullptr, 0, title, after, flags, callback, nameOfCallback); }
89 
praat_addAction2_(ClassInfo class1,integer n1,ClassInfo class2,integer n2,conststring32 title,conststring32 after,uint32 flags,UiCallback callback,conststring32 nameOfCallback)90 void praat_addAction2_ (ClassInfo class1, integer n1, ClassInfo class2, integer n2,
91 	conststring32 title, conststring32 after, uint32 flags, UiCallback callback, conststring32 nameOfCallback)
92 { praat_addAction4_ (class1, n1, class2, n2, nullptr, 0, nullptr, 0, title, after, flags, callback, nameOfCallback); }
93 
praat_addAction3_(ClassInfo class1,integer n1,ClassInfo class2,integer n2,ClassInfo class3,integer n3,conststring32 title,conststring32 after,uint32 flags,UiCallback callback,conststring32 nameOfCallback)94 void praat_addAction3_ (ClassInfo class1, integer n1, ClassInfo class2, integer n2, ClassInfo class3, integer n3,
95 	conststring32 title, conststring32 after, uint32 flags, UiCallback callback, conststring32 nameOfCallback)
96 { praat_addAction4_ (class1, n1, class2, n2, class3, n3, nullptr, 0, title, after, flags, callback, nameOfCallback); }
97 
praat_addAction4_(ClassInfo class1,integer n1,ClassInfo class2,integer n2,ClassInfo class3,integer n3,ClassInfo class4,integer n4,conststring32 title,conststring32 after,uint32 flags,UiCallback callback,conststring32 nameOfCallback)98 void praat_addAction4_ (ClassInfo class1, integer n1, ClassInfo class2, integer n2, ClassInfo class3, integer n3, ClassInfo class4, integer n4,
99 	conststring32 title, conststring32 after, uint32 flags, UiCallback callback, conststring32 nameOfCallback)
100 {
101 	try {
102 		int depth = flags, key = 0;
103 		bool unhidable = false, hidden = false, attractive = false;
104 		uint32 guiFlags = 0;
105 		if (flags > 7) {
106 			depth = ((flags & praat_DEPTH_7) >> 16);
107 			unhidable = (flags & praat_UNHIDABLE) != 0;
108 			hidden = (flags & praat_HIDDEN) != 0 && ! unhidable;
109 			key = flags & 0x000000FF;
110 			guiFlags = key ? flags & (0x000000FF | GuiMenu_SHIFT | GuiMenu_BUTTON_STATE_MASK) : flags & GuiMenu_BUTTON_STATE_MASK;
111 			attractive = (guiFlags & praat_ATTRACTIVE) != 0;
112 		}
113 		fixSelectionSpecification (& class1, & n1, & class2, & n2, & class3, & n3);
114 
115 		if (callback && ! title)
116 			Melder_throw (U"An action command with callback has no title. Classes: ",
117 				class1 ? class1 -> className : U"", U" ",
118 				class2 ? class2 -> className : U"", U" ",
119 				class3 ? class3 -> className : U"", U" ",
120 				class4 ? class4 -> className : U"", U".");
121 
122 		if (! class1)
123 			Melder_throw (U"The action command \"", title, U"\" has no first class.");
124 
125 		/*
126 		 * Determine the position of the new command.
127 		 */
128 		integer position;
129 		if (after && after [0] != U'*') {   // search for existing command with same selection
130 			integer found = lookUpMatchingAction (class1, class2, class3, class4, after);
131 			if (found == 0)
132 				Melder_throw (U"The action command \"", title, U"\" cannot be put after \"", after, U"\",\n"
133 					U"because the latter command does not exist.");
134 			position = found + 1;   // after 'after'
135 		} else {
136 			position = theActions.size + 1;   // at end
137 		}
138 
139 		/*
140 		 * Make new command.
141 		 */
142 		autoPraat_Command action = Thing_new (Praat_Command);
143 		action -> class1 = class1;
144 		action -> n1 = n1;
145 		action -> class2 = class2;
146 		action -> n2 = n2;
147 		action -> class3 = class3;
148 		action -> n3 = n3;
149 		action -> class4 = class4;
150 		action -> n4 = n4;
151 		action -> title = Melder_dup_f (title);
152 		action -> depth = depth;
153 		action -> callback = callback;   // null for a separator
154 		action -> nameOfCallback = nameOfCallback;
155 		action -> button = nullptr;
156 		action -> script = autostring32();
157 		action -> hidden = hidden;
158 		action -> unhidable = unhidable;
159 		action -> attractive = attractive;
160 
161 		/*
162 		 * Insert new command.
163 		 */
164 		theActions. addItemAtPosition_move (action.move(), position);
165 	} catch (MelderError) {
166 		Melder_flushError ();
167 	}
168 }
169 
deleteDynamicMenu()170 static void deleteDynamicMenu () {
171 	if (praatP.phase != praat_HANDLING_EVENTS) return;
172 	if (actionsInvisible) return;
173 	static integer numberOfDeletions;
174 	trace (U"deletion #", ++ numberOfDeletions);
175 	for (integer i = 1; i <= theActions.size; i ++) {
176 		Praat_Command action = theActions.at [i];
177 		if (action -> button) {
178 			trace (U"trying to destroy action ", i, U" of ", theActions.size, U": ", action -> title.get());
179 			#if gtk || cocoa
180 				if (action -> button -> d_parent == praat_form) {
181 					trace (U"destroy a label or a push button or a cascade button");
182 					GuiObject_destroy (action -> button -> d_widget);
183 				} else if (praat_writeMenu && action -> button -> d_parent == praat_writeMenu) {
184 					trace (U"destroying Save menu item");
185 					GuiObject_destroy (action -> button -> d_widget);
186 				}
187 			#elif motif
188 				if (action -> button -> classInfo == classGuiButton && action -> button -> d_widget -> subMenuId) {   // a cascade button (not a direct child of the form)?
189 					trace (U"destroy the xm menu bar; this also destroys the xm button and the xm menu");
190 					GuiObject_destroy (action -> button -> d_widget -> parent);   // the Motif parent, i.e. not d_parent -> d_widget !
191 				} else if (action -> button -> d_parent == praat_form) {
192 					trace (U"destroy a label or a push button");
193 					GuiObject_destroy (action -> button -> d_widget);
194 				}
195 			#endif
196 			action -> button = nullptr;   // undangle
197 		}
198 	}
199 	if (praat_writeMenu) {
200 		#if gtk || cocoa
201 			if (praat_writeMenuSeparator) {
202 				trace (U"destroy the Save menu separator");
203 				GuiObject_destroy (praat_writeMenuSeparator -> d_widget);
204 			}
205 			//praat_writeMenu -> f_empty ();
206 		#elif motif
207 			GuiObject_destroy (praat_writeMenu -> d_xmMenuTitle);
208 			GuiObject_destroy (praat_writeMenu -> d_widget);
209 			praat_writeMenu = GuiMenu_createInWindow (praatP.menuBar, U"Save", 0);
210 		#endif
211 		praat_writeMenuSeparator = nullptr;   // undangle
212 	}
213 	actionsInvisible = true;
214 }
215 
updateDynamicMenu()216 static void updateDynamicMenu () {
217 	if (praatP.phase != praat_HANDLING_EVENTS) return;
218 	praat_sortActions ();
219 	deleteDynamicMenu ();
220 	praat_show ();
221 }
222 
praat_addActionScript(conststring32 className1,integer n1,conststring32 className2,integer n2,conststring32 className3,integer n3,conststring32 title,conststring32 after,integer depth,conststring32 script)223 void praat_addActionScript (conststring32 className1, integer n1, conststring32 className2, integer n2, conststring32 className3, integer n3,
224 	conststring32 title, conststring32 after, integer depth, conststring32 script)
225 {
226 	try {
227 		ClassInfo class1 = nullptr, class2 = nullptr, class3 = nullptr;
228 		Melder_assert (className1 && className2 && className3 && title && after && script);
229 		if (className1 [0] != U'\0')
230 			class1 = Thing_classFromClassName (className1, nullptr);
231 		if (className2 [0] != U'\0')
232 			class2 = Thing_classFromClassName (className2, nullptr);
233 		if (className3 [0] != U'\0')
234 			class3 = Thing_classFromClassName (className3, nullptr);
235 		fixSelectionSpecification (& class1, & n1, & class2, & n2, & class3, & n3);
236 
237 		if (script [0] != U'\0' && title [0] == U'\0')
238 			Melder_throw (U"Command with callback has no title. Classes: ", className1, U" ", className2, U" ", className3, U".");
239 
240 		if (className1 [0] == U'\0')
241 			Melder_throw (U"Command \"", title, U"\" has no first class.");
242 
243 		/*
244 		 * If the button already exists, remove it.
245 		 */
246 		{// scope
247 			integer found = lookUpMatchingAction (class1, class2, class3, nullptr, title);
248 			if (found)
249 				theActions. removeItem (found);
250 		}
251 
252 		/*
253 		 * Determine the position of the new command.
254 		 */
255 		integer position;
256 		if (after [0] != U'\0') {   // search for existing command with same selection
257 			integer found = lookUpMatchingAction (class1, class2, class3, nullptr, after);
258 			if (found) {
259 				position = found + 1;   // after 'after'
260 			} else {
261 				position = theActions.size + 1;   // at end
262 			}
263 		} else {
264 			position = theActions.size + 1;   // at end
265 		}
266 
267 		/*
268 		 * Create new command.
269 		 */
270 		autoPraat_Command action = Thing_new (Praat_Command);
271 		action -> class1 = class1;
272 		action -> n1 = n1;
273 		action -> class2 = class2;
274 		action -> n2 = n2;
275 		action -> class3 = class3;
276 		action -> n3 = n3;
277 		action -> title = title [0] != U'\0' ? Melder_dup_f (title) : autostring32();   // allow old-fashioned untitled separators
278 		action -> depth = depth;
279 		action -> callback = ( script [0] != U'\0' ? DO_RunTheScriptFromAnyAddedMenuCommand : nullptr );   // null for a separator
280 		action -> button = nullptr;
281 		if (script [0] == U'\0') {
282 			action -> script = autostring32();
283 		} else {
284 			structMelderFile file { };
285 			Melder_relativePathToFile (script, & file);
286 			action -> script = Melder_dup_f (Melder_fileToPath (& file));
287 		}
288 		action -> after = ( after [0] != U'\0' ? Melder_dup_f (after) : autostring32() );
289 		action -> phase = praatP.phase;
290 		if (praatP.phase >= praat_READING_BUTTONS) {
291 			static integer uniqueID = 0;
292 			action -> uniqueID = ++ uniqueID;
293 		}
294 
295 		/*
296 		 * Insert new command.
297 		 */
298 		theActions. addItemAtPosition_move (action.move(), position);
299 		updateDynamicMenu ();
300 	} catch (MelderError) {
301 		Melder_throw (U"Praat: script action not added.");
302 	}
303 }
304 
praat_removeAction(ClassInfo class1,ClassInfo class2,ClassInfo class3,conststring32 title)305 void praat_removeAction (ClassInfo class1, ClassInfo class2, ClassInfo class3, conststring32 title) {
306 	try {
307 		integer n1, n2, n3;
308 		fixSelectionSpecification (& class1, & n1, & class2, & n2, & class3, & n3);
309 		integer found = lookUpMatchingAction (class1, class2, class3, nullptr, title);
310 		if (! found) {
311 			Melder_throw (U"Action command \"", class1 -> className,
312 				class2 ? U" & ": U"", class2 -> className,
313 				class3 ? U" & ": U"", class3 -> className,
314 				U": ", title, U"\" not found.");
315 		}
316 		theActions. removeItem (found);
317 	} catch (MelderError) {
318 		Melder_throw (U"Praat: action not removed.");
319 	}
320 }
321 
praat_removeAction_classNames(conststring32 className1,conststring32 className2,conststring32 className3,conststring32 title)322 void praat_removeAction_classNames (conststring32 className1, conststring32 className2,
323 	conststring32 className3, conststring32 title)
324 {
325 	try {
326 		ClassInfo class1 = nullptr, class2 = nullptr, class3 = nullptr;
327 		Melder_assert (className1 && className2 && className3 && title);
328 		if (className1 [0] != U'\0')
329 			class1 = Thing_classFromClassName (className1, nullptr);
330 		if (className2 [0] != U'\0')
331 			class2 = Thing_classFromClassName (className2, nullptr);
332 		if (className3 [0] != U'\0')
333 			class3 = Thing_classFromClassName (className3, nullptr);
334 		praat_removeAction (class1, class2, class3, title);
335 		updateDynamicMenu ();
336 	} catch (MelderError) {
337 		Melder_throw (U"Praat: action not removed.");
338 	}
339 }
340 
praat_hideAction(ClassInfo class1,ClassInfo class2,ClassInfo class3,conststring32 title)341 void praat_hideAction (ClassInfo class1, ClassInfo class2, ClassInfo class3, conststring32 title) {
342 	try {
343 		integer n1, n2, n3;
344 		fixSelectionSpecification (& class1, & n1, & class2, & n2, & class3, & n3);
345 		integer found = lookUpMatchingAction (class1, class2, class3, nullptr, title);
346 		if (! found) {
347 			Melder_throw (U"Praat: action command \"", class1 ? class1 -> className : nullptr,
348 				class2 ? U" & ": nullptr, class2 ? class2 -> className : nullptr,
349 				class3 ? U" & ": nullptr, class3 ? class3 -> className : nullptr,
350 				U": ", title, U"\" not found.");
351 		}
352 		Praat_Command action = theActions.at [found];
353 		if (! action -> hidden) {
354 			action -> hidden = true;
355 			if (praatP.phase >= praat_READING_BUTTONS) action -> toggled = ! action -> toggled;
356 			updateDynamicMenu ();
357 		}
358 	} catch (MelderError) {
359 		Melder_throw (U"Praat: action not hidden.");
360 	}
361 }
362 
praat_hideAction_classNames(conststring32 className1,conststring32 className2,conststring32 className3,conststring32 title)363 void praat_hideAction_classNames (conststring32 className1, conststring32 className2,
364 	conststring32 className3, conststring32 title)
365 {
366 	try {
367 		ClassInfo class1 = nullptr, class2 = nullptr, class3 = nullptr;
368 		Melder_assert (className1 && className2 && className3 && title);
369 		if (className1 [0] != U'\0')
370 			class1 = Thing_classFromClassName (className1, nullptr);
371 		if (className2 [0] != U'\0')
372 			class2 = Thing_classFromClassName (className2, nullptr);
373 		if (className3 [0] != U'\0')
374 			class3 = Thing_classFromClassName (className3, nullptr);
375 		praat_hideAction (class1, class2, class3, title);
376 	} catch (MelderError) {
377 		Melder_throw (U"Praat: action not hidden.");
378 	}
379 }
380 
praat_showAction(ClassInfo class1,ClassInfo class2,ClassInfo class3,conststring32 title)381 void praat_showAction (ClassInfo class1, ClassInfo class2, ClassInfo class3, conststring32 title) {
382 	try {
383 		integer n1, n2, n3;
384 		fixSelectionSpecification (& class1, & n1, & class2, & n2, & class3, & n3);
385 		integer found = lookUpMatchingAction (class1, class2, class3, nullptr, title);
386 		if (! found) {
387 			Melder_throw (U"Action command \"", class1 ? class1 -> className : nullptr,
388 				class2 ? U" & ": nullptr, class2 ? class2 -> className : nullptr,
389 				class3 ? U" & ": nullptr, class3 ? class3 -> className : nullptr,
390 				U": ", title, U"\" not found.");
391 		}
392 		Praat_Command action = theActions.at [found];
393 		if (action -> hidden) {
394 			action -> hidden = false;
395 			if (praatP.phase >= praat_READING_BUTTONS) action -> toggled = ! action -> toggled;
396 			updateDynamicMenu ();
397 		}
398 	} catch (MelderError) {
399 		Melder_throw (U"Praat: action not shown.");
400 	}
401 }
402 
praat_showAction_classNames(conststring32 className1,conststring32 className2,conststring32 className3,conststring32 title)403 void praat_showAction_classNames (conststring32 className1, conststring32 className2,
404 	conststring32 className3, conststring32 title)
405 {
406 	try {
407 		ClassInfo class1 = nullptr, class2 = nullptr, class3 = nullptr;
408 		Melder_assert (className1 && className2 && className3 && title);
409 		if (className1 [0] != U'\0')
410 			class1 = Thing_classFromClassName (className1, nullptr);
411 		if (className2 [0] != U'\0')
412 			class2 = Thing_classFromClassName (className2, nullptr);
413 		if (className3 [0] != U'\0')
414 			class3 = Thing_classFromClassName (className3, nullptr);
415 		praat_showAction (class1, class2, class3, title);
416 	} catch (MelderError) {
417 		Melder_throw (U"Praat: action not shown.");
418 	}
419 }
420 
praat_sortActions()421 void praat_sortActions () {
422 	for (integer i = 1; i <= theActions.size; i ++) {
423 		Praat_Command action = theActions.at [i];
424 		action -> sortingTail = i;
425 	}
426 	std::sort (theActions.begin(), theActions.end(),
427 		[] (Praat_Command me, Praat_Command thee) {
428 			int compare = str32cmp (my class1 -> className, thy class1 -> className);
429 			if (compare != 0)
430 				return my class1 == classDaata ? true : thy class1 == classDaata ? false : ( compare < 0 );
431 			if (my class2) {
432 				if (! thy class2)
433 					return false;
434 				compare = str32cmp (my class2 -> className, thy class2 -> className);
435 				if (compare != 0)
436 					return compare < 0;
437 			} else if (thy class2)
438 				return true;
439 			if (my class3) {
440 				if (! thy class3)
441 					return false;
442 				compare = str32cmp (my class3 -> className, thy class3 -> className);
443 				if (compare != 0)
444 					return compare < 0;
445 			} else if (thy class3)
446 				return true;
447 			return my sortingTail < thy sortingTail;
448 		}
449 	);
450 }
451 
numberString(integer number)452 static conststring32 numberString (integer number) {
453 	return number == 1 ? U"one" : number == 2 ? U"two" : number == 3 ? U"three" : U"any number of";
454 }
classString(ClassInfo klas)455 static conststring32 classString (ClassInfo klas) {
456 	return klas == classDaata ? U"" : klas -> className;
457 }
objectString(integer number)458 static conststring32 objectString (integer number) {
459 	return number == 1 ? U"object" : U"objects";
460 }
allowExecutionHook(void * closure)461 static bool allowExecutionHook (void *closure) {
462 	UiCallback callback = (UiCallback) closure;
463 	Melder_assert (sizeof (callback) == sizeof (void *));
464 	integer numberOfMatchingCallbacks = 0, firstMatchingCallback = 0;
465 	for (integer i = 1; i <= theActions.size; i ++) {
466 		Praat_Command me = theActions.at [i];
467 		if (my callback == callback) {
468 			integer sel1, sel2 = 0, sel3 = 0, sel4 = 0;
469 			if (! my class1) Melder_throw (U"No class1???");
470 			numberOfMatchingCallbacks += 1;
471 			if (! firstMatchingCallback) firstMatchingCallback = i;
472 			sel1 = my class1 == classDaata ? theCurrentPraatObjects -> totalSelection : praat_numberOfSelected (my class1);
473 			if (sel1 == 0) continue;
474 			if (my class2 && (sel2 = praat_numberOfSelected (my class2)) == 0) continue;
475 			if (my class3 && (sel3 = praat_numberOfSelected (my class3)) == 0) continue;
476 			if (my class4 && (sel4 = praat_numberOfSelected (my class4)) == 0) continue;
477 			if (sel1 + sel2 + sel3 + sel4 != theCurrentPraatObjects -> totalSelection) continue;
478 			if ((my n1 && sel1 != my n1) || (my n2 && sel2 != my n2) || (my n3 && sel3 != my n3) || (my n4 && sel4 != my n4)) continue;
479 			return true;   // found a matching action
480 		}
481 	}
482 	if (numberOfMatchingCallbacks == 1) {
483 		Praat_Command me = theActions.at [firstMatchingCallback];
484 		Melder_appendError (U"Selection changed! It should be:");
485 		if (my class1)
486 			Melder_appendError (U"   ", numberString (my n1), U" ", classString (my class1), U" ", objectString (my n1));
487 		if (my class2)
488 			Melder_appendError (U"   ", numberString (my n2), U" ", classString (my class2), U" ", objectString (my n2));
489 		if (my class3)
490 			Melder_appendError (U"   ", numberString (my n3), U" ", classString (my class3), U" ", objectString (my n3));
491 		if (my class4)
492 			Melder_appendError (U"   ", numberString (my n4), U" ", classString (my class4), U" ", objectString (my n4));
493 		throw MelderError ();
494 	} else {
495 		Melder_throw (U"Selection changed!");
496 	}
497 	return false;
498 }
499 
do_menu(Praat_Command me,bool isModified)500 static void do_menu (Praat_Command me, bool isModified) {
501 	if (my callback == DO_RunTheScriptFromAnyAddedMenuCommand) {
502 		UiHistory_write (U"\nrunScript: ");
503 		try {
504 			DO_RunTheScriptFromAnyAddedMenuCommand (nullptr, 0, nullptr, my script.get(), nullptr, nullptr, false, nullptr);
505 		} catch (MelderError) {
506 			Melder_flushError (U"Command \"", my title.get(), U"\" not executed.");
507 		}
508 		praat_updateSelection (); return;
509 	} else {
510 		if (my title && ! str32str (my title.get(), U"...")) {
511 			UiHistory_write (U"\n");
512 			UiHistory_write (my title.get());
513 		}
514 		Ui_setAllowExecutionHook (allowExecutionHook, (void *) my callback);   // BUG: one shouldn't assign a function pointer to a void pointer
515 		try {
516 			my callback (nullptr, 0, nullptr, nullptr, nullptr, my title.get(), isModified, nullptr);
517 		} catch (MelderError) {
518 			Melder_flushError (U"Command \"", my title.get(), U"\" not executed.");
519 		}
520 		Ui_setAllowExecutionHook (nullptr, nullptr);
521 		praat_updateSelection (); return;
522 	}
523 }
524 
cb_menu(Praat_Command me,GuiMenuItemEvent event)525 static void cb_menu (Praat_Command me, GuiMenuItemEvent event) {
526 	bool isModified = event -> shiftKeyPressed || event -> commandKeyPressed || event -> optionKeyPressed;
527 	do_menu (me, isModified);
528 }
529 
gui_button_cb_menu(Praat_Command me,GuiButtonEvent event)530 static void gui_button_cb_menu (Praat_Command me, GuiButtonEvent event) {
531 	bool isModified = event -> shiftKeyPressed || event -> commandKeyPressed || event -> optionKeyPressed;
532 	do_menu (me, isModified);
533 }
534 
praat_actions_show()535 void praat_actions_show () {
536 	#if defined (macintosh)
537 		const int BUTTON_VSPACING = 8;
538 	#else
539 		const int BUTTON_VSPACING = 5;
540 	#endif
541 	/*
542 	 * The selection has changed;
543 	 * kill the dynamic menu and the write menu.
544 	 */
545 	if (! theCurrentPraatApplication -> batch) {
546 		deleteDynamicMenu ();
547 		if (! Melder_backgrounding) {
548 			GuiThing_setSensitive (praat_writeMenu, false);
549 			if (praat_writeMenuSeparator) GuiThing_hide (praat_writeMenuSeparator);
550 		}
551 
552 		/* Determine the visibility and sensitivity of all the actions.
553 		 */
554 		if (theCurrentPraatObjects -> totalSelection != 0 && ! Melder_backgrounding)
555 			GuiThing_setSensitive (praat_writeMenu, true);
556 	}
557 	for (integer i = 1; i <= theActions.size; i ++) {
558 		Praat_Command action = theActions.at [i];
559 		integer sel1 = 0, sel2 = 0, sel3 = 0, sel4 = 0;
560 		integer n1 = action -> n1, n2 = action -> n2, n3 = action -> n3, n4 = action -> n4;
561 
562 		/* Clean up from previous selection. */
563 
564 		action -> visible = false;
565 		action -> executable = false;
566 
567 		/* Match the actually selected classes with the selection required for this visibility. */
568 
569 		if (! action -> class1) continue;   // at least one class selected
570 		sel1 = action -> class1 == classDaata ? theCurrentPraatObjects -> totalSelection : praat_numberOfSelected (action -> class1);
571 		if (sel1 == 0) continue;
572 		if (action -> class2 && (sel2 = praat_numberOfSelected (action -> class2)) == 0) continue;
573 		if (action -> class3 && (sel3 = praat_numberOfSelected (action -> class3)) == 0) continue;
574 		if (action -> class4 && (sel4 = praat_numberOfSelected (action -> class4)) == 0) continue;
575 		if (sel1 + sel2 + sel3 + sel4 != theCurrentPraatObjects -> totalSelection) continue;   // other classes selected? Do not show
576 		action -> visible = ! action -> hidden;
577 
578 		/* Match the actually selected objects with the selection required for this action. */
579 
580 		if (! action -> callback) continue;   // separators are not executable
581 		if ((n1 && sel1 != n1) || (n2 && sel2 != n2) || (n3 && sel3 != n3) || (n4 && sel4 != n4)) continue;
582 		action -> executable = true;
583 	}
584 
585 	/* Create a new column of buttons in the dynamic menu. */
586 	if (! theCurrentPraatApplication -> batch && ! Melder_backgrounding) {
587 		actionsInvisible = false;
588 		GuiMenu currentSubmenu1 = nullptr, currentSubmenu2 = nullptr;
589 		bool writeMenuGoingToSeparate = false;
590 		int y = Machine_getMenuBarBottom () + 10;
591 		for (integer i = 1; i <= theActions.size; i ++) {   // add buttons or make existing buttons sensitive (executable)
592 			Praat_Command me = theActions.at [i];
593 			if (my depth == 0) currentSubmenu1 = nullptr, currentSubmenu2 = nullptr;   // prevent attachment of later deep actions to earlier submenus after removal of label
594 			if (my depth == 1) currentSubmenu2 = nullptr;   // prevent attachment of later deep actions to earlier submenus after removal of label
595 			if (! my visible) continue;
596 			if (my callback) {
597 				/* Apparently a true command: create a button in the dynamic menu.
598 				 * If it is a subcommand (depth > 0), put it in the current submenu,
599 				 * but only if this exists (umbrella against stray submenu specifications).
600 				 */
601 				GuiMenu parentMenu = my depth > 1 && currentSubmenu2 ? currentSubmenu2 : my depth > 0 && currentSubmenu1 ? currentSubmenu1 : nullptr;
602 
603 				if (str32nequ (my title.get(), U"Save ", 5) || str32nequ (my title.get(), U"Write ", 6) || str32nequ (my title.get(), U"Append to ", 10)) {
604 					parentMenu = praat_writeMenu;
605 					if (! praat_writeMenuSeparator) {
606 						if (writeMenuGoingToSeparate)
607 							praat_writeMenuSeparator = GuiMenu_addSeparator (parentMenu);
608 						else if (str32equ (my title.get(), U"Save as binary file..."))
609 							writeMenuGoingToSeparate = true;
610 					}
611 				}
612 				if (parentMenu) {
613 					my button = GuiMenu_addItem (parentMenu, my title.get(),
614 						( my executable ? 0 : GuiMenu_INSENSITIVE ),
615 						cb_menu, me);
616 				} else {
617 					my button = GuiButton_createShown (praat_form,
618 						BUTTON_LEFT, BUTTON_RIGHT, y, y + Gui_PUSHBUTTON_HEIGHT,
619 						my title.get(), gui_button_cb_menu,
620 						me,
621 							( my executable ? 0 : GuiButton_INSENSITIVE ) | ( my attractive ? GuiButton_ATTRACTIVE : 0 ));
622 					y += Gui_PUSHBUTTON_HEIGHT + BUTTON_VSPACING;
623 				}
624 			} else if (i == theActions.size || theActions.at [i + 1] -> depth == 0) {
625 				/*
626 				 * Apparently a labelled separator.
627 				 */
628 				my button = GuiLabel_createShown (praat_form, BUTTON_LEFT, BUTTON_RIGHT, y, y + Gui_LABEL_HEIGHT, my title.get(), 0);
629 				y += Gui_LABEL_HEIGHT + BUTTON_VSPACING;
630 			} else if (! my title || my title [0] == U'-') {
631 				/*
632 				 * Apparently a separator in a submenu.
633 				 */
634 				if (currentSubmenu2 || currentSubmenu1) {   // these separators are not shown in a flattened menu
635 					my button = GuiMenu_addSeparator (currentSubmenu2 ? currentSubmenu2 : currentSubmenu1);
636 					GuiThing_show (my button);
637 				}
638 			} else {
639 				/*
640 				 * Apparently a submenu.
641 				 */
642 				if (my depth == 0 || ! currentSubmenu1) {
643 					currentSubmenu1 = GuiMenu_createInForm (praat_form,
644 						BUTTON_LEFT, BUTTON_RIGHT, y, y + Gui_PUSHBUTTON_HEIGHT,
645 						my title.get(), 0);
646 					y += Gui_PUSHBUTTON_HEIGHT + BUTTON_VSPACING;
647 					my button = currentSubmenu1 -> d_cascadeButton.get();
648 				} else {
649 					currentSubmenu2 = GuiMenu_createInMenu (currentSubmenu1, my title.get(), 0);
650 					my button = currentSubmenu2 -> d_menuItem.get();
651 				}
652 				GuiThing_show (my button);
653 			}
654 		}
655 	}
656 }
657 
praat_actions_createWriteMenu(GuiWindow window)658 void praat_actions_createWriteMenu (GuiWindow window) {
659 	if (theCurrentPraatApplication -> batch) return;
660 	praat_writeMenu = GuiMenu_createInWindow (window, U"Save", GuiMenu_INSENSITIVE);
661 	#if gtk
662 		GuiMenu_addSeparator (praat_writeMenu);
663 	#endif
664 }
665 
praat_actions_init()666 void praat_actions_init () {
667 }
668 
praat_actions_createDynamicMenu(GuiWindow window)669 void praat_actions_createDynamicMenu (GuiWindow window) {
670 	if (theCurrentPraatApplication -> batch) return;
671 	praat_form = window;
672 }
673 
praat_saveAddedActions(MelderString * buffer)674 void praat_saveAddedActions (MelderString *buffer) {
675 	integer maxID = 0;
676 	for (integer iaction = 1; iaction <= theActions.size; iaction ++) {
677 		Praat_Command action = theActions.at [iaction];
678 		if (action -> uniqueID > maxID)
679 			maxID = action -> uniqueID;
680 	}
681 	for (integer ident = 1; ident <= maxID; ident ++)
682 		for (integer iaction = 1; iaction <= theActions.size; iaction ++) {
683 			Praat_Command me = theActions.at [iaction];
684 			if (my uniqueID == ident && ! my hidden && my title) {
685 				MelderString_append (buffer, U"Add action command...",
686 					U" ", my class1 -> className, U" ", my n1,
687 					U" ", ( my class2 ? my class2 -> className : U"\"\"" ), U" ", my n2,
688 					U" ", ( my class3 ? my class3 -> className : U"\"\"" ), U" ", my n3,
689 					U" \"", my title.get(), U"\" \"", ( my after ? my after.get() : U"" ), U"\" ", my depth);
690 				MelderString_append (buffer, U" ", my script ? my script.get() : U"", U"\n");
691 				break;
692 			}
693 		}
694 }
695 
praat_saveToggledActions(MelderString * buffer)696 void praat_saveToggledActions (MelderString *buffer) {
697 	for (integer iaction = 1; iaction <= theActions.size; iaction ++) {
698 		Praat_Command me = theActions.at [iaction];
699 		if (my toggled && my title && ! my uniqueID && ! my script) {
700 			MelderString_append (buffer, ( my hidden ? U"Hide" : U"Show" ), U" action command...",
701 				U" ", my class1 -> className,
702 				U" ", ( my class2 ? my class2 -> className : U"\"\"" ),
703 				U" ", ( my class3 ? my class3 -> className : U"\"\"" ),
704 				U" ", my title.get(), U"\n");
705 		}
706 	}
707 }
708 
praat_doAction(conststring32 title,conststring32 arguments,Interpreter interpreter)709 int praat_doAction (conststring32 title, conststring32 arguments, Interpreter interpreter) {
710 	Praat_Command actionFound = nullptr;
711 	for (integer i = 1; i <= theActions.size; i ++) {
712 		Praat_Command action = theActions.at [i];
713 		if (action -> executable && str32equ (action -> title.get(), title)) {
714 			actionFound = action;
715 			break;
716 		}
717 	}
718 	if (! actionFound)
719 		return 0;
720 	if (actionFound -> callback == DO_RunTheScriptFromAnyAddedMenuCommand) {
721 		const conststring32 scriptPath = actionFound -> script.get();
722 		const conststring32 preferencesFolderPath = Melder_dirToPath (& Melder_preferencesFolder);
723 		const bool scriptIsInPlugin =
724 				Melder_stringMatchesCriterion (scriptPath, kMelder_string::STARTS_WITH, preferencesFolderPath, true);
725 		Melder_throw (
726 			U"From a script you cannot directly call a menu command that calls another script. Use instead: \nrunScript: ",
727 			scriptIsInPlugin ? U"preferencesDirectory$ + " : U"",
728 			U"\"",
729 			scriptIsInPlugin ? scriptPath + str32len (preferencesFolderPath) : scriptPath,
730 			U"\"",
731 			arguments && arguments [0] ? U", " : U"",
732 			arguments && arguments [0] ? arguments : U"",
733 			U"\n"
734 		);
735 	}
736 	actionFound -> callback (nullptr, 0, nullptr, arguments, interpreter, title, false, nullptr);
737 	return 1;
738 }
739 
praat_doAction(conststring32 title,integer narg,Stackel args,Interpreter interpreter)740 int praat_doAction (conststring32 title, integer narg, Stackel args, Interpreter interpreter) {
741 	Praat_Command actionFound = nullptr;
742 	for (integer i = 1; i <= theActions.size; i ++) {
743 		Praat_Command action = theActions.at [i];
744 		if (action -> executable && str32equ (action -> title.get(), title)) {
745 			actionFound = action;
746 			break;
747 		}
748 	}
749 	if (! actionFound)
750 		return 0;
751 	if (actionFound -> callback == DO_RunTheScriptFromAnyAddedMenuCommand) {
752 		const conststring32 scriptPath = actionFound -> script.get();
753 		const conststring32 preferencesFolderPath = Melder_dirToPath (& Melder_preferencesFolder);
754 		const bool scriptIsInPlugin =
755 				Melder_stringMatchesCriterion (scriptPath, kMelder_string::STARTS_WITH, preferencesFolderPath, true);
756 		Melder_throw (
757 			U"From a script you cannot directly call a menu command that calls another script. Use instead: \nrunScript: ",
758 			scriptIsInPlugin ? U"preferencesDirectory$ + " : U"",
759 			U"\"",
760 			scriptIsInPlugin ? scriptPath + str32len (preferencesFolderPath) : scriptPath,
761 			U"\"",
762 			narg > 0 ? U", ..." : U"",
763 			U"\n"
764 		);
765 	}
766 	actionFound -> callback (nullptr, narg, args, nullptr, interpreter, title, false, nullptr);
767 	return 1;
768 }
769 
praat_getNumberOfActions()770 integer praat_getNumberOfActions () { return theActions.size; }
771 
praat_getAction(integer i)772 Praat_Command praat_getAction (integer i)
773 	{ return i < 0 || i > theActions.size ? nullptr : theActions.at [i]; }
774 
praat_background()775 void praat_background () {
776 	if (Melder_batch)
777 		return;
778 	if (Melder_backgrounding)
779 		return;
780 	deleteDynamicMenu ();
781 	praat_list_background ();
782 	Melder_backgrounding = true;
783 }
784 
praat_foreground()785 void praat_foreground () {
786 	if (Melder_batch)
787 		return;
788 	if (! Melder_backgrounding)
789 		return;
790 	Melder_backgrounding = false;
791 	praat_list_foreground ();
792 	praat_show ();
793 }
794 
actionIsToBeIncluded(Praat_Command command,bool deprecated,bool includeSaveAPI,bool includeQueryAPI,bool includeModifyAPI,bool includeToAPI,bool includePlayAPI,bool includeDrawAPI,bool includeHelpAPI,bool includeWindowAPI)795 static bool actionIsToBeIncluded (Praat_Command command, bool deprecated, bool includeSaveAPI,
796 	bool includeQueryAPI, bool includeModifyAPI, bool includeToAPI,
797 	bool includePlayAPI, bool includeDrawAPI, bool includeHelpAPI, bool includeWindowAPI)
798 {
799 	const bool obsolete = ( deprecated && (command -> deprecationYear < PRAAT_YEAR - 10 || command -> deprecationYear < 2017) );
800 	const bool hiddenByDefault = ( command -> hidden != command -> toggled );
801 	const bool explicitlyHidden = hiddenByDefault && ! deprecated;
802 	const bool hidden = explicitlyHidden || ! command -> callback || command -> noApi || obsolete ||
803 		(! includeWindowAPI && Melder_nequ (command -> nameOfCallback, U"WINDOW_", 7)) ||
804 		(! includeHelpAPI && Melder_nequ (command -> nameOfCallback, U"HELP_", 5)) ||
805 		(! includeDrawAPI && Melder_nequ (command -> nameOfCallback, U"GRAPHICS_", 9)) ||
806 		(! includePlayAPI && Melder_nequ (command -> nameOfCallback, U"PLAY_", 5)) ||
807 		(! includeToAPI && Melder_nequ (command -> nameOfCallback, U"CONVERT_", 8)) ||
808 		(! includeModifyAPI && Melder_nequ (command -> nameOfCallback, U"MODIFY_", 7)) ||
809 		(! includeQueryAPI && Melder_nequ (command -> nameOfCallback, U"QUERY_", 6)) ||
810 		(! includeSaveAPI && Melder_nequ (command -> nameOfCallback, U"SAVE_", 5));
811 	return (command -> forceApi || ! hidden) && command -> callback != DO_RunTheScriptFromAnyAddedMenuCommand;
812 }
813 
actionHasFileNameArgument(Praat_Command command)814 static bool actionHasFileNameArgument (Praat_Command command) {
815 	const bool hasFileNameArgument =
816 		Melder_nequ (command -> nameOfCallback, U"READ1_", 6) ||
817 		Melder_nequ (command -> nameOfCallback, U"SAVE_", 5)
818 	;
819 	return hasFileNameArgument;
820 }
821 
getReturnType(Praat_Command command)822 static conststring32 getReturnType (Praat_Command command) {
823 	const conststring32 returnType =
824 		Melder_nequ (command -> nameOfCallback, U"NEW1_", 5) ? U"PraatObject" :
825 		Melder_nequ (command -> nameOfCallback, U"READ1_", 6) ? U"PraatObject" :
826 		Melder_nequ (command -> nameOfCallback, U"REAL_", 5) ? U"double" :
827 		Melder_nequ (command -> nameOfCallback, U"INTEGER_", 8) ? U"int64_t" :
828 		Melder_nequ (command -> nameOfCallback, U"STRING_", 7) ? U"char *" :
829 		Melder_nequ (command -> nameOfCallback, U"REPORT_", 7) ? U"char *" :
830 		Melder_nequ (command -> nameOfCallback, U"LIST_", 5) ? U"char *" :
831 		Melder_nequ (command -> nameOfCallback, U"INFO_", 5) ? U"char *" :
832 		Melder_nequ (command -> nameOfCallback, U"HINT_", 5) ? U"char *" :
833 		U"void";
834 	return returnType;
835 }
836 
praat_actions_writeC(bool isInHeaderFile,bool includeSaveAPI,bool includeQueryAPI,bool includeModifyAPI,bool includeToAPI,bool includePlayAPI,bool includeDrawAPI,bool includeHelpAPI,bool includeWindowAPI)837 void praat_actions_writeC (bool isInHeaderFile, bool includeSaveAPI,
838 	bool includeQueryAPI, bool includeModifyAPI, bool includeToAPI,
839 	bool includePlayAPI, bool includeDrawAPI, bool includeHelpAPI, bool includeWindowAPI)
840 {
841 	integer i = 1;
842 	try {
843 		integer numberOfApiActions = 0;
844 		for (; i <= theActions.size; i ++) {
845 			Melder_casual (i, U": ", theActions.at [i] -> class1 -> className, U": ", theActions.at [i] -> title.get());
846 			Praat_Command command = theActions.at [i];
847 			const bool deprecated = ( command -> deprecationYear > 0 );
848 			if (! actionIsToBeIncluded (command, deprecated, includeSaveAPI, includeQueryAPI, includeModifyAPI,
849 				includeToAPI, includePlayAPI, includeDrawAPI, includeHelpAPI, includeWindowAPI)) continue;
850 			MelderInfo_writeLine (U"\n/* Action command \"", command -> title.get(), U"\"",
851 				deprecated ? U", deprecated " : U"", deprecated ? Melder_integer (command -> deprecationYear) : U"",
852 				U" */");
853 			conststring32 returnType = getReturnType (command);
854 			MelderInfo_writeLine (returnType, U" Praat", str32chr (command -> nameOfCallback, U'_'), U" (");
855 			const bool isDirect = ! str32str (command -> title.get(), U"...");
856 			if (isDirect) {
857 			} else {
858 				command -> callback (nullptr, -1, nullptr, nullptr, nullptr, nullptr, false, nullptr);
859 			}
860 			if (actionHasFileNameArgument (command))
861 				MelderInfo_writeLine (U"\tconst char *fileName");
862 			MelderInfo_write (U")");
863 			if (isInHeaderFile) {
864 				MelderInfo_writeLine (U";");
865 			} else {
866 				MelderInfo_writeLine (U" {");
867 				MelderInfo_writeLine (U"}");
868 			}
869 			numberOfApiActions += 1;
870 		}
871 	} catch (MelderError) {
872 		Melder_throw (U"Action not written to C library: ", i,
873 			U": ", theActions.at [i] -> class1 ? theActions.at [i] -> class1 -> className : U"?? class ??",
874 			U": ", theActions.at [i] -> title.get()
875 		);
876 	}
877 }
878 
879 /* End of file praat_actions.cpp */
880