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