| 1 | /* praat.cpp |
| 2 | * |
| 3 | * Copyright (C) 1992-2026 Paul Boersma |
| 4 | * |
| 5 | * This code is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation; either version 3 of the License, or (at |
| 8 | * your option) any later version. |
| 9 | * |
| 10 | * This code is distributed in the hope that it will be useful, but |
| 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 | * See the GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | #include "melder.h" |
| 20 | #include <stdarg.h> |
| 21 | #if defined (UNIX) || defined (macintosh) |
| 22 | #include <sys/types.h> |
| 23 | #include <sys/stat.h> |
| 24 | #include <signal.h> |
| 25 | #endif |
| 26 | #include <locale.h> |
| 27 | #if defined (UNIX) |
| 28 | #include <unistd.h> |
| 29 | #endif |
| 30 | #if defined (_WIN32) |
| 31 | #include <windows.h> |
| 32 | #include <fcntl.h> |
| 33 | #include <io.h> |
| 34 | #include <process.h> // getpid |
| 35 | #endif |
| 36 | |
| 37 | #include "praatP.h" |
| 38 | #include "praatM.h" |
| 39 | #include "praat_script.h" |
| 40 | #include "site.h" |
| 41 | #include "machine.h" |
| 42 | #include "Printer.h" |
| 43 | #include "ScriptEditor.h" |
| 44 | #include "NotebookEditor.h" |
| 45 | #include "Strings_.h" |
| 46 | #include "../kar/UnicodeData.h" |
| 47 | #include "InfoEditor.h" |
| 48 | |
| 49 | Thing_implement (Praat_Command, Thing, 0); |
| 50 | |
| 51 | #define EDITOR theCurrentPraatObjects -> list [IOBJECT]. editors |
| 52 | |
| 53 | #define WINDOW_WIDTH 520 |
| 54 | #define WINDOW_HEIGHT 700 |
| 55 | |
| 56 | /* |
| 57 | Six globals, not `inline` (see praat.h 2021-04-15). |
| 58 | */ |
| 59 | structPraatApplication theForegroundPraatApplication; |
| 60 | PraatApplication theCurrentPraatApplication = & theForegroundPraatApplication; |
| 61 | structPraatObjects theForegroundPraatObjects; |
| 62 | PraatObjects theCurrentPraatObjects = & theForegroundPraatObjects; |
| 63 | structPraatPicture theForegroundPraatPicture; |
| 64 | PraatPicture theCurrentPraatPicture = & theForegroundPraatPicture; |
| 65 | |
| 66 | bool praat_commandsWithExternalSideEffectsAreAllowed () { |
| 67 | return |
| 68 | theCurrentPraatObjects == & theForegroundPraatObjects || |
| 69 | ! theCurrentPraatApplication -> manPages || |
| 70 | theCurrentPraatApplication -> manPages -> commandsWithExternalSideEffectsAreAllowed |
| 71 | ; |
| 72 | }; |
| 73 | |
| 74 | static structMelderFolder homeDir { }; |
| 75 | |
| 76 | /* |
| 77 | * Melder_preferencesFolder: a folder containing preferences file, buttons file, message files, tracing file, plugins. |
| 78 | * Unix: /home/miep/.config/praat |
| 79 | * Windows: C:\Users\Miep\Praat |
| 80 | * MacOS: /Users/Miep/Library/Application Support/Praat |
| 81 | */ |
| 82 | // inline structMelderFolder Melder_preferencesFolder { }; // already declared in Melder_files.h (checked 2021-03-07) |
| 83 | |
| 84 | /* |
| 85 | * prefsFile: preferences file. |
| 86 | * Unix: /home/miep/.config/praat/Preferences.txt |
| 87 | * Windows: C:\Users\Miep\AppData\Roaming\Praat\Preferences.txt |
| 88 | * MacOS: /Users/Miep/Library/Application Support/Praat/Preferences.txt |
| 89 | */ |
| 90 | static structMelderFile prefsFile5 { }, prefsFile7 { }; |
| 91 | |
| 92 | /* |
| 93 | * buttonsFile: buttons file. |
| 94 | * Unix: /home/miep/.config/praat/Buttons.txt |
| 95 | * Windows: C:\Users\Miep\AppData\Roaming\Praat\Buttons.txt |
| 96 | * MacOS: /Users/Miep/Library/Application Support/Praat/Buttons.txt |
| 97 | */ |
| 98 | static structMelderFile buttonsFile5 { }, buttonsFile7 { }; |
| 99 | |
| 100 | /* |
| 101 | * tracingFile: tracing file. |
| 102 | * Unix: /home/miep/.config/praat/Tracing.txt |
| 103 | * Windows: C:\Users\Miep\AppData\Roaming\Praat\Tracing.txt |
| 104 | * MacOS: /Users/Miep/Library/Application Support/Praat/Tracing.txt |
| 105 | */ |
| 106 | static structMelderFile tracingFile { }; |
| 107 | |
| 108 | /* |
| 109 | * messageFile: message file: where sendpraat or --send writes its message. |
| 110 | * Unix: /home/miep/.config/praat/Message.txt |
| 111 | * Windows: C:\Users\Miep\AppData\Roaming\Praat\Message.txt |
| 112 | * MacOS: /Users/Miep/Library/Application Support/Praat/Message.txt |
| 113 | */ |
| 114 | static structMelderFile messageFile { }; |
| 115 | #if defined (UNIX) |
| 116 | static structMelderFile pidFile { }; // like /home/miep/.config/praat/pid |
| 117 | #endif |
| 118 | |
| 119 | static GuiList praatList_objects; |
| 120 | |
| 121 | /***** selection *****/ |
| 122 | |
| 123 | integer praat_idOfSelected (ClassInfo klas, integer inplace) { |
| 124 | integer place = inplace, IOBJECT; |
| 125 | if (place == 0) |
| 126 | place = 1; |
| 127 | if (place > 0) { |
| 128 | WHERE (SELECTED && (! klas || CLASS == klas)) { |
| 129 | if (place == 1) |
| 130 | return ID; |
| 131 | place --; |
| 132 | } |
| 133 | } else { |
| 134 | WHERE_DOWN (SELECTED && (! klas || CLASS == klas)) { |
| 135 | if (place == -1) |
| 136 | return ID; |
| 137 | place ++; |
| 138 | } |
| 139 | } |
| 140 | if (inplace) |
| 141 | Melder_throw (U"No ", klas ? klas -> className : U"object", U" #", inplace, U" selected."); |
| 142 | else |
| 143 | Melder_throw (U"No ", klas ? klas -> className : U"object", U" selected."); |
| 144 | return 0; |
| 145 | } |
| 146 | |
| 147 | autoVEC praat_idsOfAllSelected (ClassInfo klas) { |
| 148 | autoVEC result = raw_VEC (praat_numberOfSelected (klas)); |
| 149 | integer selectedObjectNumber = 0, IOBJECT; |
| 150 | WHERE (SELECTED && (! klas || CLASS == klas)) |
| 151 | result [++ selectedObjectNumber] = ID; |
| 152 | return result; |
| 153 | } |
| 154 | |
| 155 | autoSTRVEC praat_namesOfAllSelected (ClassInfo klas) { |
| 156 | autoSTRVEC result (praat_numberOfSelected (klas)); |
| 157 | integer selectedObjectNumber = 0, IOBJECT; |
| 158 | WHERE (SELECTED && (! klas || CLASS == klas)) |
| 159 | result [++ selectedObjectNumber] = Melder_dup (klas ? NAME : FULL_NAME); |
| 160 | return result; |
| 161 | } |
| 162 | |
| 163 | char32 * praat_nameOfSelected (ClassInfo klas, integer inplace) { |
| 164 | integer place = inplace, IOBJECT; |
| 165 | if (place == 0) |
| 166 | place = 1; |
| 167 | if (place > 0) { |
| 168 | WHERE (SELECTED && (! klas || CLASS == klas)) { |
| 169 | if (place == 1) |
| 170 | return klas ? NAME : FULL_NAME; |
| 171 | place --; |
| 172 | } |
| 173 | } else { |
| 174 | WHERE_DOWN (SELECTED && (! klas || CLASS == klas)) { |
| 175 | if (place == -1) |
| 176 | return klas ? NAME : FULL_NAME; |
| 177 | place ++; |
| 178 | } |
| 179 | } |
| 180 | if (inplace) |
| 181 | Melder_throw (U"No ", klas ? klas -> className : U"object", U" #", inplace, U" selected."); |
| 182 | else |
| 183 | Melder_throw (U"No ", klas ? klas -> className : U"object", U" selected."); |
| 184 | return nullptr; // failure, but never reached anyway |
| 185 | } |
| 186 | |
| 187 | integer praat_numberOfSelected (ClassInfo klas) { |
| 188 | if (! klas) |
| 189 | return theCurrentPraatObjects -> totalSelection; |
| 190 | integer readableClassId = klas -> sequentialUniqueIdOfReadableClass; |
| 191 | if (readableClassId == 0) |
| 192 | Melder_crash (U"No sequential unique ID for class ", klas -> className, U" (numberOfSelected)."); |
| 193 | return theCurrentPraatObjects -> numberOfSelected [readableClassId]; |
| 194 | } |
| 195 | |
| 196 | void praat_deselect (integer IOBJECT) { |
| 197 | if (! SELECTED) |
| 198 | return; |
| 199 | SELECTED = false; |
| 200 | theCurrentPraatObjects -> totalSelection -= 1; |
| 201 | integer readableClassId = theCurrentPraatObjects -> list [IOBJECT]. object -> classInfo -> sequentialUniqueIdOfReadableClass; |
| 202 | Melder_assert (readableClassId != 0); |
| 203 | theCurrentPraatObjects -> numberOfSelected [readableClassId] -= 1; |
| 204 | if (! theCurrentPraatApplication -> batch && ! Melder_backgrounding) { |
| 205 | trace (U"deselecting object ", IOBJECT); |
| 206 | GuiList_deselectItem (praatList_objects, IOBJECT); |
| 207 | trace (U"deselected object ", IOBJECT); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | void praat_deselectAll () { |
| 212 | integer IOBJECT; |
| 213 | WHERE (1) |
| 214 | praat_deselect (IOBJECT); |
| 215 | } |
| 216 | |
| 217 | void praat_select (integer IOBJECT) { |
| 218 | if (SELECTED) |
| 219 | return; |
| 220 | SELECTED = true; |
| 221 | theCurrentPraatObjects -> totalSelection += 1; |
| 222 | Thing object = theCurrentPraatObjects -> list [IOBJECT]. object; |
| 223 | Melder_assert (object); |
| 224 | integer readableClassId = object -> classInfo -> sequentialUniqueIdOfReadableClass; |
| 225 | if (readableClassId == 0) |
| 226 | Melder_crash (U"No sequential unique ID for class ", object -> classInfo -> className, U" (selectObject)."); |
| 227 | theCurrentPraatObjects -> numberOfSelected [readableClassId] += 1; |
| 228 | if (! theCurrentPraatApplication -> batch && ! Melder_backgrounding) |
| 229 | GuiList_selectItem (praatList_objects, IOBJECT); |
| 230 | } |
| 231 | |
| 232 | void praat_selectAll () { |
| 233 | integer IOBJECT; |
| 234 | WHERE (true) |
| 235 | praat_select (IOBJECT); |
| 236 | } |
| 237 | |
| 238 | void praat_list_background () { |
| 239 | integer IOBJECT; |
| 240 | WHERE (SELECTED) |
| 241 | GuiList_deselectItem (praatList_objects, IOBJECT); |
| 242 | } |
| 243 | void praat_list_foreground () { |
| 244 | integer IOBJECT; |
| 245 | WHERE (SELECTED) |
| 246 | GuiList_selectItem (praatList_objects, IOBJECT); |
| 247 | } |
| 248 | |
| 249 | autoCollection praat_getSelectedObjects () { |
| 250 | autoCollection thee = Collection_create (); |
| 251 | integer IOBJECT; |
| 252 | LOOP { |
| 253 | iam_LOOP (Daata); |
| 254 | thy addItem_ref (me); |
| 255 | } |
| 256 | return thee; |
| 257 | } |
| 258 | |
| 259 | char32 *praat_name (integer IOBJECT) { return str32chr (FULL_NAME, U' ') + 1; } |
| 260 | |
| 261 | void praat_write_do (UiForm dia, conststring32 extension) { |
| 262 | static MelderString defaultFileName; |
| 263 | if (extension && str32chr (extension, U'.')) { |
| 264 | /* |
| 265 | Apparently, the "extension" is a complete file name. |
| 266 | This should be used as the default file name. |
| 267 | (This case typically occurs when saving a picture.) |
| 268 | */ |
| 269 | MelderString_copy (& defaultFileName, extension); |
| 270 | } else { |
| 271 | /* |
| 272 | Apparently, the "extension" is not a complete file name. |
| 273 | We are expected to prepend the "extension" with the name of a selected object. |
| 274 | */ |
| 275 | integer IOBJECT, found = 0; |
| 276 | Daata data = nullptr; |
| 277 | WHERE (SELECTED) { |
| 278 | if (! data) |
| 279 | data = (Daata) OBJECT; |
| 280 | found += 1; |
| 281 | } |
| 282 | if (found == 1) { |
| 283 | MelderString_copy (& defaultFileName, data -> name.get()); |
| 284 | if (defaultFileName.length > 200) { |
| 285 | defaultFileName.string [200] = U'\0'; |
| 286 | defaultFileName.length = 200; |
| 287 | } |
| 288 | MelderString_append (& defaultFileName, U".", extension ? extension : Thing_className (data)); |
| 289 | } else if (! extension) { |
| 290 | MelderString_copy (& defaultFileName, U"praat.Collection"); |
| 291 | } else { |
| 292 | MelderString_copy (& defaultFileName, U"praat.", extension); |
| 293 | } |
| 294 | } |
| 295 | UiOutfile_do (dia, defaultFileName.string); |
| 296 | } |
| 297 | |
| 298 | static void removeAllReferencesToMoribundEditor (Editor editor) { |
| 299 | /* |
| 300 | Remove all references to this editor. |
| 301 | It may be editing multiple objects. |
| 302 | */ |
| 303 | for (integer iobject = 1; iobject <= theCurrentPraatObjects -> n; iobject ++) |
| 304 | for (integer ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) |
| 305 | if (theCurrentPraatObjects -> list [iobject]. editors [ieditor] == editor) |
| 306 | theCurrentPraatObjects -> list [iobject]. editors [ieditor] = nullptr; |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | Remove the "object" from the list, |
| 311 | killing everything that has to do with the selection. |
| 312 | */ |
| 313 | static void praat_remove (integer iobject, bool removeVisibly) { |
| 314 | Melder_assert (iobject >= 1 && iobject <= theCurrentPraatObjects -> n); |
| 315 | if (theCurrentPraatObjects -> list [iobject]. isBeingCreated) { |
| 316 | theCurrentPraatObjects -> list [iobject]. isBeingCreated = false; |
| 317 | theCurrentPraatObjects -> totalBeingCreated --; |
| 318 | } |
| 319 | if (removeVisibly) |
| 320 | praat_deselect (iobject); |
| 321 | |
| 322 | /* |
| 323 | To prevent synchronization problems, kill editors before killing the data. |
| 324 | */ |
| 325 | for (integer ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) { |
| 326 | Editor editor = theCurrentPraatObjects -> list [iobject]. editors [ieditor]; // save this one reference |
| 327 | if (editor) { |
| 328 | trace (U"remove references to editor ", ieditor); |
| 329 | removeAllReferencesToMoribundEditor (editor); |
| 330 | trace (U"forget editor ", ieditor); |
| 331 | if (removeVisibly) |
| 332 | forget (editor); // TODO: doesn't this call removeAllReferencesToMoribundEditor() again? |
| 333 | trace (U"forgotten editor ", ieditor); |
| 334 | } |
| 335 | } |
| 336 | MelderFile_setToNull (& theCurrentPraatObjects -> list [iobject]. file); |
| 337 | theCurrentPraatObjects -> list [iobject]. name. reset(); |
| 338 | forget (theCurrentPraatObjects -> list [iobject]. object); // note: this might save a file-based object to file |
| 339 | } |
| 340 | |
| 341 | void praat_cleanUpName (char32 *name) { |
| 342 | /* |
| 343 | Replaces spaces and special characters by underscores. |
| 344 | */ |
| 345 | for (; *name; name ++) |
| 346 | if (str32chr (U" ,.:;\\/()[]{}~`\'<>*&^%#@!?$\"|", *name)) |
| 347 | *name = U'_'; |
| 348 | } |
| 349 | |
| 350 | /***** objects + commands *****/ |
| 351 | |
| 352 | static void praat_new_unpackCollection (autoCollection me, const char32* myName) { |
| 353 | for (integer idata = 1; idata <= my size; idata ++) { |
| 354 | autoDaata object; |
| 355 | object. adoptFromAmbiguousOwner ((Daata) my at [idata]); |
| 356 | my at [idata] = nullptr; // disown; once the elements are autoThings, the move will handle this |
| 357 | const conststring32 name = ( object -> name ? object -> name.get() : myName ); |
| 358 | Melder_assert (name); |
| 359 | praat_new (object.move(), name); // recurse |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | void praat_newWithFile (autoDaata me, MelderFile file, conststring32 myName) { |
| 364 | if (! me) |
| 365 | Melder_throw (U"No object was put into the list."); |
| 366 | |
| 367 | if (my classInfo == classCollection) { |
| 368 | praat_new_unpackCollection (me.static_cast_move <structCollection>(), myName); |
| 369 | return; |
| 370 | } |
| 371 | |
| 372 | autoMelderString name, givenName; |
| 373 | if (myName && myName [0]) { |
| 374 | MelderString_copy (& givenName, myName); |
| 375 | /* |
| 376 | Remove extension. |
| 377 | */ |
| 378 | char32 *p = str32rchr (givenName.string, U'.'); |
| 379 | if (p) |
| 380 | *p = U'\0'; |
| 381 | } else { |
| 382 | MelderString_copy (& givenName, my name && my name [0] ? my name.get() : U"untitled"); |
| 383 | } |
| 384 | praat_cleanUpName (givenName.string); |
| 385 | MelderString_append (& name, Thing_className (me.get()), U" ", givenName.string); |
| 386 | |
| 387 | if (theCurrentPraatObjects -> n == praat_MAXNUM_OBJECTS) { |
| 388 | //forget (me); |
| 389 | Melder_throw (U"The Object Window cannot contain more than ", praat_MAXNUM_OBJECTS, U" objects. You could remove some objects."); |
| 390 | } |
| 391 | |
| 392 | integer IOBJECT = ++ theCurrentPraatObjects -> n; |
| 393 | Melder_assert (FULL_NAME == nullptr); |
| 394 | theCurrentPraatObjects -> list [IOBJECT]. name = Melder_dup_f (name.string); // all right to crash if out of memory |
| 395 | ++ theCurrentPraatObjects -> sequentialUniqueIdOfLatestObjectInList; |
| 396 | |
| 397 | if (! theCurrentPraatApplication -> batch) // put a new object on the screen, at the bottom of the list |
| 398 | GuiList_insertItem ( |
| 399 | praatList_objects, |
| 400 | Melder_cat (theCurrentPraatObjects -> sequentialUniqueIdOfLatestObjectInList, U". ", name.string), |
| 401 | theCurrentPraatObjects -> n |
| 402 | ); |
| 403 | CLASS = my classInfo; |
| 404 | OBJECT = me.releaseToAmbiguousOwner(); // FIXME: should be move() |
| 405 | SELECTED = false; |
| 406 | for (int ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) |
| 407 | EDITOR [ieditor] = nullptr; |
| 408 | if (file) |
| 409 | MelderFile_copy (file, & theCurrentPraatObjects -> list [IOBJECT]. file); |
| 410 | else |
| 411 | MelderFile_setToNull (& theCurrentPraatObjects -> list [IOBJECT]. file); |
| 412 | ID = theCurrentPraatObjects -> sequentialUniqueIdOfLatestObjectInList; |
| 413 | theCurrentPraatObjects -> list [IOBJECT]. isBeingCreated = true; |
| 414 | Thing_setName (OBJECT, givenName.string); |
| 415 | theCurrentPraatObjects -> totalBeingCreated ++; |
| 416 | } |
| 417 | |
| 418 | static MelderString thePraatNewName; |
| 419 | void praat_new (autoDaata me) { |
| 420 | praat_newWithFile (me.move(), nullptr, U""); |
| 421 | } |
| 422 | void praat_new (autoDaata me, const MelderArg& arg) { |
| 423 | praat_newWithFile (me.move(), nullptr, arg._arg); |
| 424 | } |
| 425 | void praat_new (autoDaata me, |
| 426 | const MelderArg& arg1, const MelderArg& arg2, const MelderArg& arg3, |
| 427 | const MelderArg& arg4, const MelderArg& arg5) |
| 428 | { |
| 429 | MelderString_copy (& thePraatNewName, arg1._arg, arg2._arg, arg3._arg, arg4._arg, arg5._arg); |
| 430 | praat_new (me.move(), thePraatNewName.string); |
| 431 | } |
| 432 | |
| 433 | void praat_updateSelection () { |
| 434 | if (theCurrentPraatObjects -> totalBeingCreated > 0) { |
| 435 | integer IOBJECT; |
| 436 | praat_deselectAll (); |
| 437 | WHERE (theCurrentPraatObjects -> list [IOBJECT]. isBeingCreated) { |
| 438 | praat_select (IOBJECT); |
| 439 | theCurrentPraatObjects -> list [IOBJECT]. isBeingCreated = false; |
| 440 | } |
| 441 | theCurrentPraatObjects -> totalBeingCreated = 0; |
| 442 | praat_show (); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | static void gui_cb_list_selectionChanged (Thing /* boss */, GuiList_SelectionChangedEvent event) { |
| 447 | Melder_assert (event -> list == praatList_objects); |
| 448 | integer IOBJECT; |
| 449 | bool first = true; |
| 450 | WHERE (SELECTED) { |
| 451 | SELECTED = false; |
| 452 | integer readableClassId = theCurrentPraatObjects -> list [IOBJECT]. object -> classInfo -> sequentialUniqueIdOfReadableClass; |
| 453 | theCurrentPraatObjects -> numberOfSelected [readableClassId] --; |
| 454 | Melder_assert (theCurrentPraatObjects -> numberOfSelected [readableClassId] >= 0); |
| 455 | } |
| 456 | theCurrentPraatObjects -> totalSelection = 0; |
| 457 | autoINTVEC selected = GuiList_getSelectedPositions (praatList_objects); |
| 458 | for (integer iselected = 1; iselected <= selected.size; iselected ++) { |
| 459 | IOBJECT = selected [iselected]; |
| 460 | SELECTED = true; |
| 461 | integer readableClassId = theCurrentPraatObjects -> list [IOBJECT]. object -> classInfo -> sequentialUniqueIdOfReadableClass; |
| 462 | theCurrentPraatObjects -> numberOfSelected [readableClassId] ++; |
| 463 | Melder_assert (theCurrentPraatObjects -> numberOfSelected [readableClassId] > 0); |
| 464 | UiHistory_write (first ? U"\nselectObject: \"" : U"\nplusObject: \""); |
| 465 | UiHistory_write_expandQuotes (FULL_NAME); |
| 466 | UiHistory_write (U"\""); |
| 467 | first = false; |
| 468 | theCurrentPraatObjects -> totalSelection += 1; |
| 469 | } |
| 470 | praat_show (); |
| 471 | } |
| 472 | |
| 473 | void praat_list_renameAndSelect (integer position, conststring32 name) { |
| 474 | if (! theCurrentPraatApplication -> batch) { |
| 475 | GuiList_replaceItem (praatList_objects, name, position); // void if name equal |
| 476 | if (! Melder_backgrounding) |
| 477 | GuiList_selectItem (praatList_objects, position); |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | /***** objects *****/ |
| 482 | |
| 483 | void praat_name2 (char32 *name, ClassInfo klas1, ClassInfo klas2) { |
| 484 | int i1 = 1; |
| 485 | while (theCurrentPraatObjects -> list [i1]. isSelected == 0 || theCurrentPraatObjects -> list [i1]. klas != klas1) |
| 486 | i1 ++; |
| 487 | int i2 = 1; |
| 488 | while (theCurrentPraatObjects -> list [i2]. isSelected == 0 || theCurrentPraatObjects -> list [i2]. klas != klas2) |
| 489 | i2 ++; |
| 490 | char32 *name1 = str32chr (theCurrentPraatObjects -> list [i1]. name.get(), U' ') + 1; |
| 491 | char32 *name2 = str32chr (theCurrentPraatObjects -> list [i2]. name.get(), U' ') + 1; |
| 492 | if (str32equ (name1, name2)) |
| 493 | Melder_sprint (name,200, name1); |
| 494 | else |
| 495 | Melder_sprint (name,200, name1, U"_", name2); |
| 496 | } |
| 497 | |
| 498 | void praat_removeObject (integer i) { |
| 499 | praat_remove (i, true); // dangle |
| 500 | for (integer j = i; j < theCurrentPraatObjects -> n; j ++) |
| 501 | theCurrentPraatObjects -> list [j] = std::move (theCurrentPraatObjects -> list [j + 1]); // undangle but create second references |
| 502 | theCurrentPraatObjects -> list [theCurrentPraatObjects -> n]. name. reset(); |
| 503 | theCurrentPraatObjects -> list [theCurrentPraatObjects -> n]. object = nullptr; // undangle or remove second reference |
| 504 | theCurrentPraatObjects -> list [theCurrentPraatObjects -> n]. isSelected = 0; |
| 505 | for (int ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) |
| 506 | theCurrentPraatObjects -> list [theCurrentPraatObjects -> n]. editors [ieditor] = nullptr; // undangle or remove second reference |
| 507 | MelderFile_setToNull (& theCurrentPraatObjects -> list [theCurrentPraatObjects -> n]. file); // undangle or remove second reference |
| 508 | -- theCurrentPraatObjects -> n; |
| 509 | if (! theCurrentPraatApplication -> batch) |
| 510 | GuiList_deleteItem (praatList_objects, i); |
| 511 | } |
| 512 | |
| 513 | static void praat_exit (int exit_code) { |
| 514 | //Melder_setTracing (true); |
| 515 | integer IOBJECT; |
| 516 | trace (U"destroy the picture window"); |
| 517 | praat_picture_exit (); |
| 518 | praat_statistics_exit (); // record total memory use across sessions |
| 519 | |
| 520 | if (! praatP.ignorePreferenceFiles) { |
| 521 | trace (U"stop receiving messages"); |
| 522 | #ifdef UNIX |
| 523 | /* |
| 524 | We are going to delete the process ID ("pid") file, if it's ours. |
| 525 | We consider it ours if its process ID equals our own process ID |
| 526 | (no more checks are necessary; the pid file cannot have been created |
| 527 | by a different Praat instance in an earlier computer session, |
| 528 | because if we arrive here, we are sure to have created a new pid file |
| 529 | in the current computer session). |
| 530 | */ |
| 531 | if (! MelderFile_isNull (& pidFile)) { |
| 532 | try { |
| 533 | /* |
| 534 | To see whether we own the pid file, |
| 535 | we look into it to see whether its pid equals our pid. |
| 536 | If not, then we are probably living in an old invocation of the program, |
| 537 | and the pid file was written by the latest invocation of the program, |
| 538 | which owns the pid (this means sendpraat can only send to the latest Praat if more than one are open). |
| 539 | */ |
| 540 | autofile f = Melder_fopen (& pidFile, "r"); |
| 541 | int pidOfLatestPraatInvocation; |
| 542 | if (fscanf (f, "%d", & pidOfLatestPraatInvocation) < 1) |
| 543 | throw MelderError (); |
| 544 | f.close (& pidFile); |
| 545 | int pidOfCurrentPraatIncoation = getpid (); |
| 546 | if (pidOfLatestPraatInvocation == pidOfCurrentPraatIncoation) |
| 547 | MelderFile_delete (& pidFile); // ...then we own the pid file and can delete it |
| 548 | } catch (MelderError) { |
| 549 | Melder_clearError (); // if the pid file is somehow missing or corrupted, we just ignore that |
| 550 | } |
| 551 | } |
| 552 | #endif |
| 553 | |
| 554 | trace (U"save the preferences"); |
| 555 | Melder_assert (str32equ (Melder_double (1.5), U"1.5")); // refuse to write the preferences if the locale is wrong (even if tracing is on) |
| 556 | Preferences_write_i (& prefsFile7); |
| 557 | if (Melder_appVersion() < 8000) { // allow the concurrent use of Praat 6 and 7, until Praat 8 |
| 558 | if (MelderFile_readable (& prefsFile7)) // If successful in writing the modern (Praat 7/8) settings file... |
| 559 | MelderFile_delete (& prefsFile5); // ... then delete the obsolete (Praat 6) settings file. |
| 560 | } |
| 561 | |
| 562 | trace (U"save the script buttons"); |
| 563 | if (! theCurrentPraatApplication -> batch) { |
| 564 | try { |
| 565 | autoMelderString buffer; |
| 566 | MelderString_append (& buffer, U"# Buttons (1).\n"); |
| 567 | MelderString_append (& buffer, U"# This file is generated automatically when you quit the ", Melder_upperCaseAppName(), U" program.\n"); |
| 568 | MelderString_append (& buffer, U"# It contains the buttons that you added interactively to the fixed or dynamic menus,\n"); |
| 569 | MelderString_append (& buffer, U"# and the buttons that you hid or showed.\n\n"); |
| 570 | praat_saveAddedMenuCommands (& buffer); |
| 571 | praat_saveToggledMenuCommands (& buffer); |
| 572 | praat_saveAddedActions (& buffer); |
| 573 | praat_saveToggledActions (& buffer); |
| 574 | MelderFile_writeText_i (& buttonsFile7, buffer.string, kMelder_textOutputEncoding::ASCII_THEN_UTF16); |
| 575 | if (Melder_appVersion() < 8000) { // allow the concurrent use of Praat 6 and 7, until Praat 8 |
| 576 | if (MelderFile_readable (& buttonsFile7)) // If successful in writing the modern (Praat 7/8) buttons file... |
| 577 | MelderFile_delete (& buttonsFile5); // ... then delete the obsolete (Praat 6) buttons file. |
| 578 | } |
| 579 | } catch (MelderError) { |
| 580 | Melder_clearError (); |
| 581 | } |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | trace (U"flush the file-based objects"); |
| 586 | WHERE_DOWN (! MelderFile_isNull (& theCurrentPraatObjects -> list [IOBJECT]. file)) { |
| 587 | trace (U"removing object based on file ", & theCurrentPraatObjects -> list [IOBJECT]. file); |
| 588 | praat_remove (IOBJECT, false); |
| 589 | } |
| 590 | |
| 591 | trace (U"leave the program"); |
| 592 | praat_menuCommands_exit_optimizeByLeaking (); // these calls are superflous if subsequently _Exit() is called instead of exit() |
| 593 | praat_actions_exit_optimizeByLeaking (); |
| 594 | Preferences_exit_optimizeByLeaking (); |
| 595 | /* |
| 596 | OPTIMIZE with an exercise in self-documenting code |
| 597 | */ |
| 598 | constexpr bool weWouldLikeToOptimizeExitingSpeed = ((true)); |
| 599 | constexpr bool callingExitTimeDestructorsIsSlow = (true); |
| 600 | constexpr bool notCallingExitTimeDestructorsCausesCorrectBehaviour = (true); |
| 601 | constexpr bool weAreReallySureAboutThat = (true); |
| 602 | constexpr bool weWillUseUnderscoreExitInsteadOfExit = |
| 603 | weWouldLikeToOptimizeExitingSpeed && |
| 604 | callingExitTimeDestructorsIsSlow && |
| 605 | notCallingExitTimeDestructorsCausesCorrectBehaviour && |
| 606 | weAreReallySureAboutThat; |
| 607 | if ((weWillUseUnderscoreExitInsteadOfExit)) { |
| 608 | constexpr bool underscoreExitHasMoreSideEffectsThanJustNotCallingExitTimeDestructors = (true); |
| 609 | constexpr bool avoidOtherSideEffectsOfUnderscoreExit = |
| 610 | underscoreExitHasMoreSideEffectsThanJustNotCallingExitTimeDestructors; |
| 611 | if ((avoidOtherSideEffectsOfUnderscoreExit)) { |
| 612 | constexpr bool oneSideEffectIsThatOpenOutputFilesAreNotFlushed = true; |
| 613 | constexpr bool weShouldFlushAllOpenOutputFilesWhoseNonflushingWouldCauseIncorrectBehaviour = |
| 614 | oneSideEffectIsThatOpenOutputFilesAreNotFlushed; |
| 615 | if ((weShouldFlushAllOpenOutputFilesWhoseNonflushingWouldCauseIncorrectBehaviour)) { |
| 616 | constexpr bool stdoutIsOpen = (true); |
| 617 | constexpr bool stderrIsOpen = (true); |
| 618 | constexpr bool stdoutIsBufferedByDefault = true; |
| 619 | constexpr bool stderrIsBufferedByDefault = false; |
| 620 | constexpr bool weKnowThatSetbufHasNotBeenCalledOnStdout = (false); |
| 621 | constexpr bool weKnowThatSetbufHasNotBeenCalledOnStderr = (false); |
| 622 | constexpr bool stdoutHasCertainlyBeenFlushed = |
| 623 | ! stdoutIsBufferedByDefault && weKnowThatSetbufHasNotBeenCalledOnStdout; |
| 624 | constexpr bool stderrHasCertainlyBeenFlushed = |
| 625 | ! stderrIsBufferedByDefault && weKnowThatSetbufHasNotBeenCalledOnStderr; |
| 626 | constexpr bool notFlushingStdoutCouldCauseIncorrectBehaviour = |
| 627 | stdoutIsOpen && ! stdoutHasCertainlyBeenFlushed; |
| 628 | constexpr bool notFlushingStderrCouldCauseIncorrectBehaviour = |
| 629 | stderrIsOpen && ! stderrHasCertainlyBeenFlushed; |
| 630 | constexpr bool shouldFlushStdout = notFlushingStdoutCouldCauseIncorrectBehaviour; |
| 631 | constexpr bool shouldFlushStderr = notFlushingStderrCouldCauseIncorrectBehaviour; |
| 632 | if ((shouldFlushStdout)) |
| 633 | fflush (Melder_stdout); |
| 634 | if ((shouldFlushStderr)) |
| 635 | fflush (Melder_stderr); |
| 636 | constexpr bool thereAreOtherOpenFiles = (false); |
| 637 | constexpr bool thereAreOtherOpenFilesWhoseNonflushingCouldCauseIncorrectBehaviour = |
| 638 | thereAreOtherOpenFiles; |
| 639 | if ((! thereAreOtherOpenFilesWhoseNonflushingCouldCauseIncorrectBehaviour)) {} |
| 640 | } |
| 641 | constexpr bool thereAreNoOtherSideEffectsBesideNotCallingExitDestructorsAndNotFlushingOpenFiles = (true); |
| 642 | if ((thereAreNoOtherSideEffectsBesideNotCallingExitDestructorsAndNotFlushingOpenFiles)) {} |
| 643 | } |
| 644 | _Exit (exit_code); |
| 645 | } else { |
| 646 | exit (exit_code); |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | static void cb_Editor_destruction (Editor me) { |
| 651 | removeAllReferencesToMoribundEditor (me); |
| 652 | } |
| 653 | |
| 654 | static void cb_Editor_dataChanged (Editor me) { |
| 655 | for (integer iobject = 1; iobject <= theCurrentPraatObjects -> n; iobject ++) { |
| 656 | /* |
| 657 | Am I editing this object? |
| 658 | */ |
| 659 | bool editingThisObject = false; |
| 660 | for (int ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) |
| 661 | editingThisObject |= ( theCurrentPraatObjects -> list [iobject]. editors [ieditor] == me ); |
| 662 | if (editingThisObject) { |
| 663 | /* |
| 664 | Notify all editors associated with this object, *including myself*. |
| 665 | But the receiver will be able to check whether the notification comes from self or not; |
| 666 | e.g. the DataEditor will react differently on a message from outside than on a message from inside. |
| 667 | (last checked 2022-09-30) |
| 668 | */ |
| 669 | for (int ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) { |
| 670 | Editor otherEditor = theCurrentPraatObjects -> list [iobject]. editors [ieditor]; |
| 671 | if (otherEditor) |
| 672 | Editor_dataChanged (otherEditor, me); |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | static void cb_Editor_publication (Editor /* me */, autoDaata publication) { |
| 679 | /* |
| 680 | The default publish callback. |
| 681 | Works nicely if the publisher invents a name. |
| 682 | */ |
| 683 | try { |
| 684 | praat_new (publication.move(), U""); |
| 685 | } catch (MelderError) { |
| 686 | Melder_flushError (); |
| 687 | } |
| 688 | praat_updateSelection (); |
| 689 | } |
| 690 | |
| 691 | void praat_installEditor (Editor editor, integer IOBJECT) { |
| 692 | if (! editor) |
| 693 | return; |
| 694 | for (integer ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) { |
| 695 | if (! EDITOR [ieditor]) { |
| 696 | EDITOR [ieditor] = editor; |
| 697 | Editor_setDestructionCallback (editor, cb_Editor_destruction); |
| 698 | Editor_setDataChangedCallback (editor, cb_Editor_dataChanged); |
| 699 | if (! editor -> d_publicationCallback) |
| 700 | Editor_setPublicationCallback (editor, cb_Editor_publication); |
| 701 | //Thing_setName (editor, Melder_cat (editor -> name.get(), U" [", ieditor + 1, U"]")); // would break existing scripts |
| 702 | return; |
| 703 | } |
| 704 | } |
| 705 | Melder_throw (U"(praat_installEditor:) Cannot have more than ", praat_MAXNUM_EDITORS, U" editors with one object."); |
| 706 | } |
| 707 | |
| 708 | void praat_installEditor2 (Editor editor, integer i1, integer i2) { |
| 709 | if (! editor) |
| 710 | return; |
| 711 | integer ieditor1 = 0; |
| 712 | for (; ieditor1 < praat_MAXNUM_EDITORS; ieditor1 ++) |
| 713 | if (! theCurrentPraatObjects -> list [i1]. editors [ieditor1]) |
| 714 | break; |
| 715 | integer ieditor2 = 0; |
| 716 | for (; ieditor2 < praat_MAXNUM_EDITORS; ieditor2 ++) |
| 717 | if (! theCurrentPraatObjects -> list [i2]. editors [ieditor2]) |
| 718 | break; |
| 719 | if (ieditor1 < praat_MAXNUM_EDITORS && ieditor2 < praat_MAXNUM_EDITORS) { |
| 720 | theCurrentPraatObjects -> list [i1]. editors [ieditor1] = theCurrentPraatObjects -> list [i2]. editors [ieditor2] = editor; |
| 721 | Editor_setDestructionCallback (editor, cb_Editor_destruction); |
| 722 | Editor_setDataChangedCallback (editor, cb_Editor_dataChanged); |
| 723 | if (! editor -> d_publicationCallback) |
| 724 | Editor_setPublicationCallback (editor, cb_Editor_publication); |
| 725 | } else { |
| 726 | Melder_throw (U"(praat_installEditor2:) Cannot have more than ", praat_MAXNUM_EDITORS, U" editors with one object."); |
| 727 | } |
| 728 | } |
| 729 | |
| 730 | void praat_installEditor3 (Editor editor, integer i1, integer i2, integer i3) { |
| 731 | if (! editor) |
| 732 | return; |
| 733 | integer ieditor1 = 0; |
| 734 | for (; ieditor1 < praat_MAXNUM_EDITORS; ieditor1 ++) |
| 735 | if (! theCurrentPraatObjects -> list [i1]. editors [ieditor1]) |
| 736 | break; |
| 737 | integer ieditor2 = 0; |
| 738 | for (; ieditor2 < praat_MAXNUM_EDITORS; ieditor2 ++) |
| 739 | if (! theCurrentPraatObjects -> list [i2]. editors [ieditor2]) |
| 740 | break; |
| 741 | integer ieditor3 = 0; |
| 742 | for (; ieditor3 < praat_MAXNUM_EDITORS; ieditor3 ++) |
| 743 | if (! theCurrentPraatObjects -> list [i3]. editors [ieditor3]) |
| 744 | break; |
| 745 | if (ieditor1 < praat_MAXNUM_EDITORS && ieditor2 < praat_MAXNUM_EDITORS && ieditor3 < praat_MAXNUM_EDITORS) { |
| 746 | theCurrentPraatObjects -> list [i1]. editors [ieditor1] = theCurrentPraatObjects -> list [i2]. editors [ieditor2] = theCurrentPraatObjects -> list [i3]. editors [ieditor3] = editor; |
| 747 | Editor_setDestructionCallback (editor, cb_Editor_destruction); |
| 748 | Editor_setDataChangedCallback (editor, cb_Editor_dataChanged); |
| 749 | if (! editor -> d_publicationCallback) |
| 750 | Editor_setPublicationCallback (editor, cb_Editor_publication); |
| 751 | } else { |
| 752 | Melder_throw (U"(praat_installEditor3:) Cannot have more than ", praat_MAXNUM_EDITORS, U" editors with one object."); |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | void praat_installEditorN (Editor editor, DaataList objects) { |
| 757 | if (! editor) |
| 758 | return; |
| 759 | /* |
| 760 | First check whether all objects in the DaataList are also in the List of Objects (Praat crashes if not), |
| 761 | and check whether there is room to add an editor for each. |
| 762 | */ |
| 763 | for (integer iOrderedObject = 1; iOrderedObject <= objects->size; iOrderedObject ++) { |
| 764 | Daata object = objects->at [iOrderedObject]; |
| 765 | integer iPraatObject = 1; |
| 766 | for (; iPraatObject <= theCurrentPraatObjects -> n; iPraatObject ++) { |
| 767 | if (object == theCurrentPraatObjects -> list [iPraatObject]. object) { |
| 768 | int ieditor = 0; |
| 769 | for (; ieditor < praat_MAXNUM_EDITORS; ieditor ++) |
| 770 | if (! theCurrentPraatObjects -> list [iPraatObject]. editors [ieditor]) |
| 771 | break; |
| 772 | if (ieditor >= praat_MAXNUM_EDITORS) |
| 773 | Melder_throw (U"Cannot view the same object in more than ", praat_MAXNUM_EDITORS, U" windows."); |
| 774 | break; |
| 775 | } |
| 776 | } |
| 777 | Melder_assert (iPraatObject <= theCurrentPraatObjects -> n); // an element of the Ordered does not occur in the List of Objects |
| 778 | } |
| 779 | /* |
| 780 | There appears to be room for all elements of the DaataList. The editor window can appear. Install the editor in all objects. |
| 781 | */ |
| 782 | for (integer iOrderedObject = 1; iOrderedObject <= objects->size; iOrderedObject ++) { |
| 783 | Daata object = objects->at [iOrderedObject]; |
| 784 | integer iPraatObject = 1; |
| 785 | for (; iPraatObject <= theCurrentPraatObjects -> n; iPraatObject ++) { |
| 786 | if (object == theCurrentPraatObjects -> list [iPraatObject]. object) { |
| 787 | int ieditor = 0; |
| 788 | for (; ieditor < praat_MAXNUM_EDITORS; ieditor ++) { |
| 789 | if (! theCurrentPraatObjects -> list [iPraatObject]. editors [ieditor]) { |
| 790 | theCurrentPraatObjects -> list [iPraatObject]. editors [ieditor] = editor; |
| 791 | Editor_setDestructionCallback (editor, cb_Editor_destruction); |
| 792 | Editor_setDataChangedCallback (editor, cb_Editor_dataChanged); |
| 793 | if (! editor -> d_publicationCallback) |
| 794 | Editor_setPublicationCallback (editor, cb_Editor_publication); |
| 795 | break; |
| 796 | } |
| 797 | } |
| 798 | Melder_assert (ieditor < praat_MAXNUM_EDITORS); // we just checked, but nevertheless |
| 799 | break; |
| 800 | } |
| 801 | } |
| 802 | Melder_assert (iPraatObject <= theCurrentPraatObjects -> n); // we already checked, but still |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | void praat_dataChanged (Daata object) { |
| 807 | /* |
| 808 | This function can be called at error time, which is weird. |
| 809 | */ |
| 810 | autostring32 saveError; |
| 811 | const bool duringError = Melder_hasError (); |
| 812 | if (duringError) { |
| 813 | if (Melder_hasCrash ()) |
| 814 | return; // straight to the exit, without attempting to notify any editors of any data, which might well be corrupted |
| 815 | saveError = Melder_dup_f (Melder_getError ()); |
| 816 | Melder_clearError (); |
| 817 | } |
| 818 | integer IOBJECT; |
| 819 | WHERE (OBJECT == object) { |
| 820 | for (int ieditor = 0; ieditor < praat_MAXNUM_EDITORS; ieditor ++) { |
| 821 | Editor editor = EDITOR [ieditor]; |
| 822 | if (editor) { |
| 823 | Editor_dataChanged (editor, nullptr); |
| 824 | if (duringError) |
| 825 | Melder_clearError (); // accept only the original error, and not the extra ones generated in the editors |
| 826 | } |
| 827 | } |
| 828 | } |
| 829 | if (duringError) { |
| 830 | Melder_appendError_noLine (saveError.get()); // restore the original error message |
| 831 | /* |
| 832 | If we are during error time, then this error should be caught |
| 833 | either by `throw` (see praatM.h, two occurrences) or by Melder_flushError (also see praatM.h, one occurrence). |
| 834 | (last checked 2021-12-02) |
| 835 | */ |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | static void helpProc (conststring32 query) { |
| 840 | if (theCurrentPraatApplication -> batch) { |
| 841 | Melder_flushError (U"Cannot view manual from batch."); |
| 842 | return; |
| 843 | } |
| 844 | try { |
| 845 | autoManual manual = Manual_create (query, nullptr, theCurrentPraatApplication -> manPages, false, true); |
| 846 | manual.releaseToUser(); |
| 847 | } catch (MelderError) { |
| 848 | Melder_flushError (U"help: no help on \"", query, U"\"."); |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | static int publishProc (autoDaata me) { |
| 853 | try { |
| 854 | praat_new (me.move(), U""); |
| 855 | praat_updateSelection (); |
| 856 | return 1; |
| 857 | } catch (MelderError) { |
| 858 | Melder_throw (U"Not published."); |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | /***** QUIT *****/ |
| 863 | |
| 864 | FORM (DO_Quit, U"Confirm Quit", U"Quit") { |
| 865 | MUTABLE_COMMENT (label1, U"You have objects in your list!") |
| 866 | MUTABLE_COMMENT (label2, U"Do you still want to quit?") |
| 867 | OK |
| 868 | { |
| 869 | const bool youHaveObjectsInYourList = ( theCurrentPraatObjects -> n > 0 ); |
| 870 | const bool youHaveUnsavedScriptsOrNotebooks = ( ScriptEditors_dirty () || NotebookEditors_dirty () ); |
| 871 | if (youHaveObjectsInYourList || youHaveUnsavedScriptsOrNotebooks) { |
| 872 | if (youHaveObjectsInYourList && youHaveUnsavedScriptsOrNotebooks) |
| 873 | SET_STRING (label1, U"You have objects in your list, and unsaved scripts or notebooks!") |
| 874 | else if (youHaveUnsavedScriptsOrNotebooks) |
| 875 | SET_STRING (label1, U"You have unsaved scripts or notebooks!") |
| 876 | else |
| 877 | SET_STRING (label1, U"You have objects in your list!") |
| 878 | char32 prompt [200]; |
| 879 | Melder_sprint (prompt,200, U"Do you still want to quit ", Melder_upperCaseAppName(), U"?"); |
| 880 | SET_STRING (label2, prompt) |
| 881 | } else { |
| 882 | praat_exit (0); |
| 883 | } |
| 884 | } |
| 885 | DO |
| 886 | praat_exit (0); |
| 887 | END_NO_NEW_DATA |
| 888 | } |
| 889 | |
| 890 | static void cb_quitApplication () { |
| 891 | DO_Quit (nullptr, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, nullptr); |
| 892 | } |
| 893 | |
| 894 | static void gui_cb_quit (Thing /* me */) { |
| 895 | Gui_runQuitApplicationCallback (); |
| 896 | } |
| 897 | |
| 898 | void praat_dontUsePictureWindow () { praatP.dontUsePictureWindow = true; } |
| 899 | |
| 900 | /********** INITIALIZATION OF THE PRAAT SHELL **********/ |
| 901 | |
| 902 | #if defined (UNIX) && ! defined (NO_GUI) |
| 903 | /* |
| 904 | sendpraat messages can only enter via SIGUSR1 at interrupt time. |
| 905 | We generate an event that should enter the main event loop at loop time. |
| 906 | */ |
| 907 | static void cb_sigusr1 (int signum) { |
| 908 | Melder_assert (signum == SIGUSR1); |
| 909 | signal (SIGUSR1, cb_sigusr1); // keep this handler in the air |
| 910 | GdkEventProperty gevent; // or GdkEventSetting, once we can find its signal name |
| 911 | gevent. type = GDK_PROPERTY_NOTIFY; // or GDK_SETTING |
| 912 | gevent. window = gtk_widget_get_window (GTK_WIDGET (theCurrentPraatApplication -> topShell -> d_gtkWindow)); |
| 913 | gevent. send_event = 1; |
| 914 | gevent. atom = gdk_atom_intern_static_string ("SENDPRAAT"); |
| 915 | gevent. time = 0; |
| 916 | gevent. state = GDK_PROPERTY_NEW_VALUE; |
| 917 | // Melder_casual (U"event put"); |
| 918 | gdk_event_put ((GdkEvent *) & gevent); // this is safe only if gdk_event_put is reentrant, which is unlikely because the event queue is global |
| 919 | } |
| 920 | #endif |
| 921 | |
| 922 | #if defined (UNIX) |
| 923 | #if ! defined (NO_GUI) |
| 924 | static gboolean cb_userMessage (GtkWidget /* widget */, GdkEventProperty * /* event */, gpointer /* userData */) { |
| 925 | trace (U"client event called"); |
| 926 | autofile f; |
| 927 | try { |
| 928 | f = Melder_fopen (& messageFile, "r"); |
| 929 | } catch (MelderError) { |
| 930 | Melder_clearError (); |
| 931 | return true; // OK |
| 932 | } |
| 933 | integer pid = 0; |
| 934 | int narg = fscanf (f, "#%td", & pid); |
| 935 | f.close (& messageFile); |
| 936 | {// scope |
| 937 | autoPraatBackground background; |
| 938 | try { |
| 939 | praat_executeScript_noGUI (& messageFile, true); // trust all messages, because they are sent by other apps that have control |
| 940 | } catch (MelderError) { |
| 941 | Melder_flushError (Melder_upperCaseAppName(), U": message not completely handled."); |
| 942 | } |
| 943 | } |
| 944 | if (narg != 0 && pid != 0) |
| 945 | kill (pid, SIGUSR2); |
| 946 | return true; |
| 947 | } |
| 948 | #endif |
| 949 | #elif defined (_WIN32) |
| 950 | static int cb_userMessage () { |
| 951 | autoPraatBackground background; |
| 952 | try { |
| 953 | praat_executeScript_noGUI (& messageFile, true); // trust all messages, because they are sent by other apps that have control |
| 954 | } catch (MelderError) { |
| 955 | Melder_flushError (Melder_upperCaseAppName(), U": message not completely handled."); |
| 956 | } |
| 957 | return 0; |
| 958 | } |
| 959 | #if 0 |
| 960 | static void cb_openDocument (MelderFile file) { |
| 961 | char32 text [kMelder_MAXPATH+25]; |
| 962 | /* |
| 963 | The user dropped a file on the Praat icon, |
| 964 | or double-clicked a Praat file, |
| 965 | while Praat is already running. |
| 966 | */ |
| 967 | Melder_sprint (text,500, U"Read from file: ~", MelderFile_peekPath (file)); |
| 968 | sendpraat (nullptr, Melder_peek32to8 (Melder_upperCaseAppName()), 0, Melder_peek32to8 (text)); |
| 969 | } |
| 970 | static void cb_finishedOpeningDocuments () { |
| 971 | praat_updateSelection (); |
| 972 | } |
| 973 | #endif |
| 974 | #elif macintosh |
| 975 | static int (*theUserMessageCallback) (); |
| 976 | static void mac_setUserMessageCallback (int (*userMessageCallback) ()) { |
| 977 | theUserMessageCallback = userMessageCallback; |
| 978 | } |
| 979 | static pascal OSErr mac_processSignal8 (const AppleEvent *theAppleEvent, AppleEvent * /* reply */, long /* handlerRefCon */) { |
| 980 | static bool duringAppleEvent = false; // FIXME: may have to be atomic? |
| 981 | if (! duringAppleEvent) { |
| 982 | //char *buffer; |
| 983 | //Size actualSize; |
| 984 | duringAppleEvent = true; |
| 985 | ProcessSerialNumber psn; |
| 986 | GetCurrentProcess (& psn); |
| 987 | SetFrontProcess (& psn); |
| 988 | //AEGetParamPtr (theAppleEvent, 1, typeUTF8Text, nullptr, nullptr, 0, & actualSize); |
| 989 | //buffer = (char *) malloc ((size_t) actualSize); |
| 990 | //AEGetParamPtr (theAppleEvent, 1, typeUTF8Text, nullptr, & buffer [0], actualSize, nullptr); |
| 991 | if (theUserMessageCallback) { |
| 992 | //autostring32 buffer32 = Melder_8to32_e (buffer); |
| 993 | //theUserMessageCallback (buffer32.get()); |
| 994 | theUserMessageCallback (); |
| 995 | } |
| 996 | //free (buffer); |
| 997 | duringAppleEvent = false; |
| 998 | } |
| 999 | return noErr; |
| 1000 | } |
| 1001 | static int cb_userMessage () { |
| 1002 | autoPraatBackground background; |
| 1003 | try { |
| 1004 | //praat_executeScriptFromText (message); |
| 1005 | praat_executeScript_noGUI (& messageFile, true); // trust all messages, because they are sent by other apps that have control |
| 1006 | } catch (MelderError) { |
| 1007 | Melder_flushError (Melder_upperCaseAppName(), U": message not completely handled."); |
| 1008 | } |
| 1009 | return 0; |
| 1010 | } |
| 1011 | #endif |
| 1012 | |
| 1013 | static conststring32 thePraatStandAloneScriptText = nullptr; |
| 1014 | |
| 1015 | void praat_setStandAloneScriptText (conststring32 text) { |
| 1016 | thePraatStandAloneScriptText = text; |
| 1017 | } |
| 1018 | |
| 1019 | static bool tryToAttachToTheCommandLine () |
| 1020 | { |
| 1021 | bool weHaveSucceeded = false; |
| 1022 | #if defined (_WIN32) |
| 1023 | /* |
| 1024 | * On Windows, console applications are automatically attached to the command line, |
| 1025 | * but Praat is always a Windows application instead, so command line attachment |
| 1026 | * has to be handled explicitly, as here. |
| 1027 | */ |
| 1028 | if (AttachConsole (ATTACH_PARENT_PROCESS)) { // was Praat called from either a console window or a "system" command? |
| 1029 | weHaveSucceeded = true; |
| 1030 | } |
| 1031 | #else |
| 1032 | weHaveSucceeded = isatty (fileno (stdin)) || isatty (fileno (stdout)) || isatty (fileno (stderr)); |
| 1033 | /* |
| 1034 | The result is `true` if Praat was called from a terminal window or some system() commands or Xcode, |
| 1035 | and `false` if Praat was called from the Finder by double-clicking or dropping a file. |
| 1036 | |
| 1037 | This might be incorrectly false only if all three streams are redirected to a file or pipe, |
| 1038 | but this hasn't been tested yet. |
| 1039 | */ |
| 1040 | #endif |
| 1041 | return weHaveSucceeded; |
| 1042 | } |
| 1043 | |
| 1044 | static void setThePraatLocale () { |
| 1045 | /* |
| 1046 | We use only the "C" locale, because iswalpha works differently |
| 1047 | on different platforms, even if UTF-8 is specified (e.g. try 0x0905, |
| 1048 | which is an `alpha` on Windows but not on Mac and Linux). |
| 1049 | We do have to replace everything from <wctype.h>: |
| 1050 | - all iswalpha by iswalpha_portable |
| 1051 | - all iswalnum by iswalnum_portable |
| 1052 | - all iswpunct by iswpunct_portable |
| 1053 | - all iswspace by iswspace_portable |
| 1054 | - all iswdigit by iswdigit_portable |
| 1055 | - all iswlower by iswlower_portable |
| 1056 | - all iswupper by iswupper_portable |
| 1057 | */ |
| 1058 | setlocale (LC_ALL, "C"); // said to be superfluous on Windows, but cannot hurt |
| 1059 | } |
| 1060 | |
| 1061 | static void installPraatShellPreferences () { |
| 1062 | praat_statistics_prefs (); // number of sessions, memory used... |
| 1063 | praat_picture_prefs (); // font... |
| 1064 | Graphics_prefs (); |
| 1065 | Ui_prefs (); |
| 1066 | structDataGui :: f_preferences (); // erase picture first... |
| 1067 | structEditor :: f_preferences (); // shell size... |
| 1068 | structHyperPage :: f_preferences (); // font... |
| 1069 | Site_prefs (); // print command... |
| 1070 | Melder_audio_prefs (); // asynchronicity, silence after... |
| 1071 | Melder_textEncoding_prefs (); |
| 1072 | Printer_prefs (); // paper size, printer command... |
| 1073 | structTextEditor :: f_preferences (); // font size... |
| 1074 | } |
| 1075 | |
| 1076 | extern "C" void praatlib_init () { |
| 1077 | setThePraatLocale (); // FIXME: don't use the global locale |
| 1078 | Melder_init (); |
| 1079 | Melder_rememberShellDirectory (); |
| 1080 | installPraatShellPreferences (); // needed in the library, because this sets the defaults |
| 1081 | praatP.argc = 0; |
| 1082 | praatP.argv = nullptr; |
| 1083 | praatP.argumentNumber = 1; |
| 1084 | Melder_batch = true; |
| 1085 | praatP.userWantsToOpen = false; |
| 1086 | Melder_setAppName (U"Praatlib"); |
| 1087 | theCurrentPraatApplication -> batch = true; |
| 1088 | Melder_getHomeDir (& homeDir); |
| 1089 | Thing_recognizeClassesByName (classCollection, classStrings, classManPages, classStringSet); |
| 1090 | Thing_recognizeClassByOtherName (classStringSet, U"SortedSetOfString"); |
| 1091 | Melder_backgrounding = true; |
| 1092 | praat_addMenus (nullptr); |
| 1093 | praat_addFixedButtons (nullptr); |
| 1094 | praat_addMenus2 (); |
| 1095 | } |
| 1096 | |
| 1097 | static void injectMessageAndInformationProcs (GuiWindow parent) { |
| 1098 | Gui_injectMessageProcs (parent); |
| 1099 | InfoEditor_injectInformationProc (); |
| 1100 | } |
| 1101 | |
| 1102 | static void printHelp () { |
| 1103 | MelderInfo_writeLine (U"Usage:"); |
| 1104 | MelderInfo_writeLine (U" To start up Praat with a new GUI:"); |
| 1105 | MelderInfo_writeLine (U" praat [OPTION]..."); |
| 1106 | MelderInfo_writeLine (U""); |
| 1107 | MelderInfo_writeLine (U" To run a Praat script without a GUI:"); |
| 1108 | MelderInfo_writeLine (U" praat [--run] [OPTION]... SCRIPT-FILE-NAME [SCRIPT-ARGUMENT]..."); |
| 1109 | MelderInfo_writeLine (U" The switch --run is superfluous when you use a Console or Terminal"); |
| 1110 | MelderInfo_writeLine (U" interactively, but necessary if you call Praat programmatically."); |
| 1111 | MelderInfo_writeLine (U""); |
| 1112 | MelderInfo_writeLine (U" To open one or more files, preferably in an existing GUI instance of Praat:"); |
| 1113 | MelderInfo_writeLine (U" praat --open [OPTION]... FILE-NAME..."); |
| 1114 | MelderInfo_writeLine (U" Data files will open in the Objects window, script files in a script window."); |
| 1115 | MelderInfo_writeLine (U""); |
| 1116 | MelderInfo_writeLine (U" To open one or more files in a new GUI instance of Praat:"); |
| 1117 | MelderInfo_writeLine (U" praat --new-open [OPTION]... FILE-NAME..."); |
| 1118 | MelderInfo_writeLine (U""); |
| 1119 | MelderInfo_writeLine (U" To run a Praat script in a preferably existing GUI instance of Praat:"); |
| 1120 | MelderInfo_writeLine (U" praat --send [OPTION]... SCRIPT-FILE-NAME [SCRIPT-ARGUMENT]..."); |
| 1121 | MelderInfo_writeLine (U""); |
| 1122 | MelderInfo_writeLine (U" To run a Praat script in a new GUI instance of Praat:"); |
| 1123 | MelderInfo_writeLine (U" praat --new-send [OPTION]... SCRIPT-FILE-NAME [SCRIPT-ARGUMENT]..."); |
| 1124 | MelderInfo_writeLine (U""); |
| 1125 | MelderInfo_writeLine (U" As --send, but potentially presenting a form to query for arguments:"); |
| 1126 | MelderInfo_writeLine (U" praat --send-or-form [OPTION]... SCRIPT-FILE-NAME"); |
| 1127 | MelderInfo_writeLine (U""); |
| 1128 | MelderInfo_writeLine (U" As --new-send, but potentially presenting a form to query for arguments:"); |
| 1129 | MelderInfo_writeLine (U" praat --new-send-or-form [OPTION]... SCRIPT-FILE-NAME"); |
| 1130 | MelderInfo_writeLine (U""); |
| 1131 | MelderInfo_writeLine (U" To start up Praat in an interactive command line session:"); |
| 1132 | MelderInfo_writeLine (U" praat [OPTION]... -"); |
| 1133 | MelderInfo_writeLine (U""); |
| 1134 | MelderInfo_writeLine (U" To print the Praat version:"); |
| 1135 | MelderInfo_writeLine (U" praat --version"); |
| 1136 | MelderInfo_writeLine (U""); |
| 1137 | MelderInfo_writeLine (U" To print this list of command line options:"); |
| 1138 | MelderInfo_writeLine (U" praat --help"); |
| 1139 | MelderInfo_writeLine (U""); |
| 1140 | MelderInfo_writeLine (U"Options:"); |
| 1141 | MelderInfo_writeLine (U" --FULL-TRUST allow this script to save files and run system commands"); |
| 1142 | MelderInfo_writeLine (U" --no-pref-files don't read or write the preferences file and the buttons file"); |
| 1143 | MelderInfo_writeLine (U" --no-plugins don't activate the plugins"); |
| 1144 | MelderInfo_writeLine (U" --pref-dir=<DIR> set the preferences folder to <DIR>"); |
| 1145 | MelderInfo_writeLine (U" -u, --utf16 use UTF-16LE output encoding, no BOM (the default on Windows)"); |
| 1146 | MelderInfo_writeLine (U" -8, --utf8 use UTF-8 output encoding (the default on MacOS and Linux)"); |
| 1147 | MelderInfo_writeLine (U" -a, --ansi use ISO Latin-1 output encoding (lossy, hence not recommended)"); |
| 1148 | MelderInfo_writeLine (U" (on Windows, use -8 or -a when you redirect to a pipe or file)"); |
| 1149 | MelderInfo_writeLine (U" --trace switch tracing on at start-up (see Praat > Technical > Debug)"); |
| 1150 | MelderInfo_writeLine (U" --hide-picture hide the Picture window at start-up"); |
| 1151 | MelderInfo_writeLine (U" --debug=58 set the Debug option to e.g. 58 at start-up"); |
| 1152 | } |
| 1153 | |
| 1154 | #ifdef _WIN32 |
| 1155 | static void *theWinApplicationWindow; |
| 1156 | #endif |
| 1157 | |
| 1158 | static bool tryToSwitchToRunningPraat (bool foundTheOpenOption, bool foundTheSendOption, bool foundTheSendOrFormOption) { |
| 1159 | /* |
| 1160 | This function returns true only if we can be certain that we have sent |
| 1161 | the command line to an already running invocation of Praat that is not identical to ourselves |
| 1162 | (though its Praat version has to be identical to ours). |
| 1163 | If there are doubts anywhere, then we just return false, |
| 1164 | because having zero instances of Praat is worse than having two. |
| 1165 | */ |
| 1166 | const integer pidOfCurrentPraat = getpid (); |
| 1167 | if (pidOfCurrentPraat == 0) { |
| 1168 | trace (U"We have no PID, so we will not be able to check that we are different from any running Praat."); |
| 1169 | return false; |
| 1170 | } |
| 1171 | trace (U"Process ID of current Praat: ", pidOfCurrentPraat); |
| 1172 | /* |
| 1173 | Figure out the Process ID of an already running instance of Praat. |
| 1174 | */ |
| 1175 | integer pidOfRunningPraat = 0; // mutable, to be filled in from file |
| 1176 | #if defined (macintosh) |
| 1177 | /* |
| 1178 | We have to implement this differently from how sendpraat implements this, |
| 1179 | because sendpraat just sends its message to a program with application signature 'PpgB', |
| 1180 | which by default is the current (starting-up) Praat rather than the already running Praat. |
| 1181 | These two instances of Praat can be distinguished by their Process ID. |
| 1182 | We look up the Process ID of the running Praat in a list associated with the running program's Bundle ID. |
| 1183 | */ |
| 1184 | NSRunningApplication *currentPraat = [NSRunningApplication currentApplication]; |
| 1185 | NSString *currentBundleIdentifier = [currentPraat bundleIdentifier]; // for instance @"org.praat.Praat" |
| 1186 | trace (U"Current bundle identifier: ", Melder_peek8to32_u ([currentBundleIdentifier UTF8String])); |
| 1187 | NSArray<NSRunningApplication *> *list = [NSRunningApplication runningApplicationsWithBundleIdentifier: currentBundleIdentifier]; |
| 1188 | NSRunningApplication *runningPraat = nullptr; |
| 1189 | const integer numberOfPraats = uinteger_to_integer_a ([list count]); |
| 1190 | for (integer ipraat = 1; ipraat <= numberOfPraats; ipraat ++) { |
| 1191 | NSRunningApplication *praat = [list objectAtIndex: ipraat-1]; |
| 1192 | pid_t pidOfPraat = [praat processIdentifier]; |
| 1193 | trace (U"Process ID ", pidOfPraat); |
| 1194 | if (pidOfPraat != pidOfCurrentPraat) { |
| 1195 | runningPraat = praat; |
| 1196 | pidOfRunningPraat = pidOfPraat; |
| 1197 | } |
| 1198 | } |
| 1199 | if (pidOfRunningPraat == 0) { |
| 1200 | trace (U"There seem to be no other running instances of Praat."); |
| 1201 | return false; |
| 1202 | } |
| 1203 | #elif defined (_WIN32) |
| 1204 | HWND winWindow = HWND (theWinApplicationWindow); |
| 1205 | if (! winWindow) |
| 1206 | return false; |
| 1207 | #elif defined (UNIX) |
| 1208 | integer versionOfRunningPraat = 0; // mutable, to be filled in from file |
| 1209 | try { |
| 1210 | autofile f = Melder_fopen (& pidFile, "r"); |
| 1211 | int numberOfRead = fscanf (f, "%td %td", & pidOfRunningPraat, & versionOfRunningPraat); |
| 1212 | if (numberOfRead < 1) { |
| 1213 | trace (U"No PID in PID file, " |
| 1214 | "so we will not be able to check that Praat is already running."); |
| 1215 | return false; |
| 1216 | } |
| 1217 | if (numberOfRead < 2) { |
| 1218 | trace (U"No Praat version number in PID file, " |
| 1219 | "so we will not be able to check that the same version of Praat is already running."); |
| 1220 | return false; |
| 1221 | } |
| 1222 | } catch (MelderError) { |
| 1223 | Melder_clearError (); // it is not an error if the PID file does not exist or is broken |
| 1224 | trace (U"PID file does not exist, " |
| 1225 | "so Praat is probably not running yet. We are process ", pidOfCurrentPraat, U"."); |
| 1226 | return false; |
| 1227 | } |
| 1228 | const integer versionOfCurrentPraat = Melder_appVersion(); |
| 1229 | if (versionOfRunningPraat != versionOfCurrentPraat) { |
| 1230 | trace (U"The current version of Praat differs from the version of the Praat that may already be running, " |
| 1231 | "so we cannot be sure it would respond as we would."); |
| 1232 | return false; |
| 1233 | } |
| 1234 | if (pidOfRunningPraat == pidOfCurrentPraat) { |
| 1235 | trace (U"Very rare condition: a Praat that crashed had the same PID as we have (in an earlier computer session), " |
| 1236 | "so Praat is probably not running yet."); |
| 1237 | return false; |
| 1238 | } |
| 1239 | trace (U"An instance with PID ", pidOfRunningPraat, U" is still running."); |
| 1240 | #endif |
| 1241 | /* |
| 1242 | Bring the running Praat to the foreground. |
| 1243 | */ |
| 1244 | Melder_casual (U"An instance of Praat that is not me is already running."); |
| 1245 | #if defined (macintosh) |
| 1246 | int activationVersion = 1; // 1 or 2 |
| 1247 | if (activationVersion == 1) { // deprecated since OS X 10.9, but it works, unlike the alternative |
| 1248 | ProcessSerialNumber psnOfRunningPraat; |
| 1249 | GetProcessForPID (pidOfRunningPraat, & psnOfRunningPraat); |
| 1250 | SetFrontProcess (& psnOfRunningPraat); // this works |
| 1251 | } else if (activationVersion == 2) { |
| 1252 | const bool activated = [runningPraat |
| 1253 | activateWithOptions: |
| 1254 | NSApplicationActivateAllWindows | // this option seems to be refused (if you take it alone, `activated` will be false) |
| 1255 | NSApplicationActivateIgnoringOtherApps // (is the activation policy right?) |
| 1256 | ]; |
| 1257 | Melder_casual (U"activated: ", activated); |
| 1258 | } |
| 1259 | #elif defined (_WIN32) |
| 1260 | if (IsIconic (winWindow)) |
| 1261 | ShowWindow (winWindow, SW_RESTORE); |
| 1262 | SetForegroundWindow (winWindow); |
| 1263 | #elif defined (UNIX) |
| 1264 | /* |
| 1265 | TODO: bring Praat to the foreground on GTK. |
| 1266 | */ |
| 1267 | #endif |
| 1268 | if (! foundTheOpenOption && ! foundTheSendOption && ! foundTheSendOrFormOption) |
| 1269 | return true; |
| 1270 | /* |
| 1271 | Send something to the running Praat, and bail out. |
| 1272 | */ |
| 1273 | autoMelderString text32; |
| 1274 | if (foundTheOpenOption) { |
| 1275 | /* |
| 1276 | praat --open [OPTION]... FILE-NAME... |
| 1277 | */ |
| 1278 | for (integer iarg = praatP.argumentNumber; iarg < praatP.argc; iarg ++) { // do not change praatP.argumentNumber itself (we might return false) |
| 1279 | TRACE |
| 1280 | structMelderFile file { }; |
| 1281 | Melder_relativePathToFile (Melder_peek8to32_u (praatP.argv [iarg]), & file); |
| 1282 | conststring32 absolutePath = MelderFile_peekPath (& file); |
| 1283 | MelderString_append (& text32, U"Read from file: ~", absolutePath, U"\n"); |
| 1284 | trace (U"Argument ", iarg, U": will open path ", absolutePath); |
| 1285 | } // TODO: we could send an openDocuments message instead |
| 1286 | } else if (foundTheSendOption) { |
| 1287 | /* |
| 1288 | praat --send [OPTION]... SCRIPT-FILE-NAME [SCRIPT-ARGUMENT]... |
| 1289 | */ |
| 1290 | MelderString_append (& text32, U"setWorkingDirectory: "); |
| 1291 | structMelderFolder currentFolder { }; |
| 1292 | Melder_getCurrentFolder (& currentFolder); |
| 1293 | MelderString_append (& text32, quote_doubleSTR (MelderFolder_peekPath (& currentFolder)).get()); |
| 1294 | MelderString_append (& text32, U"\nrunScript: "); |
| 1295 | structMelderFile scriptFile { }; |
| 1296 | Melder_relativePathToFile (theCurrentPraatApplication -> batchName.string, & scriptFile); |
| 1297 | conststring32 absolutePath = MelderFile_peekPath (& scriptFile); |
| 1298 | MelderString_append (& text32, quote_doubleSTR (absolutePath).get()); |
| 1299 | //TRACE |
| 1300 | trace (U"--send ", absolutePath); |
| 1301 | for (integer iarg = praatP.argumentNumber; iarg < praatP.argc; iarg ++) // do not change praatP.argumentNumber itself (we might return false) |
| 1302 | MelderString_append (& text32, U", ", quote_doubleSTR (Melder_peek8to32_u (praatP.argv [iarg])).get()); |
| 1303 | } else if (foundTheSendOrFormOption) { |
| 1304 | /* |
| 1305 | praat --send-or-form [OPTION]... SCRIPT-FILE-NAME |
| 1306 | */ |
| 1307 | MelderString_append (& text32, U"setWorkingDirectory: "); |
| 1308 | structMelderFolder currentFolder { }; |
| 1309 | Melder_getCurrentFolder (& currentFolder); |
| 1310 | MelderString_append (& text32, quote_doubleSTR (MelderFolder_peekPath (& currentFolder)).get()); |
| 1311 | MelderString_append (& text32, U"\nrunScriptWithForm: "); |
| 1312 | structMelderFile scriptFile { }; |
| 1313 | Melder_relativePathToFile (theCurrentPraatApplication -> batchName.string, & scriptFile); |
| 1314 | conststring32 absolutePath = MelderFile_peekPath (& scriptFile); |
| 1315 | MelderString_append (& text32, quote_doubleSTR (absolutePath).get()); |
| 1316 | //TRACE |
| 1317 | trace (U"--send-or-form ", absolutePath); |
| 1318 | Melder_require (praatP.argc - praatP.argumentNumber == 0, |
| 1319 | U"The --send-or-form switch should be followed by precisely one argument, namely the name of the script file."); |
| 1320 | } |
| 1321 | autostring8 text8 = Melder_32to8 (text32.string); |
| 1322 | #if defined (macintosh) |
| 1323 | autofile f; |
| 1324 | try { |
| 1325 | f = Melder_fopen (& messageFile, "w"); |
| 1326 | if (praatP. fullTrust) |
| 1327 | fprintf (f, "\n# --FULL-TRUST\n"); |
| 1328 | fprintf (f, "%s", text8.get()); |
| 1329 | f.close (& messageFile); |
| 1330 | } catch (MelderError) { |
| 1331 | Melder_clearError (); |
| 1332 | Melder_casual (U"Cannot write message file \"", MelderFile_messageName (& messageFile), |
| 1333 | U"\" (no privilege to write to folder, or disk full)."); |
| 1334 | return false; |
| 1335 | } |
| 1336 | |
| 1337 | |
| 1338 | const int timeOut = 0; |
| 1339 | AESendMode aeOptions = ( timeOut == 0 ? kAENoReply : kAEWaitReply ) | kAECanInteract | kAECanSwitchLayer; |
| 1340 | int appleEventVersion = 2; // 1, 2 or 3 |
| 1341 | if (appleEventVersion == 1) { |
| 1342 | ProcessSerialNumber psnOfRunningPraat; |
| 1343 | GetProcessForPID (pidOfRunningPraat, & psnOfRunningPraat); |
| 1344 | AppleEvent psnProgramDescriptor = { typeNull, nullptr }; |
| 1345 | OSErr err = AECreateDesc (typeProcessSerialNumber, & psnOfRunningPraat, sizeof (psnOfRunningPraat), & psnProgramDescriptor); |
| 1346 | if (err != noErr) |
| 1347 | return false; |
| 1348 | AppleEvent appleEvent; |
| 1349 | err = AECreateAppleEvent (758934755, 0, & psnProgramDescriptor, kAutoGenerateReturnID, 1, & appleEvent); |
| 1350 | if (err != noErr) { |
| 1351 | AEDisposeDesc (& psnProgramDescriptor); |
| 1352 | return false; |
| 1353 | } |
| 1354 | err = AEPutParamPtr (& appleEvent, 1, typeChar, text8.get(), (Size) strlen (text8.get()) + 1); |
| 1355 | if (err != noErr) { |
| 1356 | AEDisposeDesc (& appleEvent); |
| 1357 | AEDisposeDesc (& psnProgramDescriptor); |
| 1358 | return false; |
| 1359 | } |
| 1360 | AppleEvent reply; |
| 1361 | OSStatus status = AESendMessage (& appleEvent, & reply, aeOptions, timeOut == 0 ? kNoTimeOut : 60 * timeOut); |
| 1362 | if (status != 0) { |
| 1363 | AEDisposeDesc (& appleEvent); |
| 1364 | AEDisposeDesc (& psnProgramDescriptor); |
| 1365 | return false; // event not sent correctly |
| 1366 | } |
| 1367 | return true; // we did send an event to a running non-identical Praat successfully |
| 1368 | } else if (appleEventVersion == 2) { |
| 1369 | pid_t pidOfRunningPraat_pidt = pid_t (pidOfRunningPraat); |
| 1370 | NSAppleEventDescriptor *pidProgramDescriptor = [NSAppleEventDescriptor |
| 1371 | descriptorWithDescriptorType: typeKernelProcessID bytes: & pidOfRunningPraat_pidt length: sizeof (pid_t)]; |
| 1372 | if (! pidProgramDescriptor) |
| 1373 | return false; |
| 1374 | AppleEvent appleEvent; |
| 1375 | OSErr err = AECreateAppleEvent (758934755, 0, [pidProgramDescriptor aeDesc], kAutoGenerateReturnID, 1, & appleEvent); |
| 1376 | if (err != noErr) { |
| 1377 | // pidProgramDescriptor is autoreleased |
| 1378 | return false; |
| 1379 | } |
| 1380 | err = AEPutParamPtr (& appleEvent, 1, typeChar, text8.get(), (Size) strlen (text8.get()) + 1); |
| 1381 | if (err != noErr) { |
| 1382 | AEDisposeDesc (& appleEvent); |
| 1383 | // pidProgramDescriptor is autoreleased |
| 1384 | return false; |
| 1385 | } |
| 1386 | AppleEvent reply; |
| 1387 | OSStatus status = AESendMessage (& appleEvent, & reply, aeOptions, timeOut == 0 ? kNoTimeOut : 60 * timeOut); |
| 1388 | if (status != 0) { |
| 1389 | AEDisposeDesc (& appleEvent); |
| 1390 | // pidProgramDescriptor is autoreleased |
| 1391 | return false; // event not sent correctly |
| 1392 | } |
| 1393 | TRACE |
| 1394 | trace (U"event sent successfully"); |
| 1395 | return true; // we did send an event to a running non-identical Praat successfully |
| 1396 | } else if (appleEventVersion == 3) { // from 10.11 on |
| 1397 | NSAppleEventDescriptor *pidProgramDescriptor = [NSAppleEventDescriptor |
| 1398 | descriptorWithProcessIdentifier: pidOfRunningPraat]; |
| 1399 | if (! pidProgramDescriptor) |
| 1400 | return false; |
| 1401 | NSAppleEventDescriptor *appleEvent = [NSAppleEventDescriptor |
| 1402 | appleEventWithEventClass: 758934755 eventID: 0 targetDescriptor: pidProgramDescriptor |
| 1403 | returnID: kAutoGenerateReturnID transactionID: 1 |
| 1404 | ]; |
| 1405 | if (! appleEvent) |
| 1406 | return false; |
| 1407 | // somewhere add text8 |
| 1408 | NSAppleEventSendOptions nsOptions = (unsigned long) aeOptions; // identical numbers, fortunately |
| 1409 | NSError *error; |
| 1410 | [appleEvent |
| 1411 | sendEventWithOptions: nsOptions |
| 1412 | timeout: (double) timeOut |
| 1413 | error: & error |
| 1414 | ]; |
| 1415 | if (error) |
| 1416 | return false; // event not sent correctly |
| 1417 | return true; // we did send an event to a running non-identical Praat successfully |
| 1418 | } else { |
| 1419 | Melder_crash (U"Unknown Apple Event version."); |
| 1420 | } |
| 1421 | #elif defined (UNIX) |
| 1422 | autofile f; |
| 1423 | try { |
| 1424 | f = Melder_fopen (& messageFile, "w"); |
| 1425 | fprintf (f, "%s", text8.get()); |
| 1426 | f.close (& messageFile); |
| 1427 | } catch (MelderError) { |
| 1428 | Melder_clearError (); |
| 1429 | Melder_casual (U"Cannot write message file \"", MelderFile_messageName (& messageFile), |
| 1430 | U"\" (no privilege to write to folder, or disk full)."); |
| 1431 | return false; |
| 1432 | } |
| 1433 | if (kill (pidOfRunningPraat, SIGUSR1)) { |
| 1434 | Melder_casual (U"Cannot send message. The program may have crashed."); |
| 1435 | return false; |
| 1436 | } |
| 1437 | return true; |
| 1438 | #elif defined (_WIN32) |
| 1439 | autofile f; |
| 1440 | try { |
| 1441 | f = Melder_fopen (& messageFile, "w"); |
| 1442 | fprintf (f, "%s", text8.get()); |
| 1443 | f.close (& messageFile); |
| 1444 | } catch (MelderError) { |
| 1445 | Melder_clearError (); |
| 1446 | Melder_casual (U"Cannot write message file \"", MelderFile_messageName (& messageFile), |
| 1447 | U"\" (no privilege to write to folder, or disk full)."); |
| 1448 | return false; |
| 1449 | } |
| 1450 | if (SendMessage (HWND (theWinApplicationWindow), WM_APP, 0, 0)) { |
| 1451 | Melder_casual (U"Cannot send message."); |
| 1452 | return false; |
| 1453 | } |
| 1454 | return true; |
| 1455 | #endif |
| 1456 | return false; // the default |
| 1457 | } |
| 1458 | |
| 1459 | /* |
| 1460 | This function translates the command-line arguments to fields in `praatP`. |
| 1461 | It doesn't do too much by itself, because many of the relevant entities (such as preferences folder and tracing file) |
| 1462 | haven't been set yet (because setting these entities depends on the command-line arguments). |
| 1463 | */ |
| 1464 | static void interpretCommandLineArguments (bool weWereStartedFromTheCommandLine, int argc, char **argv) { |
| 1465 | //TRACE // the tracing file may not have been set yet, so this will probably go to stderr |
| 1466 | for (int iarg = 0; iarg < argc; iarg ++) |
| 1467 | trace (U"arg ", iarg, U": <<", Melder_peek8to32_u (argv [iarg]), U">>"); |
| 1468 | |
| 1469 | praatP.argc = argc; |
| 1470 | praatP.argv = argv; |
| 1471 | praatP.argumentNumber = 1; |
| 1472 | |
| 1473 | /* |
| 1474 | Running Praat from the command line. |
| 1475 | */ |
| 1476 | while (praatP.argumentNumber < argc && argv [praatP.argumentNumber] [0] == '-') { |
| 1477 | if (strequ (argv [praatP.argumentNumber], "-")) { |
| 1478 | praatP.hasCommandLineInput = true; |
| 1479 | praatP.argumentNumber += 1; |
| 1480 | } else if (strequ (argv [praatP.argumentNumber], "--run")) { |
| 1481 | praatP.foundTheRunSwitch = true; |
| 1482 | praatP.argumentNumber += 1; |
| 1483 | } else if (strequ (argv [praatP.argumentNumber], "--open")) { |
| 1484 | praatP.foundTheOpenSwitch = true; |
| 1485 | praatP.argumentNumber += 1; |
| 1486 | } else if (strequ (argv [praatP.argumentNumber], "--new-open")) { |
| 1487 | praatP.foundTheNewSwitch = true; |
| 1488 | praatP.foundTheOpenSwitch = true; |
| 1489 | praatP.argumentNumber += 1; |
| 1490 | } else if (strequ (argv [praatP.argumentNumber], "--send")) { |
| 1491 | praatP.foundTheSendSwitch = true; |
| 1492 | praatP.argumentNumber += 1; |
| 1493 | } else if (strequ (argv [praatP.argumentNumber], "--new-send")) { |
| 1494 | praatP.foundTheNewSwitch = true; |
| 1495 | praatP.foundTheSendSwitch = true; |
| 1496 | praatP.argumentNumber += 1; |
| 1497 | } else if (strequ (argv [praatP.argumentNumber], "--send-or-form")) { |
| 1498 | praatP.foundTheSendOrFormSwitch = true; |
| 1499 | praatP.argumentNumber += 1; |
| 1500 | } else if (strequ (argv [praatP.argumentNumber], "--new-send-or-form")) { |
| 1501 | praatP.foundTheNewSwitch = true; |
| 1502 | praatP.foundTheSendOrFormSwitch = true; |
| 1503 | praatP.argumentNumber += 1; |
| 1504 | } else if (strequ (argv [praatP.argumentNumber], "--FULL-TRUST")) { |
| 1505 | praatP.fullTrust = true; |
| 1506 | praatP.argumentNumber += 1; |
| 1507 | } else if (strequ (argv [praatP.argumentNumber], "--no-pref-files")) { |
| 1508 | praatP.ignorePreferenceFiles = true; |
| 1509 | praatP.argumentNumber += 1; |
| 1510 | } else if (strequ (argv [praatP.argumentNumber], "--no-plugins")) { |
| 1511 | praatP.ignorePlugins = true; |
| 1512 | praatP.argumentNumber += 1; |
| 1513 | } else if (strnequ (argv [praatP.argumentNumber], "--pref-dir=", 11)) { |
| 1514 | Melder_setPreferencesFolder (Melder_peek8to32_u (argv [praatP.argumentNumber] + 11)); |
| 1515 | praatP.argumentNumber += 1; |
| 1516 | } else if (strequ (argv [praatP.argumentNumber], "--version")) { |
| 1517 | Melder_information (Melder_upperCaseAppName(), U" ", Melder_appVersionSTR(), |
| 1518 | U" (", Melder_appMonthSTR(), U" ", Melder_appDay(), U" ", Melder_appYear(), U")"); |
| 1519 | exit (0); |
| 1520 | } else if (strequ (argv [praatP.argumentNumber], "--trace")) { |
| 1521 | Melder_setTracing (true); |
| 1522 | praatP.argumentNumber += 1; |
| 1523 | } else if (strequ (argv [praatP.argumentNumber], "--hide-picture")) { |
| 1524 | praatP.commandLineOptions.hidePicture = true; |
| 1525 | praatP.argumentNumber += 1; |
| 1526 | } else if (strnequ (argv [praatP.argumentNumber], "--debug=", 8)) { |
| 1527 | Melder_debug = atoi (argv [praatP.argumentNumber] + 8); |
| 1528 | praatP.argumentNumber += 1; |
| 1529 | } else if (strequ (argv [praatP.argumentNumber], "--help")) { |
| 1530 | MelderInfo_open (); |
| 1531 | printHelp (); |
| 1532 | MelderInfo_close (); |
| 1533 | exit (0); |
| 1534 | } else if (strequ (argv [praatP.argumentNumber], "-8") || strequ (argv [praatP.argumentNumber], "--utf8")) { |
| 1535 | MelderConsole::setEncoding (MelderConsole::Encoding::UTF8); |
| 1536 | praatP.argumentNumber += 1; |
| 1537 | } else if (strequ (argv [praatP.argumentNumber], "-u") || strequ (argv [praatP.argumentNumber], "--utf16")) { |
| 1538 | MelderConsole::setEncoding (MelderConsole::Encoding::UTF16); |
| 1539 | praatP.argumentNumber += 1; |
| 1540 | } else if (strequ (argv [praatP.argumentNumber], "-a") || strequ (argv [praatP.argumentNumber], "--ansi")) { |
| 1541 | MelderConsole::setEncoding (MelderConsole::Encoding::ANSI); |
| 1542 | praatP.argumentNumber += 1; |
| 1543 | #if defined (macintosh) |
| 1544 | } else if (strequ (argv [praatP.argumentNumber], "-NSDocumentRevisionsDebugMode")) { |
| 1545 | (void) 0; // ignore this option, which was added by Xcode |
| 1546 | praatP.argumentNumber += 2; // jump over the argument, which is usually "YES" (this jump works correctly even if this argument is missing) |
| 1547 | } else if (strnequ (argv [praatP.argumentNumber], "-psn_", 5)) { |
| 1548 | (void) 0; // ignore this option, which was added by the Finder, perhaps when dragging a file on Praat (Process Serial Number) |
| 1549 | trace (U"Process serial number ", Melder_peek8to32_u (argv [praatP.argumentNumber])); |
| 1550 | praatP.argumentNumber += 1; |
| 1551 | #endif |
| 1552 | } else if (strequ (argv [praatP.argumentNumber], "-sgi") || |
| 1553 | strequ (argv [praatP.argumentNumber], "-motif") || |
| 1554 | strequ (argv [praatP.argumentNumber], "-cde") || |
| 1555 | strequ (argv [praatP.argumentNumber], "-solaris") || |
| 1556 | strequ (argv [praatP.argumentNumber], "-hp") || |
| 1557 | strequ (argv [praatP.argumentNumber], "-sun4") || |
| 1558 | strequ (argv [praatP.argumentNumber], "-mac") || |
| 1559 | strequ (argv [praatP.argumentNumber], "-win32") || |
| 1560 | strequ (argv [praatP.argumentNumber], "-linux") || |
| 1561 | strequ (argv [praatP.argumentNumber], "-cocoa") || |
| 1562 | strequ (argv [praatP.argumentNumber], "-chrome") |
| 1563 | ) { |
| 1564 | praatP.argumentNumber += 1; |
| 1565 | } else { |
| 1566 | MelderInfo_open (); |
| 1567 | MelderInfo_writeLine (U"Unrecognized command line option ", Melder_peek8to32_u (argv [praatP.argumentNumber]), U"\n"); |
| 1568 | printHelp (); |
| 1569 | MelderInfo_close (); |
| 1570 | exit (-1); |
| 1571 | } |
| 1572 | } |
| 1573 | const bool thereIsAFileNameInTheArgumentList = ( praatP.argumentNumber < argc ); |
| 1574 | trace (U"Start-up flags: cornsff = ", |
| 1575 | weWereStartedFromTheCommandLine, praatP.foundTheOpenSwitch, praatP.foundTheRunSwitch, |
| 1576 | praatP.foundTheNewSwitch, praatP.foundTheSendSwitch, praatP.foundTheSendOrFormSwitch, thereIsAFileNameInTheArgumentList |
| 1577 | ); |
| 1578 | if (praatP.foundTheRunSwitch && praatP.foundTheOpenSwitch) { |
| 1579 | MelderInfo_open (); |
| 1580 | MelderInfo_writeLine (U"Conflicting command line switches --run and --open (or --new-open).", U"\n"); |
| 1581 | printHelp (); |
| 1582 | MelderInfo_close (); |
| 1583 | exit (-1); |
| 1584 | } |
| 1585 | if (praatP.foundTheRunSwitch && praatP.foundTheSendSwitch) { |
| 1586 | MelderInfo_open (); |
| 1587 | MelderInfo_writeLine (U"Conflicting command line switches --run and --send (or --new-send).", U"\n"); |
| 1588 | printHelp (); |
| 1589 | MelderInfo_close (); |
| 1590 | exit (-1); |
| 1591 | } |
| 1592 | if (praatP.foundTheRunSwitch && praatP.foundTheSendOrFormSwitch) { |
| 1593 | MelderInfo_open (); |
| 1594 | MelderInfo_writeLine (U"Conflicting command line switches --run and --send-or-form (or --new-send-or-form).", U"\n"); |
| 1595 | printHelp (); |
| 1596 | MelderInfo_close (); |
| 1597 | exit (-1); |
| 1598 | } |
| 1599 | if (praatP.foundTheOpenSwitch && praatP.foundTheSendSwitch) { |
| 1600 | MelderInfo_open (); |
| 1601 | MelderInfo_writeLine (U"Conflicting command line switches --open (or --new-open) and --send (or --new-send).", U"\n"); |
| 1602 | printHelp (); |
| 1603 | MelderInfo_close (); |
| 1604 | exit (-1); |
| 1605 | } |
| 1606 | if (praatP.foundTheOpenSwitch && praatP.foundTheSendOrFormSwitch) { |
| 1607 | MelderInfo_open (); |
| 1608 | MelderInfo_writeLine (U"Conflicting command line switches --open (or --new-open) and --send-or-form (or --new-send-or-form).", U"\n"); |
| 1609 | printHelp (); |
| 1610 | MelderInfo_close (); |
| 1611 | exit (-1); |
| 1612 | } |
| 1613 | if (praatP.foundTheSendSwitch && praatP.foundTheSendOrFormSwitch) { |
| 1614 | MelderInfo_open (); |
| 1615 | MelderInfo_writeLine (U"Conflicting command line switches --send (or --new-send) and --send-or-form (or --new-send-or-form).", U"\n"); |
| 1616 | printHelp (); |
| 1617 | MelderInfo_close (); |
| 1618 | exit (-1); |
| 1619 | } |
| 1620 | if (praatP.foundTheRunSwitch && ! thereIsAFileNameInTheArgumentList) { |
| 1621 | MelderInfo_open (); |
| 1622 | MelderInfo_writeLine (U"The switch --run requires a script file name.", U"\n"); |
| 1623 | printHelp (); |
| 1624 | MelderInfo_close (); |
| 1625 | exit (-1); |
| 1626 | } |
| 1627 | if (praatP.foundTheSendSwitch && ! thereIsAFileNameInTheArgumentList) { |
| 1628 | MelderInfo_open (); |
| 1629 | MelderInfo_writeLine (U"The switch --send requires a script file name.", U"\n"); |
| 1630 | printHelp (); |
| 1631 | MelderInfo_close (); |
| 1632 | exit (-1); |
| 1633 | } |
| 1634 | if (praatP.foundTheSendOrFormSwitch && ! thereIsAFileNameInTheArgumentList) { |
| 1635 | MelderInfo_open (); |
| 1636 | MelderInfo_writeLine (U"The switch --send-or-form requires a script file name.", U"\n"); |
| 1637 | printHelp (); |
| 1638 | MelderInfo_close (); |
| 1639 | exit (-1); |
| 1640 | } |
| 1641 | if (praatP.foundTheOpenSwitch && ! thereIsAFileNameInTheArgumentList) { |
| 1642 | MelderInfo_open (); |
| 1643 | MelderInfo_writeLine (U"The switch --open requires at least one file name.", U"\n"); |
| 1644 | printHelp (); |
| 1645 | MelderInfo_close (); |
| 1646 | exit (-1); |
| 1647 | } |
| 1648 | Melder_batch = |
| 1649 | ! praatP.foundTheOpenSwitch && |
| 1650 | ! praatP.foundTheSendSwitch && |
| 1651 | ! praatP.foundTheSendOrFormSwitch && |
| 1652 | (praatP.foundTheRunSwitch || thereIsAFileNameInTheArgumentList && weWereStartedFromTheCommandLine) // this line to be removed |
| 1653 | ; |
| 1654 | bool userWantsGui = ! Melder_batch; |
| 1655 | praatP.fileNamesCameInByDropping = |
| 1656 | userWantsGui && |
| 1657 | ! praatP.foundTheRunSwitch && ! praatP.foundTheOpenSwitch && ! praatP.foundTheSendSwitch && ! praatP.foundTheSendOrFormSwitch && |
| 1658 | thereIsAFileNameInTheArgumentList |
| 1659 | ; // doesn't happen on the Mac |
| 1660 | trace (U"Did file names come in by dropping? ", praatP.fileNamesCameInByDropping); |
| 1661 | praatP.userWantsToOpen = userWantsGui && (praatP.foundTheOpenSwitch || praatP.fileNamesCameInByDropping); |
| 1662 | trace (U"User wants to open: ", praatP.userWantsToOpen); |
| 1663 | praatP.userWantsToSend = userWantsGui && praatP.foundTheSendSwitch; |
| 1664 | trace (U"User wants to send: ", praatP.userWantsToSend); |
| 1665 | praatP.userWantsToSendOrForm = userWantsGui && praatP.foundTheSendOrFormSwitch; |
| 1666 | trace (U"User wants to send-or-form: ", praatP.userWantsToSendOrForm); |
| 1667 | praatP.userWantsExistingInstance = (praatP.userWantsToOpen || praatP.userWantsToSend || praatP.userWantsToSendOrForm) && ! praatP.foundTheNewSwitch |
| 1668 | || (userWantsGui && ! weWereStartedFromTheCommandLine); |
| 1669 | trace (U"User wants existing instance: ", praatP.userWantsExistingInstance); |
| 1670 | |
| 1671 | if (Melder_batch || praatP.userWantsToSend || praatP.userWantsToSendOrForm) { |
| 1672 | Melder_assert (praatP.argumentNumber < argc); |
| 1673 | /* |
| 1674 | We now get the script file name. It is next on the command line |
| 1675 | (not necessarily *last* on the line, because there may be script arguments after it). |
| 1676 | */ |
| 1677 | MelderString_copy (& theCurrentPraatApplication -> batchName, Melder_peek8to32_u (argv [praatP.argumentNumber ++])); |
| 1678 | if (praatP.hasCommandLineInput) |
| 1679 | Melder_throw (U"Cannot have both command line input and a script file."); |
| 1680 | } else { |
| 1681 | MelderString_copy (& theCurrentPraatApplication -> batchName, U""); |
| 1682 | } |
| 1683 | //Melder_casual (U"Script file name <<", theCurrentPraatApplication -> batchName.string, U">>"); |
| 1684 | |
| 1685 | if (!! thePraatStandAloneScriptText) { |
| 1686 | Melder_batch = true; |
| 1687 | userWantsGui = false; |
| 1688 | if (praatP.foundTheRunSwitch) { |
| 1689 | MelderInfo_open (); |
| 1690 | MelderInfo_writeLine (U"The switch --run is not compatible with running a stand-alone script.", U"\n"); |
| 1691 | printHelp (); |
| 1692 | MelderInfo_close (); |
| 1693 | exit (-1); |
| 1694 | } |
| 1695 | if (praatP.foundTheOpenSwitch) { |
| 1696 | MelderInfo_open (); |
| 1697 | MelderInfo_writeLine (U"The switch --open (or --new-open) is not compatible with running a stand-alone script.", U"\n"); |
| 1698 | printHelp (); |
| 1699 | MelderInfo_close (); |
| 1700 | exit (-1); |
| 1701 | } |
| 1702 | if (praatP.foundTheSendSwitch) { |
| 1703 | MelderInfo_open (); |
| 1704 | MelderInfo_writeLine (U"The switch --send (or --new-send) is not compatible with running a stand-alone script.", U"\n"); |
| 1705 | printHelp (); |
| 1706 | MelderInfo_close (); |
| 1707 | exit (-1); |
| 1708 | } |
| 1709 | if (praatP.foundTheSendOrFormSwitch) { |
| 1710 | MelderInfo_open (); |
| 1711 | MelderInfo_writeLine (U"The switch --send-or-form (or --new-send-or-form) is not compatible with running a stand-alone script.", U"\n"); |
| 1712 | printHelp (); |
| 1713 | MelderInfo_close (); |
| 1714 | exit (-1); |
| 1715 | } |
| 1716 | if (thereIsAFileNameInTheArgumentList) { |
| 1717 | MelderInfo_open (); |
| 1718 | MelderInfo_writeLine (U"Having a file name is not compatible with running a stand-alone script.", U"\n"); |
| 1719 | printHelp (); |
| 1720 | MelderInfo_close (); |
| 1721 | exit (-1); |
| 1722 | } |
| 1723 | Melder_assert (! praatP.userWantsToOpen); |
| 1724 | Melder_assert (! praatP.userWantsExistingInstance); |
| 1725 | } |
| 1726 | |
| 1727 | /* |
| 1728 | Running the Praat shell from the command line: |
| 1729 | praat - |
| 1730 | */ |
| 1731 | if (praatP.hasCommandLineInput) { |
| 1732 | Melder_batch = true; |
| 1733 | userWantsGui = false; |
| 1734 | if (praatP.foundTheRunSwitch) { |
| 1735 | MelderInfo_open (); |
| 1736 | MelderInfo_writeLine (U"The switch --run is not compatible with running Praat interactively from the command line.", U"\n"); |
| 1737 | printHelp (); |
| 1738 | MelderInfo_close (); |
| 1739 | exit (-1); |
| 1740 | } |
| 1741 | if (praatP.foundTheOpenSwitch) { |
| 1742 | MelderInfo_open (); |
| 1743 | MelderInfo_writeLine (U"The switch --open (or --new-open) is not compatible with running Praat interactively from the command line.", U"\n"); |
| 1744 | printHelp (); |
| 1745 | MelderInfo_close (); |
| 1746 | exit (-1); |
| 1747 | } |
| 1748 | if (praatP.foundTheSendSwitch) { |
| 1749 | MelderInfo_open (); |
| 1750 | MelderInfo_writeLine (U"The switch --send (or --new-send) is not compatible with running Praat interactively from the command line.", U"\n"); |
| 1751 | printHelp (); |
| 1752 | MelderInfo_close (); |
| 1753 | exit (-1); |
| 1754 | } |
| 1755 | if (praatP.foundTheSendOrFormSwitch) { |
| 1756 | MelderInfo_open (); |
| 1757 | MelderInfo_writeLine (U"The switch --send-form (or --new-send-form) is not compatible with running Praat interactively from the command line.", U"\n"); |
| 1758 | printHelp (); |
| 1759 | MelderInfo_close (); |
| 1760 | exit (-1); |
| 1761 | } |
| 1762 | if (thereIsAFileNameInTheArgumentList) { |
| 1763 | MelderInfo_open (); |
| 1764 | MelderInfo_writeLine (U"Having a file name is not compatible with running Praat interactively from the command line.", U"\n"); |
| 1765 | printHelp (); |
| 1766 | MelderInfo_close (); |
| 1767 | exit (-1); |
| 1768 | } |
| 1769 | Melder_assert (! praatP.userWantsToOpen); |
| 1770 | Melder_assert (! praatP.userWantsExistingInstance); |
| 1771 | } |
| 1772 | } |
| 1773 | |
| 1774 | static void setPreferencesFolder () { |
| 1775 | /* |
| 1776 | Get the app's preferences folder (if not yet set by the --pref-dir option): |
| 1777 | in Praat 6: |
| 1778 | "/home/miep/.praat-dir" (Linux) |
| 1779 | "/Users/miep/Library/Preferences/Praat Prefs" (Mac) |
| 1780 | "C:\Users\Miep\Praat" (Windows) |
| 1781 | in Praat 7: |
| 1782 | $XDG_CONFIG_HOME/praat or else "/home/miep/.config/praat" (Linux) |
| 1783 | "/Users/miep/Library/Application Support/Praat" (Mac) |
| 1784 | "C:\Users\Miep\AppData\Roaming\Praat" (Windows) |
| 1785 | and construct a preferences-file name and a script-buttons-file name like |
| 1786 | /home/miep/.praat-dir/prefs5 |
| 1787 | /home/miep/.praat-dir/buttons5 |
| 1788 | /home/miep/.config/praat/Preferences.txt |
| 1789 | /home/miep/.config/praat/Buttons.txt |
| 1790 | or |
| 1791 | /Users/miep/Library/Preferences/Praat Prefs/Prefs5 |
| 1792 | /Users/miep/Library/Preferences/Praat Prefs/Buttons5 |
| 1793 | /Users/miep/Library/Application Support/Praat/Preferences.txt |
| 1794 | /Users/miep/Library/Application Support/Praat/Buttons.txt |
| 1795 | or |
| 1796 | C:\Users\Miep\Praat\Preferences5.ini |
| 1797 | C:\Users\Miep\Praat\Buttons5.ini |
| 1798 | C:\Users\Miep\AppData\Roaming\Praat\Preferences.txt |
| 1799 | C:\Users\Miep\AppData\Roaming\Praat\Buttons.txt |
| 1800 | Also create names for message and tracing files. |
| 1801 | |
| 1802 | Platform-dependently preferred cache location: |
| 1803 | - same as prefs folder (Mac, Windows) |
| 1804 | - $XDG_CACHE_HOME/praat or else /home/miep/.cache/praat (Linux) |
| 1805 | Platform-dependently preferred log file location: |
| 1806 | - same as prefs folder (Mac, Windows) |
| 1807 | - $XDG_STATE_HOME/praat or else /home/miep/.local/state/praat (Linux) |
| 1808 | Platform-dependently preferred data file location: |
| 1809 | - same as prefs folder (Mac, Windows) |
| 1810 | - $XDG_DATA_HOME/praat or else /home/miep/.local/share/praat (Linux) |
| 1811 | Platform-dependently preferred message file location: |
| 1812 | - same as prefs folder (Mac, Windows) |
| 1813 | - $XDG_RUNTIME_DIR/praat (Linux, access mode 0700) |
| 1814 | */ |
| 1815 | if (MelderFolder_isNull (Melder_preferencesFolder())) { // not yet set by the --pref-dir option? |
| 1816 | try { |
| 1817 | Melder_setPreferencesFolder (MelderFolder_peekPath (Melder_preferencesFolder7())); |
| 1818 | MelderFolder_create (Melder_preferencesFolder()); // only version 7 has to be created |
| 1819 | } catch (MelderError) { |
| 1820 | /* |
| 1821 | If we arrive here, the directory could not be created, |
| 1822 | and all the files are null. Praat should nevertheless start up. |
| 1823 | */ |
| 1824 | Melder_clearError (); |
| 1825 | } |
| 1826 | } |
| 1827 | if (! MelderFolder_isNull (Melder_preferencesFolder())) { |
| 1828 | /* |
| 1829 | All the version-5 and version-7 paths. |
| 1830 | The version-5 paths will have to be remembered and accessed even in version 7. |
| 1831 | */ |
| 1832 | #if defined (UNIX) |
| 1833 | MelderFolder_getFile (Melder_preferencesFolder5(), U"prefs5", & prefsFile5); |
| 1834 | MelderFolder_getFile (Melder_preferencesFolder5(), U"buttons5", & buttonsFile5); |
| 1835 | #elif defined (_WIN32) |
| 1836 | MelderFolder_getFile (Melder_preferencesFolder5(), U"Preferences5.ini", & prefsFile5); |
| 1837 | MelderFolder_getFile (Melder_preferencesFolder5(), U"Buttons5.ini", & buttonsFile5); |
| 1838 | #elif defined (macintosh) |
| 1839 | MelderFolder_getFile (Melder_preferencesFolder5(), U"Prefs5", & prefsFile5); |
| 1840 | MelderFolder_getFile (Melder_preferencesFolder5(), U"Buttons5", & buttonsFile5); |
| 1841 | #endif |
| 1842 | /* |
| 1843 | All the version-7 paths. |
| 1844 | It cannot hurt that they are already known in version 6. |
| 1845 | */ |
| 1846 | MelderFolder_getFile (Melder_preferencesFolder7(), U"Preferences.txt", & prefsFile7); |
| 1847 | MelderFolder_getFile (Melder_preferencesFolder7(), U"Buttons.txt", & buttonsFile7); |
| 1848 | MelderFolder_getFile (Melder_preferencesFolder7(), U"Tracing.txt", & tracingFile); |
| 1849 | MelderFolder_getFile (Melder_preferencesFolder7(), U"Message.txt", & messageFile); |
| 1850 | #if defined (UNIX) |
| 1851 | MelderFolder_getFile (Melder_preferencesFolder7(), U"pid.txt", & pidFile); |
| 1852 | #endif |
| 1853 | Melder_tracingToFile (& tracingFile); |
| 1854 | } |
| 1855 | } |
| 1856 | |
| 1857 | void praat_init (conststring32 title, |
| 1858 | conststring32 versionText, integer versionNumber, |
| 1859 | integer year, integer month, integer day, |
| 1860 | conststring32 firstPartOfEmailAddress, conststring32 secondPartOfEmailAddress, |
| 1861 | int argc, char **argv |
| 1862 | ) { |
| 1863 | setThePraatLocale (); |
| 1864 | Melder_init (); |
| 1865 | const bool weWereStartedFromTheCommandLine = tryToAttachToTheCommandLine (); |
| 1866 | MelderConsole_init (); |
| 1867 | |
| 1868 | /* |
| 1869 | Construct a main-window title like "Praat". |
| 1870 | Construct an app name like "praat" for file and folder names. |
| 1871 | */ |
| 1872 | Melder_setAppName (title && title [0] != U'\0' ? title : U"Praat"); |
| 1873 | Melder_setAppVersion (versionText, versionNumber); |
| 1874 | Melder_setAppDate (year, month, day); |
| 1875 | Melder_setAppContactAddress (firstPartOfEmailAddress, secondPartOfEmailAddress); |
| 1876 | |
| 1877 | /* |
| 1878 | Get the home folder, e.g. "/home/miep/", or "/Users/miep/", or just "/". |
| 1879 | */ |
| 1880 | Melder_getHomeDir (& homeDir); |
| 1881 | |
| 1882 | interpretCommandLineArguments (weWereStartedFromTheCommandLine, argc, argv); |
| 1883 | |
| 1884 | setPreferencesFolder (); |
| 1885 | |
| 1886 | /* |
| 1887 | Remember the current directory. Useful only for scripts run from batch. |
| 1888 | */ |
| 1889 | Melder_rememberShellDirectory (); |
| 1890 | |
| 1891 | installPraatShellPreferences (); |
| 1892 | |
| 1893 | theCurrentPraatApplication -> batch = Melder_batch; |
| 1894 | |
| 1895 | #if defined (NO_GUI) |
| 1896 | if (! Melder_batch) { |
| 1897 | fprintf (Melder_stderr, "A no-GUI edition of Praat cannot be used interactively. " |
| 1898 | "Supply \"--run\" and a script file name on the command line.\n"); |
| 1899 | exit (1); |
| 1900 | } |
| 1901 | #endif |
| 1902 | |
| 1903 | /* |
| 1904 | Check whether we can transfer control to an already running instance of Praat. |
| 1905 | */ |
| 1906 | #if defined (macintosh) |
| 1907 | NSApplication *theApp = [GuiCocoaApplication sharedApplication]; // initialize, so that our bundle identifier exists even if we started from outside Xcode |
| 1908 | #elif defined (_WIN32) |
| 1909 | theWinApplicationWindow = GuiWin_initialize1 (Melder_upperCaseAppName()); |
| 1910 | #endif |
| 1911 | if (praatP.userWantsExistingInstance) |
| 1912 | if (tryToSwitchToRunningPraat (praatP.userWantsToOpen, praatP.userWantsToSend, praatP.userWantsToSendOrForm)) |
| 1913 | exit (0); |
| 1914 | |
| 1915 | #ifdef UNIX |
| 1916 | if (! Melder_batch) { |
| 1917 | /* |
| 1918 | Write our process id into the pid file. |
| 1919 | Messages from "sendpraat" are caught very early this way, |
| 1920 | though they will be responded to much later. |
| 1921 | */ |
| 1922 | try { |
| 1923 | autofile f = Melder_fopen (& pidFile, "w"); |
| 1924 | fprintf (f, "%td %td", integer (getpid ()), integer (Melder_appVersion())); |
| 1925 | f.close (& pidFile); |
| 1926 | } catch (MelderError) { |
| 1927 | Melder_clearError (); |
| 1928 | } |
| 1929 | } |
| 1930 | #endif |
| 1931 | #if defined (_WIN32) |
| 1932 | if (! Melder_batch) |
| 1933 | motif_win_setUserMessageCallback (cb_userMessage); |
| 1934 | #endif |
| 1935 | #if defined (macintosh) |
| 1936 | if (! Melder_batch) |
| 1937 | mac_setUserMessageCallback (cb_userMessage); // not earlier |
| 1938 | #endif |
| 1939 | Gui_setQuitApplicationCallback (cb_quitApplication); |
| 1940 | |
| 1941 | GuiWindow raam = nullptr; |
| 1942 | if (! Melder_batch) { |
| 1943 | trace (U"starting the GUI application"); |
| 1944 | Machine_initLookAndFeel (argc, argv); |
| 1945 | #if gtk |
| 1946 | trace (U"locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1947 | g_set_application_name (Melder_peek32to8 (title)); |
| 1948 | trace (U"locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1949 | #elif motif |
| 1950 | GuiWin_initialize2 (argc, argv); |
| 1951 | #elif cocoa |
| 1952 | /* |
| 1953 | We want to get rid of the Search field in the help menu. |
| 1954 | By default, such a Search field will come up automatically when we create a menu with the title "Help". |
| 1955 | By changing this title to "SomeFakeTitleOfAMenuThatWillNeverBeInstantiated", |
| 1956 | we trick macOS into thinking that our help menu is called "SomeFakeTitleOfAMenuThatWillNeverBeInstantiated". |
| 1957 | As a result, the Search field will come up only when we create a menu |
| 1958 | titled "SomeFakeTitleOfAMenuThatWillNeverBeInstantiated", which is never. |
| 1959 | */ |
| 1960 | theApp.helpMenu = [[NSMenu alloc] initWithTitle:@"SomeFakeTitleOfAMenuThatWillNeverBeInstantiated"]; |
| 1961 | #endif |
| 1962 | |
| 1963 | trace (U"creating and installing the Objects window"); |
| 1964 | char32 objectWindowTitle [100]; |
| 1965 | Melder_sprint (objectWindowTitle,100, Melder_upperCaseAppName(), U" Objects"); |
| 1966 | double x, y; |
| 1967 | trace (U"locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1968 | Gui_getWindowPositioningBounds (& x, & y, nullptr, nullptr); |
| 1969 | trace (U"locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1970 | theCurrentPraatApplication -> topShell = raam = GuiWindow_create (x + 10, y, WINDOW_WIDTH, WINDOW_HEIGHT, 450, 250, |
| 1971 | objectWindowTitle, gui_cb_quit, nullptr, 0); |
| 1972 | trace (U"locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1973 | #if motif |
| 1974 | GuiApp_setApplicationShell (theCurrentPraatApplication -> topShell -> d_xmShell); |
| 1975 | #endif |
| 1976 | trace (U"before objects window shows locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1977 | GuiThing_show (raam); |
| 1978 | trace (U"after objects window shows locale ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 1979 | } |
| 1980 | Thing_recognizeClassesByName (classCollection, classStrings, classManPages, classStringSet); |
| 1981 | Thing_recognizeClassByOtherName (classStringSet, U"SortedSetOfString"); |
| 1982 | if (Melder_batch) { |
| 1983 | Melder_backgrounding = true; |
| 1984 | trace (U"adding menus without GUI"); |
| 1985 | praat_addMenus (nullptr); |
| 1986 | trace (U"adding fixed buttons without GUI"); |
| 1987 | praat_addFixedButtons (nullptr); |
| 1988 | } else { |
| 1989 | #ifdef macintosh |
| 1990 | trace (U"initializing the Gui early (MacOS)"); |
| 1991 | AEInstallEventHandler (758934755, 0, (AEEventHandlerProcPtr) (mac_processSignal8), 0, false); // for receiving sendpraat |
| 1992 | injectMessageAndInformationProcs (raam); // BUG: default Melder_assert would call printf recursively!!! |
| 1993 | #endif |
| 1994 | trace (U"creating the menu bar in the Objects window"); |
| 1995 | GuiWindow_addMenuBar (raam); |
| 1996 | praatP.menuBar = raam; |
| 1997 | praat_addMenus (praatP.menuBar); |
| 1998 | |
| 1999 | trace (U"creating the object list in the Objects window"); |
| 2000 | GuiLabel_createShown (raam, 3, -250, Machine_getMenuBarBottom () + 5, Machine_getMenuBarBottom () + 5 + Gui_LABEL_HEIGHT, U"Objects:", 0); |
| 2001 | praatList_objects = GuiList_create (raam, 0, -250, Machine_getMenuBarBottom () + 26, -100, true, U" Objects "); |
| 2002 | GuiList_setSelectionChangedCallback (praatList_objects, gui_cb_list_selectionChanged, nullptr); |
| 2003 | GuiThing_show (praatList_objects); |
| 2004 | praat_addFixedButtons (raam); |
| 2005 | |
| 2006 | trace (U"creating the dynamic menu in the Objects window"); |
| 2007 | praat_actions_createDynamicMenu (raam); |
| 2008 | trace (U"showing the Objects window"); |
| 2009 | GuiThing_show (raam); |
| 2010 | #ifdef UNIX |
| 2011 | if (! praatP.ignorePreferenceFiles) { |
| 2012 | /* |
| 2013 | TODO: explain why this is needed here. |
| 2014 | could have to do with e.g. the font size setting in praat_picture_init, though that shoudl also be handlable by praat_picture_prefsChanged |
| 2015 | or don't Graphics_setFontSize and/or Picture_setMouseSelectsInnerViewport work in that situation? |
| 2016 | */ |
| 2017 | Preferences_read_i (& prefsFile5); // Read the old settings first... |
| 2018 | Preferences_read_i (& prefsFile7); // ... and the new settings second. |
| 2019 | } |
| 2020 | #endif |
| 2021 | #if ! defined (macintosh) |
| 2022 | trace (U"initializing the Gui late (Windows and Linux)"); |
| 2023 | injectMessageAndInformationProcs (theCurrentPraatApplication -> topShell); // Mac: done this earlier |
| 2024 | #endif |
| 2025 | Melder_setHelpProc (helpProc); |
| 2026 | } |
| 2027 | Data_setPublishProc (publishProc); |
| 2028 | theCurrentPraatApplication -> manPages = ManPages_create ().releaseToAmbiguousOwner(); |
| 2029 | |
| 2030 | trace (U"creating the Picture window"); |
| 2031 | trace (U"before picture window shows: locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2032 | if (! praatP.dontUsePictureWindow) |
| 2033 | praat_picture_init (! praatP.commandLineOptions.hidePicture); |
| 2034 | trace (U"after picture window shows: locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2035 | } |
| 2036 | |
| 2037 | static void executeStartUpFile (MelderFolder startUpDirectory, conststring32 fileNameHead, conststring32 fileNameTail) { |
| 2038 | char32 name [256]; |
| 2039 | Melder_sprint (name,256, fileNameHead, Melder_lowerCaseAppName(), fileNameTail); |
| 2040 | if (! MelderFolder_isNull (startUpDirectory)) { // should not occur on modern systems |
| 2041 | structMelderFile startUp { }; |
| 2042 | MelderFolder_getFile (startUpDirectory, name, & startUp); |
| 2043 | if (! MelderFile_readable (& startUp)) |
| 2044 | return; // it's OK if the file doesn't exist |
| 2045 | try { |
| 2046 | praat_executeScript_noGUI (& startUp, false); |
| 2047 | } catch (MelderError) { |
| 2048 | Melder_flushError (Melder_upperCaseAppName(), U": start-up file ", & startUp, U" not completed."); |
| 2049 | } |
| 2050 | } |
| 2051 | } |
| 2052 | |
| 2053 | #if gtk |
| 2054 | #include <gdk/gdkkeysyms.h> |
| 2055 | static gint theKeySnooper (GtkWidget *widget, GdkEventKey *event, gpointer data) { |
| 2056 | trace (U"keyval ", event -> keyval, U", type ", event -> type); |
| 2057 | if ((event -> keyval == GDK_KEY_Tab || event -> keyval == GDK_KEY_ISO_Left_Tab) && event -> type == GDK_KEY_PRESS) { |
| 2058 | using TabCallback = void (*) (GuiObject, gpointer); |
| 2059 | trace (U"tab key pressed in window ", Melder_pointer (widget)); |
| 2060 | constexpr bool theTabKeyShouldWorkEvenIfNumLockIsOn = true; |
| 2061 | constexpr uint32 theProbableNumLockModifierMask = GDK_MOD2_MASK; |
| 2062 | constexpr uint32 modifiersToIgnore = ( theTabKeyShouldWorkEvenIfNumLockIsOn ? theProbableNumLockModifierMask : 0 ); |
| 2063 | constexpr uint32 modifiersNotToIgnore = GDK_MODIFIER_MASK & ~ modifiersToIgnore; |
| 2064 | if ((event -> state & modifiersNotToIgnore) == 0) { |
| 2065 | if (GTK_IS_WINDOW (widget)) { |
| 2066 | GtkWidget *shell = gtk_widget_get_toplevel (GTK_WIDGET (widget)); |
| 2067 | trace (U"tab pressed in GTK window ", Melder_pointer (shell)); |
| 2068 | TabCallback tabCallback = (TabCallback) g_object_get_data (G_OBJECT (widget), "tabCallback"); |
| 2069 | if (tabCallback) { |
| 2070 | trace (U"a tab callback exists"); |
| 2071 | void *tabClosure = g_object_get_data (G_OBJECT (widget), "tabClosure"); |
| 2072 | tabCallback (widget, tabClosure); |
| 2073 | return true; |
| 2074 | } |
| 2075 | } |
| 2076 | } else if ((event -> state & modifiersNotToIgnore) == GDK_SHIFT_MASK) { |
| 2077 | if (GTK_IS_WINDOW (widget)) { |
| 2078 | GtkWidget *shell = gtk_widget_get_toplevel (GTK_WIDGET (widget)); |
| 2079 | trace (U"shift-tab pressed in GTK window ", Melder_pointer (shell)); |
| 2080 | TabCallback tabCallback = (TabCallback) g_object_get_data (G_OBJECT (widget), "shiftTabCallback"); |
| 2081 | if (tabCallback) { |
| 2082 | trace (U"a shift tab callback exists"); |
| 2083 | void *tabClosure = g_object_get_data (G_OBJECT (widget), "shiftTabClosure"); |
| 2084 | tabCallback (widget, tabClosure); |
| 2085 | return true; |
| 2086 | } |
| 2087 | } |
| 2088 | } |
| 2089 | } |
| 2090 | trace (U"end"); |
| 2091 | return false; // pass event on |
| 2092 | } |
| 2093 | #endif |
| 2094 | |
| 2095 | void praat_run () { |
| 2096 | trace (U"adding menus, second round"); |
| 2097 | praat_addMenus2 (); |
| 2098 | trace (U"locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2099 | |
| 2100 | trace (U"adding the Quit command"); |
| 2101 | praat_addMenuCommand (U"Objects", U"Praat", U"-- quit --", nullptr, 0, nullptr); |
| 2102 | praat_addMenuCommand (U"Objects", U"Praat", Melder_cat (U"Quit ", Melder_upperCaseAppName ()), nullptr, GuiMenu_UNHIDABLE | 'Q' | GuiMenu_NO_API, DO_Quit); |
| 2103 | praat_addMenuCommand (U"Objects", U"Praat", U"Quit", nullptr, GuiMenu_HIDDEN | GuiMenu_NO_API, DO_Quit); |
| 2104 | |
| 2105 | trace (U"read the preferences file, and notify those who want to be notified of this"); |
| 2106 | /* ...namely, those who already have a window (namely, the Picture window), |
| 2107 | * and those that regard the start of a new session as a meaningful event |
| 2108 | * (namely, the session counter and the cross-session memory counter). |
| 2109 | */ |
| 2110 | if (! praatP.ignorePreferenceFiles) { |
| 2111 | Preferences_read_i (& prefsFile5); // Read the old settings first... |
| 2112 | Preferences_read_i (& prefsFile7); // ... and the new settings second. |
| 2113 | if (! praatP.dontUsePictureWindow) |
| 2114 | praat_picture_prefsChanged (); |
| 2115 | praat_statistics_prefsChanged (); |
| 2116 | } |
| 2117 | |
| 2118 | praatP.phase = praat_STARTING_UP; |
| 2119 | |
| 2120 | trace (U"execute start-up file(s)"); |
| 2121 | /* |
| 2122 | On Unix and the Mac, we try no less than three start-up file names. |
| 2123 | */ |
| 2124 | if (Melder_appVersion() < 7000) { |
| 2125 | #if defined (UNIX) || defined (macintosh) |
| 2126 | structMelderFolder usrLocal { }; |
| 2127 | Melder_pathToFolder (U"/usr/local", & usrLocal); |
| 2128 | executeStartUpFile (& usrLocal, U"", U"-startUp"); |
| 2129 | #endif |
| 2130 | #if defined (UNIX) || defined (macintosh) |
| 2131 | executeStartUpFile (& homeDir, U".", U"-user-startUp"); // not on Windows (empty file name error) |
| 2132 | #endif |
| 2133 | #if defined (UNIX) || defined (macintosh) || defined (_WIN32) |
| 2134 | executeStartUpFile (& homeDir, U"", U"-user-startUp"); |
| 2135 | #endif |
| 2136 | } else { |
| 2137 | // use plug-ins instead |
| 2138 | } |
| 2139 | |
| 2140 | autoSTRVEC pluginFolderNames7, pluginFolderNames5; |
| 2141 | if (! MelderFolder_isNull (Melder_preferencesFolder7()) && ! praatP.ignorePlugins) { |
| 2142 | trace (U"initialize plug-ins (", MelderFolder_peekPath (Melder_preferencesFolder7()), U")"); |
| 2143 | trace (U"locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2144 | /* |
| 2145 | The Praat phase should remain praat_STARTING_UP, |
| 2146 | because any added commands must not be included in the buttons file. |
| 2147 | In plug-ins, pause windows should therefore be made modal. |
| 2148 | */ |
| 2149 | structMelderFile searchPattern { }; |
| 2150 | MelderFolder_getFile (Melder_preferencesFolder7(), U"plugin_*", & searchPattern); |
| 2151 | try { |
| 2152 | pluginFolderNames7 = folderNames_STRVEC (MelderFile_peekPath (& searchPattern)); |
| 2153 | for (integer i = 1; i <= pluginFolderNames7.size; i ++) { |
| 2154 | structMelderFolder pluginFolder { }; |
| 2155 | structMelderFile plugin { }; |
| 2156 | MelderFolder_getSubfolder (Melder_preferencesFolder7(), pluginFolderNames7 [i].get(), & pluginFolder); |
| 2157 | MelderFolder_getFile (& pluginFolder, U"setup.praat", & plugin); |
| 2158 | if (MelderFile_readable (& plugin)) { |
| 2159 | Melder_backgrounding = true; |
| 2160 | try { |
| 2161 | praat_executeScript_noGUI (& plugin, false); |
| 2162 | } catch (MelderError) { |
| 2163 | Melder_flushError (Melder_upperCaseAppName(), U": plugin ", & plugin, U" contains an error."); |
| 2164 | } |
| 2165 | Melder_backgrounding = false; |
| 2166 | } |
| 2167 | } |
| 2168 | } catch (MelderError) { |
| 2169 | Melder_clearError (); // in case folderNames_STRVEC() threw an error |
| 2170 | } |
| 2171 | } |
| 2172 | if (! MelderFolder_isNull (Melder_preferencesFolder5()) && ! praatP.ignorePlugins) { |
| 2173 | trace (U"initialize plug-ins (", MelderFolder_peekPath (Melder_preferencesFolder5()), U")"); |
| 2174 | trace (U"locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2175 | /* |
| 2176 | The Praat phase should remain praat_STARTING_UP, |
| 2177 | because any added commands must not be included in the buttons file. |
| 2178 | In plug-ins, pause windows should therefore be made modal. |
| 2179 | */ |
| 2180 | structMelderFile searchPattern { }; |
| 2181 | MelderFolder_getFile (Melder_preferencesFolder5(), U"plugin_*", & searchPattern); |
| 2182 | try { |
| 2183 | pluginFolderNames5 = folderNames_STRVEC (MelderFile_peekPath (& searchPattern)); |
| 2184 | for (integer i = 1; i <= pluginFolderNames5.size; i ++) { |
| 2185 | if (NUMfindFirst (pluginFolderNames7.get(), pluginFolderNames5 [i].get()) != 0) { |
| 2186 | /* |
| 2187 | Ignore this plugin, because it has already been installed. |
| 2188 | */ |
| 2189 | Melder_casual (U"Plugin “", pluginFolderNames5 [i].get(), U"” occurs both in “", |
| 2190 | MelderFolder_peekPath (Melder_preferencesFolder7()), U"” and in “", MelderFolder_peekPath (Melder_preferencesFolder5()), |
| 2191 | U"”; only the former is installed." |
| 2192 | ); |
| 2193 | } else { |
| 2194 | structMelderFolder pluginFolder { }; |
| 2195 | structMelderFile plugin { }; |
| 2196 | MelderFolder_getSubfolder (Melder_preferencesFolder5(), pluginFolderNames5 [i].get(), & pluginFolder); |
| 2197 | MelderFolder_getFile (& pluginFolder, U"setup.praat", & plugin); |
| 2198 | if (MelderFile_readable (& plugin)) { |
| 2199 | Melder_backgrounding = true; |
| 2200 | try { |
| 2201 | praat_executeScript_noGUI (& plugin, false); |
| 2202 | } catch (MelderError) { |
| 2203 | Melder_flushError (Melder_upperCaseAppName(), U": plugin ", & plugin, U" contains an error."); |
| 2204 | } |
| 2205 | Melder_backgrounding = false; |
| 2206 | } |
| 2207 | } |
| 2208 | } |
| 2209 | } catch (MelderError) { |
| 2210 | Melder_clearError (); // in case folderNames_STRVEC() threw an error |
| 2211 | } |
| 2212 | } |
| 2213 | |
| 2214 | /* |
| 2215 | Check the locale, to ensure identical behaviour on all computers. |
| 2216 | */ |
| 2217 | Melder_assert (str32equ (Melder_double (1.5), U"1.5")); // check locale settings; because of the required file portability Praat cannot stand "1,5" |
| 2218 | Melder_assert (Melder_isHorizontalOrVerticalSpace (' ')); |
| 2219 | Melder_assert (Melder_isHorizontalOrVerticalSpace ('\r')); |
| 2220 | Melder_assert (Melder_isHorizontalOrVerticalSpace ('\n')); |
| 2221 | Melder_assert (Melder_isHorizontalOrVerticalSpace ('\t')); |
| 2222 | Melder_assert (Melder_isHorizontalOrVerticalSpace ('\f')); |
| 2223 | Melder_assert (Melder_isHorizontalOrVerticalSpace ('\v')); |
| 2224 | |
| 2225 | { |
| 2226 | double *a = nullptr; |
| 2227 | double *b = & a [0]; |
| 2228 | Melder_assert (! b); |
| 2229 | } |
| 2230 | |
| 2231 | /* |
| 2232 | According to ISO 30112, a non-breaking space is not a space. |
| 2233 | We do not agree, as long as spaces are assumed to be word breakers: |
| 2234 | non-breaking spaces are used to prevent line breaks, not to prevent word breaks. |
| 2235 | For instance, in English it's possible to insert a non-breaking space |
| 2236 | after "e.g." in "...take drastic measures, e.g. pose a ban on...", |
| 2237 | just because otherwise a line would end in a period that does not signal end of sentence; |
| 2238 | this use does not mean that "e.g." and "pose" aren't separate words. |
| 2239 | */ |
| 2240 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_NO_BREAK_SPACE)); |
| 2241 | |
| 2242 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_OGHAM_SPACE_MARK)); // ISO 30112 |
| 2243 | |
| 2244 | /* |
| 2245 | According to ISO 30112, a Mongolian vowel separator is a space. |
| 2246 | However, this character is used to separate vowels *within* a word, |
| 2247 | so it should not be a word breaker. |
| 2248 | This means that as long as all spaces are assumed to be word breakers, |
| 2249 | this character cannot be a space. |
| 2250 | */ |
| 2251 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_MONGOLIAN_VOWEL_SEPARATOR)); |
| 2252 | |
| 2253 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_EN_QUAD)); // ISO 30112 |
| 2254 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_EM_QUAD)); // ISO 30112 |
| 2255 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_EN_SPACE)); // ISO 30112 |
| 2256 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_EM_SPACE)); // ISO 30112 |
| 2257 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_THREE_PER_EM_SPACE)); // ISO 30112 |
| 2258 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_FOUR_PER_EM_SPACE)); // ISO 30112 |
| 2259 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_SIX_PER_EM_SPACE)); // ISO 30112 |
| 2260 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_FIGURE_SPACE)); // questionable |
| 2261 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_PUNCTUATION_SPACE)); // ISO 30112 |
| 2262 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_THIN_SPACE)); // ISO 30112 |
| 2263 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_HAIR_SPACE)); // ISO 30112 |
| 2264 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_ZERO_WIDTH_SPACE)); // questionable |
| 2265 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_ZERO_WIDTH_NON_JOINER)); |
| 2266 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_ZERO_WIDTH_JOINER)); |
| 2267 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_ZERO_WIDTH_NO_BREAK_SPACE)); // this is the byte-order mark! |
| 2268 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_LINE_SEPARATOR)); // ISO 30112 |
| 2269 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_PARAGRAPH_SEPARATOR)); // ISO 30112 |
| 2270 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_NARROW_NO_BREAK_SPACE)); |
| 2271 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_LEFT_TO_RIGHT_EMBEDDING)); |
| 2272 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_RIGHT_TO_LEFT_EMBEDDING)); |
| 2273 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_POP_DIRECTIONAL_FORMATTING)); |
| 2274 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_LEFT_TO_RIGHT_OVERRIDE)); |
| 2275 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_RIGHT_TO_LEFT_OVERRIDE)); |
| 2276 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_MEDIUM_MATHEMATICAL_SPACE)); // ISO 30112 |
| 2277 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_WORD_JOINER)); |
| 2278 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_FUNCTION_APPLICATION)); |
| 2279 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_INVISIBLE_TIMES)); |
| 2280 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_INVISIBLE_SEPARATOR)); |
| 2281 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_INHIBIT_SYMMETRIC_SWAPPING)); |
| 2282 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_ACTIVATE_SYMMETRIC_SWAPPING)); |
| 2283 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_INHIBIT_ARABIC_FORM_SHAPING)); |
| 2284 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_ACTIVATE_ARABIC_FORM_SHAPING)); |
| 2285 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_NATIONAL_DIGIT_SHAPES)); |
| 2286 | Melder_assert (! Melder_isHorizontalOrVerticalSpace (UNICODE_NOMINAL_DIGIT_SHAPES)); |
| 2287 | Melder_assert (Melder_isHorizontalOrVerticalSpace (UNICODE_IDEOGRAPHIC_SPACE)); // ISO 30112; occurs on Japanese computers |
| 2288 | |
| 2289 | { unsigned char dummy = 200; |
| 2290 | Melder_assert ((int) dummy == 200); |
| 2291 | } |
| 2292 | Melder_assert (integer_abs (-1000) == integer (1000)); |
| 2293 | { int dummy = 200; |
| 2294 | Melder_assert ((int) (signed char) dummy == -56); // bingeti8 relies on this |
| 2295 | Melder_assert ((int) (unsigned char) dummy == 200); |
| 2296 | Melder_assert ((double) dummy == 200.0); |
| 2297 | Melder_assert ((double) (signed char) dummy == -56.0); |
| 2298 | Melder_assert ((double) (unsigned char) dummy == 200.0); |
| 2299 | } |
| 2300 | { int64 dummy = 200; |
| 2301 | Melder_assert ((int) (signed char) dummy == -56); |
| 2302 | Melder_assert ((int) (unsigned char) dummy == 200); |
| 2303 | Melder_assert ((double) dummy == 200.0); |
| 2304 | Melder_assert ((double) (signed char) dummy == -56.0); |
| 2305 | Melder_assert ((double) (unsigned char) dummy == 200.0); |
| 2306 | } |
| 2307 | { uint16 dummy = 40000; |
| 2308 | Melder_assert ((int) (int16) dummy == -25536); // bingeti16 relies on this |
| 2309 | Melder_assert ((short) (int16) dummy == -25536); // bingete16 relies on this |
| 2310 | Melder_assert ((integer) dummy == 40000); // Melder_integer relies on this |
| 2311 | Melder_assert ((double) dummy == 40000.0); |
| 2312 | Melder_assert ((double) (int16) dummy == -25536.0); |
| 2313 | } |
| 2314 | { unsigned int dummy = 40000; |
| 2315 | Melder_assert ((int) (int16) dummy == -25536); |
| 2316 | Melder_assert ((short) (int16) dummy == -25536); |
| 2317 | Melder_assert ((integer) dummy == 40000); // Melder_integer relies on this |
| 2318 | Melder_assert ((double) dummy == 40000.0); |
| 2319 | Melder_assert ((double) (int16) dummy == -25536.0); |
| 2320 | } |
| 2321 | { |
| 2322 | int64 dummy = 1000000000000; |
| 2323 | if (! str32equ (Melder_integer (dummy), U"1000000000000")) |
| 2324 | Melder_crash (U"The number 1000000000000 is mistakenly written on this machine as ", dummy, U"."); |
| 2325 | } |
| 2326 | { uint32 dummy = 0xffffffff; |
| 2327 | Melder_assert ((int64) dummy == 4294967295LL); |
| 2328 | Melder_assert (str32equ (Melder_integer (dummy), U"4294967295")); |
| 2329 | Melder_assert (double (dummy) == 4294967295.0); |
| 2330 | } |
| 2331 | { double dummy = 3000000000.0; |
| 2332 | Melder_assert ((uint32) dummy == 3000000000); |
| 2333 | } |
| 2334 | { |
| 2335 | Melder_assert (Melder_length (U"hello") == 5); |
| 2336 | Melder_assert (str32ncmp (U"hellogoodbye", U"hellogee", 6) == 0); |
| 2337 | Melder_assert (str32ncmp (U"hellogoodbye", U"hellogee", 7) > 0); |
| 2338 | Melder_assert (str32str (U"hellogoodbye", U"ogo")); |
| 2339 | Melder_assert (! str32str (U"hellogoodbye", U"oygo")); |
| 2340 | } |
| 2341 | Melder_assert (isundef (undefined)); |
| 2342 | Melder_assert (isinf (1.0 / 0.0)); |
| 2343 | Melder_assert (isnan (0.0 / 0.0)); |
| 2344 | { |
| 2345 | double x = sqrt (-10.0); |
| 2346 | Melder_assert (isundef (x)); |
| 2347 | x = NUMsqrt_u (-10.0); |
| 2348 | Melder_assert (isundef (x)); |
| 2349 | } |
| 2350 | Melder_assert (isdefined (0.0)); |
| 2351 | Melder_assert (isdefined (1e300)); |
| 2352 | Melder_assert (isundef (double (1e160 * 1e160))); |
| 2353 | Melder_assert (isundef (pow (10.0, 330))); |
| 2354 | Melder_assert (isundef (0.0 / 0.0)); |
| 2355 | Melder_assert (isundef (1.0 / 0.0)); |
| 2356 | Melder_assert (undefined != undefined); |
| 2357 | Melder_assert (undefined - undefined != 0.0); |
| 2358 | Melder_assert ((1.0/0.0) == (1.0/0.0)); |
| 2359 | Melder_assert ((1.0/0.0) - (1.0/0.0) != 0.0); |
| 2360 | { |
| 2361 | /* |
| 2362 | Assumptions made in abcio.cpp: |
| 2363 | `frexp()` returns an infinity if its argument is an infinity, |
| 2364 | and not-a-number if its argument is not-a-number. |
| 2365 | */ |
| 2366 | int exponent; |
| 2367 | Melder_assert (isundef (frexp (HUGE_VAL, & exponent))); |
| 2368 | Melder_assert (isundef (frexp (0.0/0.0, & exponent))); |
| 2369 | Melder_assert (isundef (frexp (undefined, & exponent))); |
| 2370 | /* |
| 2371 | The following relies on the facts that: |
| 2372 | - positive infinity is not less than 1.0 (because it is greater than 1.0) |
| 2373 | - NaN is not less than 1.0 (because it is not ordered) |
| 2374 | |
| 2375 | Note: we cannot replace `! (... < 1.0)` with `... >= 1.0`, |
| 2376 | because `! (NaN < 1.0)` is true but `NaN >= 1.0` is false. |
| 2377 | */ |
| 2378 | Melder_assert (! (frexp (HUGE_VAL, & exponent) < 1.0)); |
| 2379 | Melder_assert (! (frexp (0.0/0.0, & exponent) < 1.0)); |
| 2380 | Melder_assert (! (frexp (undefined, & exponent) < 1.0)); |
| 2381 | } |
| 2382 | Melder_assert (str32equ (Melder_integer (1234567), U"1234567")); |
| 2383 | Melder_assert (str32equ (Melder_integer (-1234567), U"-1234567")); |
| 2384 | MelderColour notExplicitlyInitialized; |
| 2385 | Melder_assert (str32equ (Melder_colour (notExplicitlyInitialized), U"{0,0,0}")); |
| 2386 | Melder_assert (str32equ (Melder_colour (MelderColour (0.25, 0.50, 0.875)), U"{0.25,0.5,0.875}")); |
| 2387 | { |
| 2388 | VEC xn; // "uninitialized", but initializes x.cells to nullptr and x.size to 0 |
| 2389 | Melder_assert (! xn.cells); |
| 2390 | Melder_assert (xn.size == 0); |
| 2391 | VEC xn2 = xn; // copy construction |
| 2392 | xn2 = xn; // copy assignment |
| 2393 | VEC x { }; |
| 2394 | Melder_assert (! x.cells); |
| 2395 | Melder_assert (x.size == 0); |
| 2396 | constVEC xnc; // zero-initialized |
| 2397 | Melder_assert (! xnc.cells); |
| 2398 | Melder_assert (xnc.size == 0); |
| 2399 | constVEC xc { }; |
| 2400 | Melder_assert (! xc.cells); |
| 2401 | Melder_assert (xc.size == 0); |
| 2402 | MAT yn; |
| 2403 | Melder_assert (! yn.cells); |
| 2404 | Melder_assert (yn.nrow == 0); |
| 2405 | Melder_assert (yn.ncol == 0); |
| 2406 | MAT y { }; |
| 2407 | Melder_assert (! y.cells); |
| 2408 | Melder_assert (y.nrow == 0); |
| 2409 | Melder_assert (y.ncol == 0); |
| 2410 | //autoMAT z {y.cells,y.nrow,y.ncol}; // "No matching constructor for initialization of autoMAT" (2021-04-05) |
| 2411 | autoMAT a = autoMAT { }; |
| 2412 | Melder_assert (! a.cells); |
| 2413 | Melder_assert (a.nrow == 0); |
| 2414 | Melder_assert (a.ncol == 0); |
| 2415 | //a = z.move(); |
| 2416 | //double q [11]; |
| 2417 | //autoVEC s { & q [1], 10 }; // "No matching constructor for initialization of autoVEC" (2021-04-05) |
| 2418 | //autoVEC b { x }; // "No matching constructor for initialization of autoVEC" (2021-04-05) |
| 2419 | //autoVEC c = x; // "No viable conversion from VEC to autoVEC" (2021-04-05) |
| 2420 | double aa [] = { 3.14, 2.717999999999999971578290569595992565155029296875 }; // the second number is 765048986699563 / 2^48 |
| 2421 | VEC x3 (aa, 2); // initializes x3 to 2 values from a base-0 array |
| 2422 | Melder_assert (x3 [2] == 2.717999999999999971578290569595992565155029296875); |
| 2423 | autoVEC x4 = { 3.14, 2.717999999999999971578290569595992565155029296875 }; |
| 2424 | Melder_assert (x4 [2] == 2.717999999999999971578290569595992565155029296875); |
| 2425 | } |
| 2426 | Melder_assert (Melder_iroundUpToPowerOfTwo (-10) == 1); |
| 2427 | Melder_assert (Melder_iroundUpToPowerOfTwo (-1) == 1); |
| 2428 | Melder_assert (Melder_iroundUpToPowerOfTwo (0) == 1); |
| 2429 | Melder_assert (Melder_iroundUpToPowerOfTwo (1) == 1); |
| 2430 | Melder_assert (Melder_iroundUpToPowerOfTwo (2) == 2); |
| 2431 | Melder_assert (Melder_iroundUpToPowerOfTwo (3) == 4); |
| 2432 | Melder_assert (Melder_iroundUpToPowerOfTwo (4) == 4); |
| 2433 | Melder_assert (Melder_iroundUpToPowerOfTwo (5) == 8); |
| 2434 | Melder_assert (Melder_iroundUpToPowerOfTwo (6) == 8); |
| 2435 | Melder_assert (Melder_iroundUpToPowerOfTwo (7) == 8); |
| 2436 | Melder_assert (Melder_iroundUpToPowerOfTwo (8) == 8); |
| 2437 | Melder_assert (Melder_iroundUpToPowerOfTwo (9) == 16); |
| 2438 | Melder_assert (Melder_iroundUpToPowerOfTwo (44100) == 65536); |
| 2439 | Melder_assert (Melder_iroundUpToPowerOfTwo (131071) == 131072); |
| 2440 | Melder_assert (Melder_iroundUpToPowerOfTwo (131072) == 131072); |
| 2441 | Melder_assert (Melder_iroundUpToPowerOfTwo (131073) == 262144); |
| 2442 | if constexpr (sizeof (integer) == 4) { |
| 2443 | Melder_assert (Melder_iroundUpToPowerOfTwo (1073741823) == 1073741824); // 2^30 - 1 |
| 2444 | Melder_assert (Melder_iroundUpToPowerOfTwo (1073741824) == 1073741824); // 2^30 |
| 2445 | Melder_assert (Melder_iroundUpToPowerOfTwo (1073741825) == 0); // 2^30 + 1 |
| 2446 | Melder_assert (Melder_iroundUpToPowerOfTwo (2147483647) == 0); // 2^31 - 1, i.e. INTEGER_MAX |
| 2447 | } else { |
| 2448 | Melder_assert (Melder_iroundUpToPowerOfTwo (4611686018427387903LL) == 4611686018427387904LL); // 2^62 - 1 |
| 2449 | Melder_assert (Melder_iroundUpToPowerOfTwo (4611686018427387904LL) == 4611686018427387904LL); // 2^62 |
| 2450 | Melder_assert (Melder_iroundUpToPowerOfTwo (4611686018427387905LL) == 0); // 2^62 + 1 |
| 2451 | Melder_assert (Melder_iroundUpToPowerOfTwo (9223372036854775807LL) == 0); // 2^63 - 1, i.e. INTEGER_MAX |
| 2452 | } |
| 2453 | Melder_assert (Melder_iroundUpToPowerOfTwo (4) == 4); |
| 2454 | { |
| 2455 | autoMAT mat = { { 10, 20, 30, 40 }, { 60, 70, 80, 90 }, { 170, 180, 190, -300 } }; |
| 2456 | Melder_assert (mat [1] [1] == 10.0); |
| 2457 | Melder_assert (mat [1] [4] == 40.0); |
| 2458 | Melder_assert (mat [2] [3] == 80.0); |
| 2459 | Melder_assert (mat [3] [1] == 170.0); |
| 2460 | Melder_assert (mat [3] [4] == -300.0); |
| 2461 | } |
| 2462 | static_assert (sizeof (float) == 4, |
| 2463 | "sizeof(float) should be 4"); |
| 2464 | static_assert (sizeof (double) == 8, |
| 2465 | "sizeof(double) should be 8"); |
| 2466 | static_assert (sizeof (longdouble) >= 8, |
| 2467 | "sizeof(longdouble) should be at least 8"); // this can be 8, 12 or 16 |
| 2468 | static_assert (sizeof (integer) == sizeof (void *), |
| 2469 | "sizeof(integer) should equal the size of a pointer"); |
| 2470 | static_assert (sizeof (off_t) >= 8, |
| 2471 | "sizeof(off_t) is less than 8. Compile Praat with -D_FILE_OFFSET_BITS=64."); |
| 2472 | |
| 2473 | /* |
| 2474 | Some libraries expect the definition of endian information. |
| 2475 | Check here at compile time that these are #defined, |
| 2476 | and check here at runtime that they have the correct value. |
| 2477 | */ |
| 2478 | #if ! defined (__BYTE_ORDER__) || ! defined (__ORDER_BIG_ENDIAN__) || ! defined (__ORDER_LITTLE_ENDIAN__) |
| 2479 | #if defined (_MSC_VER) |
| 2480 | #error On MSVC, define __ORDER_BIG_ENDIAN__=4321, __ORDER_LITTLE_ENDIAN__=1234, and __BYTE_ORDER__=1234 |
| 2481 | #else |
| 2482 | #error __BYTE_ORDER__, __ORDER_BIG_ENDIAN__ and __ORDER_LITTLE_ENDIAN__ should be #defined |
| 2483 | #endif |
| 2484 | #endif |
| 2485 | if (Melder_integersAreBigEndian()) |
| 2486 | Melder_assert (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__); |
| 2487 | else |
| 2488 | Melder_assert (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__); |
| 2489 | |
| 2490 | /* |
| 2491 | The type "integer" is defined as intptr_t, analogously to uinteger as uintptr_t |
| 2492 | (last checked 2024-08-18). |
| 2493 | However, the usual definition of an integer type that has 32 bits on 32-bit platforms |
| 2494 | and 64 bits on 64-bit platforms would be ptrdiff_t. |
| 2495 | Check that these definitions are the same. |
| 2496 | */ |
| 2497 | static_assert (sizeof (integer) == sizeof (ptrdiff_t), |
| 2498 | "sizeof(integer) should equal sizeof(ptrdiff_t)"); |
| 2499 | /* |
| 2500 | The format %td is designed for ptrdiff_t, and should therefore also work for our "integer" type, |
| 2501 | as "integer" has been defined as intptr_t, which we just checked is equivalent to ptrdiff_t. |
| 2502 | Check that %td indeed works correctly for "integer". |
| 2503 | */ |
| 2504 | { |
| 2505 | integer n1, n2; |
| 2506 | sscanf ("456789 -12345", "%td%td", & n1, & n2); |
| 2507 | Melder_assert (n1 == 456789 && n2 == -12345); |
| 2508 | } |
| 2509 | |
| 2510 | /* |
| 2511 | Check some assumptions about non-argument-evaluation during void tracing, |
| 2512 | and about the order of argument evaluation. |
| 2513 | */ |
| 2514 | { |
| 2515 | //TRACE |
| 2516 | int i = 0; |
| 2517 | trace (U"digits 1 to 9: ", ++ i, ++ i, ++ i, ++ i, ++ i, ++ i, ++ i, ++ i, ++ i); |
| 2518 | if (Melder_isTracingLocally || Melder_isTracingGlobally) |
| 2519 | Melder_assert (i == 9); |
| 2520 | else |
| 2521 | Melder_assert (i == 0); |
| 2522 | i = 0; |
| 2523 | trace (U"digits 1 to 9: ", i ++, i ++, i ++, i ++, i ++, i ++, i ++, i ++, i ++); |
| 2524 | if (Melder_isTracingLocally || Melder_isTracingGlobally) |
| 2525 | Melder_assert (i == 9); |
| 2526 | else |
| 2527 | Melder_assert (i == 0); |
| 2528 | char buffer [40]; |
| 2529 | i = 0; |
| 2530 | snprintf (buffer,40, "digits 1 to 9: %d%d%d%d%d%d%d%d%d", ++ i, ++ i, ++ i, ++ i, ++ i, ++ i, ++ i, ++ i, ++ i); |
| 2531 | Melder_assert (i == 9); |
| 2532 | trace (Melder_peek8to32_u (buffer)); |
| 2533 | i = 0; |
| 2534 | snprintf (buffer,40, "digits 1 to 9: %d%d%d%d%d%d%d%d%d", i ++, i ++, i ++, i ++, i ++, i ++, i ++, i ++, i ++); |
| 2535 | Melder_assert (i == 9); |
| 2536 | trace (Melder_peek8to32_u (buffer)); |
| 2537 | /* |
| 2538 | Results: trace and snprintf yield the same sequence as each other, on all systems we tested (last checked 2024-08-18) |
| 2539 | Pre-incrementing gives: |
| 2540 | 123456789 on Xcode, Msys Clang ARM64/Intel64/Intel32 |
| 2541 | preliminary generalization: all Clang |
| 2542 | 999999999 on Msys Gcc Intel64/Intel32, Cygwin Gcc Intel64/Intel32, Orb Ubuntu Gcc ARM64/Intel64, Raspberry Pi Gcc ARMv7, LinuxONE Gcc s390x |
| 2543 | preliminary generalization: all Gcc |
| 2544 | Post-incrementing gives: |
| 2545 | 012345678 on Xcode, Msys Clang ARM64/Intel64/Intel32, Orb Ubuntu Gcc ARM64, Raspberry Pi Gcc ARMv7, LinuxONE Gcc s390x |
| 2546 | preliminary generalization: all Clang, as well as all Gcc on anything else than Intel64/Intel32 |
| 2547 | 876543210 on Msys Gcc Intel64/32, Cygwin Gcc Intel64/Intel32, Orb Ubuntu Gcc Intel64 |
| 2548 | preliminary generalization: all Gcc on Intel64/Intel32 |
| 2549 | 000000000 on none yet |
| 2550 | A pleasing degree of variation! |
| 2551 | It's good to know that the order doesn't depend on whether the function is implemented in a recursive template (as trace) |
| 2552 | or in the C library (as snprintf). For instance, this means that even though the recursive-template implementation |
| 2553 | may look as though it evaluates from left to right, it doesn't necessarily do that. |
| 2554 | The bottom line is that for a given variable you can use only a single pre-increment or a single post-increment |
| 2555 | in any function call, even for the recursive templates of our own devising. |
| 2556 | */ |
| 2557 | } |
| 2558 | |
| 2559 | if (Melder_batch) { |
| 2560 | if (thePraatStandAloneScriptText) { |
| 2561 | try { |
| 2562 | praat_executeScriptFromText (thePraatStandAloneScriptText); // executed with full trust, because *we* made it |
| 2563 | praat_exit (0); |
| 2564 | } catch (MelderError) { |
| 2565 | Melder_flushError (Melder_upperCaseAppName(), U": stand-alone script session interrupted."); |
| 2566 | praat_exit (-1); |
| 2567 | } |
| 2568 | } else if (praatP.hasCommandLineInput) { |
| 2569 | try { |
| 2570 | praat_executeCommandFromStandardInput (Melder_upperCaseAppName()); |
| 2571 | praat_exit (0); |
| 2572 | } catch (MelderError) { |
| 2573 | Melder_flushError (Melder_upperCaseAppName(), U": command line session interrupted."); |
| 2574 | praat_exit (-1); |
| 2575 | } |
| 2576 | } else { |
| 2577 | try { |
| 2578 | #ifdef _WIN32 |
| 2579 | /* |
| 2580 | Our WinMain app cannot be a true console app when run from the Console. |
| 2581 | |
| 2582 | The following is what we expect from a console app: |
| 2583 | 1. After you enter `Praat.exe myScript.praat` into the Console, |
| 2584 | the Console should go to the next line, but show nothing else. |
| 2585 | 2. Any console output (i.e. output to stdout and stderr) should appear |
| 2586 | on this line and the next lines. |
| 2587 | 3. When Praat finishes, the Console should show the new prompt, |
| 2588 | like `C:\Users\Me\myFolder>`, on a new line. |
| 2589 | |
| 2590 | Instead, if we do nothing special here, Praat will do the following in the Console: |
| 2591 | 1. After you enter `Praat.exe myScript.praat`, the Console will immediately |
| 2592 | present the `C:\Users\Me\myFolder>` prompt again. We know of no way |
| 2593 | to change this behaviour, short of compiling Praat as a console app. |
| 2594 | 2. Any console output (i.e. output to stdout and stderr) will appear |
| 2595 | immediately after the `C:\Users\Me\myFolder>` prompt. |
| 2596 | 3. When Praat finishes, the Console will show no new prompt, because |
| 2597 | it has already shown a prompt (too early). A new prompt will appear |
| 2598 | only once you type the Enter key. |
| 2599 | |
| 2600 | The most important problem to repair is 3, because otherwise it will look |
| 2601 | as if Praat has not finished. So in Chunk 2 we fake an Enter. |
| 2602 | |
| 2603 | Problem 2 is repaired in Chunk 1 by sending a line to stderr (not stdout, |
| 2604 | because the line break should not end up in a file if redirected). |
| 2605 | The line that is sent should not be empty, because an empty line would suggest |
| 2606 | that Praat has finished, so we send a visible comment with hashes ("##########"). |
| 2607 | |
| 2608 | Our output will still look different from a real console app because of the extra |
| 2609 | prompt at the beginning (prepended to our comment) and perhaps the extra |
| 2610 | empty line that will appear now at the end of the output. |
| 2611 | (last checked 2022-10-12) |
| 2612 | |
| 2613 | Chunk 1 (sending a comment to stderr): |
| 2614 | */ |
| 2615 | HWND optionalConsoleWindowHandle = GetConsoleWindow (); |
| 2616 | if (optionalConsoleWindowHandle) |
| 2617 | Melder_casual (U" ########## Running Praat script ", theCurrentPraatApplication -> batchName.string); |
| 2618 | #endif |
| 2619 | praat_executeScriptFromCommandLine (theCurrentPraatApplication -> batchName.string, |
| 2620 | praatP.argc - praatP.argumentNumber, & praatP.argv [praatP.argumentNumber], praatP.fullTrust); |
| 2621 | #ifdef _WIN32 |
| 2622 | /* |
| 2623 | Chunk 2 (faking an Enter): |
| 2624 | */ |
| 2625 | if (optionalConsoleWindowHandle) |
| 2626 | PostMessage (optionalConsoleWindowHandle, WM_KEYDOWN, VK_RETURN, 0); |
| 2627 | |
| 2628 | FreeConsole (); // this may not do anything? (last checked 2022-10-12) |
| 2629 | #endif |
| 2630 | praat_exit (0); |
| 2631 | } catch (MelderError) { |
| 2632 | Melder_flushError (Melder_upperCaseAppName(), U": script command <<", |
| 2633 | theCurrentPraatApplication -> batchName.string, U">> not completed."); |
| 2634 | praat_exit (-1); |
| 2635 | } |
| 2636 | } |
| 2637 | } else /* GUI */ { |
| 2638 | if (! praatP.ignorePreferenceFiles) { |
| 2639 | trace (U"reading the added script buttons"); |
| 2640 | /* Each line separately: every error should be ignored. |
| 2641 | */ |
| 2642 | praatP.phase = praat_READING_BUTTONS; |
| 2643 | {// scope |
| 2644 | autostring32 buttons; |
| 2645 | try { |
| 2646 | if (MelderFile_readable (& buttonsFile7)) |
| 2647 | buttons = MelderFile_readText (& buttonsFile7); // first choice |
| 2648 | else |
| 2649 | buttons = MelderFile_readText (& buttonsFile5); // second choice; note: this will be converted to buttonsFile7 upon exit |
| 2650 | } catch (MelderError) { |
| 2651 | Melder_clearError (); // ignore if a buttons file doesn't exist |
| 2652 | } |
| 2653 | if (buttons) { |
| 2654 | char32 *line = buttons.get(); |
| 2655 | for (;;) { |
| 2656 | char32 *newline = str32chr (line, U'\n'); |
| 2657 | if (newline) *newline = U'\0'; |
| 2658 | try { |
| 2659 | (void) praat_executeCommand (nullptr, line); // should contain no cases of "nocheck" |
| 2660 | } catch (MelderError) { |
| 2661 | Melder_clearError (); // ignore this line, but not necessarily the next |
| 2662 | } |
| 2663 | if (! newline) |
| 2664 | break; |
| 2665 | line = newline + 1; |
| 2666 | } |
| 2667 | } |
| 2668 | } |
| 2669 | } |
| 2670 | |
| 2671 | trace (U"sorting the commands"); |
| 2672 | trace (U"locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2673 | praat_sortMenuCommands (); |
| 2674 | praat_sortActions (); |
| 2675 | |
| 2676 | praatP.phase = praat_HANDLING_EVENTS; |
| 2677 | |
| 2678 | if (praatP.userWantsToOpen) { |
| 2679 | /* |
| 2680 | praat --new-open [OPTION]... FILE-NAME... |
| 2681 | praat --open [OPTION]... FILE-NAME... (if not yet running) |
| 2682 | */ |
| 2683 | for (; praatP.argumentNumber < praatP.argc; praatP.argumentNumber ++) { |
| 2684 | autostring32 text = Melder_dup (Melder_cat (U"Read from file: ~", |
| 2685 | Melder_peek8to32_u (praatP.argv [praatP.argumentNumber]))); |
| 2686 | trace (U"Argument ", praatP.argumentNumber, U": <<", text.get(), U">>"); |
| 2687 | try { |
| 2688 | praat_executeScriptFromText (text.get()); // executed with full trust, because we just constructed the whole script |
| 2689 | } catch (MelderError) { |
| 2690 | Melder_flushError (); |
| 2691 | } |
| 2692 | } |
| 2693 | } else if (praatP.userWantsToSend) { |
| 2694 | /* |
| 2695 | praat --new-send [OPTION]... SCRIPT-FILE-NAME [SCRIPT-ARGUMENT]... |
| 2696 | praat --send [OPTION]... SCRIPT-FILE-NAME [SCRIPT-ARGUMENT]... (if not yet running) |
| 2697 | */ |
| 2698 | autoPraatBackground background; // to e.g. make audio synchronous |
| 2699 | try { |
| 2700 | praat_executeScriptFromCommandLine (theCurrentPraatApplication -> batchName.string, |
| 2701 | praatP.argc - praatP.argumentNumber, & praatP.argv [praatP.argumentNumber], praatP.fullTrust); |
| 2702 | } catch (MelderError) { |
| 2703 | Melder_flushError (); |
| 2704 | } |
| 2705 | } else if (praatP.userWantsToSendOrForm) { |
| 2706 | /* |
| 2707 | praat --new-send-or-form [OPTION]... SCRIPT-FILE-NAME |
| 2708 | praat --send-or-form [OPTION]... SCRIPT-FILE-NAME (if not yet running) |
| 2709 | */ |
| 2710 | autoPraatBackground background; // to e.g. make audio synchronous |
| 2711 | try { |
| 2712 | praat_runScriptWithForm (theCurrentPraatApplication -> batchName.string, praatP.fullTrust); |
| 2713 | } catch (MelderError) { |
| 2714 | Melder_flushError (); |
| 2715 | } |
| 2716 | } |
| 2717 | //TRACE |
| 2718 | trace (U"Before main event loop: ", Melder_stopwatch ()); |
| 2719 | |
| 2720 | #if gtk |
| 2721 | //gtk_widget_add_events (G_OBJECT (theCurrentPraatApplication -> topShell), GDK_ALL_EVENTS_MASK); |
| 2722 | trace (U"install GTK key snooper"); |
| 2723 | trace (U"locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2724 | //g_signal_newv ("SENDPRAAT", G_TYPE_FROM_CLASS (gobject_class), G_SIGNAL_RUN_LAST, NULL, NULL, NULL, NULL, G_TYPE_NONE, 0, NULL); |
| 2725 | g_signal_connect (G_OBJECT (theCurrentPraatApplication -> topShell -> d_gtkWindow), "property-notify-event", |
| 2726 | G_CALLBACK (cb_userMessage), nullptr); |
| 2727 | signal (SIGUSR1, cb_sigusr1); |
| 2728 | gtk_key_snooper_install (theKeySnooper, 0); |
| 2729 | trace (U"start the GTK event loop"); |
| 2730 | trace (U"locale is ", Melder_peek8to32_u (setlocale (LC_ALL, nullptr))); |
| 2731 | gtk_main (); |
| 2732 | #elif motif |
| 2733 | for (;;) { |
| 2734 | XEvent event; |
| 2735 | GuiNextEvent (& event); |
| 2736 | XtDispatchEvent (& event); |
| 2737 | } |
| 2738 | #elif cocoa |
| 2739 | [NSApp run]; |
| 2740 | #endif |
| 2741 | } |
| 2742 | } |
| 2743 | |
| 2744 | /* End of file praat.cpp */ |