6 # SpeakGoodChinese: sgc2.praat is the master GUI of SpeakGoodChinese
7 # It is written in Praat script for the Demo window
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
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.
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.
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
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$")
36 # These are simply "useful" defaults
37 # The local Table directory only exists when running SGC as a script
39 localTableDir$ = "Data"
43 buttonsTableName$ = "MainPage"
44 configTableName$ = "Config"
50 te.buttonPressValue = 0
51 samplingFrequency = 44100
54 # Pop-Up window colors
55 sgc2.popUp_bordercolor$ = "{0.5,0.5,1}"
56 sgc2.popUp_backgroundcolor$ = "{0.9,0.9,1}"
58 # If running in a packed script binary
59 if index_regex(preferencesDirectory$, "(?i'sgc2.demoAppName$')$")
60 preferencesAppDir$ = preferencesDirectory$
61 elsif index_regex(preferencesDirectory$, "[pP]raat(\-dir| Prefs)?$")
62 # If running as a Praat script, create a new preferences directory
64 preferencesAppDir$ = "'preferencesDirectory$'/../.'sgc2.demoAppName$'"
66 preferencesAppDir$ = "'preferencesDirectory$'/../'sgc2.demoAppName$'"
69 # It has to go somewhere. Make a subdirectory in the current preferences directory
70 preferencesAppDir$ = "'preferencesDirectory$'/'sgc2.demoAppName$'"
74 # Parameters for isolating recorded speech from noise
75 # Should be mostly left alone unless you are using ultra clean
76 # or very noisy recordings
82 # Set up button height
88 defaultFont$ = "Helvetica"
94 # Load supporting scripts
95 # Load tables in script format
96 include CreateTables.praat
97 include CreateWordlists.praat
98 # Set up system and load preferences
99 include InitialiseSGC2.praat
100 # Include the main page buttons and procedures
101 include MainPage.praat
102 # Include the configuration page buttons and procedures
106 # replaySGC2LogFunction$ = "replaySGC2LogFunction"
107 # procedure replaySGC2LogFunction
116 # Start instruction loop
117 while demoWaitForInput()
125 call buttonClicked 'buttons$' '.clickX' '.clickY'
126 .label$ = buttonClicked.label$
127 elsif demoKeyPressed()
128 .pressed$ = demoKey$()
129 call keyPressed 'buttons$' '.pressed$'
130 .label$ = keyPressed.label$
133 # You cannot select a text field
134 if startsWith(.label$, "$")
140 te.buttonPressValue = 0
142 call Draw_button 'buttons$' '.label$' 1
143 call process_label '.label$' '.clickX' '.clickY' '.pressed$'
145 call Draw_button 'buttons$' '.label$' 'te.buttonPressValue'
152 ########################################################
154 # Definitions of procedures
156 ########################################################
159 procedure process_label .label$ .clickX .clickY .pressed$
160 # Prcoess the command
161 if .label$ <> "" and not startsWith(.label$,"!")
162 .label$ = replace_regex$(.label$, "^[#]", "", 0)
163 .label$ = replace$(.label$, "_", " ", 0)
166 'sgc2.logging$' call process'buttons$''.label$' '.clickX' '.clickY' '.pressed$'
168 call process'buttons$''.label$' '.clickX' '.clickY' '.pressed$'
173 procedure init_buttons
175 call Draw_all_buttons 'buttons$'
181 procedure Draw_all_buttons .table$
182 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
183 select Table '.table$'
184 .numRows = Get number of rows
187 .label$ = Get value... '.row' Label
188 if not startsWith(.label$, "!")
190 # Determine the "pressed" state of a button
191 # A variable with the same name as the button will act as a
193 .variableName$ = .varPrefix$+"."+(replace_regex$(.label$, "^(.)", "\l\1", 0))
194 # Simple boolean variables
195 if index(.variableName$, "_") <= 0 and variableExists(.variableName$)
197 if '.variableName$' > 0
200 elsif '.variableName$' < 0
203 elsif index(.variableName$, "_") <= 0 and variableExists("'.variableName$'$")
205 if '.variableName$'$ <> "" and '.variableName$'$ <> "0"
208 # Complex buttons with an variableName+'_'+value structure
209 # varableName$ -> name of button, e.g., "language"
210 elsif index(.variableName$, "_")
211 .generalVar$ = left$(.variableName$, rindex(.variableName$, "_") - 1)
212 .currentVariableName$ = .generalVar$
214 if variableExists(.generalVar$+"$")
215 .currentVariableName$ = .generalVar$ + "$"
217 # Remove one level of indirection
218 if variableExists(.currentVariableName$)
219 if index(.currentVariableName$, "$")
220 .currentVariableName$ = '.currentVariableName$'
222 .currentValue = '.currentVariableName$'
223 .currentVariableName$ = "'.currentValue'"
225 # Remove next level of indirection
226 .currentContent$ = "'.currentVariableName$'"
227 if .currentContent$ = "_DISABLED_"
230 # Reconstruct label from current values
231 .currentLabelValue$ = .generalVar$ + "_" + .currentContent$
232 # Set PRESSED from label
233 if .variableName$ = .currentLabelValue$
238 # You did erase everything before you started here? So do not do that again
239 call Draw_button_internal 0 '.table$' '.label$' '.pressed'
244 # Draw a button from a predefined button table
245 # Normally, erase the area around a button
246 procedure Draw_button .table$ .label$ .push
247 call Draw_button_internal 1 '.table$' '.label$' '.push'
250 # Use this function if you want to control erasing
251 procedure Draw_button_internal .erase_button_area .table$ .label$ .push
252 # Do not draw invisible buttons starting with #
253 goto NOBUTTON startsWith(.label$, "#")
255 # Scale rounding of rounded rectangles
257 .mm = demo Horizontal wc to mm... '.wc'
258 # Allow to overide ! skip directive
260 if startsWith(.label$, "+")
261 .label$ = right$(.label$, length(.label$)-1)
265 select Table '.table$'
266 .row = Search column... Label '.label$'
268 call emergency_table_exit Button Table '.table$' does not have a row with label '.label$'
271 # Perspective shift sizes
276 .shiftDown = 0.1*buttonbevel
277 .shiftX = -0.2*buttonbevel
278 .shiftY = 0.40*buttonbevel
281 # Set drawing parameters
282 .topBackGroundColorUp$ = "{0.93,0.93,0.93}"
283 .topLineColorUp$ = "Black"
284 .topLineWidthUp = 1.5
285 .topBackGroundColorDown$ = "{0.89,0.89,0.94}"
286 .topLineColorDown$ = "{0.2,0.2,0.2}"
287 .topLineWidthDown = 2.0
288 .topBackGroundColorDisabled$ = "{0.85,0.85,0.85}"
289 .topLineColorDisabled$ = "{0.70,0.70,0.70}"
290 .topLineWidthDisabled = 1.5
291 .flankBackGroundColorUp$ = "{0.6,0.6,0.6}"
292 .flankLineColorUp$ = "{0.2,0.2,0.2}"
293 .flankLineWidthUp = 1.5
294 .flankBackGroundColorDown$ = "{0.75,0.75,0.75}"
295 .flankLineColorDown$ = .flankLineColorUp$
296 .flankLineWidthDown = 1.5
297 .buttonFontSize = defaultFontSize
300 .leftX = Get value... '.row' LeftX
301 .rightX = Get value... '.row' RightX
302 .lowY = Get value... '.row' LowY
303 .highY = Get value... '.row' HighY
304 .buttonText$ = Get value... '.row' Text
305 .buttonColor$ = Get value... '.row' Color
306 .buttonDraw$ = Get value... '.row' Draw
307 .buttonKey$ = Get value... '.row' Key
309 .noDraw = startsWith(.label$, "!") or (.leftX < 0) or (.rightX < 0) or (.lowY < 0) or (.highY < 0)
312 if index_regex(.buttonText$, "^![0-9\.]+!")
313 .rotation = extractNumber(.buttonText$, "!")
314 .buttonText$ = replace_regex$(.buttonText$, "^![0-9\.]+!", "", 0)
317 goto NOBUTTON .noDraw and not .forceDraw
319 # Replace button text with ALERT
321 .buttonText$ = alertText$
324 # Adapt font size to button size
325 .maxWidth = (.rightX - .leftX) - 2
326 .maxHeight = (.highY - .lowY) - 1
328 # Adapt size of button to length of text if necessary
329 call adjustFontSizeOnWidth 'defaultFont$' '.buttonFontSize' '.maxWidth' '.buttonText$'
330 .buttonFontSize = adjustFontSizeOnWidth.newFontSize
331 if adjustFontSizeOnWidth.diff > 0
332 .rightX += adjustFontSizeOnWidth.diff/2
333 .leftX -= adjustFontSizeOnWidth.diff/2
335 call set_font_size '.buttonFontSize'
337 # Adapt size of button to length of text
338 call adjustFontSizeOnHeight 'defaultFont$' '.buttonFontSize' '.maxHeight'
339 if adjustFontSizeOnHeight.diff > 0
340 .lowY -= adjustFontSizeOnHeight.diff/2
341 .highY += adjustFontSizeOnHeight.diff/2
343 .buttonFontSize = adjustFontSizeOnHeight.newFontSize
345 # With non-horizontal text, only change font size
346 call adjustRotatedFontSizeOnBox 'defaultFont$' '.buttonFontSize' '.maxWidth' '.maxHeight' '.rotation' '.buttonText$'
347 .buttonFontSize = adjustRotatedFontSizeOnBox.newFontSize
350 # Reset and erase button area
352 demo Line width... 'defaultLineWidth'
354 .shiftRightX = .rightX - .shiftX
355 .shiftLowY = .lowY - .shiftY
357 if .erase_button_area
358 # Make erase area minutely larger
359 .eraseLeft = .shiftLeftX - 0.01
360 .eraseRight = .shiftRightX + 0.01
361 .eraseBottom = .shiftLowY - 0.01
362 .eraseTop = .shiftHighY + 0.01
363 demo Paint rectangle... White .eraseLeft .eraseRight .eraseBottom .eraseTop
366 # If label starts with "$", it is a text field. Then do not draw the button
367 if not startsWith(.label$, "$")
368 # Give some depth to button: Draw flank outline
369 if .shiftDown or .shiftX or .shiftY
371 demo Paint rounded rectangle... '.flankBackGroundColorUp$' .shiftLeftX .shiftRightX .shiftLowY .shiftHighY '.mm'
372 demo Colour... '.flankLineColorUp$'
373 demo Line width... '.flankLineWidthUp'
375 demo Paint rounded rectangle... '.flankBackGroundColorDown$' .shiftLeftX .shiftRightX .shiftLowY .shiftHighY '.mm'
376 demo Colour... '.flankLineColorDown$'
377 demo Line width... '.flankLineWidthDown'
379 demo Draw rounded rectangle... .shiftLeftX .shiftRightX .shiftLowY .shiftHighY '.mm'
382 # Button Down will shift the top perspective
384 # Draw the button top
386 demo Paint rounded rectangle... '.topBackGroundColorUp$' '.leftX' '.rightX' '.lowY' '.highY' '.mm'
387 demo Colour... '.topLineColorUp$'
388 demo Line width... '.topLineWidthUp'
390 demo Paint rounded rectangle... '.topBackGroundColorDisabled$' '.leftX' '.rightX' '.lowY' '.highY' '.mm'
391 demo Colour... '.topLineColorDisabled$'
392 demo Line width... '.topLineWidthDisabled'
396 .rightX += .shiftDown
400 demo Paint rounded rectangle... '.topBackGroundColorDown$' .leftX .rightX .lowY .highY '.mm'
401 demo Colour... '.topLineColorDown$'
402 demo Line width... '.topLineWidthDown'
404 demo Draw rounded rectangle... '.leftX' '.rightX' '.lowY' '.highY' '.mm'
407 # The button text and symbol
408 .horWC = demo Horizontal mm to wc... 10.0
409 .verWC = demo Vertical mm to wc... 10.0
411 .verCoeff = .horWC / .verWC
416 .centerX = (.leftX + .rightX)/2
417 .centerY = .lowY + 0.6*(.highY-.lowY)
418 .radius = min(.verCoeff * (.highY - .lowY ), (.rightX - .leftX))/3
419 .buttonKey$ = replace$(.buttonKey$, "\", "\\", 0)
420 .buttonKey$ = replace$(.buttonKey$, """", "\""""", 0)
421 .keyText$ = replace$(.buttonKey$, "\", "", 0)
422 .keyText$ = replace$(.keyText$, "-", "", 0)
423 if .keyText$ <> "" and index_regex(.keyText$, "[\[\]]") <= 0
424 .newText$ = replace_regex$(.buttonText$, "['.keyText$']", "#%&", 1)
427 .newText$ = .buttonText$
429 # Variable text field, read corresponding variable
430 if index(.newText$, "$$$")
431 .fieldName$ = replace_regex$(.label$, "^[!$#]", "", 0)
432 .fieldName$ = replace_regex$(.fieldName$, "^(.)", "\l\1", 0)
433 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
434 .newText$ = replace$(.newText$, "$$$", '.varPrefix$'.'.fieldName$'$, 0)
436 if .push = 1 or .push = -1
438 if .buttonColor$ = "Red"
439 .buttonColor$ = "Pink"
440 elsif .buttonColor$ = "Blue"
441 .buttonColor$ = "{0.5,0.5,1}"
443 .buttonColor$ = "Grey"
446 .buttonColor$ = "Maroon"
451 call '.buttonDraw$' '.buttonColor$' '.centerX' '.centerY' '.radius'
452 call set_font_size '.buttonFontSize'
453 demo Colour... '.buttonColor$'
456 .verticalAlignment$ = "Bottom"
458 .anchorY = .lowY + 0.5*(.highY-.lowY)
459 .verticalAlignment$ = "Half"
461 demo Text special... '.centerX' Centre '.anchorY' '.verticalAlignment$' 'defaultFont$' '.buttonFontSize' '.rotation' '.newText$'
465 call set_font_size 'defaultFontSize'
467 demo Line width... 'defaultLineWidth'
472 procedure set_window_title .table$ .addedText$
473 select Table '.table$'
474 .row = Search column... Label !WindowTitle
476 call emergency_table_exit Button Table '.table$' does not have a row with label !WindowTitle
478 .windowText$ = Get value... '.row' Text
479 call convert_praat_to_latin1 '.windowText$'
480 .windowText$ = convert_praat_to_latin1.text$
482 if index(.windowText$, "$$$")
483 .displayWindowText$ = replace$(.windowText$, "$$$", .addedText$, 0)
485 .displayWindowText$ = .windowText$ + .addedText$
488 demoWindowTitle(.displayWindowText$ )
491 # Handle language setting
492 procedure processLanguageCodes .table$ .label$
494 call Draw_button 'config$' Language_'config.language$' 0
495 call Draw_button 'config$' '.label$' 2
496 # Someone might have to use more than 2 chars for the language code
497 .numChars = length(.label$) - length("Language_")
498 .lang$ = right$(.label$, .numChars)
500 call set_language '.lang$'
504 procedure set_language .lang$
508 select Table 'buttons$'
513 select Table 'config$'
518 # See whether there is a custom language
519 sgc.customLanguage$ = ""
520 .langList = nocheck Create Strings as file list: "CustomLanguages", preferencesTableDir$+"/Config_*.Table"
521 # NOTE: The list might not exist!!!
522 if .langList = undefined
525 .numLanguages = Get number of strings
527 if .numLanguages <= 0
528 if not .langList = undefined
531 .langList = nocheck Create Strings as file list: "CustomLanguages", globaltablelists$+"/Config_*.Table"
532 if .langList = undefined
535 .numLanguages = Get number of strings
539 .configTable$ = Get string: 1
540 .startChar = rindex(.configTable$, "_")
541 sgc.customLanguage$ = right$(.configTable$, length(.configTable$) - .startChar)
542 sgc.customLanguage$ = left$(sgc.customLanguage$, index(sgc.customLanguage$, ".") -1)
544 if not .langList = undefined
550 call checkTable 'configTableName$'_'.lang$'
551 if checkTable.available
552 config.language$ = .lang$
554 config.language$ = "EN"
557 if config.language$ = "JA"
558 CJK font style preferences: "Japanese"
560 CJK font style preferences: "Chinese"
563 # Load buttons tables
564 call loadTable 'buttonsTableName$'
565 buttons$ = selected$("Table")
566 Append column... Text
568 Append column... Helptext
569 .numLabels = Get number of rows
570 call testLoadTable 'buttonsTableName$'_'config.language$'
571 if testLoadTable.table > 0
572 call loadTable 'buttonsTableName$'_'config.language$'
574 call loadTable 'buttonsTableName$'_EN
576 .buttonsLang$ = selected$("Table")
577 for .row to .numLabels
578 select Table 'buttons$'
579 .label$ = Get value... '.row' Label
580 call findLabel '.buttonsLang$' '.label$'
582 select Table '.buttonsLang$'
583 .valueText$ = Get value... 'findLabel.row' Text
584 .valueKey$ = Get value... 'findLabel.row' Key
585 .valueHelp$ = Get value... 'findLabel.row' Helptext
586 select Table 'buttons$'
587 Set string value... '.row' Text '.valueText$'
588 Set string value... '.row' Key '.valueKey$'
589 Set string value... '.row' Helptext '.valueHelp$'
590 elsif index(.label$, "_")
591 # Load alternative language table
592 .startChar = rindex(.label$, "_")
593 .otherLanguage$ = right$(.label$, length(.label$) - .startChar)
594 call loadTable 'buttonsTableName$'_'.otherLanguage$'
595 .otherbuttonsLang$ = selected$("Table")
596 call findLabel '.otherbuttonsLang$' '.label$'
598 select Table '.buttonsLang$'
599 .valueText$ = Get value... 'findLabel.row' Text
600 .valueKey$ = Get value... 'findLabel.row' Key
601 .valueHelp$ = Get value... 'findLabel.row' Helptext
602 select Table 'buttons$'
603 Set string value... '.row' Text '.valueText$'
604 Set string value... '.row' Key '.valueKey$'
605 Set string value... '.row' Helptext '.valueHelp$'
607 call emergency_table_exit Cannot find Label: '.otherbuttonsLang$' '.label$'
609 select Table '.otherbuttonsLang$'
612 call emergency_table_exit Cannot find Label: '.buttonsLang$' '.label$'
615 select Table '.buttonsLang$'
618 # Load configuration table
619 call loadTable 'configTableName$'
620 config$ = selected$("Table")
621 .configTable = selected()
622 # Substitute or remove optional languages
623 .optRow = Search column: "Label", "!Language_???"
626 if sgc.customLanguage$ <> ""
627 .row = Search column: "Label", "Language_"+sgc.customLanguage$
629 if .row <= 0 and sgc.customLanguage$ <> ""
630 Set string value: .optRow, "Label", "Language_"+sgc.customLanguage$
632 .tableLength = Get number of rows
633 # Should never ever happen
637 Set string value: .optRow, "Label", "Language_EN"
643 Append column... Text
645 Append column... Helptext
646 .numLabels = Get number of rows
647 call testLoadTable 'configTableName$'_'config.language$'
648 if testLoadTable.table > 0
649 call loadTable 'configTableName$'_'config.language$'
651 call loadTable 'configTableName$'_EN
653 .configLang$ = selected$("Table")
654 for .row to .numLabels
655 select Table 'config$'
656 .label$ = Get value... '.row' Label
657 call findLabel '.configLang$' '.label$'
659 select Table '.configLang$'
660 .valueText$ = Get value... 'findLabel.row' Text
661 .valueKey$ = Get value... 'findLabel.row' Key
662 .valueHelp$ = Get value... 'findLabel.row' Helptext
663 select Table 'config$'
664 Set string value... '.row' Text '.valueText$'
665 Set string value... '.row' Key '.valueKey$'
666 Set string value... '.row' Helptext '.valueHelp$'
667 elsif index(.label$, "_")
668 .startChar = rindex(.label$, "_")
669 .otherLanguage$ = right$(.label$, length(.label$) - .startChar)
670 call loadTable 'configTableName$'_'.otherLanguage$'
671 .otherconfigLang$ = selected$("Table")
672 call findLabel '.otherconfigLang$' '.label$'
674 select Table '.otherconfigLang$'
675 .valueText$ = Get value... 'findLabel.row' Text
676 .valueKey$ = Get value... 'findLabel.row' Key
677 .valueHelp$ = Get value... 'findLabel.row' Helptext
678 select Table 'config$'
679 Set string value... '.row' Text '.valueText$'
680 Set string value... '.row' Key '.valueKey$'
681 Set string value... '.row' Helptext '.valueHelp$'
683 call emergency_table_exit Cannot find Label: '.otherconfigLang$' '.label$'
685 select Table '.otherconfigLang$'
688 call emergency_table_exit Cannot find Label: '.configLang$' '.label$'
691 select Table '.configLang$'
694 # Make language change visible
696 call Draw_config_page
701 ###############################################################
703 # Button Drawing Routines
705 ###############################################################
707 # A stub for buttons that do not have a drawing routine (yet)
708 procedure DrawNull .color$ .x .y .size
711 procedure DrawHelp .color$ .x .y .size
712 .currentFontSize = 24
715 call adjustFontSizeOnHeight 'defaultFont$' '.currentFontSize' '.maxHeight'
716 .currentFontSize = adjustFontSizeOnHeight.currentFontSize
717 call set_font_size '.currentFontSize'
718 demo Colour... '.color$'
719 demo Text... '.x' Centre '.y' Bottom ?
720 call set_font_size 'defaultFontSize'
723 ###############################################################
725 # Button Processing Routines
727 ###############################################################
729 # Search row in table on label
730 procedure findKey .table$ .label$
732 select Table '.table$'
733 .to$ = selected$("Table")
735 .numRows = Get number of rows
737 .currentKey$ = '.to$'$[.i, "Key"]
738 if .label$ = .currentKey$
744 if .row <= 0 and index(.label$, "_") <= 0
745 printline "'.label$'" is not a key in '.table$'
749 procedure findLabel .table$ .label$
751 select Table '.table$'
752 .to$ = selected$("Table")
754 .numRows = Get number of rows
756 .currentKey$ = '.to$'$[.i, "Label"]
757 if .label$ = .currentKey$
763 if .row <= 0 and index(.label$, "_") <= 0
764 call emergency_table_exit "'.label$'" is not a key in '.table$'
769 procedure buttonClicked table$ .x .y
771 select Table 'table$'
772 .bo$ = selected$("Table")
774 .numRows = Get number of rows
777 .leftX = '.bo$'[.i, "LeftX"]
778 .rightX = '.bo$'[.i, "RightX"]
779 .lowY = '.bo$'[.i, "LowY"]
780 .highY = '.bo$'[.i, "HighY"]
781 if .x > .leftX and .x < .rightX and .y > .lowY and .y < .highY
782 .label$ = '.bo$'$[.i, "Label"]
788 procedure keyPressed table$ .pressed$
791 if .pressed$ = "" and not demoShiftKeyPressed()
794 .lowerPressed$ = replace_regex$(.pressed$, ".", "\L&", 0)
795 .upperPressed$ = replace_regex$(.pressed$, ".", "\U&", 0)
796 select Table 'table$'
797 .bo$ = selected$("Table")
799 .numRows = Get number of rows
802 .key$ = '.bo$'$[.i, "Key"]
803 if index(.key$, .lowerPressed$) or index(.key$, .upperPressed$)
804 .label$ = '.bo$'$[.i, "Label"]
810 procedure count_syllables
813 select sgc.currentWordlist
814 if sgc.currentWord > 0 and sgc.currentWord <= sgc.numberOfWords
815 .sound$ = Get value... 'sgc.currentWord' Sound
816 call readPinyin 'sgc.currentWord'
817 .pinyin$ = readPinyin.pinyin$
819 call add_missing_neutral_tones '.pinyin$'
820 .pinyin$ = add_missing_neutral_tones.pinyin$
821 if index_regex(.pinyin$, "[0-9]") > 0
822 .number = length(replace_regex$(.pinyin$, "[^\d]+([\d]+)", "1", 0))
828 procedure play_sound .sound
830 if sgc.useAlternativePlayer and fileReadable(sgc.playCommandFile$)
831 .scratchFile$ = "'sgc.scratchAudioDir$'SCRATCH.wav"
833 Save as WAV file: .scratchFile$
834 .command$ < 'sgc.playCommandFile$'
835 .command$ = replace$(.command$, "[']", """", 0)
836 .command$ = replace$(.command$, "'newline$'", " ", 0)
838 system_nocheck bash -c -- ''.command$' "'.scratchFile$'"'
840 system_nocheck call '.command$' "'.scratchFile$'"
842 deleteFile(.scratchFile$)
850 procedure record_sound .recordingTime
851 if .recordingTime <= 0
852 .recordingTime = recordingTime
856 # NOTE: Some sound can be playing! This will not be stopped.
858 # There is a very nasty delay before the first recording starts, do a dummy record
859 if not variableExists("recordingInitialized") and not sgc.useAlternativeRecorder
860 call basic_sound_recording 'samplingFrequency' 0.1
862 recordingInitialized = 1
865 demo Paint circle... Red 5 95 2
868 # In Windows XP interaction between demoWaitForInput and Record Sound blocks drawing the feedback
869 # This code might be removed #
870 if windows and endsWith(build_SHA$, " XP")
871 # Display a pause window to flush the graphics buffer
872 beginPause ("DESTROY WINDOW ")
874 endPause ("DESTROY WINDOW ", 1)
876 demo Paint circle... Red 5 95 2
879 ##############################
880 call basic_sound_recording 'samplingFrequency' '.recordingTime'
882 demo Paint circle... White 5 95 2.5
883 call wipeArea 'wipeFeedbackArea$'
885 # Feedback on recording level
886 .extremum = Get absolute extremum... 0 0 None
887 .radius = 2 * .extremum
896 elsif .extremum >= 0.49
899 .green = .extremum / 0.5
901 .color$ = "{'.red','.green','.blue'}"
902 demo Colour... '.color$'
904 demo Draw circle... 5 95 '.radius'
908 demo Line width... 'defaultLineWidth'
912 Rename... Pronunciation
913 recordedSound$ = selected$("Sound")
914 sgc.recordedSound = selected("Sound")
917 select Sound 'recordedSound$'
918 sgc.recordedSound = selected("Sound")
920 # Cut out real sound from silences/noise
921 call sound_detection 'recordedSound$' 'soundMargin'
922 select Sound 'recordedSound$'
923 sgc.recordedSound = selected("Sound")
925 # Store audio if requested
926 if sgc.saveAudioOn and sgc.saveAudio$ <> ""
927 if sgc.savePerf$ <> "" and fileReadable(sgc.savePerf$)
929 select sgc.currentWordlist
930 if sgc.currentWord > 0 and sgc.currentWord <= sgc.numberOfWords
931 call readPinyin 'sgc.currentWord'
932 .pinyin$ = readPinyin.pinyin$
933 .outputName$ = "'sgc.saveAudio$'/'.pinyin$'.wav"
934 select sgc.recordedSound
935 Save as WAV file: .outputName$
938 # The Audio directory disappeared
944 config.clearSummary = 0
945 config.audioName$ = ""
951 # Uses global variables!!!
952 procedure basic_sound_recording .samplingFrequency .recordingTime
953 # Use a different recorder program
954 if sgc.useAlternativeRecorder and fileReadable(sgc.recordCommandFile$)
955 .scratchFile$ = "'sgc.scratchAudioDir$'SCRATCH.wav"
956 .command$ < 'sgc.recordCommandFile$'
957 .command$ = replace$(.command$, "[']", """", 0)
958 .command$ = replace$(.command$, "'newline$'", " ", 0)
960 if unix and .recordingTime < 1
963 system_nocheck bash -c -- ''.command$' '.recordingTime''
965 system_nocheck call '.command$' '.recordingTime'
967 .sound = Read from file: .scratchFile$
968 deleteFile(.scratchFile$)
970 .sound = nocheck noprogress nowarn Record Sound (fixed time)... 'config.input$' 0.99 0.5 '.samplingFrequency' '.recordingTime'
971 if .sound = undefined
972 .sound = Create Sound: "Pronunciation", 0, .recordingTime, .samplingFrequency, "0"
976 # The recorded sound should now be the selected object!!!
980 # Select real sound from recording
981 # Uses some global variable
982 procedure sound_detection .sound$ .margin
983 select Sound '.sound$'
984 .soundlength = Get total duration
985 .internalSilence = 2*.margin
987 # Silence and remove noise, DANGEROUS
988 To TextGrid (silences)... 'minimumPitch' 0 'noiseThresshold' '.internalSilence' 0.1 silent sounding
989 Rename... Input'.sound$'
991 select TextGrid Input'.sound$'
992 .numberofIntervals = Get number of intervals... 1
993 if .numberofIntervals < 2
994 .numberofIntervals = 0
997 # The code below will suppress noise, but also weak third tones
998 # This handles the problem that third tones can be realized with
999 # alternative cues, e.g, non-standard voice and very low levels
1001 # Remove buzzing and other obnoxious sounds (if switched on)
1002 for .i from 1 to .numberofIntervals
1003 select TextGrid Input'.sound$'
1004 .value$ = Get label of interval... 1 '.i'
1005 .begintime = Get starting point... 1 '.i'
1006 .endtime = Get end point... 1 '.i'
1009 if .value$ = "silent"
1010 select Sound '.sound$'
1011 Set part to zero... '.begintime' '.endtime' at nearest zero crossing
1015 # Select target sound
1016 .maximumIntensity = -1
1018 for i from 1 to .numberofIntervals
1019 select TextGrid Input'.sound$'
1021 .value$ = Get label of interval... 1 'i'
1022 .begintime = Get starting point... 1 'i'
1023 .endtime = Get end point... 1 'i'
1025 if .value$ != "silent"
1026 if .begintime > .margin
1027 .begintime -= .margin
1031 if .endtime + .margin < .soundlength
1034 .endtime = .soundlength
1037 select Sound '.sound$'
1038 Extract part... '.begintime' '.endtime' Rectangular 1.0 no
1039 Rename... Tmp'.sound$'
1041 .newIntensity = Get intensity (dB)
1042 if .newIntensity > .maximumIntensity
1043 if .maximumIntensity > 0
1044 select Sound New'.sound$'
1047 select Sound Tmp'.sound$'
1048 Rename... New'.sound$'
1049 .maximumIntensity = .newIntensity
1051 select Sound Tmp'.sound$'
1057 if .maximumIntensity > minimumIntensity
1058 select Sound '.sound$'
1060 select Sound New'.sound$'
1062 elsif .maximumIntensity > -1
1063 select Sound New'.sound$'
1066 select TextGrid Input'.sound$'
1069 select Sound '.sound$'
1072 procedure end_program
1073 call write_preferences ""
1080 ######################################################
1082 # Configuration Page
1084 ######################################################
1085 procedure config_page
1087 demoWindowTitle("Speak Good Chinese: Change settings")
1089 call Draw_config_page
1091 goto GOBACK index_regex(replaySGC2Log$, "^\s*#") <= 0
1093 while (.label$ <> "Return") and demoWaitForInput()
1101 call buttonClicked 'config$' '.clickX' '.clickY'
1102 .label$ = buttonClicked.label$
1103 elsif demoKeyPressed()
1104 .pressed$ = demoKey$()
1105 call keyPressed 'config$' '.pressed$'
1106 .label$ = keyPressed.label$
1109 # You cannot select a text field
1110 if startsWith(.label$, "$")
1116 # Handle push button in process_config
1117 call process_config '.label$' '.clickX' '.clickY' '.pressed$'
1120 if .label$ = "Return"
1130 procedure Draw_config_page
1133 if config.showBackground
1134 call draw_background Background
1137 call Draw_all_buttons 'config$'
1138 call set_window_title 'config$'
1139 # Set correct buttons (alert)
1140 call setConfigMainPage
1144 procedure process_config .label$ .clickX .clickY .pressed$
1145 if .label$ <> "" and not startsWith(.label$,"!")
1146 .label$ = replace_regex$(.label$, "^[#]", "", 0)
1147 .label$ = replace$(.label$, "_", " ", 0)
1150 'sgc2.logging$' call process'config$''.label$' '.clickX' '.clickY' '.pressed$'
1152 call process'config$''.label$' '.clickX' '.clickY' '.pressed$'
1156 ###############################################################
1158 # Presenting help texts
1160 ###############################################################
1163 procedure help_loop .table$ .redrawProc$
1165 call write_help_title '.table$'
1169 call Draw_button '.table$' Help 2
1170 goto HELPGOBACK index_regex(replaySGC2Log$, "^\s*#") <= 0
1173 while (.label$ <> "Help") and demoWaitForInput()
1178 call buttonClicked '.table$' '.clickX' '.clickY'
1179 .label$ = buttonClicked.label$
1180 elsif demoKeyPressed()
1181 .pressed$ = demoKey$()
1182 call keyPressed '.table$' '.pressed$'
1183 .label$ = keyPressed.label$
1186 if .label$ != "" and .label$ <> "Help"
1194 call Draw_button '.table$' Help 2
1195 call write_help_title '.table$'
1197 # Handle push button in process_config
1198 call write_help_text '.table$' '.label$'
1201 'sgc2.logging$' demo Erase all
1202 'sgc2.logging$' call '.redrawProc$'
1203 'sgc2.logging$' call write_help_title '.table$'
1204 'sgc2.logging$' call write_help_text '.table$' '.label$'
1211 call Draw_button '.table$' Help 0
1217 procedure write_help_text .table$ .label$
1218 call findLabel '.table$' '.label$'
1219 .row = findLabel.row
1220 select Table '.table$'
1223 call findLabel '.table$' Help
1224 .row = findLabel.row
1225 select Table '.table$'
1227 .helpText$ = Get value... '.row' Helptext
1228 .helpKey$ = Get value... '.row' Key
1229 .helpKey$ = replace$(.helpKey$, "\", "", 0)
1230 .helpKey$ = replace$(.helpKey$, "_", "\_ ", 0)
1231 if index_regex(.helpKey$, "\S")
1232 .helpText$ = .helpText$+" ("+.helpKey$+")"
1235 .leftX = Get value... '.row' LeftX
1236 .rightX = Get value... '.row' RightX
1237 .lowY = Get value... '.row' LowY
1238 .highY = Get value... '.row' HighY
1241 .currentHelpFontSize = defaultFontSize
1242 call set_font_size '.currentHelpFontSize'
1243 .helpTextSize = demo Text width (wc)... '.helpText$'
1247 .htXright = .htXleft + .helpTextSize + 5
1251 .htXleft = .htXright - .helpTextSize - 5
1256 .htYhigh = .htYlow + 7
1261 .htYlow = .htYhigh - 7
1266 # Adapt font size to horizontal dimensions
1268 call adjustFontSizeOnWidth 'defaultFont$' '.currentHelpFontSize' '.maxWidth' '.helpText$'
1269 .currentHelpFontSize = adjustFontSizeOnWidth.newFontSize
1270 if .htXleft < 0 or .htXright > 100
1272 .htXright = .htXleft + adjustFontSizeOnWidth.textWidth + 5
1274 call set_font_size '.currentHelpFontSize'
1276 # Adapt vertical dimensions to font height
1277 call points_to_wc '.currentHelpFontSize'
1278 .lineHeight = points_to_wc.wc
1279 if .lineHeight > .htYhigh - .htYlow - 4
1280 .htYhigh = .htYlow + .lineHeight + 4
1283 # Determine arrow endpoints
1285 if abs(.htXleft - .xstart) > abs(.htXright - .xstart)
1288 if abs((.htXleft+.htXright)/2 - .xstart) < min(abs(.htXright - .xstart),abs(.htXleft - .xstart))
1289 .xend = (.htXleft+.htXright)/2
1292 .xtext = .htXleft + 2
1293 .ytext = .htYlow + 1
1296 .mm2wc = demo Horizontal mm to wc... 1
1297 .lineWidth = 2/.mm2wc
1298 demo Line width... '.lineWidth'
1299 demo Arrow size... '.lineWidth'
1300 demo Colour... 'sgc2.popUp_bordercolor$'
1301 demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.htXleft' '.htXright' '.htYlow' '.htYhigh'
1302 demo Draw rectangle... '.htXleft' '.htXright' '.htYlow' '.htYhigh'
1303 demo Draw arrow... '.xstart' '.ystart' '.xend' '.yend'
1304 demo Line width... 'defaultLineWidth'
1305 demo Arrow size... 1
1307 demo Text... '.xtext' Left '.ytext' Bottom '.helpText$'
1309 call set_font_size 'defaultFontSize'
1313 procedure write_help_title .table$
1314 # Set help text title
1316 call findLabel '.table$' Help
1317 .row = findLabel.row
1318 select Table '.table$'
1319 .helpTitle$ = Get value... '.row' Helptext
1320 .helpKey$ = Get value... '.row' Key
1321 .helpKey$ = replace$(.helpKey$, "\", "", 0)
1322 .helpKey$ = replace$(.helpKey$, "_", "\_ ", 0)
1323 .helpTitle$ = .helpTitle$+" ("+.helpKey$+")"
1326 .helpTitleFontSize = 14
1327 # Adapt size of button to length of text
1329 call adjustFontSizeOnWidth 'defaultFont$' '.helpTitleFontSize' '.maxWidth' '.helpTitle$'
1330 .helpTitleFontSize = adjustFontSizeOnWidth.newFontSize
1331 call set_font_size '.helpTitleFontSize'
1334 demo Select inner viewport... 0 100 0 100
1335 demo Axes... 0 100 0 100
1336 demo Text... 50 Centre '.helpTop' Top '.helpTitle$'
1337 call set_font_size 'defaultFontSize'
1341 ###############################################################
1343 # Miscelaneous procedures
1345 ###############################################################
1346 procedure printPageToPrinter
1348 demo Print... 'printerName$' 'printerPresets$'
1352 procedure points_to_wc .points
1353 .mm = .points * 0.3527777778
1354 .wc = demo Vertical mm to wc... '.mm'
1357 procedure reset_viewport
1358 .low = viewportMargin
1359 .high = 100 - viewportMargin
1360 demo Select inner viewport... '.low' '.high' '.low' '.high'
1361 demo Axes... 0 100 0 100
1364 procedure set_font_size .fontSize
1366 demo Font size... '.fontSize'
1370 procedure wipeArea .areaCommand$
1375 procedure adjustFontSizeOnWidth .font$ .currentFontSize .maxWidth .text$
1377 call set_font_size '.currentFontSize'
1378 .textWidth = demo Text width (wc)... '.text$'
1379 while .textWidth > .maxWidth and .currentFontSize > 2
1380 .currentFontSize -= 0.5
1381 call set_font_size '.currentFontSize'
1382 .textWidth = demo Text width (wc)... '.text$'
1384 .diff = .textWidth - .maxWidth
1385 .newFontSize = .currentFontSize
1389 procedure adjustRotatedFontSizeOnBox .font$ .currentFontSize .maxWidth .maxHeight .rotation .text$
1391 .radians = .rotation/360 * 2 * pi
1392 .horWC = demo Horizontal mm to wc... 10.0
1393 .verWC = demo Vertical mm to wc... 10.0
1395 .verCoeff = .verWC / .horWC
1399 call set_font_size '.currentFontSize'
1400 .textLength = demo Text width (wc)... '.text$'
1401 while (.textLength * .verCoeff * sin(.radians) > .maxHeight or .textLength * cos(.radians) > .maxWidth) and .currentFontSize > 2
1402 .currentFontSize -= 0.5
1403 call set_font_size '.currentFontSize'
1404 .textLength = demo Text width (wc)... '.text$'
1406 .diff = .textLength - .maxHeight
1407 .newFontSize = .currentFontSize
1411 procedure adjustFontSizeOnHeight .font$ .currentFontSize .maxHeight
1413 call points_to_wc '.currentFontSize'
1414 .lineHeight = points_to_wc.wc
1415 while .lineHeight > .maxHeight and .currentFontSize > 2
1416 .currentFontSize -= 0.5
1417 call points_to_wc '.currentFontSize'
1418 .lineHeight = points_to_wc.wc
1420 .diff = .lineHeight - .maxHeight
1421 .newFontSize = .currentFontSize
1425 # Load a table with button info etc.
1426 # Load local tables if present. Else load
1427 # build-in scripted tables
1428 procedure loadTable .tableName$
1429 .tableVariableName$ = replace_regex$(.tableName$, "[^\w]", "_", 0);
1430 # Search for the table in local, preference, and global directories
1431 if localTableDir$ <> "" and fileReadable("'localTableDir$'/'.tableName$'.Table")
1432 .table = Read from file... 'localTableDir$'/'.tableName$'.Table
1433 elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1434 .table = Read from file... 'preferencesTableDir$'/'.tableName$'.Table
1435 elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1436 .table = Read from file... 'globaltablelists$'/'.tableName$'.Table
1437 # Load them from script
1438 elsif variableExists("procCreate'.tableVariableName$'$")
1439 call Create'.tableVariableName$'
1441 .table = selected("Table")
1443 call emergency_table_exit '.tableName$' cannot be found
1446 # Check whether this is a real table
1447 selectObject: .table
1448 .fullName$ = selected$ ()
1449 .type$ = extractWord$(.fullName$, "")
1450 if .type$ <> "Table"
1456 call emergency_table_exit '.tableFileName$' corrupted or cannot be found
1460 procedure testLoadTable .tableName$
1462 .tableVariableName$ = replace_regex$(.tableName$, "[^\w]", "_", 0);
1463 # Search for the table in local, preference, and global directories
1464 if localTableDir$ <> "" and fileReadable("'localTableDir$'/'.tableName$'.Table")
1466 elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1468 elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1470 # Load them from script
1471 elsif variableExists("procCreate'.tableVariableName$'$")
1478 procedure checkTable .tableName$
1480 if localTableDir$ <> "" and fileReadable("'localTableDir$'/'.tableName$'.Table")
1482 elsif fileReadable("'preferencesTableDir$'/'.tableName$'.Table")
1484 elsif fileReadable("'globaltablelists$'/'.tableName$'.Table")
1486 # Load them from script
1487 elsif variableExists("procCreate'.tableName$'$")
1494 # Create a pop-up window with text from a Text Table
1495 procedure write_text_table .table$
1502 # Get table with text and longest line
1504 call testLoadTable '.table$'
1505 if testLoadTable.table > 0
1506 call loadTable '.table$'
1507 .instructionText = selected()
1508 .numLines = Get number of rows
1510 goto ESCAPEwrite_text_table
1512 .instructionFontSize = 14
1513 .referenceText$ = ""
1519 select '.instructionText'
1520 .currentText$ = Get value... '.l' text
1521 # Expand variables, eg, 'praatVersion$'
1522 call expand_praat_variables '.currentText$'
1523 .currentText$ = expand_praat_variables.text$
1525 .font$ = Get value... '.l' font
1526 .fontSize = Get value... '.l' size
1527 call set_font_size '.fontSize'
1528 .textWidth = demo Text width (wc)... '.currentText$'
1529 if .fontSize > .maxFontSize
1530 .maxFontSize = .fontSize
1532 if .textWidth > .maxWidth
1533 .maxWidth = .textWidth
1534 .instructionFontSize = .fontSize
1538 select '.instructionText'
1539 .referenceText$ = Get value... '.maxLine' text
1540 .maxLineFont$ = Get value... '.maxLine' font
1541 .instructionFontSize = Get value... '.maxLine' size
1542 call set_font_size '.maxFontSize'
1544 # Adapt size of button to length of text
1545 .maxWidth = (.xright - .xleft) - 4
1546 .origFontSize = .instructionFontSize
1547 call adjustFontSizeOnWidth 'defaultFont$' '.instructionFontSize' '.maxWidth' '.referenceText$'
1548 call adjustFontSizeOnHeight 'defaultFont$' '.maxFontSize' '.lineHeight'
1549 .instructionFontSize = min(adjustFontSizeOnWidth.newFontSize, adjustFontSizeOnHeight.newFontSize)
1550 if adjustFontSizeOnWidth.diff > 0
1551 .xright += adjustFontSizeOnWidth.diff/4
1552 .xleft -= 3*adjustFontSizeOnWidth.diff/4
1554 call set_font_size '.instructionFontSize'
1555 .fontSizeFactor = .instructionFontSize / .origFontSize
1557 .numRows = Get number of rows
1558 # Calculate length from number of lines.
1560 .midY = .yhigh - (.yhigh - .ylow)/2
1561 .yhigh = .midY + (.numRows+1) * .dy / 2
1562 .ylow = .yhigh - (.numRows+1) * .dy
1563 .textleft = .xleft + 2
1565 demo Line width... 8
1566 demo Colour... 'sgc2.popUp_bordercolor$'
1567 demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1568 demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1569 demo Line width... 'defaultLineWidth'
1571 .ytext = .yhigh - 2 - .dy
1573 select '.instructionText'
1574 .font$ = Get value... '.i' font
1575 .fontSize = Get value... '.i' size
1576 .font$ = extractWord$(.font$, "")
1578 .fontSize = floor(.fontSize*.fontSizeFactor)
1582 .line$ = Get value... '.i' text
1583 # Expand variables, eg, 'praatVersion$'
1584 call expand_praat_variables '.line$'
1585 .line$ = expand_praat_variables.text$
1588 demo Text special... '.textleft' Left '.ytext' Bottom '.font$' '.fontSize' 0 '.line$'
1592 call set_font_size 'defaultFontSize'
1594 select '.instructionText'
1597 label ESCAPEwrite_text_table
1601 # Create a pop-up window with text from an existing Table object
1602 procedure write_tabbed_table .table$ .labelTextTable$
1609 # Get table with text and longest line
1610 call testLoadTable '.table$'
1611 if testLoadTable.table <= 0
1612 call loadTable '.labelTextTable$'
1613 .labelText$ = selected$("Table")
1616 select Table '.table$'
1617 .tabbedText = selected()
1618 .numLines = Get number of rows
1619 .numCols = Get number of columns
1620 .font$ = defaultFont$
1621 .fontSize = defaultFontSize
1623 .widthCanvas = .xright - .xleft
1624 .dx = (.widthCanvas - 4) / (.numCols)
1628 call set_font_size '.fontSize'
1630 for .i from 0 to .numLines
1631 .xtext = .xleft + .dx / 2
1633 select '.tabbedText'
1634 .currentLabel$ = Get column label... '.j'
1636 .line$ = Get value... '.i' '.currentLabel$'
1638 .line$ = .currentLabel$
1639 select Table '.labelText$'
1640 call findLabel '.labelText$' '.line$'
1641 select Table '.labelText$'
1642 .line$ = Get value... 'findLabel.row' Text
1644 # Expand variables, eg, 'praatVersion$'
1645 call expand_praat_variables '.line$'
1646 .line$ = expand_praat_variables.text$
1647 .textWidth = demo Text width (wc)... '.line$'
1648 if .textWidth > .maxWidth
1649 .maxWidth = .textWidth
1653 if .dx > 1.2 * .maxWidth
1654 .widthCanvas = 1.2 * .maxWidth * .numCols + 4
1655 .xleft = 50 - .widthCanvas / 2
1656 .xright = 50 + .widthCanvas / 2
1657 .dx = (.widthCanvas - 4) / (.numCols)
1662 # Calculate length from number of lines.
1663 .dy = .lineHeight + 0.5
1664 .midY = .yhigh - (.yhigh - .ylow)/2
1665 .yhigh = .midY + (.numLines+2) * .dy / 2
1666 .ylow = .yhigh - (.numLines+2) * .dy
1667 .textleft = .xleft + 2
1669 demo Line width... 8
1670 demo Colour... 'sgc2.popUp_bordercolor$'
1671 demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1672 demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1673 demo Line width... 'defaultLineWidth'
1675 .ytext = .yhigh - 2 - .dy
1676 # First the column names, then the items
1677 for .i from 0 to .numLines
1678 .xtext = .textleft + .dx / 2
1680 select '.tabbedText'
1681 .currentLabel$ = Get column label... '.j'
1683 .line$ = Get value... '.i' '.currentLabel$'
1685 .line$ = .currentLabel$
1686 select Table '.labelText$'
1687 call findLabel '.labelText$' '.line$'
1688 select Table '.labelText$'
1689 .line$ = Get value... 'findLabel.row' Text
1691 # Expand variables, eg, 'praatVersion$'
1692 call expand_praat_variables '.line$'
1693 .line$ = expand_praat_variables.text$
1694 call adjustFontSizeOnWidth '.font$' '.fontSize' '.maxWidth' '.line$'
1695 .currentFontSize = adjustFontSizeOnWidth.newFontSize
1698 demo Text special... '.xtext' Centre '.ytext' Bottom '.font$' '.currentFontSize' 0 '.line$'
1704 call set_font_size 'defaultFontSize'
1705 select Table '.labelText$'
1708 label ESCAPEwrite_tabbed_table
1711 # Create a pop-up window with a given text
1712 procedure write_text_popup .font$ .size .text$
1719 # Adapt size of button to length of text
1720 .maxWidth = (.xright - .xleft) - 4
1721 call adjustFontSizeOnWidth 'defaultFont$' '.size' '.maxWidth' '.text$'
1722 call adjustFontSizeOnHeight 'defaultFont$' '.size' '.lineHeight'
1723 .popupFontSize = min(adjustFontSizeOnWidth.newFontSize, adjustFontSizeOnHeight.newFontSize)
1724 if adjustFontSizeOnWidth.diff > 0
1725 .xright += adjustFontSizeOnWidth.diff/4
1726 .xleft -= 3*adjustFontSizeOnWidth.diff/4
1728 .xleft = ((.xright + .xleft) - adjustFontSizeOnWidth.textWidth)/2 - 2
1729 .xright = ((.xright + .xleft) + adjustFontSizeOnWidth.textWidth)/2 + 2
1733 # Calculate length from number of lines.
1735 .midY = .yhigh - (.yhigh - .ylow)/2
1736 .yhigh = .midY + (.numRows+1) * .dy / 2
1737 .ylow = .yhigh - (.numRows+1) * .dy
1738 .textleft = .xleft + 2
1739 .xmid = (.textleft + .xright - 2)/2
1741 demo Line width... 8
1742 demo Colour... 'sgc2.popUp_bordercolor$'
1743 demo Paint rectangle... 'sgc2.popUp_backgroundcolor$' '.xleft' '.xright' '.ylow' '.yhigh'
1744 demo Draw rectangle... '.xleft' '.xright' '.ylow' '.yhigh'
1745 demo Line width... 'defaultLineWidth'
1747 .ytext = .yhigh - 2 - .dy
1749 demo Text special... '.xmid' Centre '.ytext' Bottom '.font$' '.popupFontSize' 0 '.text$'
1753 call set_font_size 'defaultFontSize'
1756 # Write the background from a Text Table
1757 procedure draw_background .table$
1763 .defaultColour$ = "{0.9,0.9,0.9}"
1764 .defaultAlign$ = "centre"
1766 # Get table with text and longest line
1767 call loadTable '.table$'
1768 .backgroundText = selected()
1769 .numLines = Get number of rows
1770 .backgroundFontSize = 28
1771 .referenceText$ = ""
1778 select '.backgroundText'
1779 .currentText$ = Get value... '.l' text
1780 # Expand variables, eg, 'praatVersion$'
1781 call expand_praat_variables '.currentText$'
1782 .currentText$ = expand_praat_variables.text$
1784 .font$ = Get value... '.l' font
1785 .fontSize = Get value... '.l' size
1786 if .fontSize > .maxFontSize
1787 .maxFontSize = .fontSize
1789 if not startsWith(.font$, "!")
1790 call set_font_size '.fontSize'
1791 .textWidth = demo Text width (wc)... '.currentText$'
1792 if .textWidth > .maxWidth
1793 .maxWidth = .textWidth
1794 .backgroundFontSize = .fontSize
1802 select '.backgroundText'
1803 .referenceText$ = Get value... '.maxLine' text
1804 .maxLineFont$ = Get value... '.maxLine' font
1805 .backgroundFontSize = Get value... '.maxLine' size
1806 .backgroundFontColour$ = Get value... '.maxLine' colour
1807 call set_font_size '.maxFontSize'
1809 .maxFontSize = .backgroundFontSize
1812 # Adapt size of button to length of text
1813 .maxWidth = (.xright - .xleft) - 4
1814 .origFontSize = .backgroundFontSize
1815 call adjustFontSizeOnWidth 'defaultFont$' '.backgroundFontSize' '.maxWidth' '.referenceText$'
1816 .fontSizeFactor = adjustFontSizeOnWidth.newFontSize / .backgroundFontSize
1817 .backgroundFontSize = adjustFontSizeOnWidth.newFontSize
1818 call set_font_size '.backgroundFontSize'
1820 call adjustFontSizeOnHeight 'defaultFont$' '.backgroundFontSize' '.lineHeight'
1821 .lineHeight /= adjustFontSizeOnHeight.newFontSize / .backgroundFontSize
1822 if adjustFontSizeOnHeight.newFontSize >= .origFontSize and (.textLines+1) * .lineHeight > (.yhigh - .ylow - 4)
1823 .lineHeight = (.yhigh - .ylow - 4)/(.textLines + 1)
1824 call adjustFontSizeOnHeight 'defaultFont$' '.maxFontSize' '.lineHeight'
1825 .fontSizeFactor = adjustFontSizeOnHeight.newFontSize / .backgroundFontSize
1828 .numRows = Get number of rows
1829 # Calculate length from number of lines.
1831 .midY = .yhigh - (.yhigh - .ylow)/2
1832 .yhigh = .midY + (.textLines+1) * .dy / 2
1833 .ylow = .yhigh - (.textLines+1) * .dy
1834 .textleft = .xleft + 2
1835 .textright = .xright - 2
1836 .textmid = (.xright - .xleft)/2
1839 .ytext = .yhigh - 2 - .dy
1841 select '.backgroundText'
1842 .font$ = Get value... '.i' font
1843 .fontSize = Get value... '.i' size
1844 .fontColour$ = Get value... '.i' colour
1845 .fontColour$ = replace_regex$(.fontColour$, "^[\- ]$", ".defaultColour$", 1)
1846 .fontAlign$ = Get value... '.i' align
1847 .fontAlign$ = replace_regex$(.fontAlign$, "^[\- ]$", ".defaultAlign$", 1)
1848 .line$ = Get value... '.i' text
1849 # Expand variables, eg, 'praatVersion$'
1850 call expand_praat_variables '.line$'
1851 .line$ = expand_praat_variables.text$
1854 .fontSize = floor(.fontSize*.fontSizeFactor)
1855 if not startsWith(.font$, "!")
1856 .font$ = extractWord$(.font$, "")
1858 if .fontAlign$ = "centre"
1860 elsif .fontAlign$ = "right"
1869 demo Colour... '.fontColour$'
1870 demo Text special... '.xtext' '.fontAlign$' '.ytext' Bottom '.font$' '.fontSize' 0 '.line$'
1872 elsif .font$ = "!demo command"
1873 demo Colour... '.fontColour$'
1874 .line$ = replace_regex$(.line$, "\{FONTSIZE\$\}", "'.fontSize'", 0)
1875 .line$ = replace_regex$(.line$, "\{XTEXT\$\}", "'.xtext'", 0)
1876 .line$ = replace_regex$(.line$, "\{YTEXT\$\}", "'.ytext'", 0)
1877 .line$ = replace_regex$(.line$, "\{DY\$\}", "'.dy'", 0)
1878 .line$ = replace_regex$(.line$, "\{[^\}]*\}", "", 0)
1879 while index(.line$, "[[")
1880 .nextBracketOpen = index(.line$, "[[")
1881 .nextBracketOpen += 2
1882 .nextBracketClose = index(.line$, "]]")
1883 .bracketLength = .nextBracketClose - .nextBracketOpen
1885 if .bracketLength > 0
1886 .expression$ = mid$(.line$, .nextBracketOpen, .bracketLength)
1887 .expression$ = replace_regex$(.expression$, "\s", "", 0)
1888 if length(.expression$) > 0
1889 # Test expression for security, only allow explicitely defined functions
1890 .allowedStrings$ = "e|pi|not|and|or|div|mod|abs|round|floor|ceiling"
1891 .allowedStrings$ = .allowedStrings$ + "|sqrt|min|max|imin|imax|sin|cos|tan|arcsin|arccos|arctan|arctan2|sinc|sincpi"
1892 .allowedStrings$ = .allowedStrings$ + "|exp|ln|log10|log2|sinh|cosh|tanh|arcsinh|arccosh|arctanh"
1893 .allowedStrings$ = .allowedStrings$ + "|sigmoid|invSigmoid|erf|erfc|randomUniform|randomInteger|randomGauss|randomPoisson"
1894 .allowedStrings$ = .allowedStrings$ + "|lnGamma|gaussP|gaussQ|invGaussQ|chiSquareP|chiSquareQ"
1895 .allowedStrings$ = .allowedStrings$ + "|invChiSquareP|invChiSquareQ|studentP|studentQ|invStudentP|invStudentQ"
1896 .allowedStrings$ = .allowedStrings$ + "|beta|besselI|besselK"
1897 .testExpression$ = replace_regex$(.expression$, "(^|\W)('.allowedStrings$')(?=$|\W)", "\1\3", 0)
1898 .testExpression$ = replace_regex$(.testExpression$, "[0-9\.,\-+/*^()<>= ]", "", 0)
1899 if .testExpression$ = ""
1900 .calc = '.expression$'
1901 .result$ = "'.calc'"
1906 # Replace expression by result
1907 .lastLeft = .nextBracketOpen - 3
1908 .newLine$ = left$(.line$, .lastLeft)
1909 .newLine$ = .newLine$ + .result$
1910 .numCopy = length(.line$) - .nextBracketClose - 1
1911 .newLine$ = .newLine$ + right$(.line$, .numCopy)
1919 call set_font_size 'defaultFontSize'
1921 select '.backgroundText'
1925 procedure convert_praat_to_utf8 .text$
1926 .text$ = replace_regex$(.text$, "\\a""", "\xc3\xa4", 0)
1927 .text$ = replace_regex$(.text$, "\\A""", "\xc3\x84", 0)
1928 .text$ = replace_regex$(.text$, "\\o""", "\xc3\xb6", 0)
1929 .text$ = replace_regex$(.text$, "\\O""", "\xc3\x96", 0)
1930 .text$ = replace_regex$(.text$, "\\u""", "\xc3\xbc", 0)
1931 .text$ = replace_regex$(.text$, "\\U""", "\xc3\x9c", 0)
1932 .text$ = replace_regex$(.text$, "\\i""", "\xc3\xaf", 0)
1933 .text$ = replace_regex$(.text$, "\\I""", "\xc3\x8f", 0)
1934 .text$ = replace_regex$(.text$, "\\e""", "\xc3\xab", 0)
1935 .text$ = replace_regex$(.text$, "\\E""", "\xc3\x8b", 0)
1936 .text$ = replace_regex$(.text$, "\\y""", "\xc3\xbf", 0)
1937 .text$ = replace_regex$(.text$, "\\e'", "\xc3\xa9", 0)
1938 .text$ = replace_regex$(.text$, "\\E'", "\xc3\x89", 0)
1939 .text$ = replace_regex$(.text$, "\\ss", "\xc3\x9f", 0)
1942 procedure convert_praat_to_latin1 .text$
1943 .text$ = replace_regex$(.text$, "\\a""", "\xe4", 0)
1944 .text$ = replace_regex$(.text$, "\\A""", "\xc4", 0)
1945 .text$ = replace_regex$(.text$, "\\o""", "\xf6", 0)
1946 .text$ = replace_regex$(.text$, "\\O""", "\xd6", 0)
1947 .text$ = replace_regex$(.text$, "\\u""", "\xfc", 0)
1948 .text$ = replace_regex$(.text$, "\\U""", "\xdc", 0)
1949 .text$ = replace_regex$(.text$, "\\i""", "\xef", 0)
1950 .text$ = replace_regex$(.text$, "\\I""", "\xcf", 0)
1951 .text$ = replace_regex$(.text$, "\\e""", "\xeb", 0)
1952 .text$ = replace_regex$(.text$, "\\E""", "\xcb", 0)
1953 .text$ = replace_regex$(.text$, "\\y""", "\xff", 0)
1954 .text$ = replace_regex$(.text$, "\\Y""", "Y", 0)
1955 .text$ = replace_regex$(.text$, "\\e'", "\xe9", 0)
1956 .text$ = replace_regex$(.text$, "\\E'", "\xc9", 0)
1957 .text$ = replace_regex$(.text$, "\\ss", "\xdf", 0)
1960 # Expand 'variable$' into the value of variable$.
1961 # Eg, 'praatVersion$' becomes 5.1.45 or whatever is the current version
1962 # Single quotes can be protected by \'
1963 procedure expand_praat_variables .text$
1964 if index(.text$, "'")
1965 .tempText$ = replace_regex$(.text$, "(^|[^\\])'([\w\$\.]+)'", "\1""+\2+""", 0)
1966 .tempText$ = replace_regex$(.tempText$, "[\\]'", "'", 0)
1967 .tempText$ = """"+.tempText$+""""
1968 # Check whether all the variables actually exist. Ignore any variable that does not exist
1969 .checkVars$ = .tempText$
1970 while length(.checkVars$) > 0 and index(.checkVars$, "+")
1971 .start = index(.checkVars$, "+")
1972 .checkVars$ = right$(.checkVars$, length(.checkVars$) - .start)
1973 .end = index(.checkVars$, "+")
1975 .variable$ = left$(.checkVars$, .end - 1)
1976 if not variableExists(.variable$)
1977 .tempText$ = replace$(.tempText$, """+'.variable$'+""", "'"+.variable$+"'", 0)
1979 .checkVars$ = right$(.checkVars$, length(.checkVars$) - .end)
1984 .text$ = '.tempText$'
1988 # Get a time stamp in normalized format
1989 procedure getTimeStamp
1990 .currentDateTime$ = date$()
1991 .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)
1994 # A table error, can be insiduously caused by an outdate preferences file!
1995 procedure emergency_table_exit .message$
1996 # If you come here as a user, your preferences file is borked
1997 if preferencesAppFile$ <> "" and fileReadable(preferencesAppFile$)
1998 deleteFile(preferencesAppFile$)
2001 call get_feedback_text 'config.language$' Cancel
2002 call convert_praat_to_latin1 'get_feedback_text.text$'
2003 .cancelText$ = convert_praat_to_latin1.text$
2004 beginPause: "Fatal Error"
2006 endPause: .cancelText$, 1
2010 # Remove previous files from system
2011 procedure clean_up_sound
2012 if recordedSound$ = ""
2013 sgc.recordedSound = 0
2015 if sgc.recordedSound > 0
2016 select sgc.recordedSound
2019 sgc.recordedSound = 0
2021 if te.recordedPitch > 0
2022 select te.recordedPitch
2024 te.recordedPitch = 0
2026 if sgc.alignedTextGrid > 0
2027 select sgc.alignedTextGrid
2029 sgc.alignedTextGrid = -1
2033 # Safely read a table
2034 procedure readTable .filename$
2036 if .filename$ <> "" and fileReadable(.filename$) and index_regex(.filename$, "(?i\.(tsv|table|csv))$") > 0
2037 if index_regex(.filename$, "(?i\.(csv))$") > 0
2038 .tableID = Read Table from comma-separated file: .filename$
2039 elsif index_regex(.filename$, "(?i\.(tsv))$") > 0
2040 .tableID = nocheck Read Table from tab-separated file: .filename$
2042 .tableID = nocheck Read from file... '.filename$'
2044 if .tableID = undefined or .tableID <= 0
2047 .fullName$ = selected$ ()
2048 .type$ = extractWord$(.fullName$, "")
2049 if .type$ <> "Table"
2057 # Read feedback table and get keyed text
2058 procedure get_feedback_text .language$ .key$
2059 if not endsWith(feedbackTableName$, "_'.language$'")
2060 if feedbackTableName$ <> ""
2061 select Table 'feedbackTableName$'
2064 call testLoadTable 'feedbackTablePrefix$'_'.language$'
2065 if testLoadTable.table > 0
2066 call loadTable 'feedbackTablePrefix$'_'.language$'
2068 call loadTable 'feedbackTablePrefix$'_EN
2070 feedbackTableName$ = selected$("Table")
2072 call findKey 'feedbackTableName$' '.key$'
2074 select Table 'feedbackTableName$'
2075 .text$ = Get value... '.row' Text
2076 # Expand variables, eg, 'praatVersion$'
2077 call expand_praat_variables '.text$'
2078 .text$ = expand_praat_variables.text$
2082 # Read evaluation table and get keyed text. Only praat converted Text
2083 procedure get_evaluation_text .language$ .key$
2084 if not endsWith(evaluationTableName$, "_'.language$'")
2085 if evaluationTableName$ <> ""
2086 select Table 'evaluationTableName$'
2089 call testLoadTable 'evaluationTablePrefix$'_'.language$'
2090 if testLoadTable.table > 0
2091 call loadTable 'evaluationTablePrefix$'_'.language$'
2093 call loadTable 'evaluationTablePrefix$'_EN
2095 evaluationTableName$ = selected$("Table")
2097 call findLabel 'evaluationTableName$' '.key$'
2098 .row = findLabel.row
2099 select Table 'evaluationTableName$'
2100 .text$ = Get value... '.row' Text
2101 # Expand variables, eg, 'praatVersion$'
2102 call expand_praat_variables '.text$'
2103 .rawtext$ = expand_praat_variables.text$
2104 call convert_praat_to_latin1 '.rawtext$'
2105 .text$ = convert_praat_to_latin1.text$
2108 # Read all the relevant evaluation labels and put them in "eval.<label>$" variables
2109 procedure get_evaluation_table_labels .language$
2110 call get_evaluation_text '.language$' Performance
2111 eval.performance$ = get_evaluation_text.text$
2112 call get_evaluation_text '.language$' Pinyin
2113 eval.pinyin$ = get_evaluation_text.text$
2114 call get_evaluation_text '.language$' Correct
2115 eval.correct$ = get_evaluation_text.text$
2116 call get_evaluation_text '.language$' Wrong
2117 eval.wrong$ = get_evaluation_text.text$
2118 call get_evaluation_text '.language$' Total
2119 eval.total$ = get_evaluation_text.text$
2120 call get_evaluation_text '.language$' High
2121 eval.high$ = get_evaluation_text.text$
2122 call get_evaluation_text '.language$' Low
2123 eval.low$ = get_evaluation_text.text$
2124 call get_evaluation_text '.language$' Wide
2125 eval.wide$ = get_evaluation_text.text$
2126 call get_evaluation_text '.language$' Narrow
2127 eval.narrow$ = get_evaluation_text.text$
2128 call get_evaluation_text '.language$' Unknown
2129 eval.unknown$ = get_evaluation_text.text$
2130 call get_evaluation_text '.language$' Commented
2131 eval.commented$ = get_evaluation_text.text$
2132 call get_evaluation_text '.language$' Level
2133 eval.level$ = get_evaluation_text.text$
2134 call get_evaluation_text '.language$' Time
2135 eval.time$ = get_evaluation_text.text$
2140 procedure saveLogOfActivity .command$
2141 # Do not log in binary!
2143 createDirectory(preferencesLogDir$)
2144 appendFileLine: "'preferencesLogDir$'/'logtimeStamp$'.log", .command$
2148 # Replay a log file with commands sgc.replaySleep inserts a pause
2149 procedure replaySGC2LogFunction
2150 if not variableExists("sgc.replaySleep")
2151 sgc.replaySleep = -1
2153 # Do not replay in binary!
2155 # Ask for the input file
2156 .filename$ = chooseReadFile$ ("Select file to replay")
2157 if .filename$ <> "" and fileReadable(.filename$)
2158 .replayFile = Read Strings from raw text file: .filename$
2159 if .replayFile <> undefined
2161 if sgc.replaySleep > 0
2162 call basic_sound_recording 'samplingFrequency' 'sgc.replaySleep'
2166 .numStrings = Get number of strings
2167 for .l to .numStrings
2169 .line$ = Get string: .l
2170 if index_regex(.line$, "process(MainPage|Config)(Help|Config|Return|Quit)")
2171 if index(.line$, "processMainPageConfig")
2172 .line$ = "call Draw_config_page"
2173 elsif index_regex(.line$, "processConfigReturn")
2174 .line$ = "call init_window"
2175 elsif index_regex(.line$, "processMainPageHelp")
2176 .line$ = "call init_window"
2177 elsif index_regex(.line$, "processConfigHelp")
2178 .line$ = "call Draw_config_page"
2180 .line$ = "# " + .line$
2183 if index_regex(.line$, "[a-zA-Z]") > 0 and index_regex(.line$, "\s*#") <= 0
2188 if sgc.replaySleep > 0
2189 call basic_sound_recording 'samplingFrequency' 'sgc.replaySleep'