Made sound playing asynchronous on Mac and Linux, Interruptable on Windows
[sgc2.git] / sgc2.praat
blob463157bd6f797f210db41b28231abfb52afbf4a7
2 # SpeakGoodChinese 2.0
3
4 # Master Praat script
6 #     SpeakGoodChinese: sgc2.praat is the master GUI of SpeakGoodChinese
7 #     It is written in Praat script for the Demo window 
8 #     
9 #     Copyright (C) 2007-2010  R.J.J.H. van Son and 2010 the Netherlands Cancer Institute
10 #     The SpeakGoodChinese team are:
11 #     Guangqin Chen, Zhonyan Chen, Stefan de Koning, Eveline van Hagen, 
12 #     Rob van Son, Dennis Vierkant, David Weenink
13
14 #     This program is free software; you can redistribute it and/or modify
15 #     it under the terms of the GNU General Public License as published by
16 #     the Free Software Foundation; either version 2 of the License, or
17 #     (at your option) any later version.
18
19 #     This program is distributed in the hope that it will be useful,
20 #     but WITHOUT ANY WARRANTY; without even the implied warranty of
21 #     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 #     GNU General Public License for more details.
23
24 #     You should have received a copy of the GNU General Public License
25 #     along with this program; if not, write to the Free Software
26 #     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
27
28 # The real application name
29 sgc2.demoAppName$ = "SpeakGoodChinese2"
31 # Define variable that might be reset in Initialise*.praat
32 if not variableExists("build_SHA$")
33         build_SHA$ = "-"
34 endif
36 # These are simply "useful" defaults
37 localTableDir$ = "Data"
38 buttonsTableName$ = "MainPage"
39 configTableName$ = "Config"
40 buttons$ = ""
41 config$ = ""
42 recordedSound$ = ""
43 sgc.recordedSound = 0
44 te.recordedPitch = 0
45 te.buttonPressValue = 0
46 samplingFrequency = 44100
47 recordingTime = 2
49 # Pop-Up window colors
50 sgc2.popUp_bordercolor$ = "{0.5,0.5,1}"
51 sgc2.popUp_backgroundcolor$ = "{0.9,0.9,1}"
53 # If running in a packed script binary
54 if index_regex(preferencesDirectory$, "(?i'sgc2.demoAppName$')$")
55         preferencesAppDir$ = preferencesDirectory$
56 elsif index_regex(preferencesDirectory$, "[pP]raat(\-dir| Prefs)?$")
57         # If running as a Praat script, create a new preferences directory
58         if unix
59                 preferencesAppDir$ = "'preferencesDirectory$'/../.'sgc2.demoAppName$'"
60         else
61                 preferencesAppDir$ = "'preferencesDirectory$'/../'sgc2.demoAppName$'"
62         endif
63 else
64         # It has to go somewhere. Make a subdirectory in the current preferences directory
65         preferencesAppDir$ = "'preferencesDirectory$'/'sgc2.demoAppName$'"
66 endif
69 # Parameters for isolating recorded speech from noise
70 # Should be mostly left alone unless you are using ultra clean
71 # or very noisy recordings
72 noiseThresshold = -30
73 minimumPitch = 60
74 soundMargin = 0.25
75 minimumIntensity = 30
77 # Set up button height
78 buttonbevel = 0
80 # Define canvas
81 viewportMargin = 5
82 defaultFontSize = 12
83 defaultFont$ = "Helvetica"
84 defaultLineWidth = 1
86 # Set up system
87 call reset_viewport
89 # Load supporting scripts
90 # Load tables in script format
91 include CreateTables.praat
92 include CreateWordlists.praat
93 # Set up system and load preferences
94 include InitialiseSGC2.praat
95 # Include the main page buttons and procedures
96 include MainPage.praat
97 # Include the configuration page buttons and procedures
98 include Config.praat
100 # Start instruction loop
101 while demoWaitForInput()
102         .label$ = ""
103         .clickX = -1
104         .clickY = -1
105         .pressed$ = ""
106         if demoClicked()
107                 .clickX = demoX()
108                 .clickY = demoY()
109                 call buttonClicked 'buttons$' '.clickX' '.clickY'
110                 .label$ = buttonClicked.label$
111         elsif demoKeyPressed()
112                 .pressed$ = demoKey$()
113                 call keyPressed 'buttons$' '.pressed$'
114                 .label$ = keyPressed.label$
115         endif
117         # You cannot select a text field
118         if startsWith(.label$, "$")
119                 .label$ = ""
120         endif
121         
122         # Do things
123         if .label$ != ""
124                 te.buttonPressValue = 0
125                 # Push button down
126                 call Draw_button 'buttons$' '.label$' 1
127                 call process_label '.label$' '.clickX' '.clickY' '.pressed$'
128                 # push button up
129                 call Draw_button 'buttons$' '.label$' 'te.buttonPressValue'
130         endif
131 endwhile
133 call end_program
136 ########################################################
138 # Definitions of procedures
140 ########################################################
142 # Do what is asked
143 procedure process_label .label$ .clickX .clickY .pressed$
144         # Prcoess the command
145         if .label$ <> "" and not startsWith(.label$,"!")
146                 .label$ = replace_regex$(.label$, "^[#]", "", 0)
147                 .label$ = replace$(.label$, "_", " ", 0)
148                 call process'buttons$''.label$' '.clickX' '.clickY' '.pressed$'
149         endif
150 endproc
152 # Intialize buttons
153 procedure init_buttons
154         noerase = 1
155         call Draw_all_buttons 'buttons$'
156         noerase = 0
157 endproc
159 # Draw all buttons
160 noerase = 0
161 procedure Draw_all_buttons .table$
162         .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
163         select Table '.table$'
164         .numRows = Get number of rows
165         
166         for .row to .numRows
167                 .label$ = Get value... '.row' Label
168         if not startsWith(.label$, "!")
169                         .pressed = 0
170                         # Determine the "pressed" state of a button
171                         # A variable with the same name as the button will act as a
172                         # "pressed state"
173                         .variableName$ = .varPrefix$+"."+(replace_regex$(.label$, "^(.)", "\l\1", 0))
174                         # Simple boolean variables
175                         if index(.variableName$, "_") <= 0 and variableExists(.variableName$)
176                                 # True: Pressed
177                                 if '.variableName$' > 0
178                                         .pressed = 2
179                                 # <0: Grayed out
180                                 elsif '.variableName$' < 0
181                                         .pressed = -1
182                                 endif
183                         elsif index(.variableName$, "_") <= 0 and variableExists("'.variableName$'$")
184                                 # Non zero: Pressed
185                                 if '.variableName$'$ <> "" and '.variableName$'$ <> "0"
186                                         .pressed = 2
187                                 endif
188                         # Complex buttons with an variableName+'_'+value structure
189                         # varableName$ -> name of button, e.g., "language"
190                         elsif index(.variableName$, "_")
191                                 .generalVar$ = left$(.variableName$, rindex(.variableName$, "_") - 1)
192                                 .currentVariableName$ = .generalVar$
193                                 # Is it a string?
194                                 if variableExists(.generalVar$+"$")
195                                         .currentVariableName$ = .generalVar$ + "$"
196                                 endif
197                                 # Remove one level of indirection
198                                 if variableExists(.currentVariableName$)
199                                         if index(.currentVariableName$, "$")
200                                                 .currentVariableName$ = '.currentVariableName$'
201                                         else
202                                                 .currentValue = '.currentVariableName$'
203                                                 .currentVariableName$ = "'.currentValue'"
204                                         endif
205                                         # Remove next level of indirection
206                                         .currentContent$ = "'.currentVariableName$'"
207                                         if .currentContent$ = "_DISABLED_"
208                                                 .pressed = -1
209                                         endif
210                                         # Reconstruct label from current values
211                                         .currentLabelValue$ = .generalVar$ + "_" + .currentContent$
212                                         # Set PRESSED from label
213                                         if .variableName$ = .currentLabelValue$
214                                                 .pressed = 2
215                                         endif
216                                 endif
217                         endif
218                         # You did erase everything before you started here? So do not do that again
219                     call Draw_button_internal 0 '.table$' '.label$' '.pressed'
220         endif
221         endfor
222 endproc
224 # Draw a button from a predefined button table
225 # Normally, erase the area around a button
226 procedure Draw_button .table$ .label$ .push
227         call Draw_button_internal 1 '.table$' '.label$' '.push'
228 endproc
230 # Use this function if you want to control erasing
231 procedure Draw_button_internal .erase_button_area .table$ .label$ .push
232         # Do not draw invisible buttons starting with #
233         goto NOBUTTON startsWith(.label$, "#")
235         # Scale rounding of rounded rectangles
236         .wc = 1
237         .mm = demo Horizontal wc to mm... '.wc' 
238     # Allow to overide ! skip directive
239     .forceDraw = 0
240     if startsWith(.label$, "+")
241         .label$ = right$(.label$, length(.label$)-1)
242         .forceDraw = 1
243     endif
245     select Table '.table$'
246     .row = Search column... Label '.label$'
247         if .row < 1
248                 call emergency_table_exit Button Table '.table$' does not have a row with label '.label$'
249         endif
250         
251         # Perspective shift sizes
252         .shiftDown = 0
253         .shiftX = 0
254         .shiftY = 0
255         if buttonbevel <> 0
256                 .shiftDown = 0.1*buttonbevel
257         .shiftX = -0.2*buttonbevel
258         .shiftY = 0.40*buttonbevel
259         endif
260         
261         # Set drawing parameters
262         .topBackGroundColorUp$ = "{0.93,0.93,0.93}"
263         .topLineColorUp$ = "Black"
264         .topLineWidthUp = 1.5
265         .topBackGroundColorDown$ = "{0.89,0.89,0.94}"
266         .topLineColorDown$ = "{0.2,0.2,0.2}"
267         .topLineWidthDown = 2.0
268         .topBackGroundColorDisabled$ = "{0.85,0.85,0.85}"
269         .topLineColorDisabled$ = "{0.70,0.70,0.70}"
270         .topLineWidthDisabled = 1.5
271         .flankBackGroundColorUp$ = "{0.6,0.6,0.6}"
272         .flankLineColorUp$ = "{0.2,0.2,0.2}"
273         .flankLineWidthUp = 1.5
274         .flankBackGroundColorDown$ = "{0.75,0.75,0.75}"
275         .flankLineColorDown$ = .flankLineColorUp$
276         .flankLineWidthDown = 1.5
277         .buttonFontSize = defaultFontSize
278         
279         # Get button values
280     .leftX = Get value... '.row' LeftX
281     .rightX = Get value... '.row' RightX
282     .lowY = Get value... '.row' LowY
283     .highY = Get value... '.row' HighY
284     .buttonText$ = Get value... '.row' Text
285     .buttonColor$ = Get value... '.row' Color
286     .buttonDraw$ = Get value... '.row' Draw
287     .buttonKey$ = Get value... '.row' Key
288     
289     .noDraw = startsWith(.label$, "!") or (.leftX < 0) or (.rightX < 0) or (.lowY < 0) or (.highY < 0)
291         .rotation = 0
292         if index_regex(.buttonText$, "^![0-9\.]+!")
293                 .rotation = extractNumber(.buttonText$, "!")
294                 .buttonText$ = replace_regex$(.buttonText$, "^![0-9\.]+!", "", 0)
295         endif
297     goto NOBUTTON .noDraw and not .forceDraw
299     # Replace button text with ALERT
300     if .push = 3
301         .buttonText$ = alertText$
302     endif
303         
304         # Adapt font size to button size
305         .maxWidth = (.rightX - .leftX) - 2
306         .maxHeight = (.highY - .lowY) - 1
307         if .rotation = 0
308                 # Adapt size of button to length of text if necessary
309                 call adjustFontSizeOnWidth 'defaultFont$' '.buttonFontSize' '.maxWidth' '.buttonText$'
310                 .buttonFontSize = adjustFontSizeOnWidth.newFontSize
311                 if adjustFontSizeOnWidth.diff > 0
312                         .rightX += adjustFontSizeOnWidth.diff/2
313                         .leftX -= adjustFontSizeOnWidth.diff/2
314                 endif
315                 call set_font_size '.buttonFontSize'
317                 # Adapt size of button to length of text
318                 call adjustFontSizeOnHeight 'defaultFont$' '.buttonFontSize' '.maxHeight'
319                 if adjustFontSizeOnHeight.diff > 0
320                         .lowY -= adjustFontSizeOnHeight.diff/2
321                         .highY += adjustFontSizeOnHeight.diff/2
322                 endif
323                 .buttonFontSize = adjustFontSizeOnHeight.newFontSize
324         else
325                 # With non-horizontal text, only change font size
326                 call adjustRotatedFontSizeOnBox 'defaultFont$' '.buttonFontSize' '.maxWidth' '.maxHeight' '.rotation' '.buttonText$'
327                 .buttonFontSize = adjustRotatedFontSizeOnBox.newFontSize
328         endif
329         
330         # Reset and erase button area
331         call reset_viewport
332     demo Line width... 'defaultLineWidth'
333     .shiftLeftX = .leftX
334     .shiftRightX = .rightX - .shiftX
335     .shiftLowY = .lowY - .shiftY
336     .shiftHighY = .highY
337         if .erase_button_area
338                 # Make erase area minutely larger
339                 .eraseLeft = .shiftLeftX - 0.01
340                 .eraseRight = .shiftRightX + 0.01
341                 .eraseBottom = .shiftLowY - 0.01
342                 .eraseTop = .shiftHighY + 0.01
343                 demo Paint rectangle... White .eraseLeft .eraseRight .eraseBottom .eraseTop
344         endif
345         
346     # If label starts with "$", it is a text field. Then do not draw the button
347         if not startsWith(.label$, "$")
348         # Give some depth to button: Draw flank outline
349                 if .shiftDown or .shiftX or .shiftY
350                         if .push <= 0
351                         demo Paint rounded rectangle... '.flankBackGroundColorUp$' .shiftLeftX .shiftRightX .shiftLowY .shiftHighY '.mm'
352                                 demo Colour... '.flankLineColorUp$'
353                         demo Line width... '.flankLineWidthUp'
354                         else
355                         demo Paint rounded rectangle... '.flankBackGroundColorDown$' .shiftLeftX .shiftRightX .shiftLowY .shiftHighY '.mm'
356                                 demo Colour... '.flankLineColorDown$'
357                         demo Line width... '.flankLineWidthDown'
358                         endif
359                 demo Draw rounded rectangle... .shiftLeftX .shiftRightX .shiftLowY .shiftHighY '.mm'
360                 endif
362                 # Button Down will shift the top perspective
364         # Draw the button top
365                 if .push = 0
366                 demo Paint rounded rectangle... '.topBackGroundColorUp$' '.leftX' '.rightX' '.lowY' '.highY' '.mm'
367                         demo Colour... '.topLineColorUp$'
368                 demo Line width... '.topLineWidthUp'
369                 elsif .push < 0
370                 demo Paint rounded rectangle... '.topBackGroundColorDisabled$' '.leftX' '.rightX' '.lowY' '.highY' '.mm'
371                         demo Colour... '.topLineColorDisabled$'
372                 demo Line width... '.topLineWidthDisabled'
373                 else
374                         # Button Down
375                         .leftX += .shiftDown
376                         .rightX += .shiftDown
377                         .lowY -= .shiftDown
378                         .highY -= .shiftDown
380                 demo Paint rounded rectangle... '.topBackGroundColorDown$' .leftX .rightX .lowY .highY '.mm'
381                         demo Colour... '.topLineColorDown$'
382                 demo Line width... '.topLineWidthDown'
383                 endif
384         demo Draw rounded rectangle... '.leftX' '.rightX' '.lowY' '.highY' '.mm'
385         endif
386    
387     # The button text and symbol
388         .horWC = demo Horizontal mm to wc... 10.0
389         .verWC = demo Vertical mm to wc... 10.0
390         if .verWC > 0
391                 .verCoeff = .horWC / .verWC
392         else
393                 .verCoeff = 1
394         endif
396     .centerX = (.leftX + .rightX)/2
397     .centerY = .lowY + 0.6*(.highY-.lowY)
398     .radius = min(.verCoeff * (.highY - .lowY ), (.rightX - .leftX))/3
399         .buttonKey$ = replace$(.buttonKey$, "\", "\\", 0)
400         .buttonKey$ = replace$(.buttonKey$, """", "\""""", 0)
401         .newText$ = replace_regex$(.buttonText$, "['.buttonKey$']", "#%&", 1)
402         if .newText$ = ""
403                 .newText$ = .buttonText$
404         endif
405         # Variable text field, read corresponding variable
406         if index(.newText$, "$$$")
407                 .fieldName$ = replace_regex$(.label$, "^[!$#]", "", 0)
408                 .fieldName$ = replace_regex$(.fieldName$, "^(.)", "\l\1", 0)
409                 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
410                 .newText$ = replace$(.newText$, "$$$", '.varPrefix$'.'.fieldName$'$, 0)
411         endif
412         if .push = 1 or .push = -1
413                 demo Grey
414                 if .buttonColor$ = "Red"
415                         .buttonColor$ = "Pink"
416                 elsif .buttonColor$ = "Blue"
417                         .buttonColor$ = "{0.5,0.5,1}"
418                 else
419                         .buttonColor$ = "Grey"
420                 endif
421     elsif .push >= 2
422         .buttonColor$ = "Maroon"
423         else
424         demo Colour... Black
425         endif
427     call '.buttonDraw$' '.buttonColor$' '.centerX' '.centerY' '.radius' 
428         call set_font_size '.buttonFontSize'
429     demo Colour... '.buttonColor$'
430         if .rotation = 0
431                 .anchorY = .lowY
432                 .verticalAlignment$ = "Bottom"
433         else
434                 .anchorY = .lowY + 0.5*(.highY-.lowY)
435                 .verticalAlignment$ = "Half"
436         endif
437     demo Text special... '.centerX' Centre '.anchorY' '.verticalAlignment$' 'defaultFont$' '.buttonFontSize' '.rotation' '.newText$'
438         demoShow()
440         # Reset
441         call set_font_size 'defaultFontSize'
442     demo Black
443     demo Line width... 'defaultLineWidth'
444     
445     label NOBUTTON
446 endproc
448 procedure set_window_title .table$ .addedText$
449     select Table '.table$'
450     .row = Search column... Label !WindowTitle
451         if .row < 1
452                 call emergency_table_exit Button Table '.table$' does not have a row with label !WindowTitle
453         endif
454         .windowText$ = Get value... '.row' Text
455         call convert_praat_to_latin1 '.windowText$'
456         .windowText$ = convert_praat_to_latin1.text$
458     demoWindowTitle(.windowText$+ .addedText$)
459 endproc
461 # Handle language setting 
462 procedure processLanguageCodes .table$ .label$
463         .table$ = "Config"
464     call Draw_button 'config$' Language_'config.language$' 0
465     call Draw_button 'config$' '.label$' 2
466     # Someone might have to use more than 2 chars for the language code
467     .numChars = length(.label$) - length("Language_")
468         .lang$ = right$(.label$, .numChars)
469     # Load new tables
470     call set_language '.lang$'
471 endproc
473 # Set the language
474 procedure set_language .lang$
475         .redraw_config = 0
476     # Remove old tables
477     if buttons$ <> ""
478         select Table 'buttons$'
479         Remove
480                 .redraw_config = 1
481     endif
482     if config$ <> ""
483         select Table 'config$'
484         Remove
485                 .redraw_config = 1
486     endif
487     
488     # Set language
489         call checkTable 'buttonsTableName$'_'.lang$'
490         if checkTable.available
491                 config.language$ = .lang$
492         else
493                 config.language$ = "EN"
494         endif
495     
496     # Load buttons tables
497     call loadTable 'buttonsTableName$'
498     buttons$ = selected$("Table")
499     Append column... Text
500     Append column... Key
501     Append column... Helptext
502     .numLabels = Get number of rows
503     call loadTable 'buttonsTableName$'_'config.language$'
504     .buttonsLang$ = selected$("Table")
505     for .row to .numLabels
506                 select Table 'buttons$'
507                 .label$ = Get value... '.row' Label
508         call findLabel '.buttonsLang$' '.label$'
509             if findLabel.row > 0
510             select Table '.buttonsLang$'
511                 .valueText$ = Get value... 'findLabel.row' Text
512                 .valueKey$ = Get value... 'findLabel.row' Key
513                 .valueHelp$ = Get value... 'findLabel.row' Helptext
514                 select Table 'buttons$'
515                 Set string value... '.row' Text '.valueText$'
516                 Set string value... '.row' Key '.valueKey$'
517                 Set string value... '.row' Helptext '.valueHelp$'
518                 elsif index(.label$, "_")
519                         # Load alternative language table
520                         .startChar = rindex(.label$, "_")
521                         .otherLanguage$ = right$(.label$, length(.label$) - .startChar)
522                         call loadTable 'buttonsTableName$'_'.otherLanguage$'
523                 .otherbuttonsLang$ = selected$("Table")
524                 call findLabel '.otherbuttonsLang$' '.label$'
525                 if findLabel.row > 0
526                 select Table '.buttonsLang$'
527                         .valueText$ = Get value... 'findLabel.row' Text
528                         .valueKey$ = Get value... 'findLabel.row' Key
529                         .valueHelp$ = Get value... 'findLabel.row' Helptext
530                         select Table 'buttons$'
531                         Set string value... '.row' Text '.valueText$'
532                         Set string value... '.row' Key '.valueKey$'
533                         Set string value... '.row' Helptext '.valueHelp$'
534                 else
535                 call emergency_table_exit Cannot find Label: '.otherbuttonsLang$' '.label$'
536                 endif
537                         select Table '.otherbuttonsLang$'
538                         Remove
539         else
540             call emergency_table_exit Cannot find Label: '.buttonsLang$' '.label$'
541         endif
542     endfor
543     select Table '.buttonsLang$'
544     Remove
545     
546     # Load configuration table
547     call loadTable 'configTableName$'
548     config$ = selected$("Table")
549     Append column... Text
550     Append column... Key
551     Append column... Helptext
552     .numLabels = Get number of rows
553     call loadTable 'configTableName$'_'config.language$'
554     .configLang$ = selected$("Table")
555     for .row to .numLabels
556                 select Table 'config$'
557                 .label$ = Get value... '.row' Label
558         call findLabel '.configLang$' '.label$'
559             if findLabel.row > 0
560             select Table '.configLang$'
561                 .valueText$ = Get value... 'findLabel.row' Text
562                 .valueKey$ = Get value... 'findLabel.row' Key
563                 .valueHelp$ = Get value... 'findLabel.row' Helptext
564                 select Table 'config$'
565                 Set string value... '.row' Text '.valueText$'
566                 Set string value... '.row' Key '.valueKey$'
567                 Set string value... '.row' Helptext '.valueHelp$'
568                 elsif index(.label$, "_")
569                         .startChar = rindex(.label$, "_")
570                         .otherLanguage$ = right$(.label$, length(.label$) - .startChar)
571                         call loadTable 'configTableName$'_'.otherLanguage$'
572                 .otherconfigLang$ = selected$("Table")
573                 call findLabel '.otherconfigLang$' '.label$'
574                 if findLabel.row > 0
575                 select Table '.otherconfigLang$'
576                         .valueText$ = Get value... 'findLabel.row' Text
577                         .valueKey$ = Get value... 'findLabel.row' Key
578                         .valueHelp$ = Get value... 'findLabel.row' Helptext
579                         select Table 'config$'
580                         Set string value... '.row' Text '.valueText$'
581                         Set string value... '.row' Key '.valueKey$'
582                         Set string value... '.row' Helptext '.valueHelp$'
583                 else
584                 call emergency_table_exit Cannot find Label: '.otherconfigLang$' '.label$'
585                 endif
586                         select Table '.otherconfigLang$'
587                         Remove
588         else
589             call emergency_table_exit Cannot find Label: '.configLang$' '.label$'
590         endif
591     endfor
592     select Table '.configLang$'
593     Remove
595         # Make language change visible
596         if .redraw_config
597                 call Draw_config_page
598         endif
600 endproc
602 ###############################################################
604 # Button Drawing Routines
606 ###############################################################
608 # A stub for buttons that do not have a drawing routine (yet)
609 procedure DrawNull .color$ .x .y .size
610 endproc
612 procedure DrawHelp .color$ .x .y .size
613         .currentFontSize = 24
614         .y -= .size
615         .maxHeight = 2*.size
616         call adjustFontSizeOnHeight 'defaultFont$' '.currentFontSize' '.maxHeight'
617         .currentFontSize = adjustFontSizeOnHeight.currentFontSize
618         call set_font_size '.currentFontSize'
619         demo Colour... '.color$'
620         demo Text... '.x' Centre '.y' Bottom ?
621         call set_font_size 'defaultFontSize'
622 endproc
624 ###############################################################
626 # Button Processing Routines
628 ###############################################################
630 # Search row in table on label
631 procedure findKey .table$ .label$
632         .row = 0
633         select Table '.table$'
634         .to$ = selected$("Table")
635         .to$ = "Table_"+.to$
636         .numRows = Get number of rows
637         for .i to .numRows
638                 .currentKey$ = '.to$'$[.i, "Key"]
639                 if .label$ = .currentKey$
640                         .row = .i
641                         goto KEYFOUND
642                 endif
643         endfor
644         label KEYFOUND
645         if .row <= 0 and index(.label$, "_") <= 0
646                 printline "'.label$'" is not a key in '.table$'
647         endif
648 endproc
650 procedure findLabel .table$ .label$
651         .row = 0
652         select Table '.table$'
653         .to$ = selected$("Table")
654         .to$ = "Table_"+.to$
655         .numRows = Get number of rows
656         for .i to .numRows
657                 .currentKey$ = '.to$'$[.i, "Label"]
658                 if .label$ = .currentKey$
659                         .row = .i
660                         goto LABELFOUND
661                 endif
662         endfor
663         label LABELFOUND
664         if .row <= 0 and index(.label$, "_") <= 0
665                 call emergency_table_exit "'.label$'" is not a key in '.table$'
666         endif
667 endproc
669 # Get the label
670 procedure buttonClicked table$ .x .y
671         .label$ = ""
672         select Table 'table$'
673         .bo$ = selected$("Table")
674         .bo$ = "Table_"+.bo$
675         .numRows = Get number of rows
676         for .i to .numRows
677                 if .label$ = ""
678                         .leftX = '.bo$'[.i, "LeftX"]
679                         .rightX = '.bo$'[.i, "RightX"]
680                         .lowY = '.bo$'[.i, "LowY"]
681                         .highY = '.bo$'[.i, "HighY"]
682                         if .x > .leftX and .x < .rightX and .y > .lowY and .y < .highY
683                                 .label$ = '.bo$'$[.i, "Label"]
684                         endif
685                 endif
686         endfor
687 endproc
689 procedure keyPressed table$ .pressed$
690         .label$ = ""
691         # Magic
692         if .pressed$ = "" and not demoShiftKeyPressed()
693                 .label$ = "Refresh"
694         endif
695         .lowerPressed$ = replace_regex$(.pressed$, ".", "\L&", 0)
696         .upperPressed$ = replace_regex$(.pressed$, ".", "\U&", 0)
697         select Table 'table$'
698         .bo$ = selected$("Table")
699         .bo$ = "Table_"+.bo$
700         .numRows = Get number of rows
701         for .i to .numRows
702                 if .label$ = ""
703                         .key$ = '.bo$'$[.i, "Key"]
704                         if index(.key$, .lowerPressed$) or index(.key$, .upperPressed$)
705                                 .label$ = '.bo$'$[.i, "Label"]
706                         endif
707                 endif
708         endfor
709 endproc
711 procedure count_syllables
712         .number = 0
713         .pinyin$ = ""
714         select Table 'wordlist$'
715         if sgc.currentWord > 0 and sgc.currentWord <= sgc.numberOfWords
716                 .sound$ = Get value... 'sgc.currentWord' Sound
717                 .pinyin$ = Get value... 'sgc.currentWord' Pinyin
718         endif
719         call add_missing_neutral_tones '.pinyin$'
720         .pinyin$ = add_missing_neutral_tones.pinyin$
721         if index_regex(.pinyin$, "[0-9]") > 0
722                 .number = length(replace_regex$(.pinyin$, "[^\d]+([\d]+)", "1", 0))
723         elsif .pinyin$ <> ""
724                 .number = 1
725         endif
726 endproc
728 procedure play_sound .sound
729     if .sound > 0
730                 if sgc.useAlternativePlayer and fileReadable(sgc.playCommandFile$)
731                         .scratchFile$ = "'sgc.scratchAudioDir$'SCRATCH.wav"
732                         select .sound
733                         Save as WAV file: .scratchFile$
734                         .command$ < 'sgc.playCommandFile$'
735                         .command$ = replace$(.command$, "[']", """", 0)
736                         .command$ = replace$(.command$, "'newline$'", " ", 0)
737                         if unix or macintosh
738                                 system_nocheck bash -c -- ''.command$' "'.scratchFile$'"'
739                         elsif windows
740                                 system_nocheck call '.command$' "'.scratchFile$'"
741                         endif
742                         deleteFile(.scratchFile$)
743                 else
744                         select .sound
745                         Play
746         endif
747     endif
748 endproc
750 procedure record_sound .recordingTime
751         if .recordingTime <= 0
752                 .recordingTime = recordingTime
753         endif
754         call clean_up_sound
755         
756         # NOTE: Some sound can be playing! This will not be stopped.
757         
758         # There is a very nasty delay before the first recording starts, do a dummy record
759         if not variableExists("recordingInitialized") and not sgc.useAlternativeRecorder
760         noprogress nowarn Record Sound (fixed time)... 'config.input$' 0.99 0.5 'samplingFrequency' 0.1
761                 Remove
762                 recordingInitialized = 1
763         endif
764         # Recording light
765     demo Paint circle... Red 5 95 2
766     demoShow()
767     
768         # In Windows XP interaction between demoWaitForInput and Record Sound blocks drawing the feedback
769         # This code might be removed #
770         if windows and endsWith(build_SHA$, " XP")
771                 # Display a pause window to flush the graphics buffer
772                 beginPause ("DESTROY WINDOW ")
773                         comment (" ")
774                 endPause ("DESTROY WINDOW ", 1)
775         #call init_window
776         demo Paint circle... Red 5 95 2
777         demoShow()
778         endif
779         ##############################
780         
781         # Use a different recorder program
782     if sgc.useAlternativeRecorder and fileReadable(sgc.recordCommandFile$)
783                 .scratchFile$ = "'sgc.scratchAudioDir$'SCRATCH.wav"
784                 .command$ < 'sgc.recordCommandFile$'
785                 .command$ = replace$(.command$, "[']", """", 0)
786                 .command$ = replace$(.command$, "'newline$'", " ", 0)
787                 if unix or macintosh
788                         system_nocheck bash -c -- ''.command$' '.recordingTime''
789                 elsif windows
790                         system_nocheck call '.command$' '.recordingTime'
791                 endif
792                 Read from file: .scratchFile$
793                 deleteFile(.scratchFile$)
794         else
795                 noprogress nowarn Record Sound (fixed time)... 'config.input$' 0.99 0.5 'samplingFrequency' '.recordingTime'
796         endif
797     demo Paint circle... White 5 95 2.5
798     call wipeArea 'wipeFeedbackArea$'
800     # Feedback on recording level
801     .extremum = Get absolute extremum... 0 0 None
802     .radius = 2 * .extremum
803     if .radius <= 0
804                 .radius = 0.02
805     endif
806     .blue = 0
807     .green = 0
808     .red = 0
809     if .extremum >= 0.95
810             .red = 1
811     elsif .extremum >= 0.49
812             .green = 1
813     else
814             .green = .extremum / 0.5
815     endif
816     .color$ = "{'.red','.green','.blue'}"
817     demo Colour... '.color$'
818     demo Line width... 1
819     demo Draw circle... 5 95 '.radius'
820     # Reset
821     demoShow()
822     demo Colour... Black
823     demo Line width... 'defaultLineWidth'
824     # Process sound
825     Rename... Tmp
826     Resample... 10000 50
827     Rename... Pronunciation
828     recordedSound$ = selected$("Sound")
829     sgc.recordedSound = selected("Sound")
830     select Sound Tmp
831     Remove
832     select Sound 'recordedSound$'
833     sgc.recordedSound = selected("Sound")
834         
835     # Cut out real sound from silences/noise
836     call sound_detection 'recordedSound$' 'soundMargin'
837     select Sound 'recordedSound$'
838     sgc.recordedSound = selected("Sound")
839     
840     # Store audio if requested
841     if sgc.saveAudioOn and sgc.saveAudio$ <> ""
842                 if sgc.savePerf$ <> "" and fileReadable(sgc.savePerf$)
843                         .pinyin$ = ""
844                         select Table 'wordlist$'
845                         if sgc.currentWord > 0 and sgc.currentWord <= sgc.numberOfWords
846                                 .pinyin$ = Get value... 'sgc.currentWord' Pinyin
847                                 .outputName$ = "'sgc.saveAudio$'/'.pinyin$'.wav"
848                                 select sgc.recordedSound
849                                 Save as WAV file: .outputName$
850                         endif
851                 else
852                         # The Audio directory disappeared
853                         sgc.savePerf$ = ""
854                         sgc.saveAudioOn = 0
855                         sgc.saveAudio$ = ""
856                         config.savePerf = 0
857                         config.openPerf = 0
858                         config.clearSummary = 0
859                         config.audioName$ = ""
860                 endif
861     endif
862     
863 endproc
866 # Select real sound from recording
867 # Uses some global variable
868 procedure sound_detection .sound$ .margin
869         select Sound '.sound$'
870         .soundlength = Get total duration
871         .internalSilence = 2*.margin
872         
873         # Silence and remove noise, DANGEROUS
874         To TextGrid (silences)... 'minimumPitch' 0 'noiseThresshold' '.internalSilence' 0.1 silent sounding
875         Rename... Input'.sound$'
877         select TextGrid Input'.sound$'
878         .numberofIntervals = Get number of intervals... 1
879         if .numberofIntervals < 2
880                 .numberofIntervals = 0
881         endif
883         # The code below will suppress noise, but also weak third tones
884         # This handles the problem that third tones can be realized with 
885         # alternative cues, e.g, non-standard voice and very low levels 
886         #
887         # Remove buzzing and other obnoxious sounds (if switched on)
888         for .i from 1 to .numberofIntervals
889            select TextGrid Input'.sound$'
890            .value$ = Get label of interval... 1 '.i'
891            .begintime = Get starting point... 1 '.i'
892            .endtime = Get end point... 1 '.i'
893         
894                 # Remove noise
895                 if .value$ = "silent"
896                         select Sound '.sound$'
897                         Set part to zero... '.begintime' '.endtime' at nearest zero crossing
898                 endif
899         endfor
901         # Select target sound
902         .maximumIntensity = -1
903         .counter = 1
904         for i from 1 to .numberofIntervals
905            select TextGrid Input'.sound$'
907            .value$ = Get label of interval... 1 'i'
908            .begintime = Get starting point... 1 'i'
909            .endtime = Get end point... 1 'i'
911            if .value$ != "silent"
912            if .begintime > .margin
913                   .begintime -= .margin
914            else
915                    .begintime = 0
916            endif
917            if .endtime + .margin < .soundlength
918                    .endtime += .margin
919            else
920                    .endtime = .soundlength
921            endif
923            select Sound '.sound$'
924            Extract part... '.begintime' '.endtime' Rectangular 1.0 no
925            Rename... Tmp'.sound$'
926            Subtract mean
927            .newIntensity = Get intensity (dB)
928            if .newIntensity > .maximumIntensity
929                    if .maximumIntensity > 0
930                    select Sound New'.sound$'
931                    Remove
932                    endif
933                    select Sound Tmp'.sound$'
934                    Rename... New'.sound$'
935                    .maximumIntensity = .newIntensity
936            else
937                    select Sound Tmp'.sound$'
938                    Remove
939            endif
940            # 
941            endif
942         endfor
943         if .maximumIntensity > minimumIntensity
944                 select Sound '.sound$'
945                 Remove
946                 select Sound New'.sound$'
947                 Rename... '.sound$'
948         elsif .maximumIntensity > -1
949                 select Sound New'.sound$'
950                 Remove
951         endif
952         select TextGrid Input'.sound$'
953         Remove
954         
955         select Sound '.sound$'
956 endproc
958 procedure end_program
959         call write_preferences "" 
960         demo Erase all
961         select all
962         Remove
963         exit
964 endproc
966 ######################################################
968 # Configuration Page
970 ######################################################
971 procedure config_page
972     demo Erase all
973     demoWindowTitle("Speak Good Chinese: Change settings")
974     .label$ = ""
975     call Draw_config_page
977     while (.label$ <> "Return") and demoWaitForInput() 
978                 .clickX = -1
979                 .clickY = -1
980                 .pressed$ = ""
981             .label$ = ""
982             if demoClicked()
983                     .clickX = demoX()
984                     .clickY = demoY()
985                     call buttonClicked 'config$' '.clickX' '.clickY'
986                     .label$ = buttonClicked.label$
987             elsif demoKeyPressed()
988                     .pressed$ = demoKey$()
989                     call keyPressed 'config$' '.pressed$'
990                     .label$ = keyPressed.label$
991             endif
993                 # You cannot select a text field
994                 if startsWith(.label$, "$")
995                         .label$ = ""
996                 endif
997                 
998             # Do things
999             if .label$ != ""
1000                     # Handle push button in process_config
1001                     call process_config '.label$' '.clickX' '.clickY' '.pressed$'
1002             endif
1003         
1004         if .label$ = "Return"
1005             goto GOBACK
1006         endif
1007     endwhile
1009     # Go back
1010     label GOBACK
1011     call init_window
1012 endproc
1014 procedure Draw_config_page
1015         demo Erase all
1016         # Draw background
1017         if config.showBackground
1018                 call draw_background Background
1019         endif
1020         # Draw buttons
1021     call Draw_all_buttons 'config$'
1022         call set_window_title 'config$'  
1023     # Set correct buttons (alert)
1024         call setConfigMainPage
1025 endproc
1027 # Do what is asked
1028 procedure process_config .label$ .clickX .clickY .pressed$
1029         if .label$ <> "" and not startsWith(.label$,"!")
1030                 .label$ = replace_regex$(.label$, "^[#]", "", 0)
1031                 .label$ = replace$(.label$, "_", " ", 0)
1032                 call process'config$''.label$' '.clickX' '.clickY' '.pressed$'
1033         endif
1034 endproc
1036 ###############################################################
1038 # Presenting help texts
1040 ###############################################################
1042 # Process Help
1043 procedure help_loop .table$ .redrawProc$
1044         # General Help text
1045         call  write_help_title '.table$'
1046         
1047     .label$ = ""
1048     call Draw_button '.table$' Help 2
1049     .redrawScreen = 0
1050     while (.label$ <> "Help") and demoWaitForInput() 
1051             .label$ = ""
1052             if demoClicked()
1053                     .clickX = demoX()
1054                     .clickY = demoY()
1055                     call buttonClicked '.table$' '.clickX' '.clickY'
1056                     .label$ = buttonClicked.label$
1057             elsif demoKeyPressed()
1058                     .pressed$ = demoKey$()
1059                     call keyPressed '.table$' '.pressed$'
1060                     .label$ = keyPressed.label$
1061             endif
1063             if .label$ != "" and .label$ <> "Help"
1064                         # Redraw screen
1065                         if .redrawScreen
1066                                 demo Erase all
1067                                 call '.redrawProc$'
1068                         else
1069                         .redrawScreen = 1
1070                         endif
1071                         call Draw_button '.table$' Help 2
1072                         call  write_help_title '.table$'
1074                     # Handle push button in process_config
1075                     call write_help_text '.table$' '.label$'
1076             endif
1077         
1078     endwhile
1079         
1080         # Reset button
1081     call Draw_button '.table$' Help 0
1082         demo Erase all
1083         call '.redrawProc$'
1084 endproc
1086 # Write help text
1087 procedure write_help_text .table$ .label$
1088         call findLabel '.table$' '.label$'
1089         .row = findLabel.row
1090         select Table '.table$'
1091         # Get text
1092         if .row <= 0
1093                 call findLabel '.table$' Help
1094                 .row = findLabel.row
1095                 select Table '.table$'
1096         endif
1097         .helpText$ = Get value... '.row' Helptext
1098         .helpKey$ = Get value... '.row' Key
1099         .helpKey$ = replace$(.helpKey$, "\", "", 0)
1100         .helpKey$ = replace$(.helpKey$, "_", "\_ ", 0)
1101         if index_regex(.helpKey$, "\S")
1102                 .helpText$ = .helpText$+" ("+.helpKey$+")"
1103         endif
1104         # Get button values
1105     .leftX = Get value... '.row' LeftX
1106     .rightX = Get value... '.row' RightX
1107     .lowY = Get value... '.row' LowY
1108     .highY = Get value... '.row' HighY
1109         
1110         # PopUp dimensions
1111         .currentHelpFontSize = defaultFontSize
1112     call set_font_size '.currentHelpFontSize'
1113         .helpTextSize = demo Text width (wc)... '.helpText$'
1114         .helpTextSize += 4
1115         if .leftX > 50
1116                 .htXleft = 20
1117                 .htXright = .htXleft + .helpTextSize + 5
1118                 .xstart = .leftX
1119         else
1120                 .htXright = 80
1121                 .htXleft = .htXright - .helpTextSize - 5
1122                 .xstart = .rightX
1123         endif
1124         if .lowY > 50
1125                 .htYlow = 40
1126                 .htYhigh = .htYlow + 7
1127                 .ystart = .lowY
1128                 .yend = .htYhigh
1129         else
1130                 .htYhigh = 60
1131                 .htYlow = .htYhigh - 7
1132                 .ystart = .highY
1133                 .yend = .htYlow
1134         endif
1136         # Adapt font size to horizontal dimensions
1137         .maxWidth = 90
1138         call adjustFontSizeOnWidth 'defaultFont$' '.currentHelpFontSize' '.maxWidth' '.helpText$'
1139         .currentHelpFontSize = adjustFontSizeOnWidth.newFontSize
1140         if .htXleft < 0 or .htXright > 100
1141                 .htXleft = 0
1142                 .htXright = .htXleft + adjustFontSizeOnWidth.textWidth + 5
1143         endif
1144         call set_font_size '.currentHelpFontSize'
1146         # Adapt vertical dimensions to font height
1147         call points_to_wc '.currentHelpFontSize'
1148         .lineHeight = points_to_wc.wc
1149         if .lineHeight > .htYhigh - .htYlow - 4
1150                 .htYhigh = .htYlow + .lineHeight + 4
1151         endif
1153         # Determine arrow endpoints
1154         .xend = .htXleft
1155         if abs(.htXleft - .xstart) > abs(.htXright - .xstart)
1156                 .xend = .htXright
1157         endif
1158         if abs((.htXleft+.htXright)/2 - .xstart) < min(abs(.htXright - .xstart),abs(.htXleft - .xstart))
1159                 .xend = (.htXleft+.htXright)/2
1160         endif
1161         
1162         .xtext = .htXleft + 2
1163         .ytext = .htYlow + 1
1164         
1165         # Draw pop-up
1166         .mm2wc = demo Horizontal mm to wc... 1
1167         .lineWidth = 2/.mm2wc
1168         demo Line width... '.lineWidth'
1169         demo Arrow size... '.lineWidth'
1170         demo Colour... 'sgc2.popUp_bordercolor$'
1171         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.htXleft' '.htXright' '.htYlow' '.htYhigh'
1172         demo Draw rectangle... '.htXleft' '.htXright' '.htYlow' '.htYhigh'
1173         demo Draw arrow... '.xstart' '.ystart' '.xend' '.yend'
1174         demo Line width... 'defaultLineWidth'
1175         demo Arrow size... 1
1176         demo Black
1177         demo Text... '.xtext' Left '.ytext' Bottom '.helpText$'
1178         demoShow()
1179         call set_font_size 'defaultFontSize'
1180         
1181 endproc
1183 procedure write_help_title .table$
1184         # Set help text title
1185         # General Help text
1186         call findLabel '.table$' Help
1187         .row = findLabel.row
1188         select Table '.table$'
1189         .helpTitle$ = Get value... '.row' Helptext
1190         .helpKey$ = Get value... '.row' Key
1191         .helpKey$ = replace$(.helpKey$, "\", "", 0)
1192         .helpKey$ = replace$(.helpKey$, "_", "\_ ", 0)
1193         .helpTitle$ = .helpTitle$+" ("+.helpKey$+")"
1194         
1195         call reset_viewport
1196         .helpTitleFontSize = 14
1197         # Adapt size of button to length of text
1198         .maxWidth = 80
1199         call adjustFontSizeOnWidth 'defaultFont$' '.helpTitleFontSize' '.maxWidth' '.helpTitle$'
1200         .helpTitleFontSize = adjustFontSizeOnWidth.newFontSize
1201         call set_font_size '.helpTitleFontSize'
1202         .helpTop = 100
1203         
1204         demo Select inner viewport... 0 100 0 100
1205         demo Axes... 0 100 0 100
1206         demo Text... 50 Centre '.helpTop' Top '.helpTitle$'
1207     call set_font_size 'defaultFontSize'
1208         call reset_viewport
1209 endproc
1211 ###############################################################
1213 # Miscelaneous procedures
1215 ###############################################################
1216 procedure printPageToPrinter
1217         call print_window
1218         demo Print... 'printerName$' 'printerPresets$'
1219         call init_window
1220 endproc
1222 procedure getOpenFile .openDialogue$
1223         call clean_up_sound
1225         call convert_praat_to_latin1 '.openDialogue$'
1226         .openDialogue$ = convert_praat_to_latin1.text$
1227         .filename$ = chooseReadFile$ (.openDialogue$)
1228         .tmp = -1
1229         if .filename$ <> "" and fileReadable(.filename$)
1230                 .tmp = nocheck Read from file... '.filename$'
1231                 if .tmp !- undefined and .tmp > 0
1232                         call log_fileOpen '.filename$'
1233                 
1234                         # Get only the filename
1235                         .startName = rindex_regex(.filename$, "[/\\:]") + 1
1236                         .nameLength = rindex(.filename$, ".") - .startName
1237                         currentSoundName$ = mid$(.filename$, .startName, .nameLength)
1238                 else
1239                         .tmp = -1
1240                 endif
1241         endif
1242         if .tmp <= 0
1243                 Create Sound from formula... Speech Mono 0 1 44100 0
1244         endif
1245         recordedSound$ = selected$("Sound")
1246         sgc.recordedSound = selected("Sound")
1247         currentStartTime = 0
1248         currentEndTime = Get total duration
1249         # Reset selected window
1250         selectedStartTime = currentStartTime
1251         selectedEndTime = currentEndTime
1252 endproc
1254 procedure points_to_wc .points
1255         .mm = .points * 0.3527777778
1256         .wc = demo Vertical mm to wc... '.mm'
1257 endproc
1259 procedure reset_viewport
1260         .low = viewportMargin
1261         .high = 100 - viewportMargin
1262         demo Select inner viewport... '.low' '.high' '.low' '.high'
1263         demo Axes... 0 100 0 100
1264 endproc
1266 procedure set_font_size .fontSize
1267         call reset_viewport
1268         demo Font size... '.fontSize'
1269         call reset_viewport
1270 endproc
1272 procedure wipeArea .areaCommand$
1273         call reset_viewport
1274         '.areaCommand$'
1275 endproc
1277 procedure adjustFontSizeOnWidth .font$ .currentFontSize .maxWidth .text$
1278         demo '.font$'
1279         call set_font_size '.currentFontSize'
1280         .textWidth = demo Text width (wc)... '.text$'
1281         while .textWidth > .maxWidth and .currentFontSize > 2
1282                 .currentFontSize -= 0.5
1283                 call set_font_size '.currentFontSize'
1284                 .textWidth = demo Text width (wc)... '.text$'
1285         endwhile
1286         .diff = .textWidth - .maxWidth
1287         .newFontSize = .currentFontSize 
1288         demo 'defaultFont$'
1289 endproc
1291 procedure adjustRotatedFontSizeOnBox .font$ .currentFontSize .maxWidth .maxHeight .rotation .text$
1292         demo '.font$'
1293         .radians = .rotation/360 * 2 * pi
1294         .horWC = demo Horizontal mm to wc... 10.0
1295         .verWC = demo Vertical mm to wc... 10.0
1296         if .horWC > 0
1297                 .verCoeff = .verWC / .horWC
1298         else
1299                 .verCoeff = 1
1300         endif
1301         call set_font_size '.currentFontSize'
1302         .textLength = demo Text width (wc)... '.text$'
1303         while (.textLength * .verCoeff * sin(.radians) > .maxHeight or .textLength * cos(.radians) > .maxWidth) and .currentFontSize > 2
1304                 .currentFontSize -= 0.5
1305                 call set_font_size '.currentFontSize'
1306                 .textLength = demo Text width (wc)... '.text$'
1307         endwhile
1308         .diff = .textLength - .maxHeight
1309         .newFontSize = .currentFontSize 
1310         demo 'defaultFont$'
1311 endproc
1313 procedure adjustFontSizeOnHeight .font$ .currentFontSize .maxHeight
1314         demo '.font$'
1315         call points_to_wc '.currentFontSize'
1316         .lineHeight = points_to_wc.wc
1317         while .lineHeight > .maxHeight and .currentFontSize > 2
1318                 .currentFontSize -= 0.5
1319                 call points_to_wc '.currentFontSize'
1320                 .lineHeight = points_to_wc.wc
1321         endwhile
1322         .diff = .lineHeight - .maxHeight
1323         .newFontSize = .currentFontSize
1324         demo 'defaultFont$'
1325 endproc
1327 # Load a table with button info etc.
1328 # Load local tables if present. Else load
1329 # build-in scripted tables
1330 procedure loadTable .tableName$
1331         .tableVariableName$ = replace_regex$(.tableName$, "[^\w]", "_", 0);
1332         # Search for the table in local, preference, and global directories
1333         if fileReadable("'localTableDir$'/'.tableName$'.Table")
1334         Read from file... 'localTableDir$'/'.tableName$'.Table
1335         elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1336         Read from file... 'preferencesTableDir$'/'.tableName$'.Table
1337         elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1338         Read from file... 'globaltablelists$'/'.tableName$'.Table
1339         # Load them from script
1340         elsif variableExists("procCreate'.tableVariableName$'$")
1341                 call Create'.tableVariableName$'
1342         else
1343                 call write_text_popup 'defaultFont$' 14 '.tableName$' cannot be found
1344                 demoWaitForInput()
1345                 exit '.tableName$' cannot be found
1346         endif
1347 endproc
1349 procedure testLoadTable .tableName$
1350         .table = 0
1351         .tableVariableName$ = replace_regex$(.tableName$, "[^\w]", "_", 0);
1352         # Search for the table in local, preference, and global directories
1353         if fileReadable("'localTableDir$'/'.tableName$'.Table")
1354         .table = 1
1355         elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1356         .table = 2
1357         elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1358         .table = 3
1359         # Load them from script
1360         elsif variableExists("procCreate'.tableVariableName$'$")
1361                 .table = 4
1362         else
1363                 .table = 0
1364         endif
1365 endproc
1367 procedure checkTable .tableName$
1368         .available = 0
1369         if fileReadable("'localTableDir$'/'.tableName$'.Table")
1370         .available = 1
1371         elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1372         .available = 1
1373         elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1374         .available = 1
1375         # Load them from script
1376         elsif variableExists("procCreate'.tableName$'$")
1377         .available = 1
1378         else
1379         .available = 0
1380     endif
1381 endproc
1383 # Create a pop-up window with text from a Text Table
1384 procedure write_text_table .table$
1385         .xleft = 10
1386         .xright = 90
1387         .ylow = 20
1388         .yhigh = 85
1389         .lineHeight = 2.5
1391         # Get table with text and longest line
1392         .numLines = 0
1393         call testLoadTable '.table$'
1394         if testLoadTable.table > 0
1395                 call loadTable '.table$'
1396                 .instructionText = selected()
1397                 .numLines = Get number of rows
1398         endif
1399         .instructionFontSize = 14
1400         .referenceText$ = ""
1401         .maxlenght = 0
1402         .maxLine = 0
1403         .maxFontSize = 0
1404         .maxWidth = 0
1405         for .l to .numLines
1406                 select '.instructionText'
1407                 .currentText$ = Get value... '.l' text
1408                 # Expand variables, eg, 'praatVersion$'
1409                 call expand_praat_variables '.currentText$'
1410                 .currentText$ = expand_praat_variables.text$
1411                 
1412                 .font$ = Get value... '.l' font
1413                 .fontSize = Get value... '.l' size
1414                 call set_font_size '.fontSize'
1415                 .textWidth = demo Text width (wc)... '.currentText$'
1416                 if .fontSize > .maxFontSize
1417                         .maxFontSize = .fontSize
1418                 endif
1419                 if .textWidth > .maxWidth
1420                         .maxWidth = .textWidth
1421                         .instructionFontSize = .fontSize
1422                         .maxLine = .l
1423                 endif
1424         endfor
1425         select '.instructionText'
1426         .referenceText$ = Get value... '.maxLine' text
1427         .maxLineFont$ = Get value... '.maxLine' font
1428         .instructionFontSize = Get value... '.maxLine' size
1429         call set_font_size '.maxFontSize'
1430         
1431         # Adapt size of button to length of text
1432         .maxWidth = (.xright - .xleft) - 4
1433         .origFontSize = .instructionFontSize
1434         call adjustFontSizeOnWidth 'defaultFont$' '.instructionFontSize' '.maxWidth' '.referenceText$'
1435         call adjustFontSizeOnHeight 'defaultFont$' '.maxFontSize' '.lineHeight'
1436         .instructionFontSize = min(adjustFontSizeOnWidth.newFontSize, adjustFontSizeOnHeight.newFontSize)
1437         if adjustFontSizeOnWidth.diff > 0
1438                 .xright += adjustFontSizeOnWidth.diff/4
1439                 .xleft -= 3*adjustFontSizeOnWidth.diff/4
1440         endif
1441         call set_font_size '.instructionFontSize'
1442         .fontSizeFactor = .instructionFontSize / .origFontSize
1444         .numRows = Get number of rows
1445         # Calculate length from number of lines.
1446         .dy = .lineHeight
1447         .midY = .yhigh - (.yhigh - .ylow)/2
1448         .yhigh = .midY + (.numRows+1) * .dy / 2
1449         .ylow = .yhigh - (.numRows+1) * .dy
1450         .textleft = .xleft + 2
1451         
1452         demo Line width... 8
1453         demo Colour... 'sgc2.popUp_bordercolor$'
1454         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1455         demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1456         demo Line width... 'defaultLineWidth'
1457         demo Black
1458         .ytext = .yhigh - 2 - .dy
1459         for .i to .numRows
1460                 select '.instructionText'
1461                 .font$ = Get value... '.i' font
1462                 .fontSize = Get value... '.i' size
1463                 .font$ = extractWord$(.font$, "")
1464                 # Scale font
1465                 .fontSize = floor(.fontSize*.fontSizeFactor)
1466                 if .fontSize < 4
1467                         .fontSize = 4
1468                 endif
1469                 .line$ = Get value... '.i' text
1470                 # Expand variables, eg, 'praatVersion$'
1471                 call expand_praat_variables '.line$'
1472                 .line$ = expand_praat_variables.text$
1473                 
1474                 # Display text
1475                 demo Text special... '.textleft' Left '.ytext' Bottom '.font$' '.fontSize' 0 '.line$'
1476                 .ytext -= .dy
1477         endfor  
1478         demoShow()      
1479         call set_font_size 'defaultFontSize'
1480         
1481         select '.instructionText'
1482         Remove
1483         
1484         label ESCAPEwrite_text_table
1485 endproc
1488 # Create a pop-up window with text from an existing Table object
1489 procedure write_tabbed_table .table$ .labelTextTable$
1490         .xleft = 0
1491         .xright = 100
1492         .ylow = 20
1493         .yhigh = 85
1494         .lineHeight = 2.5
1496         # Get table with text and longest line
1497         call testLoadTable '.table$'
1498         if testLoadTable.table <= 0
1499                 call loadTable '.labelTextTable$'
1500                 .labelText$ = selected$("Table")
1501         endif
1502                 
1503         select Table '.table$'
1504         .tabbedText = selected()
1505         .numLines = Get number of rows
1506         .numCols = Get number of columns
1507         .font$ = defaultFont$
1508         .fontSize = defaultFontSize
1509         # Standard width
1510         .widthCanvas = .xright - .xleft
1511         .dx = (.widthCanvas - 4) / (.numCols)
1513         # Get longest entry
1514         demo '.font$'
1515         call set_font_size '.fontSize'
1516         .maxWidth = 0
1517         for .i from 0 to .numLines
1518                 .xtext = .xleft + .dx / 2
1519                 for .j to .numCols
1520                         select '.tabbedText'
1521                         .currentLabel$ = Get column label... '.j'
1522                         if .i > 0
1523                                 .line$ = Get value... '.i' '.currentLabel$'
1524                         else
1525                                 .line$ = .currentLabel$
1526                                 select Table '.labelText$'
1527                         call findLabel '.labelText$' '.line$'
1528                         select Table '.labelText$'
1529                         .line$ = Get value... 'findLabel.row' Text
1530                         endif
1531                         # Expand variables, eg, 'praatVersion$'
1532                         call expand_praat_variables '.line$'
1533                         .line$ = expand_praat_variables.text$
1534                         .textWidth = demo Text width (wc)... '.line$'
1535                         if .textWidth > .maxWidth
1536                                 .maxWidth = .textWidth
1537                         endif
1538                 endfor
1539         endfor
1540         if .dx > 1.2 * .maxWidth
1541                 .widthCanvas =  1.2 * .maxWidth * .numCols + 4
1542                 .xleft = 50 - .widthCanvas / 2
1543                 .xright = 50 + .widthCanvas / 2
1544                 .dx = (.widthCanvas - 4) / (.numCols)
1545         else
1546                 .maxWidth = .dx - 1
1547         endif
1548         
1549         # Calculate length from number of lines.
1550         .dy = .lineHeight + 0.5
1551         .midY = .yhigh - (.yhigh - .ylow)/2
1552         .yhigh = .midY + (.numLines+2) * .dy / 2
1553         .ylow = .yhigh - (.numLines+2) * .dy
1554         .textleft = .xleft + 2
1555         
1556         demo Line width... 8
1557         demo Colour... 'sgc2.popUp_bordercolor$'
1558         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1559         demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1560         demo Line width... 'defaultLineWidth'
1561         demo Black
1562         .ytext = .yhigh - 2 - .dy
1563         # First the column names, then the items
1564         for .i from 0 to .numLines
1565                 .xtext = .textleft + .dx / 2
1566                 for .j to .numCols
1567                         select '.tabbedText'
1568                         .currentLabel$ = Get column label... '.j'
1569                         if .i > 0
1570                                 .line$ = Get value... '.i' '.currentLabel$'
1571                         else
1572                                 .line$ = .currentLabel$
1573                                 select Table '.labelText$'
1574                         call findLabel '.labelText$' '.line$'
1575                         select Table '.labelText$'
1576                         .line$ = Get value... 'findLabel.row' Text
1577                         endif
1578                         # Expand variables, eg, 'praatVersion$'
1579                         call expand_praat_variables '.line$'
1580                         .line$ = expand_praat_variables.text$
1581                         call adjustFontSizeOnWidth '.font$' '.fontSize' '.maxWidth' '.line$'
1582                         .currentFontSize = adjustFontSizeOnWidth.newFontSize
1584                         # Display text
1585                         demo Text special... '.xtext' Centre '.ytext' Bottom '.font$' '.currentFontSize' 0 '.line$'
1586                         .xtext += .dx
1587                 endfor
1588                 .ytext -= .dy
1589         endfor  
1590         demoShow()      
1591         call set_font_size 'defaultFontSize'
1592         select Table '.labelText$'
1593         Remove
1594         
1595         label ESCAPEwrite_tabbed_table
1596 endproc
1598 # Create a pop-up window with a given text
1599 procedure write_text_popup .font$ .size .text$
1600         .xleft = 10
1601         .xright = 90
1602         .ylow = 20
1603         .yhigh = 85
1604         .lineHeight = 3
1606         # Adapt size of button to length of text
1607         .maxWidth = (.xright - .xleft) - 4
1608         call adjustFontSizeOnWidth 'defaultFont$' '.size' '.maxWidth' '.text$'
1609         call adjustFontSizeOnHeight 'defaultFont$' '.size' '.lineHeight'
1610         .popupFontSize = min(adjustFontSizeOnWidth.newFontSize, adjustFontSizeOnHeight.newFontSize)
1611         if adjustFontSizeOnWidth.diff > 0
1612                 .xright += adjustFontSizeOnWidth.diff/4
1613                 .xleft -= 3*adjustFontSizeOnWidth.diff/4
1614         else
1615                 .xleft = ((.xright + .xleft) - adjustFontSizeOnWidth.textWidth)/2 - 2
1616                 .xright = ((.xright + .xleft) + adjustFontSizeOnWidth.textWidth)/2 + 2
1617         endif
1619         .numRows = 1
1620         # Calculate length from number of lines.
1621         .dy = .lineHeight
1622         .midY = .yhigh - (.yhigh - .ylow)/2
1623         .yhigh = .midY + (.numRows+1) * .dy / 2
1624         .ylow = .yhigh - (.numRows+1) * .dy
1625         .textleft = .xleft + 2
1626         .xmid = (.textleft + .xright - 2)/2
1627         
1628         demo Line width... 8
1629         demo Colour... 'sgc2.popUp_bordercolor$'
1630         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1631         demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1632         demo Line width... 'defaultLineWidth'
1633         demo Black
1634         .ytext = .yhigh - 2 - .dy
1635         # Write text
1636         demo Text special... '.xmid' Centre '.ytext' Bottom '.font$' '.popupFontSize' 0 '.text$'
1638         demoShow()      
1639         demo 'defaultFont$'
1640         call set_font_size 'defaultFontSize'
1641 endproc
1643 # Write the background from a Text Table
1644 procedure draw_background .table$
1645         .xleft = 0
1646         .xright = 100
1647         .ylow = 0
1648         .yhigh = 100
1649         .lineHeight = 5
1650         .defaultColour$ = "{0.9,0.9,0.9}"
1651         .defaultAlign$ = "centre"
1653         # Get table with text and longest line
1654         call loadTable '.table$'
1655         .backgroundText = selected()
1656         .numLines = Get number of rows
1657         .backgroundFontSize = 28
1658         .referenceText$ = ""
1659         .maxlenght = 0
1660         .maxLine = 0
1661         .maxFontSize = 0
1662         .maxWidth = 0
1663         .textLines = 0
1664         for .l to .numLines
1665                 select '.backgroundText'
1666                 .currentText$ = Get value... '.l' text
1667                 # Expand variables, eg, 'praatVersion$'
1668                 call expand_praat_variables '.currentText$'
1669                 .currentText$ = expand_praat_variables.text$            
1670                 
1671                 .font$ = Get value... '.l' font
1672                 .fontSize = Get value... '.l' size
1673                 if .fontSize > .maxFontSize
1674                         .maxFontSize = .fontSize
1675                 endif
1676                 if not startsWith(.font$, "!")
1677                         call set_font_size '.fontSize'
1678                         .textWidth = demo Text width (wc)... '.currentText$'
1679                         if .textWidth > .maxWidth
1680                                 .maxWidth = .textWidth
1681                                 .backgroundFontSize = .fontSize
1682                                 .maxLine = .l
1683                         endif
1685                         .textLines += 1
1686                 endif
1687         endfor
1688         if .maxLine > 0
1689                 select '.backgroundText'
1690                 .referenceText$ = Get value... '.maxLine' text
1691                 .maxLineFont$ = Get value... '.maxLine' font
1692                 .backgroundFontSize = Get value... '.maxLine' size
1693                 .backgroundFontColour$ = Get value... '.maxLine' colour
1694                 call set_font_size '.maxFontSize'
1695         else
1696                 .maxFontSize = .backgroundFontSize
1697         endif
1698         
1699         # Adapt size of button to length of text
1700         .maxWidth = (.xright - .xleft) - 4
1701         .origFontSize = .backgroundFontSize
1702         call adjustFontSizeOnWidth 'defaultFont$' '.backgroundFontSize' '.maxWidth' '.referenceText$'
1703         .fontSizeFactor = adjustFontSizeOnWidth.newFontSize / .backgroundFontSize
1704         .backgroundFontSize = adjustFontSizeOnWidth.newFontSize
1705         call set_font_size '.backgroundFontSize'
1706         
1707         call adjustFontSizeOnHeight 'defaultFont$' '.backgroundFontSize' '.lineHeight'
1708         .lineHeight /= adjustFontSizeOnHeight.newFontSize / .backgroundFontSize
1709         if adjustFontSizeOnHeight.newFontSize >= .origFontSize and (.textLines+1) * .lineHeight > (.yhigh - .ylow - 4)
1710                 .lineHeight = (.yhigh - .ylow - 4)/(.textLines + 1)
1711                 call adjustFontSizeOnHeight 'defaultFont$' '.maxFontSize' '.lineHeight'
1712                 .fontSizeFactor = adjustFontSizeOnHeight.newFontSize / .backgroundFontSize
1713         endif
1715         .numRows = Get number of rows
1716         # Calculate length from number of lines.
1717         .dy = .lineHeight
1718         .midY = .yhigh - (.yhigh - .ylow)/2
1719         .yhigh = .midY + (.textLines+1) * .dy / 2
1720         .ylow = .yhigh - (.textLines+1) * .dy
1721         .textleft = .xleft + 2
1722         .textright = .xright - 2
1723         .textmid = (.xright - .xleft)/2
1724         
1725         demo Black
1726         .ytext = .yhigh - 2 - .dy
1727         for .i to .numRows
1728                 select '.backgroundText'
1729                 .font$ = Get value... '.i' font
1730                 .fontSize = Get value... '.i' size
1731                 .fontColour$ = Get value... '.i' colour
1732                 .fontColour$ = replace_regex$(.fontColour$, "^[\- ]$", ".defaultColour$", 1)
1733                 .fontAlign$ = Get value... '.i' align
1734                 .fontAlign$ = replace_regex$(.fontAlign$, "^[\- ]$", ".defaultAlign$", 1)
1735                 .line$ = Get value... '.i' text
1736                 # Expand variables, eg, 'praatVersion$'
1737                 call expand_praat_variables '.line$'
1738                 .line$ = expand_praat_variables.text$
1739                                 
1740                  # Scale font
1741                  .fontSize = floor(.fontSize*.fontSizeFactor)
1742                 if not startsWith(.font$, "!")
1743                         .font$ = extractWord$(.font$, "")
1745                         if .fontAlign$ = "centre"
1746                                 .xtext = .textmid
1747                         elsif .fontAlign$ = "right"
1748                                 .xtext = .textright
1749                         else
1750                                 .xtext = .textleft
1751                         endif
1752                         if .fontSize < 4
1753                                 .fontSize = 4
1754                         endif
1755                         # Clean up text
1756                         demo Colour... '.fontColour$'
1757                         demo Text special... '.xtext' '.fontAlign$' '.ytext' Bottom '.font$' '.fontSize' 0 '.line$'
1758                         .ytext -= .dy
1759                 elsif .font$ = "!demo command"
1760                         demo Colour... '.fontColour$'
1761                         .line$ = replace_regex$(.line$, "\{FONTSIZE\$\}", "'.fontSize'", 0)
1762                         .line$ = replace_regex$(.line$, "\{XTEXT\$\}", "'.xtext'", 0)
1763                         .line$ = replace_regex$(.line$, "\{YTEXT\$\}", "'.ytext'", 0)
1764                         .line$ = replace_regex$(.line$, "\{DY\$\}", "'.dy'", 0)
1765                         .line$ = replace_regex$(.line$, "\{[^\}]*\}", "", 0)
1766                         while index(.line$, "[[")
1767                                 .nextBracketOpen = index(.line$, "[[")
1768                                 .nextBracketOpen += 2
1769                                 .nextBracketClose = index(.line$, "]]")
1770                                 .bracketLength = .nextBracketClose - .nextBracketOpen
1771                                 .result$ = ""
1772                                 if .bracketLength > 0
1773                                         .expression$ = mid$(.line$, .nextBracketOpen, .bracketLength)
1774                                         .expression$ = replace_regex$(.expression$, "\s", "", 0)
1775                                         if length(.expression$) > 0
1776                                                 # Test expression for security, only allow explicitely defined functions
1777                                                 .allowedStrings$ = "e|pi|not|and|or|div|mod|abs|round|floor|ceiling"
1778                                                 .allowedStrings$ = .allowedStrings$ + "|sqrt|min|max|imin|imax|sin|cos|tan|arcsin|arccos|arctan|arctan2|sinc|sincpi"
1779                                                 .allowedStrings$ = .allowedStrings$ + "|exp|ln|log10|log2|sinh|cosh|tanh|arcsinh|arccosh|arctanh"
1780                                                 .allowedStrings$ = .allowedStrings$ + "|sigmoid|invSigmoid|erf|erfc|randomUniform|randomInteger|randomGauss|randomPoisson"
1781                                                 .allowedStrings$ = .allowedStrings$ + "|lnGamma|gaussP|gaussQ|invGaussQ|chiSquareP|chiSquareQ"
1782                                                 .allowedStrings$ = .allowedStrings$ + "|invChiSquareP|invChiSquareQ|studentP|studentQ|invStudentP|invStudentQ"
1783                                                 .allowedStrings$ = .allowedStrings$ + "|beta|besselI|besselK"
1784                                                 .testExpression$ = replace_regex$(.expression$, "(^|\W)('.allowedStrings$')(?=$|\W)", "\1\3", 0)
1785                                                 .testExpression$ = replace_regex$(.testExpression$, "[0-9\.,\-+/*^()<>= ]", "", 0)
1786                                                 if .testExpression$ = ""
1787                                                         .calc = '.expression$'
1788                                                         .result$ = "'.calc'"
1789                                                 endif
1790                                         endif
1791                                 endif
1792                                 
1793                                 # Replace expression by result
1794                                 .lastLeft = .nextBracketOpen - 3
1795                                 .newLine$ = left$(.line$, .lastLeft)  
1796                                 .newLine$ =  .newLine$ + .result$
1797                                 .numCopy = length(.line$) - .nextBracketClose - 1
1798                                 .newLine$ =  .newLine$ + right$(.line$, .numCopy)
1799                                 .line$ = .newLine$
1800                         endwhile
1801                         demo '.line$'
1802                 endif
1803         endfor  
1804         demo Black
1805         demoShow()      
1806         call set_font_size 'defaultFontSize'
1807         
1808         select '.backgroundText'
1809         Remove
1810 endproc
1812 procedure convert_praat_to_utf8 .text$
1813         .text$ = replace_regex$(.text$, "\\a""", "\xc3\xa4", 0)
1814         .text$ = replace_regex$(.text$, "\\A""", "\xc3\x84", 0)
1815         .text$ = replace_regex$(.text$, "\\o""", "\xc3\xb6", 0)
1816         .text$ = replace_regex$(.text$, "\\O""", "\xc3\x96", 0)
1817         .text$ = replace_regex$(.text$, "\\u""", "\xc3\xbc", 0)
1818         .text$ = replace_regex$(.text$, "\\U""", "\xc3\x9c", 0)
1819         .text$ = replace_regex$(.text$, "\\i""", "\xc3\xaf", 0)
1820         .text$ = replace_regex$(.text$, "\\I""", "\xc3\x8f", 0)
1821         .text$ = replace_regex$(.text$, "\\e""", "\xc3\xab", 0)
1822         .text$ = replace_regex$(.text$, "\\E""", "\xc3\x8b", 0)
1823         .text$ = replace_regex$(.text$, "\\y""", "\xc3\xbf", 0)
1824         .text$ = replace_regex$(.text$, "\\e'", "\xc3\xa9", 0)
1825         .text$ = replace_regex$(.text$, "\\E'", "\xc3\x89", 0)
1826         .text$ = replace_regex$(.text$, "\\ss", "\xc3\x9f", 0)
1827 endproc
1829 procedure convert_praat_to_latin1 .text$
1830         .text$ = replace_regex$(.text$, "\\a""", "\xe4", 0)
1831         .text$ = replace_regex$(.text$, "\\A""", "\xc4", 0)
1832         .text$ = replace_regex$(.text$, "\\o""", "\xf6", 0)
1833         .text$ = replace_regex$(.text$, "\\O""", "\xd6", 0)
1834         .text$ = replace_regex$(.text$, "\\u""", "\xfc", 0)
1835         .text$ = replace_regex$(.text$, "\\U""", "\xdc", 0)
1836         .text$ = replace_regex$(.text$, "\\i""", "\xef", 0)
1837         .text$ = replace_regex$(.text$, "\\I""", "\xcf", 0)
1838         .text$ = replace_regex$(.text$, "\\e""", "\xeb", 0)
1839         .text$ = replace_regex$(.text$, "\\E""", "\xcb", 0)
1840         .text$ = replace_regex$(.text$, "\\y""", "\xff", 0)
1841         .text$ = replace_regex$(.text$, "\\Y""", "Y", 0)
1842         .text$ = replace_regex$(.text$, "\\e'", "\xe9", 0)
1843         .text$ = replace_regex$(.text$, "\\E'", "\xc9", 0)
1844         .text$ = replace_regex$(.text$, "\\ss", "\xdf", 0)
1845 endproc
1847 # Expand 'variable$' into the value of variable$.
1848 # Eg, 'praatVersion$' becomes 5.1.45 or whatever is the current version
1849 # Single quotes can be protected by \'
1850 procedure expand_praat_variables .text$
1851         if index(.text$, "'")
1852                 .tempText$ = replace_regex$(.text$, "(^|[^\\])'([\w\$\.]+)'", "\1""+\2+""", 0)
1853                 .tempText$ = replace_regex$(.tempText$, "[\\]'", "'", 0)
1854                 .tempText$ = """"+.tempText$+""""
1855                 # Check whether all the variables actually exist. Ignore any variable that does not exist
1856                 .checkVars$ = .tempText$
1857                 while length(.checkVars$) > 0 and index(.checkVars$, "+")
1858                         .start = index(.checkVars$, "+")
1859                         .checkVars$ = right$(.checkVars$, length(.checkVars$) - .start)
1860                         .end = index(.checkVars$, "+")
1861                         if .end
1862                                 .variable$ = left$(.checkVars$, .end - 1)
1863                                 if not variableExists(.variable$)
1864                                         .tempText$ = replace$(.tempText$, """+'.variable$'+""", "'"+.variable$+"'", 0)
1865                                 endif
1866                                 .checkVars$ = right$(.checkVars$, length(.checkVars$) - .end)
1867                         else
1868                                 .checkVars$ = ""
1869                         endif
1870                 endwhile
1871                 .text$ = '.tempText$'
1872         endif
1873 endproc
1875 # Get a time stamp in normalized format
1876 procedure getTimeStamp
1877         .currentDateTime$ = date$()
1878         .string$ = replace_regex$(.currentDateTime$, "[A-Z][a-z]+\s+([A-Z][a-z]+)\s+(\d+)\s+(\d+)\W(\d+)\W(\d+)\s+(\d+)$", "\6-\1-\2T\3-\4-\5", 0)
1879 endproc
1881 # A table error, can be insiduously caused by an outdate preferences file!
1882 procedure emergency_table_exit .message$
1883         # If you come here as a user, your preferences file is borked
1884         if preferencesAppFile$ <> "" and fileReadable(preferencesAppFile$)
1885                 deleteFile(preferencesAppFile$)
1886         endif
1887         exit '.message$'
1888 endproc
1890 # Remove previous files from system
1891 procedure clean_up_sound
1892         if recordedSound$ = ""
1893                 sgc.recordedSound = 0
1894         endif
1895     if sgc.recordedSound > 0
1896         select sgc.recordedSound
1897         Remove
1898         recordedSound$ = ""
1899         sgc.recordedSound = 0
1900     endif
1901     if te.recordedPitch > 0
1902         select te.recordedPitch
1903         Remove
1904                 te.recordedPitch = 0
1905     endif
1906         if sgc.alignedTextGrid > 0
1907                 select sgc.alignedTextGrid
1908                 Remove
1909                 sgc.alignedTextGrid = -1
1910         endif
1911 endproc
1913 # Safely read a table
1914 procedure readTable .filename$
1915         .tableID = -1
1916         if .filename$ <> "" and fileReadable(.filename$) and index_regex(.filename$, "(?i\.(tsv|table|csv))$") > 0
1917                 .tableID = nocheck Read from file... '.filename$'
1918                 if .tableID = undefined or .tableID <= 0
1919                         .tableID = -1
1920                 else
1921                         .fullName$ = selected$ ()
1922                         .type$ = extractWord$(.fullName$, "")
1923                         if .type$ <> "Table"
1924                                 Remove
1925                                 .tableID = -1
1926                         endif
1927                 endif
1928         endif
1929 endproc
1931 # Read feedback table and get keyed text
1932 procedure get_feedback_text .language$ .key$
1933         if not endsWith(feedbackTableName$, "_'.language$'")
1934                 if feedbackTableName$ <> ""
1935                         select Table 'feedbackTableName$'
1936                         Remove
1937                 endif
1938                 call loadTable 'feedbackTablePrefix$'_'.language$'
1939                 feedbackTableName$ = selected$("Table")
1940         endif
1941         call findKey 'feedbackTableName$' '.key$'
1942         .row = findKey.row
1943         select Table 'feedbackTableName$'
1944         .text$ = Get value... '.row' Text
1945         # Expand variables, eg, 'praatVersion$'
1946         call expand_praat_variables '.text$'
1947         .text$ = expand_praat_variables.text$   
1948 endproc