| 1 | #ifndef _melder_warning_h_ |
| 2 | #define _melder_warning_h_ |
| 3 | /* melder_warning.h |
| 4 | * |
| 5 | * Copyright (C) 1992-2018,2025 Paul Boersma |
| 6 | * |
| 7 | * This code is free software; you can redistribute it and/or modify |
| 8 | * it under the terms of the GNU General Public License as published by |
| 9 | * the Free Software Foundation; either version 3 of the License, or (at |
| 10 | * your option) any later version. |
| 11 | * |
| 12 | * This code is distributed in the hope that it will be useful, but |
| 13 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 15 | * See the GNU General Public License for more details. |
| 16 | * |
| 17 | * You should have received a copy of the GNU General Public License |
| 18 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 19 | */ |
| 20 | |
| 21 | /* |
| 22 | SYNOPSIS (2018-08-08) |
| 23 | |
| 24 | Melder_warning (args...); |
| 25 | |
| 26 | Gives a warning to stderr (batch) or to a "Warning" dialog. |
| 27 | Use sparingly, because it interrupts the user's workflow. |
| 28 | */ |
| 29 | |
| 30 | namespace MelderWarning { |
| 31 | extern int _depth; |
| 32 | extern MelderString _buffer; |
| 33 | using Proc = void (*) (conststring32 message); |
| 34 | void _defaultProc (conststring32 message); |
| 35 | extern Proc _p_currentProc; |
| 36 | } |
| 37 | |
| 38 | template <typename... Arg> |
| 39 | void Melder_warning (const Arg... arg) { |
| 40 | if (MelderWarning::_depth < 0) |
| 41 | return; |
| 42 | MelderString_copy (& MelderWarning::_buffer, arg...); |
| 43 | (*MelderWarning::_p_currentProc) (MelderWarning::_buffer.string); |
| 44 | } |
| 45 | |
| 46 | void Melder_warningOff (); |
| 47 | void Melder_warningOn (); |
| 48 | |
| 49 | class autoMelderWarningOff { |
| 50 | public: |
| 51 | autoMelderWarningOff () { Melder_warningOff (); } |
| 52 | ~autoMelderWarningOff () { Melder_warningOn (); } |
| 53 | }; |
| 54 | |
| 55 | void Melder_setWarningProc (MelderWarning::Proc p_proc); |
| 56 | |
| 57 | //#define Melder_warning_once(...) \ |
| 58 | // do { static bool hasWarned = false; if (! hasWarned) { Melder_warning (__VA_ARGS__); hasWarned = true; } } while (0) |
| 59 | |
| 60 | template <int invocationSite> |
| 61 | struct MelderWarningOnce { |
| 62 | inline static std::once_flag flag; |
| 63 | }; |
| 64 | |
| 65 | template <int invocationSite, typename... Args> |
| 66 | inline void Melder_warning_once_template (Args&&... args) |
| 67 | { |
| 68 | std::call_once (MelderWarningOnce <invocationSite> :: flag, [&] { |
| 69 | Melder_warning (std::forward <Args> (args)...); |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | #define Melder_warning_once(...) Melder_warning_once_template <__COUNTER__> (__VA_ARGS__) |
| 74 | |
| 75 | #endif // !_melder_warning_h_ |