Adapted patch to Praat 5.4.09, e.g., changes in character width, char32/U/L
[sgc2.git] / sgc2.praat
blob299db30e9bb381485c29f420f37cad2d5d5035d2
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                 call readPinyin 'sgc.currentWord'
718                 .pinyin$ = readPinyin.pinyin$
719         endif
720         call add_missing_neutral_tones '.pinyin$'
721         .pinyin$ = add_missing_neutral_tones.pinyin$
722         if index_regex(.pinyin$, "[0-9]") > 0
723                 .number = length(replace_regex$(.pinyin$, "[^\d]+([\d]+)", "1", 0))
724         elsif .pinyin$ <> ""
725                 .number = 1
726         endif
727 endproc
729 procedure play_sound .sound
730     if .sound > 0
731                 if sgc.useAlternativePlayer and fileReadable(sgc.playCommandFile$)
732                         .scratchFile$ = "'sgc.scratchAudioDir$'SCRATCH.wav"
733                         select .sound
734                         Save as WAV file: .scratchFile$
735                         .command$ < 'sgc.playCommandFile$'
736                         .command$ = replace$(.command$, "[']", """", 0)
737                         .command$ = replace$(.command$, "'newline$'", " ", 0)
738                         if unix or macintosh
739                                 system_nocheck bash -c -- ''.command$' "'.scratchFile$'"'
740                         elsif windows
741                                 system_nocheck call '.command$' "'.scratchFile$'"
742                         endif
743                         deleteFile(.scratchFile$)
744                 else
745                         select .sound
746                         Play
747         endif
748     endif
749 endproc
751 procedure record_sound .recordingTime
752         if .recordingTime <= 0
753                 .recordingTime = recordingTime
754         endif
755         call clean_up_sound
756         
757         # NOTE: Some sound can be playing! This will not be stopped.
758         
759         # There is a very nasty delay before the first recording starts, do a dummy record
760         if not variableExists("recordingInitialized") and not sgc.useAlternativeRecorder
761         noprogress nowarn Record Sound (fixed time)... 'config.input$' 0.99 0.5 'samplingFrequency' 0.1
762                 Remove
763                 recordingInitialized = 1
764         endif
765         # Recording light
766     demo Paint circle... Red 5 95 2
767     demoShow()
768     
769         # In Windows XP interaction between demoWaitForInput and Record Sound blocks drawing the feedback
770         # This code might be removed #
771         if windows and endsWith(build_SHA$, " XP")
772                 # Display a pause window to flush the graphics buffer
773                 beginPause ("DESTROY WINDOW ")
774                         comment (" ")
775                 endPause ("DESTROY WINDOW ", 1)
776         #call init_window
777         demo Paint circle... Red 5 95 2
778         demoShow()
779         endif
780         ##############################
781         
782         # Use a different recorder program
783     if sgc.useAlternativeRecorder and fileReadable(sgc.recordCommandFile$)
784                 .scratchFile$ = "'sgc.scratchAudioDir$'SCRATCH.wav"
785                 .command$ < 'sgc.recordCommandFile$'
786                 .command$ = replace$(.command$, "[']", """", 0)
787                 .command$ = replace$(.command$, "'newline$'", " ", 0)
788                 if unix or macintosh
789                         system_nocheck bash -c -- ''.command$' '.recordingTime''
790                 elsif windows
791                         system_nocheck call '.command$' '.recordingTime'
792                 endif
793                 Read from file: .scratchFile$
794                 deleteFile(.scratchFile$)
795         else
796                 noprogress nowarn Record Sound (fixed time)... 'config.input$' 0.99 0.5 'samplingFrequency' '.recordingTime'
797         endif
798     demo Paint circle... White 5 95 2.5
799     call wipeArea 'wipeFeedbackArea$'
801     # Feedback on recording level
802     .extremum = Get absolute extremum... 0 0 None
803     .radius = 2 * .extremum
804     if .radius <= 0
805                 .radius = 0.02
806     endif
807     .blue = 0
808     .green = 0
809     .red = 0
810     if .extremum >= 0.95
811             .red = 1
812     elsif .extremum >= 0.49
813             .green = 1
814     else
815             .green = .extremum / 0.5
816     endif
817     .color$ = "{'.red','.green','.blue'}"
818     demo Colour... '.color$'
819     demo Line width... 1
820     demo Draw circle... 5 95 '.radius'
821     # Reset
822     demoShow()
823     demo Colour... Black
824     demo Line width... 'defaultLineWidth'
825     # Process sound
826     Rename... Tmp
827     Resample... 10000 50
828     Rename... Pronunciation
829     recordedSound$ = selected$("Sound")
830     sgc.recordedSound = selected("Sound")
831     select Sound Tmp
832     Remove
833     select Sound 'recordedSound$'
834     sgc.recordedSound = selected("Sound")
835         
836     # Cut out real sound from silences/noise
837     call sound_detection 'recordedSound$' 'soundMargin'
838     select Sound 'recordedSound$'
839     sgc.recordedSound = selected("Sound")
840     
841     # Store audio if requested
842     if sgc.saveAudioOn and sgc.saveAudio$ <> ""
843                 if sgc.savePerf$ <> "" and fileReadable(sgc.savePerf$)
844                         .pinyin$ = ""
845                         select Table 'wordlist$'
846                         if sgc.currentWord > 0 and sgc.currentWord <= sgc.numberOfWords
847                                 call readPinyin 'sgc.currentWord'
848                                 .pinyin$ = readPinyin.pinyin$
849                                 .outputName$ = "'sgc.saveAudio$'/'.pinyin$'.wav"
850                                 select sgc.recordedSound
851                                 Save as WAV file: .outputName$
852                         endif
853                 else
854                         # The Audio directory disappeared
855                         sgc.savePerf$ = ""
856                         sgc.saveAudioOn = 0
857                         sgc.saveAudio$ = ""
858                         config.savePerf = 0
859                         config.openPerf = 0
860                         config.clearSummary = 0
861                         config.audioName$ = ""
862                 endif
863     endif
864     
865 endproc
868 # Select real sound from recording
869 # Uses some global variable
870 procedure sound_detection .sound$ .margin
871         select Sound '.sound$'
872         .soundlength = Get total duration
873         .internalSilence = 2*.margin
874         
875         # Silence and remove noise, DANGEROUS
876         To TextGrid (silences)... 'minimumPitch' 0 'noiseThresshold' '.internalSilence' 0.1 silent sounding
877         Rename... Input'.sound$'
879         select TextGrid Input'.sound$'
880         .numberofIntervals = Get number of intervals... 1
881         if .numberofIntervals < 2
882                 .numberofIntervals = 0
883         endif
885         # The code below will suppress noise, but also weak third tones
886         # This handles the problem that third tones can be realized with 
887         # alternative cues, e.g, non-standard voice and very low levels 
888         #
889         # Remove buzzing and other obnoxious sounds (if switched on)
890         for .i from 1 to .numberofIntervals
891            select TextGrid Input'.sound$'
892            .value$ = Get label of interval... 1 '.i'
893            .begintime = Get starting point... 1 '.i'
894            .endtime = Get end point... 1 '.i'
895         
896                 # Remove noise
897                 if .value$ = "silent"
898                         select Sound '.sound$'
899                         Set part to zero... '.begintime' '.endtime' at nearest zero crossing
900                 endif
901         endfor
903         # Select target sound
904         .maximumIntensity = -1
905         .counter = 1
906         for i from 1 to .numberofIntervals
907            select TextGrid Input'.sound$'
909            .value$ = Get label of interval... 1 'i'
910            .begintime = Get starting point... 1 'i'
911            .endtime = Get end point... 1 'i'
913            if .value$ != "silent"
914            if .begintime > .margin
915                   .begintime -= .margin
916            else
917                    .begintime = 0
918            endif
919            if .endtime + .margin < .soundlength
920                    .endtime += .margin
921            else
922                    .endtime = .soundlength
923            endif
925            select Sound '.sound$'
926            Extract part... '.begintime' '.endtime' Rectangular 1.0 no
927            Rename... Tmp'.sound$'
928            Subtract mean
929            .newIntensity = Get intensity (dB)
930            if .newIntensity > .maximumIntensity
931                    if .maximumIntensity > 0
932                    select Sound New'.sound$'
933                    Remove
934                    endif
935                    select Sound Tmp'.sound$'
936                    Rename... New'.sound$'
937                    .maximumIntensity = .newIntensity
938            else
939                    select Sound Tmp'.sound$'
940                    Remove
941            endif
942            # 
943            endif
944         endfor
945         if .maximumIntensity > minimumIntensity
946                 select Sound '.sound$'
947                 Remove
948                 select Sound New'.sound$'
949                 Rename... '.sound$'
950         elsif .maximumIntensity > -1
951                 select Sound New'.sound$'
952                 Remove
953         endif
954         select TextGrid Input'.sound$'
955         Remove
956         
957         select Sound '.sound$'
958 endproc
960 procedure end_program
961         call write_preferences "" 
962         demo Erase all
963         select all
964         Remove
965         exit
966 endproc
968 ######################################################
970 # Configuration Page
972 ######################################################
973 procedure config_page
974     demo Erase all
975     demoWindowTitle("Speak Good Chinese: Change settings")
976     .label$ = ""
977     call Draw_config_page
979     while (.label$ <> "Return") and demoWaitForInput() 
980                 .clickX = -1
981                 .clickY = -1
982                 .pressed$ = ""
983             .label$ = ""
984             if demoClicked()
985                     .clickX = demoX()
986                     .clickY = demoY()
987                     call buttonClicked 'config$' '.clickX' '.clickY'
988                     .label$ = buttonClicked.label$
989             elsif demoKeyPressed()
990                     .pressed$ = demoKey$()
991                     call keyPressed 'config$' '.pressed$'
992                     .label$ = keyPressed.label$
993             endif
995                 # You cannot select a text field
996                 if startsWith(.label$, "$")
997                         .label$ = ""
998                 endif
999                 
1000             # Do things
1001             if .label$ != ""
1002                     # Handle push button in process_config
1003                     call process_config '.label$' '.clickX' '.clickY' '.pressed$'
1004             endif
1005         
1006         if .label$ = "Return"
1007             goto GOBACK
1008         endif
1009     endwhile
1011     # Go back
1012     label GOBACK
1013     call init_window
1014 endproc
1016 procedure Draw_config_page
1017         demo Erase all
1018         # Draw background
1019         if config.showBackground
1020                 call draw_background Background
1021         endif
1022         # Draw buttons
1023     call Draw_all_buttons 'config$'
1024         call set_window_title 'config$'  
1025     # Set correct buttons (alert)
1026         call setConfigMainPage
1027 endproc
1029 # Do what is asked
1030 procedure process_config .label$ .clickX .clickY .pressed$
1031         if .label$ <> "" and not startsWith(.label$,"!")
1032                 .label$ = replace_regex$(.label$, "^[#]", "", 0)
1033                 .label$ = replace$(.label$, "_", " ", 0)
1034                 call process'config$''.label$' '.clickX' '.clickY' '.pressed$'
1035         endif
1036 endproc
1038 ###############################################################
1040 # Presenting help texts
1042 ###############################################################
1044 # Process Help
1045 procedure help_loop .table$ .redrawProc$
1046         # General Help text
1047         call  write_help_title '.table$'
1048         
1049     .label$ = ""
1050     call Draw_button '.table$' Help 2
1051     .redrawScreen = 0
1052     while (.label$ <> "Help") and demoWaitForInput() 
1053             .label$ = ""
1054             if demoClicked()
1055                     .clickX = demoX()
1056                     .clickY = demoY()
1057                     call buttonClicked '.table$' '.clickX' '.clickY'
1058                     .label$ = buttonClicked.label$
1059             elsif demoKeyPressed()
1060                     .pressed$ = demoKey$()
1061                     call keyPressed '.table$' '.pressed$'
1062                     .label$ = keyPressed.label$
1063             endif
1065             if .label$ != "" and .label$ <> "Help"
1066                         # Redraw screen
1067                         if .redrawScreen
1068                                 demo Erase all
1069                                 call '.redrawProc$'
1070                         else
1071                         .redrawScreen = 1
1072                         endif
1073                         call Draw_button '.table$' Help 2
1074                         call  write_help_title '.table$'
1076                     # Handle push button in process_config
1077                     call write_help_text '.table$' '.label$'
1078             endif
1079         
1080     endwhile
1081         
1082         # Reset button
1083     call Draw_button '.table$' Help 0
1084         demo Erase all
1085         call '.redrawProc$'
1086 endproc
1088 # Write help text
1089 procedure write_help_text .table$ .label$
1090         call findLabel '.table$' '.label$'
1091         .row = findLabel.row
1092         select Table '.table$'
1093         # Get text
1094         if .row <= 0
1095                 call findLabel '.table$' Help
1096                 .row = findLabel.row
1097                 select Table '.table$'
1098         endif
1099         .helpText$ = Get value... '.row' Helptext
1100         .helpKey$ = Get value... '.row' Key
1101         .helpKey$ = replace$(.helpKey$, "\", "", 0)
1102         .helpKey$ = replace$(.helpKey$, "_", "\_ ", 0)
1103         if index_regex(.helpKey$, "\S")
1104                 .helpText$ = .helpText$+" ("+.helpKey$+")"
1105         endif
1106         # Get button values
1107     .leftX = Get value... '.row' LeftX
1108     .rightX = Get value... '.row' RightX
1109     .lowY = Get value... '.row' LowY
1110     .highY = Get value... '.row' HighY
1111         
1112         # PopUp dimensions
1113         .currentHelpFontSize = defaultFontSize
1114     call set_font_size '.currentHelpFontSize'
1115         .helpTextSize = demo Text width (wc)... '.helpText$'
1116         .helpTextSize += 4
1117         if .leftX > 50
1118                 .htXleft = 20
1119                 .htXright = .htXleft + .helpTextSize + 5
1120                 .xstart = .leftX
1121         else
1122                 .htXright = 80
1123                 .htXleft = .htXright - .helpTextSize - 5
1124                 .xstart = .rightX
1125         endif
1126         if .lowY > 50
1127                 .htYlow = 40
1128                 .htYhigh = .htYlow + 7
1129                 .ystart = .lowY
1130                 .yend = .htYhigh
1131         else
1132                 .htYhigh = 60
1133                 .htYlow = .htYhigh - 7
1134                 .ystart = .highY
1135                 .yend = .htYlow
1136         endif
1138         # Adapt font size to horizontal dimensions
1139         .maxWidth = 90
1140         call adjustFontSizeOnWidth 'defaultFont$' '.currentHelpFontSize' '.maxWidth' '.helpText$'
1141         .currentHelpFontSize = adjustFontSizeOnWidth.newFontSize
1142         if .htXleft < 0 or .htXright > 100
1143                 .htXleft = 0
1144                 .htXright = .htXleft + adjustFontSizeOnWidth.textWidth + 5
1145         endif
1146         call set_font_size '.currentHelpFontSize'
1148         # Adapt vertical dimensions to font height
1149         call points_to_wc '.currentHelpFontSize'
1150         .lineHeight = points_to_wc.wc
1151         if .lineHeight > .htYhigh - .htYlow - 4
1152                 .htYhigh = .htYlow + .lineHeight + 4
1153         endif
1155         # Determine arrow endpoints
1156         .xend = .htXleft
1157         if abs(.htXleft - .xstart) > abs(.htXright - .xstart)
1158                 .xend = .htXright
1159         endif
1160         if abs((.htXleft+.htXright)/2 - .xstart) < min(abs(.htXright - .xstart),abs(.htXleft - .xstart))
1161                 .xend = (.htXleft+.htXright)/2
1162         endif
1163         
1164         .xtext = .htXleft + 2
1165         .ytext = .htYlow + 1
1166         
1167         # Draw pop-up
1168         .mm2wc = demo Horizontal mm to wc... 1
1169         .lineWidth = 2/.mm2wc
1170         demo Line width... '.lineWidth'
1171         demo Arrow size... '.lineWidth'
1172         demo Colour... 'sgc2.popUp_bordercolor$'
1173         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.htXleft' '.htXright' '.htYlow' '.htYhigh'
1174         demo Draw rectangle... '.htXleft' '.htXright' '.htYlow' '.htYhigh'
1175         demo Draw arrow... '.xstart' '.ystart' '.xend' '.yend'
1176         demo Line width... 'defaultLineWidth'
1177         demo Arrow size... 1
1178         demo Black
1179         demo Text... '.xtext' Left '.ytext' Bottom '.helpText$'
1180         demoShow()
1181         call set_font_size 'defaultFontSize'
1182         
1183 endproc
1185 procedure write_help_title .table$
1186         # Set help text title
1187         # General Help text
1188         call findLabel '.table$' Help
1189         .row = findLabel.row
1190         select Table '.table$'
1191         .helpTitle$ = Get value... '.row' Helptext
1192         .helpKey$ = Get value... '.row' Key
1193         .helpKey$ = replace$(.helpKey$, "\", "", 0)
1194         .helpKey$ = replace$(.helpKey$, "_", "\_ ", 0)
1195         .helpTitle$ = .helpTitle$+" ("+.helpKey$+")"
1196         
1197         call reset_viewport
1198         .helpTitleFontSize = 14
1199         # Adapt size of button to length of text
1200         .maxWidth = 80
1201         call adjustFontSizeOnWidth 'defaultFont$' '.helpTitleFontSize' '.maxWidth' '.helpTitle$'
1202         .helpTitleFontSize = adjustFontSizeOnWidth.newFontSize
1203         call set_font_size '.helpTitleFontSize'
1204         .helpTop = 100
1205         
1206         demo Select inner viewport... 0 100 0 100
1207         demo Axes... 0 100 0 100
1208         demo Text... 50 Centre '.helpTop' Top '.helpTitle$'
1209     call set_font_size 'defaultFontSize'
1210         call reset_viewport
1211 endproc
1213 ###############################################################
1215 # Miscelaneous procedures
1217 ###############################################################
1218 procedure printPageToPrinter
1219         call print_window
1220         demo Print... 'printerName$' 'printerPresets$'
1221         call init_window
1222 endproc
1224 procedure getOpenFile .openDialogue$
1225         call clean_up_sound
1227         call convert_praat_to_latin1 '.openDialogue$'
1228         .openDialogue$ = convert_praat_to_latin1.text$
1229         .filename$ = chooseReadFile$ (.openDialogue$)
1230         .tmp = -1
1231         if .filename$ <> "" and fileReadable(.filename$)
1232                 .tmp = nocheck Read from file... '.filename$'
1233                 if .tmp !- undefined and .tmp > 0
1234                         call log_fileOpen '.filename$'
1235                 
1236                         # Get only the filename
1237                         .startName = rindex_regex(.filename$, "[/\\:]") + 1
1238                         .nameLength = rindex(.filename$, ".") - .startName
1239                         currentSoundName$ = mid$(.filename$, .startName, .nameLength)
1240                 else
1241                         .tmp = -1
1242                 endif
1243         endif
1244         if .tmp <= 0
1245                 Create Sound from formula... Speech Mono 0 1 44100 0
1246         endif
1247         recordedSound$ = selected$("Sound")
1248         sgc.recordedSound = selected("Sound")
1249         currentStartTime = 0
1250         currentEndTime = Get total duration
1251         # Reset selected window
1252         selectedStartTime = currentStartTime
1253         selectedEndTime = currentEndTime
1254 endproc
1256 procedure points_to_wc .points
1257         .mm = .points * 0.3527777778
1258         .wc = demo Vertical mm to wc... '.mm'
1259 endproc
1261 procedure reset_viewport
1262         .low = viewportMargin
1263         .high = 100 - viewportMargin
1264         demo Select inner viewport... '.low' '.high' '.low' '.high'
1265         demo Axes... 0 100 0 100
1266 endproc
1268 procedure set_font_size .fontSize
1269         call reset_viewport
1270         demo Font size... '.fontSize'
1271         call reset_viewport
1272 endproc
1274 procedure wipeArea .areaCommand$
1275         call reset_viewport
1276         '.areaCommand$'
1277 endproc
1279 procedure adjustFontSizeOnWidth .font$ .currentFontSize .maxWidth .text$
1280         demo '.font$'
1281         call set_font_size '.currentFontSize'
1282         .textWidth = demo Text width (wc)... '.text$'
1283         while .textWidth > .maxWidth and .currentFontSize > 2
1284                 .currentFontSize -= 0.5
1285                 call set_font_size '.currentFontSize'
1286                 .textWidth = demo Text width (wc)... '.text$'
1287         endwhile
1288         .diff = .textWidth - .maxWidth
1289         .newFontSize = .currentFontSize 
1290         demo 'defaultFont$'
1291 endproc
1293 procedure adjustRotatedFontSizeOnBox .font$ .currentFontSize .maxWidth .maxHeight .rotation .text$
1294         demo '.font$'
1295         .radians = .rotation/360 * 2 * pi
1296         .horWC = demo Horizontal mm to wc... 10.0
1297         .verWC = demo Vertical mm to wc... 10.0
1298         if .horWC > 0
1299                 .verCoeff = .verWC / .horWC
1300         else
1301                 .verCoeff = 1
1302         endif
1303         call set_font_size '.currentFontSize'
1304         .textLength = demo Text width (wc)... '.text$'
1305         while (.textLength * .verCoeff * sin(.radians) > .maxHeight or .textLength * cos(.radians) > .maxWidth) and .currentFontSize > 2
1306                 .currentFontSize -= 0.5
1307                 call set_font_size '.currentFontSize'
1308                 .textLength = demo Text width (wc)... '.text$'
1309         endwhile
1310         .diff = .textLength - .maxHeight
1311         .newFontSize = .currentFontSize 
1312         demo 'defaultFont$'
1313 endproc
1315 procedure adjustFontSizeOnHeight .font$ .currentFontSize .maxHeight
1316         demo '.font$'
1317         call points_to_wc '.currentFontSize'
1318         .lineHeight = points_to_wc.wc
1319         while .lineHeight > .maxHeight and .currentFontSize > 2
1320                 .currentFontSize -= 0.5
1321                 call points_to_wc '.currentFontSize'
1322                 .lineHeight = points_to_wc.wc
1323         endwhile
1324         .diff = .lineHeight - .maxHeight
1325         .newFontSize = .currentFontSize
1326         demo 'defaultFont$'
1327 endproc
1329 # Load a table with button info etc.
1330 # Load local tables if present. Else load
1331 # build-in scripted tables
1332 procedure loadTable .tableName$
1333         .tableVariableName$ = replace_regex$(.tableName$, "[^\w]", "_", 0);
1334         # Search for the table in local, preference, and global directories
1335         if fileReadable("'localTableDir$'/'.tableName$'.Table")
1336         Read from file... 'localTableDir$'/'.tableName$'.Table
1337         elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1338         Read from file... 'preferencesTableDir$'/'.tableName$'.Table
1339         elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1340         Read from file... 'globaltablelists$'/'.tableName$'.Table
1341         # Load them from script
1342         elsif variableExists("procCreate'.tableVariableName$'$")
1343                 call Create'.tableVariableName$'
1344         else
1345                 call write_text_popup 'defaultFont$' 14 '.tableName$' cannot be found
1346                 demoWaitForInput()
1347                 exit '.tableName$' cannot be found
1348         endif
1349 endproc
1351 procedure testLoadTable .tableName$
1352         .table = 0
1353         .tableVariableName$ = replace_regex$(.tableName$, "[^\w]", "_", 0);
1354         # Search for the table in local, preference, and global directories
1355         if fileReadable("'localTableDir$'/'.tableName$'.Table")
1356         .table = 1
1357         elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1358         .table = 2
1359         elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1360         .table = 3
1361         # Load them from script
1362         elsif variableExists("procCreate'.tableVariableName$'$")
1363                 .table = 4
1364         else
1365                 .table = 0
1366         endif
1367 endproc
1369 procedure checkTable .tableName$
1370         .available = 0
1371         if fileReadable("'localTableDir$'/'.tableName$'.Table")
1372         .available = 1
1373         elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1374         .available = 1
1375         elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1376         .available = 1
1377         # Load them from script
1378         elsif variableExists("procCreate'.tableName$'$")
1379         .available = 1
1380         else
1381         .available = 0
1382     endif
1383 endproc
1385 # Create a pop-up window with text from a Text Table
1386 procedure write_text_table .table$
1387         .xleft = 10
1388         .xright = 90
1389         .ylow = 20
1390         .yhigh = 85
1391         .lineHeight = 2.5
1393         # Get table with text and longest line
1394         .numLines = 0
1395         call testLoadTable '.table$'
1396         if testLoadTable.table > 0
1397                 call loadTable '.table$'
1398                 .instructionText = selected()
1399                 .numLines = Get number of rows
1400         endif
1401         .instructionFontSize = 14
1402         .referenceText$ = ""
1403         .maxlenght = 0
1404         .maxLine = 0
1405         .maxFontSize = 0
1406         .maxWidth = 0
1407         for .l to .numLines
1408                 select '.instructionText'
1409                 .currentText$ = Get value... '.l' text
1410                 # Expand variables, eg, 'praatVersion$'
1411                 call expand_praat_variables '.currentText$'
1412                 .currentText$ = expand_praat_variables.text$
1413                 
1414                 .font$ = Get value... '.l' font
1415                 .fontSize = Get value... '.l' size
1416                 call set_font_size '.fontSize'
1417                 .textWidth = demo Text width (wc)... '.currentText$'
1418                 if .fontSize > .maxFontSize
1419                         .maxFontSize = .fontSize
1420                 endif
1421                 if .textWidth > .maxWidth
1422                         .maxWidth = .textWidth
1423                         .instructionFontSize = .fontSize
1424                         .maxLine = .l
1425                 endif
1426         endfor
1427         select '.instructionText'
1428         .referenceText$ = Get value... '.maxLine' text
1429         .maxLineFont$ = Get value... '.maxLine' font
1430         .instructionFontSize = Get value... '.maxLine' size
1431         call set_font_size '.maxFontSize'
1432         
1433         # Adapt size of button to length of text
1434         .maxWidth = (.xright - .xleft) - 4
1435         .origFontSize = .instructionFontSize
1436         call adjustFontSizeOnWidth 'defaultFont$' '.instructionFontSize' '.maxWidth' '.referenceText$'
1437         call adjustFontSizeOnHeight 'defaultFont$' '.maxFontSize' '.lineHeight'
1438         .instructionFontSize = min(adjustFontSizeOnWidth.newFontSize, adjustFontSizeOnHeight.newFontSize)
1439         if adjustFontSizeOnWidth.diff > 0
1440                 .xright += adjustFontSizeOnWidth.diff/4
1441                 .xleft -= 3*adjustFontSizeOnWidth.diff/4
1442         endif
1443         call set_font_size '.instructionFontSize'
1444         .fontSizeFactor = .instructionFontSize / .origFontSize
1446         .numRows = Get number of rows
1447         # Calculate length from number of lines.
1448         .dy = .lineHeight
1449         .midY = .yhigh - (.yhigh - .ylow)/2
1450         .yhigh = .midY + (.numRows+1) * .dy / 2
1451         .ylow = .yhigh - (.numRows+1) * .dy
1452         .textleft = .xleft + 2
1453         
1454         demo Line width... 8
1455         demo Colour... 'sgc2.popUp_bordercolor$'
1456         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1457         demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1458         demo Line width... 'defaultLineWidth'
1459         demo Black
1460         .ytext = .yhigh - 2 - .dy
1461         for .i to .numRows
1462                 select '.instructionText'
1463                 .font$ = Get value... '.i' font
1464                 .fontSize = Get value... '.i' size
1465                 .font$ = extractWord$(.font$, "")
1466                 # Scale font
1467                 .fontSize = floor(.fontSize*.fontSizeFactor)
1468                 if .fontSize < 4
1469                         .fontSize = 4
1470                 endif
1471                 .line$ = Get value... '.i' text
1472                 # Expand variables, eg, 'praatVersion$'
1473                 call expand_praat_variables '.line$'
1474                 .line$ = expand_praat_variables.text$
1475                 
1476                 # Display text
1477                 demo Text special... '.textleft' Left '.ytext' Bottom '.font$' '.fontSize' 0 '.line$'
1478                 .ytext -= .dy
1479         endfor  
1480         demoShow()      
1481         call set_font_size 'defaultFontSize'
1482         
1483         select '.instructionText'
1484         Remove
1485         
1486         label ESCAPEwrite_text_table
1487 endproc
1490 # Create a pop-up window with text from an existing Table object
1491 procedure write_tabbed_table .table$ .labelTextTable$
1492         .xleft = 0
1493         .xright = 100
1494         .ylow = 20
1495         .yhigh = 85
1496         .lineHeight = 2.5
1498         # Get table with text and longest line
1499         call testLoadTable '.table$'
1500         if testLoadTable.table <= 0
1501                 call loadTable '.labelTextTable$'
1502                 .labelText$ = selected$("Table")
1503         endif
1504                 
1505         select Table '.table$'
1506         .tabbedText = selected()
1507         .numLines = Get number of rows
1508         .numCols = Get number of columns
1509         .font$ = defaultFont$
1510         .fontSize = defaultFontSize
1511         # Standard width
1512         .widthCanvas = .xright - .xleft
1513         .dx = (.widthCanvas - 4) / (.numCols)
1515         # Get longest entry
1516         demo '.font$'
1517         call set_font_size '.fontSize'
1518         .maxWidth = 0
1519         for .i from 0 to .numLines
1520                 .xtext = .xleft + .dx / 2
1521                 for .j to .numCols
1522                         select '.tabbedText'
1523                         .currentLabel$ = Get column label... '.j'
1524                         if .i > 0
1525                                 .line$ = Get value... '.i' '.currentLabel$'
1526                         else
1527                                 .line$ = .currentLabel$
1528                                 select Table '.labelText$'
1529                         call findLabel '.labelText$' '.line$'
1530                         select Table '.labelText$'
1531                         .line$ = Get value... 'findLabel.row' Text
1532                         endif
1533                         # Expand variables, eg, 'praatVersion$'
1534                         call expand_praat_variables '.line$'
1535                         .line$ = expand_praat_variables.text$
1536                         .textWidth = demo Text width (wc)... '.line$'
1537                         if .textWidth > .maxWidth
1538                                 .maxWidth = .textWidth
1539                         endif
1540                 endfor
1541         endfor
1542         if .dx > 1.2 * .maxWidth
1543                 .widthCanvas =  1.2 * .maxWidth * .numCols + 4
1544                 .xleft = 50 - .widthCanvas / 2
1545                 .xright = 50 + .widthCanvas / 2
1546                 .dx = (.widthCanvas - 4) / (.numCols)
1547         else
1548                 .maxWidth = .dx - 1
1549         endif
1550         
1551         # Calculate length from number of lines.
1552         .dy = .lineHeight + 0.5
1553         .midY = .yhigh - (.yhigh - .ylow)/2
1554         .yhigh = .midY + (.numLines+2) * .dy / 2
1555         .ylow = .yhigh - (.numLines+2) * .dy
1556         .textleft = .xleft + 2
1557         
1558         demo Line width... 8
1559         demo Colour... 'sgc2.popUp_bordercolor$'
1560         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1561         demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1562         demo Line width... 'defaultLineWidth'
1563         demo Black
1564         .ytext = .yhigh - 2 - .dy
1565         # First the column names, then the items
1566         for .i from 0 to .numLines
1567                 .xtext = .textleft + .dx / 2
1568                 for .j to .numCols
1569                         select '.tabbedText'
1570                         .currentLabel$ = Get column label... '.j'
1571                         if .i > 0
1572                                 .line$ = Get value... '.i' '.currentLabel$'
1573                         else
1574                                 .line$ = .currentLabel$
1575                                 select Table '.labelText$'
1576                         call findLabel '.labelText$' '.line$'
1577                         select Table '.labelText$'
1578                         .line$ = Get value... 'findLabel.row' Text
1579                         endif
1580                         # Expand variables, eg, 'praatVersion$'
1581                         call expand_praat_variables '.line$'
1582                         .line$ = expand_praat_variables.text$
1583                         call adjustFontSizeOnWidth '.font$' '.fontSize' '.maxWidth' '.line$'
1584                         .currentFontSize = adjustFontSizeOnWidth.newFontSize
1586                         # Display text
1587                         demo Text special... '.xtext' Centre '.ytext' Bottom '.font$' '.currentFontSize' 0 '.line$'
1588                         .xtext += .dx
1589                 endfor
1590                 .ytext -= .dy
1591         endfor  
1592         demoShow()      
1593         call set_font_size 'defaultFontSize'
1594         select Table '.labelText$'
1595         Remove
1596         
1597         label ESCAPEwrite_tabbed_table
1598 endproc
1600 # Create a pop-up window with a given text
1601 procedure write_text_popup .font$ .size .text$
1602         .xleft = 10
1603         .xright = 90
1604         .ylow = 20
1605         .yhigh = 85
1606         .lineHeight = 3
1608         # Adapt size of button to length of text
1609         .maxWidth = (.xright - .xleft) - 4
1610         call adjustFontSizeOnWidth 'defaultFont$' '.size' '.maxWidth' '.text$'
1611         call adjustFontSizeOnHeight 'defaultFont$' '.size' '.lineHeight'
1612         .popupFontSize = min(adjustFontSizeOnWidth.newFontSize, adjustFontSizeOnHeight.newFontSize)
1613         if adjustFontSizeOnWidth.diff > 0
1614                 .xright += adjustFontSizeOnWidth.diff/4
1615                 .xleft -= 3*adjustFontSizeOnWidth.diff/4
1616         else
1617                 .xleft = ((.xright + .xleft) - adjustFontSizeOnWidth.textWidth)/2 - 2
1618                 .xright = ((.xright + .xleft) + adjustFontSizeOnWidth.textWidth)/2 + 2
1619         endif
1621         .numRows = 1
1622         # Calculate length from number of lines.
1623         .dy = .lineHeight
1624         .midY = .yhigh - (.yhigh - .ylow)/2
1625         .yhigh = .midY + (.numRows+1) * .dy / 2
1626         .ylow = .yhigh - (.numRows+1) * .dy
1627         .textleft = .xleft + 2
1628         .xmid = (.textleft + .xright - 2)/2
1629         
1630         demo Line width... 8
1631         demo Colour... 'sgc2.popUp_bordercolor$'
1632         demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1633         demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1634         demo Line width... 'defaultLineWidth'
1635         demo Black
1636         .ytext = .yhigh - 2 - .dy
1637         # Write text
1638         demo Text special... '.xmid' Centre '.ytext' Bottom '.font$' '.popupFontSize' 0 '.text$'
1640         demoShow()      
1641         demo 'defaultFont$'
1642         call set_font_size 'defaultFontSize'
1643 endproc
1645 # Write the background from a Text Table
1646 procedure draw_background .table$
1647         .xleft = 0
1648         .xright = 100
1649         .ylow = 0
1650         .yhigh = 100
1651         .lineHeight = 5
1652         .defaultColour$ = "{0.9,0.9,0.9}"
1653         .defaultAlign$ = "centre"
1655         # Get table with text and longest line
1656         call loadTable '.table$'
1657         .backgroundText = selected()
1658         .numLines = Get number of rows
1659         .backgroundFontSize = 28
1660         .referenceText$ = ""
1661         .maxlenght = 0
1662         .maxLine = 0
1663         .maxFontSize = 0
1664         .maxWidth = 0
1665         .textLines = 0
1666         for .l to .numLines
1667                 select '.backgroundText'
1668                 .currentText$ = Get value... '.l' text
1669                 # Expand variables, eg, 'praatVersion$'
1670                 call expand_praat_variables '.currentText$'
1671                 .currentText$ = expand_praat_variables.text$            
1672                 
1673                 .font$ = Get value... '.l' font
1674                 .fontSize = Get value... '.l' size
1675                 if .fontSize > .maxFontSize
1676                         .maxFontSize = .fontSize
1677                 endif
1678                 if not startsWith(.font$, "!")
1679                         call set_font_size '.fontSize'
1680                         .textWidth = demo Text width (wc)... '.currentText$'
1681                         if .textWidth > .maxWidth
1682                                 .maxWidth = .textWidth
1683                                 .backgroundFontSize = .fontSize
1684                                 .maxLine = .l
1685                         endif
1687                         .textLines += 1
1688                 endif
1689         endfor
1690         if .maxLine > 0
1691                 select '.backgroundText'
1692                 .referenceText$ = Get value... '.maxLine' text
1693                 .maxLineFont$ = Get value... '.maxLine' font
1694                 .backgroundFontSize = Get value... '.maxLine' size
1695                 .backgroundFontColour$ = Get value... '.maxLine' colour
1696                 call set_font_size '.maxFontSize'
1697         else
1698                 .maxFontSize = .backgroundFontSize
1699         endif
1700         
1701         # Adapt size of button to length of text
1702         .maxWidth = (.xright - .xleft) - 4
1703         .origFontSize = .backgroundFontSize
1704         call adjustFontSizeOnWidth 'defaultFont$' '.backgroundFontSize' '.maxWidth' '.referenceText$'
1705         .fontSizeFactor = adjustFontSizeOnWidth.newFontSize / .backgroundFontSize
1706         .backgroundFontSize = adjustFontSizeOnWidth.newFontSize
1707         call set_font_size '.backgroundFontSize'
1708         
1709         call adjustFontSizeOnHeight 'defaultFont$' '.backgroundFontSize' '.lineHeight'
1710         .lineHeight /= adjustFontSizeOnHeight.newFontSize / .backgroundFontSize
1711         if adjustFontSizeOnHeight.newFontSize >= .origFontSize and (.textLines+1) * .lineHeight > (.yhigh - .ylow - 4)
1712                 .lineHeight = (.yhigh - .ylow - 4)/(.textLines + 1)
1713                 call adjustFontSizeOnHeight 'defaultFont$' '.maxFontSize' '.lineHeight'
1714                 .fontSizeFactor = adjustFontSizeOnHeight.newFontSize / .backgroundFontSize
1715         endif
1717         .numRows = Get number of rows
1718         # Calculate length from number of lines.
1719         .dy = .lineHeight
1720         .midY = .yhigh - (.yhigh - .ylow)/2
1721         .yhigh = .midY + (.textLines+1) * .dy / 2
1722         .ylow = .yhigh - (.textLines+1) * .dy
1723         .textleft = .xleft + 2
1724         .textright = .xright - 2
1725         .textmid = (.xright - .xleft)/2
1726         
1727         demo Black
1728         .ytext = .yhigh - 2 - .dy
1729         for .i to .numRows
1730                 select '.backgroundText'
1731                 .font$ = Get value... '.i' font
1732                 .fontSize = Get value... '.i' size
1733                 .fontColour$ = Get value... '.i' colour
1734                 .fontColour$ = replace_regex$(.fontColour$, "^[\- ]$", ".defaultColour$", 1)
1735                 .fontAlign$ = Get value... '.i' align
1736                 .fontAlign$ = replace_regex$(.fontAlign$, "^[\- ]$", ".defaultAlign$", 1)
1737                 .line$ = Get value... '.i' text
1738                 # Expand variables, eg, 'praatVersion$'
1739                 call expand_praat_variables '.line$'
1740                 .line$ = expand_praat_variables.text$
1741                                 
1742                  # Scale font
1743                  .fontSize = floor(.fontSize*.fontSizeFactor)
1744                 if not startsWith(.font$, "!")
1745                         .font$ = extractWord$(.font$, "")
1747                         if .fontAlign$ = "centre"
1748                                 .xtext = .textmid
1749                         elsif .fontAlign$ = "right"
1750                                 .xtext = .textright
1751                         else
1752                                 .xtext = .textleft
1753                         endif
1754                         if .fontSize < 4
1755                                 .fontSize = 4
1756                         endif
1757                         # Clean up text
1758                         demo Colour... '.fontColour$'
1759                         demo Text special... '.xtext' '.fontAlign$' '.ytext' Bottom '.font$' '.fontSize' 0 '.line$'
1760                         .ytext -= .dy
1761                 elsif .font$ = "!demo command"
1762                         demo Colour... '.fontColour$'
1763                         .line$ = replace_regex$(.line$, "\{FONTSIZE\$\}", "'.fontSize'", 0)
1764                         .line$ = replace_regex$(.line$, "\{XTEXT\$\}", "'.xtext'", 0)
1765                         .line$ = replace_regex$(.line$, "\{YTEXT\$\}", "'.ytext'", 0)
1766                         .line$ = replace_regex$(.line$, "\{DY\$\}", "'.dy'", 0)
1767                         .line$ = replace_regex$(.line$, "\{[^\}]*\}", "", 0)
1768                         while index(.line$, "[[")
1769                                 .nextBracketOpen = index(.line$, "[[")
1770                                 .nextBracketOpen += 2
1771                                 .nextBracketClose = index(.line$, "]]")
1772                                 .bracketLength = .nextBracketClose - .nextBracketOpen
1773                                 .result$ = ""
1774                                 if .bracketLength > 0
1775                                         .expression$ = mid$(.line$, .nextBracketOpen, .bracketLength)
1776                                         .expression$ = replace_regex$(.expression$, "\s", "", 0)
1777                                         if length(.expression$) > 0
1778                                                 # Test expression for security, only allow explicitely defined functions
1779                                                 .allowedStrings$ = "e|pi|not|and|or|div|mod|abs|round|floor|ceiling"
1780                                                 .allowedStrings$ = .allowedStrings$ + "|sqrt|min|max|imin|imax|sin|cos|tan|arcsin|arccos|arctan|arctan2|sinc|sincpi"
1781                                                 .allowedStrings$ = .allowedStrings$ + "|exp|ln|log10|log2|sinh|cosh|tanh|arcsinh|arccosh|arctanh"
1782                                                 .allowedStrings$ = .allowedStrings$ + "|sigmoid|invSigmoid|erf|erfc|randomUniform|randomInteger|randomGauss|randomPoisson"
1783                                                 .allowedStrings$ = .allowedStrings$ + "|lnGamma|gaussP|gaussQ|invGaussQ|chiSquareP|chiSquareQ"
1784                                                 .allowedStrings$ = .allowedStrings$ + "|invChiSquareP|invChiSquareQ|studentP|studentQ|invStudentP|invStudentQ"
1785                                                 .allowedStrings$ = .allowedStrings$ + "|beta|besselI|besselK"
1786                                                 .testExpression$ = replace_regex$(.expression$, "(^|\W)('.allowedStrings$')(?=$|\W)", "\1\3", 0)
1787                                                 .testExpression$ = replace_regex$(.testExpression$, "[0-9\.,\-+/*^()<>= ]", "", 0)
1788                                                 if .testExpression$ = ""
1789                                                         .calc = '.expression$'
1790                                                         .result$ = "'.calc'"
1791                                                 endif
1792                                         endif
1793                                 endif
1794                                 
1795                                 # Replace expression by result
1796                                 .lastLeft = .nextBracketOpen - 3
1797                                 .newLine$ = left$(.line$, .lastLeft)  
1798                                 .newLine$ =  .newLine$ + .result$
1799                                 .numCopy = length(.line$) - .nextBracketClose - 1
1800                                 .newLine$ =  .newLine$ + right$(.line$, .numCopy)
1801                                 .line$ = .newLine$
1802                         endwhile
1803                         demo '.line$'
1804                 endif
1805         endfor  
1806         demo Black
1807         demoShow()      
1808         call set_font_size 'defaultFontSize'
1809         
1810         select '.backgroundText'
1811         Remove
1812 endproc
1814 procedure convert_praat_to_utf8 .text$
1815         .text$ = replace_regex$(.text$, "\\a""", "\xc3\xa4", 0)
1816         .text$ = replace_regex$(.text$, "\\A""", "\xc3\x84", 0)
1817         .text$ = replace_regex$(.text$, "\\o""", "\xc3\xb6", 0)
1818         .text$ = replace_regex$(.text$, "\\O""", "\xc3\x96", 0)
1819         .text$ = replace_regex$(.text$, "\\u""", "\xc3\xbc", 0)
1820         .text$ = replace_regex$(.text$, "\\U""", "\xc3\x9c", 0)
1821         .text$ = replace_regex$(.text$, "\\i""", "\xc3\xaf", 0)
1822         .text$ = replace_regex$(.text$, "\\I""", "\xc3\x8f", 0)
1823         .text$ = replace_regex$(.text$, "\\e""", "\xc3\xab", 0)
1824         .text$ = replace_regex$(.text$, "\\E""", "\xc3\x8b", 0)
1825         .text$ = replace_regex$(.text$, "\\y""", "\xc3\xbf", 0)
1826         .text$ = replace_regex$(.text$, "\\e'", "\xc3\xa9", 0)
1827         .text$ = replace_regex$(.text$, "\\E'", "\xc3\x89", 0)
1828         .text$ = replace_regex$(.text$, "\\ss", "\xc3\x9f", 0)
1829 endproc
1831 procedure convert_praat_to_latin1 .text$
1832         .text$ = replace_regex$(.text$, "\\a""", "\xe4", 0)
1833         .text$ = replace_regex$(.text$, "\\A""", "\xc4", 0)
1834         .text$ = replace_regex$(.text$, "\\o""", "\xf6", 0)
1835         .text$ = replace_regex$(.text$, "\\O""", "\xd6", 0)
1836         .text$ = replace_regex$(.text$, "\\u""", "\xfc", 0)
1837         .text$ = replace_regex$(.text$, "\\U""", "\xdc", 0)
1838         .text$ = replace_regex$(.text$, "\\i""", "\xef", 0)
1839         .text$ = replace_regex$(.text$, "\\I""", "\xcf", 0)
1840         .text$ = replace_regex$(.text$, "\\e""", "\xeb", 0)
1841         .text$ = replace_regex$(.text$, "\\E""", "\xcb", 0)
1842         .text$ = replace_regex$(.text$, "\\y""", "\xff", 0)
1843         .text$ = replace_regex$(.text$, "\\Y""", "Y", 0)
1844         .text$ = replace_regex$(.text$, "\\e'", "\xe9", 0)
1845         .text$ = replace_regex$(.text$, "\\E'", "\xc9", 0)
1846         .text$ = replace_regex$(.text$, "\\ss", "\xdf", 0)
1847 endproc
1849 # Expand 'variable$' into the value of variable$.
1850 # Eg, 'praatVersion$' becomes 5.1.45 or whatever is the current version
1851 # Single quotes can be protected by \'
1852 procedure expand_praat_variables .text$
1853         if index(.text$, "'")
1854                 .tempText$ = replace_regex$(.text$, "(^|[^\\])'([\w\$\.]+)'", "\1""+\2+""", 0)
1855                 .tempText$ = replace_regex$(.tempText$, "[\\]'", "'", 0)
1856                 .tempText$ = """"+.tempText$+""""
1857                 # Check whether all the variables actually exist. Ignore any variable that does not exist
1858                 .checkVars$ = .tempText$
1859                 while length(.checkVars$) > 0 and index(.checkVars$, "+")
1860                         .start = index(.checkVars$, "+")
1861                         .checkVars$ = right$(.checkVars$, length(.checkVars$) - .start)
1862                         .end = index(.checkVars$, "+")
1863                         if .end
1864                                 .variable$ = left$(.checkVars$, .end - 1)
1865                                 if not variableExists(.variable$)
1866                                         .tempText$ = replace$(.tempText$, """+'.variable$'+""", "'"+.variable$+"'", 0)
1867                                 endif
1868                                 .checkVars$ = right$(.checkVars$, length(.checkVars$) - .end)
1869                         else
1870                                 .checkVars$ = ""
1871                         endif
1872                 endwhile
1873                 .text$ = '.tempText$'
1874         endif
1875 endproc
1877 # Get a time stamp in normalized format
1878 procedure getTimeStamp
1879         .currentDateTime$ = date$()
1880         .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)
1881 endproc
1883 # A table error, can be insiduously caused by an outdate preferences file!
1884 procedure emergency_table_exit .message$
1885         # If you come here as a user, your preferences file is borked
1886         if preferencesAppFile$ <> "" and fileReadable(preferencesAppFile$)
1887                 deleteFile(preferencesAppFile$)
1888         endif
1889         exit '.message$'
1890 endproc
1892 # Remove previous files from system
1893 procedure clean_up_sound
1894         if recordedSound$ = ""
1895                 sgc.recordedSound = 0
1896         endif
1897     if sgc.recordedSound > 0
1898         select sgc.recordedSound
1899         Remove
1900         recordedSound$ = ""
1901         sgc.recordedSound = 0
1902     endif
1903     if te.recordedPitch > 0
1904         select te.recordedPitch
1905         Remove
1906                 te.recordedPitch = 0
1907     endif
1908         if sgc.alignedTextGrid > 0
1909                 select sgc.alignedTextGrid
1910                 Remove
1911                 sgc.alignedTextGrid = -1
1912         endif
1913 endproc
1915 # Safely read a table
1916 procedure readTable .filename$
1917         .tableID = -1
1918         if .filename$ <> "" and fileReadable(.filename$) and index_regex(.filename$, "(?i\.(tsv|table|csv))$") > 0
1919                 .tableID = nocheck Read from file... '.filename$'
1920                 if .tableID = undefined or .tableID <= 0
1921                         .tableID = -1
1922                 else
1923                         .fullName$ = selected$ ()
1924                         .type$ = extractWord$(.fullName$, "")
1925                         if .type$ <> "Table"
1926                                 Remove
1927                                 .tableID = -1
1928                         endif
1929                 endif
1930         endif
1931 endproc
1933 # Read feedback table and get keyed text
1934 procedure get_feedback_text .language$ .key$
1935         if not endsWith(feedbackTableName$, "_'.language$'")
1936                 if feedbackTableName$ <> ""
1937                         select Table 'feedbackTableName$'
1938                         Remove
1939                 endif
1940                 call loadTable 'feedbackTablePrefix$'_'.language$'
1941                 feedbackTableName$ = selected$("Table")
1942         endif
1943         call findKey 'feedbackTableName$' '.key$'
1944         .row = findKey.row
1945         select Table 'feedbackTableName$'
1946         .text$ = Get value... '.row' Text
1947         # Expand variables, eg, 'praatVersion$'
1948         call expand_praat_variables '.text$'
1949         .text$ = expand_praat_variables.text$   
1950 endproc