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