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