Class GLib

java.lang.Object
org.gnome.glib.GLib

@Generated("org.javagi.JavaGI") public final class GLib extends Object
Constants and functions that are declared in the global GLib namespace.
  • Field Details

    • ALLOCATOR_LIST

      @Deprecated public static final int ALLOCATOR_LIST
      Deprecated.
      See Also:
    • ALLOCATOR_NODE

      @Deprecated public static final int ALLOCATOR_NODE
      Deprecated.
      See Also:
    • ALLOCATOR_SLIST

      @Deprecated public static final int ALLOCATOR_SLIST
      Deprecated.
      See Also:
    • ALLOC_AND_FREE

      @Deprecated public static final int ALLOC_AND_FREE
      Deprecated.
      See Also:
    • ALLOC_ONLY

      @Deprecated public static final int ALLOC_ONLY
      Deprecated.
      See Also:
    • ANALYZER_ANALYZING

      public static final int ANALYZER_ANALYZING
      See Also:
    • ASCII_DTOSTR_BUF_SIZE

      public static final int ASCII_DTOSTR_BUF_SIZE

      A good size for a buffer to be passed into asciiDtostr(String, int, double). It is guaranteed to be enough for all output of that function on systems with 64bit IEEE-compatible doubles.

      The typical usage would be something like:

      char buf[G_ASCII_DTOSTR_BUF_SIZE];
      
      fprintf (out, "value=%s\\n", g_ascii_dtostr (buf, sizeof (buf), value));
      
      See Also:
    • ATOMIC_REF_COUNT_INIT

      public static final int ATOMIC_REF_COUNT_INIT

      Evaluates to the initial reference count for gatomicrefcount.

      This macro is useful for initializing gatomicrefcount fields inside structures, for instance:

      typedef struct {
        gatomicrefcount ref_count;
        char *name;
        char *address;
      } Person;
      
      static const Person default_person = {
        .ref_count = G_ATOMIC_REF_COUNT_INIT,
        .name = "Default name",
        .address = "Default address",
      };
      
      Since:
      2.78
      See Also:
    • BIG_ENDIAN

      public static final int BIG_ENDIAN
      Specifies one of the possible types of byte order. See G_BYTE_ORDER.
      See Also:
    • CSET_A_2_Z

      public static final String CSET_A_2_Z
      The set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters in GScannerConfig.
      See Also:
    • CSET_DIGITS

      public static final String CSET_DIGITS
      The set of ASCII digits. Used for specifying valid identifier characters in GScannerConfig.
      See Also:
    • CSET_a_2_z

      public static final String CSET_a_2_z
      The set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters in GScannerConfig.
      See Also:
    • C_STD_VERSION

      public static final int C_STD_VERSION

      The C standard version the code is compiling against, it's normally defined with the same value of __STDC_VERSION__ for C standard compatible compilers, while it uses the lowest standard version in pure MSVC, given that in such compiler the definition depends on a compilation flag.

      This is granted to be undefined when compiling with a C++ compiler.

      See also: G_C_STD_CHECK_VERSION and G_CXX_STD_VERSION

      Since:
      2.76
      See Also:
    • DATALIST_FLAGS_MASK

      public static final int DATALIST_FLAGS_MASK
      A bitmask that restricts the possible flags passed to g_datalist_set_flags(). Passing a flags value where flags & ~G_DATALIST_FLAGS_MASK != 0 is an error.
      See Also:
    • DATE_BAD_DAY

      public static final int DATE_BAD_DAY
      Represents an invalid GDateDay.
      See Also:
    • DATE_BAD_JULIAN

      public static final int DATE_BAD_JULIAN
      Represents an invalid Julian day number.
      See Also:
    • DATE_BAD_YEAR

      public static final int DATE_BAD_YEAR
      Represents an invalid year.
      See Also:
    • DIR_SEPARATOR

      public static final int DIR_SEPARATOR

      The directory separator character.

      This is '/' on UNIX machines and '\\' under Windows.

      See Also:
    • DIR_SEPARATOR_S

      public static final String DIR_SEPARATOR_S

      The directory separator as a string.

      This is "/" on UNIX machines and "\\" under Windows.

      See Also:
    • E

      public static final double E
      The base of natural logarithms.
      See Also:
    • GINT16_FORMAT

      public static final String GINT16_FORMAT
      See Also:
    • GINT16_MODIFIER

      public static final String GINT16_MODIFIER
      See Also:
    • GINT32_FORMAT

      public static final String GINT32_FORMAT
      See Also:
    • GINT32_MODIFIER

      public static final String GINT32_MODIFIER
      See Also:
    • GINT64_FORMAT

      public static final String GINT64_FORMAT
      See Also:
    • GINT64_MODIFIER

      public static final String GINT64_MODIFIER
      See Also:
    • GINTPTR_FORMAT

      public static final String GINTPTR_FORMAT
      See Also:
    • GINTPTR_MODIFIER

      public static final String GINTPTR_MODIFIER
      See Also:
    • GNUC_FUNCTION

      @Deprecated public static final String GNUC_FUNCTION
      Deprecated.
      Use G_STRFUNC() instead
      Expands to "" on all modern compilers, and to FUNCTION on gcc version 2.x. Don't use it.
      See Also:
    • GNUC_PRETTY_FUNCTION

      @Deprecated public static final String GNUC_PRETTY_FUNCTION
      Deprecated.
      Use G_STRFUNC() instead
      Expands to "" on all modern compilers, and to PRETTY_FUNCTION on gcc version 2.x. Don't use it.
      See Also:
    • GSIZE_FORMAT

      public static final String GSIZE_FORMAT
      See Also:
    • GSIZE_MODIFIER

      public static final String GSIZE_MODIFIER
      See Also:
    • GSSIZE_FORMAT

      public static final String GSSIZE_FORMAT
      See Also:
    • GSSIZE_MODIFIER

      public static final String GSSIZE_MODIFIER
      See Also:
    • GUINT16_FORMAT

      public static final String GUINT16_FORMAT
      See Also:
    • GUINT32_FORMAT

      public static final String GUINT32_FORMAT
      See Also:
    • GUINT64_FORMAT

      public static final String GUINT64_FORMAT
      See Also:
    • GUINTPTR_FORMAT

      public static final String GUINTPTR_FORMAT
      See Also:
    • HAVE_GINT64

      public static final int HAVE_GINT64
      See Also:
    • HAVE_GNUC_VARARGS

      public static final int HAVE_GNUC_VARARGS
      See Also:
    • HAVE_GNUC_VISIBILITY

      public static final int HAVE_GNUC_VISIBILITY
      Defined to 1 if gcc-style visibility handling is supported.
      See Also:
    • HAVE_GROWING_STACK

      public static final int HAVE_GROWING_STACK
      See Also:
    • HAVE_ISO_VARARGS

      public static final int HAVE_ISO_VARARGS
      See Also:
    • HOOK_FLAG_USER_SHIFT

      public static final int HOOK_FLAG_USER_SHIFT
      The position of the first bit which is not reserved for internal use be the GHook implementation, i.e. 1 << G_HOOK_FLAG_USER_SHIFT is the first bit which can be used for application-defined flags.
      See Also:
    • IEEE754_DOUBLE_BIAS

      public static final int IEEE754_DOUBLE_BIAS
      The bias by which exponents in double-precision floats are offset.
      See Also:
    • IEEE754_FLOAT_BIAS

      public static final int IEEE754_FLOAT_BIAS
      The bias by which exponents in single-precision floats are offset.
      See Also:
    • KEY_FILE_DESKTOP_GROUP

      public static final String KEY_FILE_DESKTOP_GROUP

      The name of the main group of a desktop entry file, as defined in the Desktop Entry Specification.

      Consult the specification for more details about the meanings of the keys below.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_ACTIONS

      public static final String KEY_FILE_DESKTOP_KEY_ACTIONS
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string list giving the available application actions.
      Since:
      2.38
      See Also:
    • KEY_FILE_DESKTOP_KEY_CATEGORIES

      public static final String KEY_FILE_DESKTOP_KEY_CATEGORIES
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the categories in which the desktop entry should be shown in a menu.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_COMMENT

      public static final String KEY_FILE_DESKTOP_KEY_COMMENT
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the tooltip for the desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE

      public static final String KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean set to true if the application is D-Bus activatable.
      Since:
      2.38
      See Also:
    • KEY_FILE_DESKTOP_KEY_EXEC

      public static final String KEY_FILE_DESKTOP_KEY_EXEC

      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the command line to execute.

      It is only valid for desktop entries with the Application type.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_GENERIC_NAME

      public static final String KEY_FILE_DESKTOP_KEY_GENERIC_NAME
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the generic name of the desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_HIDDEN

      public static final String KEY_FILE_DESKTOP_KEY_HIDDEN
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry has been deleted by the user.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_ICON

      public static final String KEY_FILE_DESKTOP_KEY_ICON
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the name of the icon to be displayed for the desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_MIME_TYPE

      public static final String KEY_FILE_DESKTOP_KEY_MIME_TYPE
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the MIME types supported by this desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_NAME

      public static final String KEY_FILE_DESKTOP_KEY_NAME
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the specific name of the desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN

      public static final String KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should not display the desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_NO_DISPLAY

      public static final String KEY_FILE_DESKTOP_KEY_NO_DISPLAY
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry should be shown in menus.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN

      public static final String KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should display the desktop entry.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_PATH

      public static final String KEY_FILE_DESKTOP_KEY_PATH

      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string containing the working directory to run the program in.

      It is only valid for desktop entries with the Application type.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY

      public static final String KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS

      public static final String KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is string identifying the WM class or name hint of a window that the application will create, which can be used to emulate Startup Notification with older applications.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_TERMINAL

      public static final String KEY_FILE_DESKTOP_KEY_TERMINAL

      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the program should be run in a terminal window.

      It is only valid for desktop entries with the Application type.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_TRY_EXEC

      public static final String KEY_FILE_DESKTOP_KEY_TRY_EXEC

      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the file name of a binary on disk used to determine if the program is actually installed.

      It is only valid for desktop entries with the Application type.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_TYPE

      public static final String KEY_FILE_DESKTOP_KEY_TYPE

      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the type of the desktop entry.

      Usually GLib.KEY_FILE_DESKTOP_TYPE_APPLICATION, GLib.KEY_FILE_DESKTOP_TYPE_LINK, or GLib.KEY_FILE_DESKTOP_TYPE_DIRECTORY.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_URL

      public static final String KEY_FILE_DESKTOP_KEY_URL

      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the URL to access.

      It is only valid for desktop entries with the Link type.

      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_KEY_VERSION

      public static final String KEY_FILE_DESKTOP_KEY_VERSION
      A key under GLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_TYPE_APPLICATION

      public static final String KEY_FILE_DESKTOP_TYPE_APPLICATION
      The value of the GLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing applications.
      Since:
      2.14
      See Also:
    • KEY_FILE_DESKTOP_TYPE_DIRECTORY

      public static final String KEY_FILE_DESKTOP_TYPE_DIRECTORY
      The value of the GLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing directories.
      Since:
      2.14
      See Also:
    • LITTLE_ENDIAN

      public static final int LITTLE_ENDIAN
      Specifies one of the possible types of byte order. See G_BYTE_ORDER.
      See Also:
    • LN10

      public static final double LN10
      The natural logarithm of 10.
      See Also:
    • LN2

      public static final double LN2
      The natural logarithm of 2.
      See Also:
    • LOG_2_BASE_10

      public static final double LOG_2_BASE_10
      Multiplying the base 2 exponent by this number yields the base 10 exponent.
      See Also:
    • LOG_DOMAIN

      public static final byte LOG_DOMAIN

      Defines the log domain. See Log Domains.

      Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.

      Log domains must be unique, and it is recommended that they are the application or library name, optionally followed by a hyphen and a sub-domain name. For example, bloatpad or bloatpad-io.

      If undefined, it defaults to the default null (or "") log domain; this is not advisable, as it cannot be filtered against using the G_MESSAGES_DEBUG environment variable.

      For example, GTK uses this in its Makefile.am:

      AM_CPPFLAGS = -DG_LOG_DOMAIN=\\"Gtk\\"
      

      Applications can choose to leave it as the default null (or "") domain. However, defining the domain offers the same advantages as above.

      See Also:
    • LOG_FATAL_MASK

      public static final int LOG_FATAL_MASK

      GLib log levels that are considered fatal by default.

      This is not used if structured logging is enabled; see Using Structured Logging.

      See Also:
    • LOG_LEVEL_USER_SHIFT

      public static final int LOG_LEVEL_USER_SHIFT
      Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib. Higher bits can be used for user-defined log levels.
      See Also:
    • MAJOR_VERSION

      public static final int MAJOR_VERSION

      The major version number of the GLib library.

      Like glib_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

      See Also:
    • MAXINT16

      public static final short MAXINT16
      See Also:
    • MAXINT32

      public static final int MAXINT32
      See Also:
    • MAXINT64

      public static final long MAXINT64
      See Also:
    • MAXINT8

      public static final byte MAXINT8
      See Also:
    • MAXUINT16

      public static final short MAXUINT16
      See Also:
    • MAXUINT32

      public static final int MAXUINT32
      See Also:
    • MAXUINT64

      public static final long MAXUINT64
      See Also:
    • MAXUINT8

      public static final byte MAXUINT8
      See Also:
    • MICRO_VERSION

      public static final int MICRO_VERSION

      The micro version number of the GLib library.

      Like gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

      See Also:
    • MININT16

      public static final short MININT16
      The minimum value which can be held in a gint16.
      Since:
      2.4
      See Also:
    • MININT32

      public static final int MININT32
      The minimum value which can be held in a gint32.
      Since:
      2.4
      See Also:
    • MININT64

      public static final long MININT64
      The minimum value which can be held in a gint64.
      See Also:
    • MININT8

      public static final byte MININT8
      The minimum value which can be held in a gint8.
      Since:
      2.4
      See Also:
    • MINOR_VERSION

      public static final int MINOR_VERSION

      The minor version number of the GLib library.

      Like gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

      See Also:
    • MODULE_SUFFIX

      public static final String MODULE_SUFFIX
      See Also:
    • NSEC_PER_SEC

      public static final long NSEC_PER_SEC
      Number of nanoseconds in one second (1 billion). This macro is provided for code readability.
      Since:
      2.88
      See Also:
    • OPTION_REMAINING

      public static final String OPTION_REMAINING

      If a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in argv. The option must be of type OptionArg.CALLBACK, OptionArg.STRING_ARRAY or OptionArg.FILENAME_ARRAY.

      Using G_OPTION_REMAINING instead of simply scanning argv for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.

      Since:
      2.6
      See Also:
    • PDP_ENDIAN

      public static final int PDP_ENDIAN
      Specifies one of the possible types of byte order (currently unused). See G_BYTE_ORDER.
      See Also:
    • PI

      public static final double PI
      The value of pi (ratio of circle's circumference to its diameter).
      See Also:
    • PID_FORMAT

      public static final String PID_FORMAT
      A format specifier that can be used in printf()-style format strings when printing a GPid.
      Since:
      2.50
      See Also:
    • PI_2

      public static final double PI_2
      Pi divided by 2.
      See Also:
    • PI_4

      public static final double PI_4
      Pi divided by 4.
      See Also:
    • POLLFD_FORMAT

      public static final String POLLFD_FORMAT
      A format specifier that can be used in printf()-style format strings when printing the fd member of a GPollFD.
      See Also:
    • PRIORITY_DEFAULT

      public static final int PRIORITY_DEFAULT

      Use this for default priority event sources.

      In GLib this priority is used when adding timeout functions with timeoutAdd(int, int, SourceFunc). In GDK this priority is used for events from the X server.

      See Also:
    • PRIORITY_DEFAULT_IDLE

      public static final int PRIORITY_DEFAULT_IDLE

      Use this for default priority idle functions.

      In GLib this priority is used when adding idle functions with idleAdd(int, SourceFunc).

      See Also:
    • PRIORITY_HIGH

      public static final int PRIORITY_HIGH

      Use this for high priority event sources.

      It is not used within GLib or GTK.

      See Also:
    • PRIORITY_HIGH_IDLE

      public static final int PRIORITY_HIGH_IDLE

      Use this for high priority idle functions.

      GTK uses G_PRIORITY_HIGH_IDLE + 10 for resizing operations, and G_PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is done to ensure that any pending resizes are processed before any pending redraws, so that widgets are not redrawn twice unnecessarily.)

      See Also:
    • PRIORITY_LOW

      public static final int PRIORITY_LOW

      Use this for very low priority background tasks.

      It is not used within GLib or GTK.

      See Also:
    • REF_COUNT_INIT

      public static final int REF_COUNT_INIT

      Evaluates to the initial reference count for grefcount.

      This macro is useful for initializing grefcount fields inside structures, for instance:

      typedef struct {
        grefcount ref_count;
        char *name;
        char *address;
      } Person;
      
      static const Person default_person = {
        .ref_count = G_REF_COUNT_INIT,
        .name = "Default name",
        .address = "Default address",
      };
      
      Since:
      2.78
      See Also:
    • SEARCHPATH_SEPARATOR

      public static final int SEARCHPATH_SEPARATOR
      The search path separator character. This is ':' on UNIX machines and ';' under Windows.
      See Also:
    • SEARCHPATH_SEPARATOR_S

      public static final String SEARCHPATH_SEPARATOR_S
      The search path separator as a string. This is ":" on UNIX machines and ";" under Windows.
      See Also:
    • SIZEOF_LONG

      public static final int SIZEOF_LONG
      See Also:
    • SIZEOF_SIZE_T

      public static final int SIZEOF_SIZE_T
      See Also:
    • SIZEOF_SSIZE_T

      public static final int SIZEOF_SSIZE_T
      See Also:
    • SIZEOF_VOID_P

      public static final int SIZEOF_VOID_P
      See Also:
    • SOURCE_CONTINUE

      public static final boolean SOURCE_CONTINUE
      Use this macro as the return value of a GLib.SourceFunc to leave the GLib.Source in the main loop.
      Since:
      2.32
      See Also:
    • SOURCE_REMOVE

      public static final boolean SOURCE_REMOVE
      Use this macro as the return value of a GLib.SourceFunc to remove the GLib.Source from the main loop.
      Since:
      2.32
      See Also:
    • SQRT2

      public static final double SQRT2
      The square root of two.
      See Also:
    • STR_DELIMITERS

      public static final String STR_DELIMITERS
      The standard delimiters, used in strdelimit(String, String, byte).
      See Also:
    • SYSDEF_AF_INET

      public static final int SYSDEF_AF_INET
      See Also:
    • SYSDEF_AF_INET6

      public static final int SYSDEF_AF_INET6
      See Also:
    • SYSDEF_AF_UNIX

      public static final int SYSDEF_AF_UNIX
      See Also:
    • SYSDEF_MSG_DONTROUTE

      public static final int SYSDEF_MSG_DONTROUTE
      See Also:
    • SYSDEF_MSG_OOB

      public static final int SYSDEF_MSG_OOB
      See Also:
    • SYSDEF_MSG_PEEK

      public static final int SYSDEF_MSG_PEEK
      See Also:
    • TEST_OPTION_ISOLATE_DIRS

      public static final String TEST_OPTION_ISOLATE_DIRS

      A value that can be passed as an option to testInit(MemorySegment, String[], Object...).

      Creates a unique temporary directory for each unit test and uses sets XDG directories to point into subdirectories of it for the duration of the unit test. The directory tree is cleaned up after the test finishes successfully.

      Note that this doesn’t take effect until testRun() is called, so calls to (for example) getHomeDir() will return the system-wide value when made in a test program’s main() function.

      The following functions will return subdirectories of the temporary directory when this option is used. The specific subdirectory paths in use are not guaranteed to be stable API — always use a getter function to retrieve them.

      The subdirectories may not be created by the test harness; as with normal calls to functions like getUserCacheDir(), the caller must be prepared to create the directory if it doesn’t exist.

      Since:
      2.60
      See Also:
    • TEST_OPTION_NONFATAL_ASSERTIONS

      public static final String TEST_OPTION_NONFATAL_ASSERTIONS

      A value that can be passed as an option to testInit(MemorySegment, String[], Object...).

      If this option is given, assertions will not abort the process, but call testFail(). Equivalent to testSetNonfatalAssertions().

      Since:
      2.84
      See Also:
    • TEST_OPTION_NO_PRGNAME

      public static final String TEST_OPTION_NO_PRGNAME

      A value that can be passed as an option to testInit(MemorySegment, String[], Object...).

      If this option is given, testInit(MemorySegment, String[], Object...) will not call setPrgname(String).

      Since:
      2.84
      See Also:
    • TIME_SPAN_DAY

      public static final long TIME_SPAN_DAY
      Evaluates to a time span of one day.
      Since:
      2.26
      See Also:
    • TIME_SPAN_HOUR

      public static final long TIME_SPAN_HOUR
      Evaluates to a time span of one hour.
      Since:
      2.26
      See Also:
    • TIME_SPAN_MILLISECOND

      public static final long TIME_SPAN_MILLISECOND
      Evaluates to a time span of one millisecond.
      Since:
      2.26
      See Also:
    • TIME_SPAN_MINUTE

      public static final long TIME_SPAN_MINUTE
      Evaluates to a time span of one minute.
      Since:
      2.26
      See Also:
    • TIME_SPAN_SECOND

      public static final long TIME_SPAN_SECOND
      Evaluates to a time span of one second.
      Since:
      2.26
      See Also:
    • UNICHAR_MAX_DECOMPOSITION_LENGTH

      public static final int UNICHAR_MAX_DECOMPOSITION_LENGTH

      The maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.

      This is as defined by Unicode 6.1.

      Since:
      2.32
      See Also:
    • URI_RESERVED_CHARS_GENERIC_DELIMITERS

      public static final String URI_RESERVED_CHARS_GENERIC_DELIMITERS
      Generic delimiters characters as defined in RFC 3986. Includes :/?#[]@.
      Since:
      2.16
      See Also:
    • URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS

      public static final String URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS
      Subcomponent delimiter characters as defined in RFC 3986. Includes !$&'()*+,;=.
      Since:
      2.16
      See Also:
    • USEC_PER_SEC

      public static final int USEC_PER_SEC
      Number of microseconds in one second (1 million). This macro is provided for code readability.
      See Also:
    • VA_COPY_AS_ARRAY

      public static final int VA_COPY_AS_ARRAY
      See Also:
    • VERSION_MIN_REQUIRED

      public static final int VERSION_MIN_REQUIRED

      A macro that should be defined by the user prior to including the glib.h header. The definition should be one of the predefined GLib version macros: GLIB_VERSION_2_26, GLIB_VERSION_2_28,...

      This macro defines the earliest version of GLib that the package is required to be able to compile against.

      If the compiler is configured to warn about the use of deprecated functions, then using functions that were deprecated in version GLIB_VERSION_MIN_REQUIRED or earlier will cause warnings (but using functions deprecated in later releases will not).

      Since:
      2.32
      See Also:
    • WIN32_MSG_HANDLE

      public static final int WIN32_MSG_HANDLE
      See Also:
    • macro__has_attribute___noreturn__

      public static final int macro__has_attribute___noreturn__
      See Also:
    • macro__has_attribute_ifunc

      public static final int macro__has_attribute_ifunc
      See Also:
    • macro__has_attribute_no_sanitize_address

      public static final int macro__has_attribute_no_sanitize_address
      See Also:
  • Constructor Details

    • GLib

      public GLib()
  • Method Details

    • javagi$ensureInitialized

      public static void javagi$ensureInitialized()
    • access

      public static int access(String filename, int mode)

      A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.

      On Windows, the file protection mechanism is not at all POSIX-like, and the underlying function in the C library only checks the FAT-style READONLY attribute, and does not look at the ACL of a file at all. This function is this in practise almost useless on Windows. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.

      See your C library manual for more details about access().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      mode - as in access()
      Returns:
      zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.
      Since:
      2.8
    • alignedAlloc

      public static @Nullable MemorySegment alignedAlloc(long nBlocks, long nBlockBytes, long alignment)

      This function is similar to g_malloc(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to align the allocated memory to with the given alignment value. Additionally, it will detect possible overflow during multiplication.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Aligned memory allocations returned by this function can only be freed using g_aligned_free_sized() or g_aligned_free().

      Parameters:
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      alignment - the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)
      Returns:
      the allocated memory
      Since:
      2.72
    • alignedAlloc0

      public static @Nullable MemorySegment alignedAlloc0(long nBlocks, long nBlockBytes, long alignment)
      This function is similar to g_aligned_alloc(), but it will also clear the allocated memory before returning it.
      Parameters:
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      alignment - the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)
      Returns:
      the allocated, cleared memory
      Since:
      2.72
    • alignedFree

      public static void alignedFree(@Nullable MemorySegment mem)
      Frees the memory allocated by g_aligned_alloc().
      Parameters:
      mem - the memory to deallocate
      Since:
      2.72
    • alignedFreeSized

      public static void alignedFreeSized(@Nullable MemorySegment mem, long alignment, long size)

      Frees the memory pointed to by mem, assuming it is has the given size and alignment.

      If mem is null this is a no-op (and size is ignored).

      It is an error if size doesn’t match the size, or alignment doesn’t match the alignment, passed when mem was allocated. size and alignment are passed to this function to allow optimizations in the allocator. If you don’t know either of them, use g_aligned_free() instead.

      Parameters:
      mem - the memory to free
      alignment - alignment of mem
      size - size of mem, in bytes
      Since:
      2.76
    • asciiDigitValue

      public static int asciiDigitValue(byte c)

      Determines the numeric value of a character as a decimal digit. If the character is not a decimal digit according to GLib.asciiIsdigit, -1 is returned.

      Differs from unicharDigitValue(int) because it takes a char, so there's no worry about sign extension if characters are signed.

      Parameters:
      c - an ASCII character
      Returns:
      the numerical value of c if it is a decimal digit, -1 otherwise
    • asciiDtostr

      public static String asciiDtostr(String buffer, int bufLen, double d)

      Converts a gdouble to a string, using the '.' as decimal point.

      This function generates enough precision that converting the string back using asciiStrtod(String, Out) gives the same machine-number (on machines with IEEE compatible 64bit doubles). It is guaranteed that the size of the resulting string will never be larger than GLib.ASCII_DTOSTR_BUF_SIZE bytes, including the terminating nul character, which is always added.

      Parameters:
      buffer - a buffer to place the resulting string in
      bufLen - the length of the buffer
      d - the value to convert
      Returns:
      the pointer to the buffer with the converted string
    • asciiFormatd

      public static String asciiFormatd(String buffer, int bufLen, String format, double d)

      Converts a gdouble to a string, using the '.' as decimal point. To format the number you pass in a printf()-style format string. Allowed conversion specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.

      The format must just be a single format specifier starting with %, expecting a gdouble argument.

      The returned buffer is guaranteed to be nul-terminated.

      If you just want to want to serialize the value into a string, use asciiDtostr(String, int, double).

      Parameters:
      buffer - a buffer to place the resulting string in
      bufLen - the length of the buffer
      format - the printf()-style format to use for the code to use for converting
      d - the value to convert
      Returns:
      the pointer to the buffer with the converted string
    • asciiStrcasecmp

      public static int asciiStrcasecmp(String s1, String s2)

      Compare two strings, ignoring the case of ASCII characters.

      Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII bytes as if they are not letters.

      This function should be used only on strings that are known to be in encodings where the bytes corresponding to ASCII letters always represent themselves. This includes UTF-8 and the ISO-8859-* charsets, but not for instance double-byte encodings like the Windows Codepage 932, where the trailing bytes of double-byte characters include all ASCII letters. If you compare two CP932 strings using this function, you will get false matches.

      Both s1 and s2 must be non-NULL.

      Parameters:
      s1 - string to compare with s2
      s2 - string to compare with s1
      Returns:
      0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2
    • asciiStrdown

      public static String asciiStrdown(String str, long len)
      Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly match asciiTolower(byte).
      Parameters:
      str - a string
      len - length of str in bytes, or -1 if str is nul-terminated
      Returns:
      a newly-allocated string, with all the upper case characters in str converted to lower case. (Note that this is unlike the old strdown(String), which modified the string in place.)
    • asciiStringToSigned

      public static boolean asciiStringToSigned(String str, int base, long min, long max, @Nullable Out<Long> outNum) throws GErrorException

      A convenience function for converting a string to a signed number.

      This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in outNum. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input.

      base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with "0x" or "0X". Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

      Parsing failures result in an error with the G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be GLib.NumberParserError.INVALID. If the parsed number is out of bounds - GLib.NumberParserError.OUT_OF_BOUNDS.

      See asciiStrtoll(String, Out, int) if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

      Parameters:
      str - a string to convert
      base - base of a parsed number
      min - a lower bound (inclusive)
      max - an upper bound (inclusive)
      outNum - a return location for a number
      Returns:
      true if str was a number, false otherwise
      Throws:
      GErrorException - see GError
      Since:
      2.54
    • asciiStringToUnsigned

      public static boolean asciiStringToUnsigned(String str, int base, long min, long max, @Nullable Out<Long> outNum) throws GErrorException

      A convenience function for converting a string to an unsigned number.

      This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in outNum. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input. A string with a leading sign (- or +) is not a valid input for the unsigned parser.

      base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with "0x" or "0X". Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

      Parsing failures result in an error with the G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be GLib.NumberParserError.INVALID. If the parsed number is out of bounds - GLib.NumberParserError.OUT_OF_BOUNDS.

      See asciiStrtoull(String, Out, int) if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

      Parameters:
      str - a string
      base - base of a parsed number
      min - a lower bound (inclusive)
      max - an upper bound (inclusive)
      outNum - a return location for a number
      Returns:
      true if str was a number, false otherwise
      Throws:
      GErrorException - see GError
      Since:
      2.54
    • asciiStrncasecmp

      public static int asciiStrncasecmp(String s1, String s2, long n)

      Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string. If either string is less than n bytes long, comparison will stop at the first nul byte encountered.

      Unlike the BSD strncasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII characters as if they are not letters.

      The same warning as in asciiStrcasecmp(String, String) applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

      Parameters:
      s1 - string to compare with s2
      s2 - string to compare with s1
      n - number of characters to compare
      Returns:
      0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2
    • asciiStrtod

      public static double asciiStrtod(String nptr, @Nullable Out<String> endptr)

      Converts a string to a floating point value.

      This function behaves like the standard strtod() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe. A limitation of the implementation is that this function will still accept localized versions of infinities and NANs.

      This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtod() function.

      To convert from a gdouble to a string in a locale-insensitive way, use asciiDtostr(String, int, double).

      If the correct value would cause overflow, plus or minus HUGE_VAL is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

      This function resets errno before calling strtod() so that you can reliably detect overflow and underflow.

      Parameters:
      nptr - the string to convert to a numeric value
      endptr - if non-NULL, it returns the character after the last character used in the conversion
      Returns:
      the converted value
    • asciiStrtoll

      public static long asciiStrtoll(String nptr, @Nullable Out<String> endptr, int base)

      Converts a string to a gint64 value.

      This function behaves like the standard strtoll() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

      This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoll() function.

      If the correct value would cause overflow, GLib.MAXINT64 or GLib.MININT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

      Parameters:
      nptr - the string to convert to a numeric value
      endptr - if non-NULL, it returns the character after the last character used in the conversion
      base - to be used for the conversion, 2..36 or 0
      Returns:
      the converted value, or zero on error
      Since:
      2.12
    • asciiStrtoull

      public static long asciiStrtoull(String nptr, @Nullable Out<String> endptr, int base)

      Converts a string to a guint64 value.

      This function behaves like the standard strtoull() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

      Note that input with a leading minus sign (-) is accepted, and will return the negation of the parsed number, unless that would overflow a guint64. Critically, this means you cannot assume that a short fixed length input will result in a low return value, as the input could have a leading -.

      This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoull() function.

      If the correct value would cause overflow, GLib.MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

      Parameters:
      nptr - the string to convert to a numeric value
      endptr - if non-NULL, it returns the character after the last character used in the conversion
      base - to be used for the conversion, 2..36 or 0
      Returns:
      the converted value, or zero on error
      Since:
      2.2
    • asciiStrup

      public static String asciiStrup(String str, long len)
      Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly match asciiToupper(byte).
      Parameters:
      str - a string
      len - length of str in bytes, or -1 if str is nul-terminated
      Returns:
      a newly-allocated string, with all the lower case characters in str converted to upper case. (Note that this is unlike the old strup(String), which modified the string in place.)
    • asciiTolower

      public static byte asciiTolower(byte c)

      Convert a character to ASCII lower case. If the character is not an ASCII upper case letter, it is returned unchanged.

      Unlike the standard C library tolower() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are lower case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

      Parameters:
      c - any character
      Returns:
      the result of the conversion
    • asciiToupper

      public static byte asciiToupper(byte c)

      Convert a character to ASCII upper case. If the character is not an ASCII lower case letter, it is returned unchanged.

      Unlike the standard C library toupper() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are upper case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

      Parameters:
      c - any character
      Returns:
      the result of the conversion
    • asciiXdigitValue

      public static int asciiXdigitValue(byte c)

      Determines the numeric value of a character as a hexadecimal digit. If the character is not a hex digit according to GLib.asciiIsxdigit, -1 is returned.

      Differs from unicharXdigitValue(int) because it takes a char, so there's no worry about sign extension if characters are signed.

      Differs from unicharXdigitValue(int) because it takes a char, so there's no worry about sign extension if characters are signed.

      Parameters:
      c - an ASCII character
      Returns:
      the numerical value of c if it is a hex digit, -1 otherwise
    • assertWarning

      public static void assertWarning(String logDomain, String file, int line, String prettyFunction, String expression)
    • assertionMessage

      public static void assertionMessage(String domain, String file, int line, String func, String message)
    • assertionMessageCmpint

      public static void assertionMessageCmpint(String domain, String file, int line, String func, String expr, long arg1, String cmp, long arg2, byte numtype)
    • assertionMessageCmpnum

      public static void assertionMessageCmpnum(String domain, String file, int line, String func, String expr, double arg1, String cmp, double arg2, byte numtype)
    • assertionMessageCmpstr

      public static void assertionMessageCmpstr(String domain, String file, int line, String func, String expr, String arg1, String cmp, String arg2)
    • assertionMessageCmpstrv

      public static void assertionMessageCmpstrv(String domain, String file, int line, String func, String expr, String arg1, String arg2, long firstWrongIdx)
    • assertionMessageError

      public static void assertionMessageError(String domain, String file, int line, String func, String expr, GError error, Quark errorDomain, int errorCode)
    • assertionMessageExpr

      public static void assertionMessageExpr(@Nullable String domain, String file, int line, String func, @Nullable String expr)
      Internal function used to print messages from the public g_assert() and g_assert_not_reached() macros.
      Parameters:
      domain - log domain
      file - file containing the assertion
      line - line number of the assertion
      func - function containing the assertion
      expr - expression which failed
    • atexit

      @Deprecated public static void atexit(@Nullable VoidFunc func)
      Deprecated.
      It is best to avoid g_atexit().

      Specifies a function to be called at normal program termination.

      Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls g_atexit(), i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when g_atexit() was a function in the GLib DLL.

      The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

      On POSIX systems, calling g_atexit() (or atexit()) in a dynamically loaded module which is unloaded before the program terminates might well cause a crash at program exit.

      Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.

      On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.

      As can be seen from the above, for portability it's best to avoid calling g_atexit() (or atexit()) except in the main executable of a program.

      Parameters:
      func - the function to call on normal program termination.
    • atomicIntAdd

      public static int atomicIntAdd(@Nullable MemorySegment atomic, int val)

      Atomically adds val to the value of atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      Before version 2.30, this function did not return a value (but g_atomic_int_exchange_and_add() did, and had the same meaning).

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      val - the value to add
      Returns:
      the value of atomic before the add, signed
      Since:
      2.4
    • atomicIntAnd

      public static int atomicIntAnd(@Nullable MemorySegment atomic, int val)

      Performs an atomic bitwise 'and' of the value of atomic and val, storing the result back in atomic.

      This call acts as a full compiler and hardware memory barrier.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      val - the value to 'and'
      Returns:
      the value of atomic before the operation, unsigned
      Since:
      2.30
    • atomicIntCompareAndExchange

      public static boolean atomicIntCompareAndExchange(@Nullable MemorySegment atomic, int oldval, int newval)

      Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

      This compare and exchange is done atomically.

      Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      oldval - the value to compare with
      newval - the value to conditionally replace with
      Returns:
      true if the exchange took place
      Since:
      2.4
    • atomicIntCompareAndExchangeFull

      public static boolean atomicIntCompareAndExchangeFull(@Nullable MemorySegment atomic, int oldval, int newval, Out<Integer> preval)

      Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs. In any case the value of atomic before this operation is stored in preval.

      This compare and exchange is done atomically.

      Think of this operation as an atomic version of { *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

      This call acts as a full compiler and hardware memory barrier.

      See also g_atomic_int_compare_and_exchange()

      Parameters:
      atomic - a pointer to a gint or guint
      oldval - the value to compare with
      newval - the value to conditionally replace with
      preval - the contents of atomic before this operation
      Returns:
      true if the exchange took place
      Since:
      2.74
    • atomicIntDecAndTest

      public static boolean atomicIntDecAndTest(@Nullable MemorySegment atomic)

      Decrements the value of atomic by 1.

      Think of this operation as an atomic version of { *atomic -= 1; return (*atomic == 0); }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      Returns:
      true if the resultant value is zero
      Since:
      2.4
    • atomicIntExchange

      public static int atomicIntExchange(@Nullable MemorySegment atomic, int newval)

      Sets the atomic to newval and returns the old value from atomic.

      This exchange is done atomically.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic = val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      Parameters:
      atomic - a pointer to a gint or guint
      newval - the value to replace with
      Returns:
      the value of atomic before the exchange, signed
      Since:
      2.74
    • atomicIntExchangeAndAdd

      @Deprecated public static int atomicIntExchangeAndAdd(@Nullable MemorySegment atomic, int val)
      Deprecated.
      Use g_atomic_int_add() instead.
      This function existed before g_atomic_int_add() returned the prior value of the integer (which it now does). It is retained only for compatibility reasons. Don't use this function in new code.
      Parameters:
      atomic - a pointer to a gint
      val - the value to add
      Returns:
      the value of atomic before the add, signed
      Since:
      2.4
    • atomicIntGet

      public static int atomicIntGet(@Nullable MemorySegment atomic)

      Gets the current value of atomic.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      Returns:
      the value of the integer
      Since:
      2.4
    • atomicIntInc

      public static void atomicIntInc(@Nullable MemorySegment atomic)

      Increments the value of atomic by 1.

      Think of this operation as an atomic version of { *atomic += 1; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      Since:
      2.4
    • atomicIntOr

      public static int atomicIntOr(@Nullable MemorySegment atomic, int val)

      Performs an atomic bitwise 'or' of the value of atomic and val, storing the result back in atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      val - the value to 'or'
      Returns:
      the value of atomic before the operation, unsigned
      Since:
      2.30
    • atomicIntSet

      public static void atomicIntSet(@Nullable MemorySegment atomic, int newval)

      Sets the value of atomic to newval.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      newval - a new value to store
      Since:
      2.4
    • atomicIntXor

      public static int atomicIntXor(@Nullable MemorySegment atomic, int val)

      Performs an atomic bitwise 'xor' of the value of atomic and val, storing the result back in atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gint or guint
      val - the value to 'xor'
      Returns:
      the value of atomic before the operation, unsigned
      Since:
      2.30
    • atomicPointerAdd

      public static long atomicPointerAdd(MemorySegment atomic, long val)

      Atomically adds val to the value of atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      In GLib 2.80, the return type was changed from gssize to gintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      val - the value to add
      Returns:
      the value of atomic before the add, signed
      Since:
      2.30
    • atomicPointerAnd

      public static long atomicPointerAnd(MemorySegment atomic, long val)

      Performs an atomic bitwise 'and' of the value of atomic and val, storing the result back in atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      In GLib 2.80, the return type was changed from gsize to guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      val - the value to 'and'
      Returns:
      the value of atomic before the operation, unsigned
      Since:
      2.30
    • atomicPointerCompareAndExchange

      public static boolean atomicPointerCompareAndExchange(MemorySegment atomic, @Nullable MemorySegment oldval, @Nullable MemorySegment newval)

      Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

      This compare and exchange is done atomically.

      Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      oldval - the value to compare with
      newval - the value to conditionally replace with
      Returns:
      true if the exchange took place
      Since:
      2.4
    • atomicPointerCompareAndExchangeFull

      public static boolean atomicPointerCompareAndExchangeFull(MemorySegment atomic, @Nullable MemorySegment oldval, @Nullable MemorySegment newval, Out<MemorySegment> preval)

      Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs. In any case the value of atomic before this operation is stored in preval.

      This compare and exchange is done atomically.

      Think of this operation as an atomic version of { *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

      This call acts as a full compiler and hardware memory barrier.

      See also g_atomic_pointer_compare_and_exchange()

      Parameters:
      atomic - a pointer to a gpointer-sized value
      oldval - the value to compare with
      newval - the value to conditionally replace with
      preval - the contents of atomic before this operation
      Returns:
      true if the exchange took place
      Since:
      2.74
    • atomicPointerExchange

      public static @Nullable MemorySegment atomicPointerExchange(@Nullable MemorySegment atomic, @Nullable MemorySegment newval)

      Sets the atomic to newval and returns the old value from atomic.

      This exchange is done atomically.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic = val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      newval - the value to replace with
      Returns:
      the value of atomic before the exchange
      Since:
      2.74
    • atomicPointerGet

      public static @Nullable MemorySegment atomicPointerGet(MemorySegment atomic)

      Gets the current value of atomic.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      Returns:
      the value of the pointer
      Since:
      2.4
    • atomicPointerOr

      public static long atomicPointerOr(MemorySegment atomic, long val)

      Performs an atomic bitwise 'or' of the value of atomic and val, storing the result back in atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      In GLib 2.80, the return type was changed from gsize to guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      val - the value to 'or'
      Returns:
      the value of atomic before the operation, unsigned
      Since:
      2.30
    • atomicPointerSet

      public static void atomicPointerSet(MemorySegment atomic, @Nullable MemorySegment newval)

      Sets the value of atomic to newval.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      newval - a new value to store
      Since:
      2.4
    • atomicPointerXor

      public static long atomicPointerXor(MemorySegment atomic, long val)

      Performs an atomic bitwise 'xor' of the value of atomic and val, storing the result back in atomic.

      Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

      This call acts as a full compiler and hardware memory barrier.

      While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

      In GLib 2.80, the return type was changed from gsize to guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

      Parameters:
      atomic - a pointer to a gpointer-sized value
      val - the value to 'xor'
      Returns:
      the value of atomic before the operation, unsigned
      Since:
      2.30
    • atomicRcBoxAcquire

      public static MemorySegment atomicRcBoxAcquire(MemorySegment memBlock)
      Atomically acquires a reference on the data pointed by memBlock.
      Parameters:
      memBlock - a pointer to reference counted data
      Returns:
      a pointer to the data, with its reference count increased
      Since:
      2.58
    • atomicRcBoxAlloc

      public static MemorySegment atomicRcBoxAlloc(long blockSize)

      Allocates blockSize bytes of memory, and adds atomic reference counting semantics to it.

      The data will be freed when its reference count drops to zero.

      The allocated data is guaranteed to be suitably aligned for any built-in type.

      Parameters:
      blockSize - the size of the allocation, must be greater than 0
      Returns:
      a pointer to the allocated memory
      Since:
      2.58
    • atomicRcBoxAlloc0

      public static MemorySegment atomicRcBoxAlloc0(long blockSize)

      Allocates blockSize bytes of memory, and adds atomic reference counting semantics to it.

      The contents of the returned data is set to zero.

      The data will be freed when its reference count drops to zero.

      The allocated data is guaranteed to be suitably aligned for any built-in type.

      Parameters:
      blockSize - the size of the allocation, must be greater than 0
      Returns:
      a pointer to the allocated memory
      Since:
      2.58
    • atomicRcBoxDup

      public static MemorySegment atomicRcBoxDup(long blockSize, MemorySegment memBlock)
      Allocates a new block of data with atomic reference counting semantics, and copies blockSize bytes of memBlock into it.
      Parameters:
      blockSize - the number of bytes to copy, must be greater than 0
      memBlock - the memory to copy
      Returns:
      a pointer to the allocated memory
      Since:
      2.58
    • atomicRcBoxGetSize

      public static long atomicRcBoxGetSize(MemorySegment memBlock)
      Retrieves the size of the reference counted data pointed by memBlock.
      Parameters:
      memBlock - a pointer to reference counted data
      Returns:
      the size of the data, in bytes
      Since:
      2.58
    • atomicRcBoxRelease

      public static void atomicRcBoxRelease(MemorySegment memBlock)

      Atomically releases a reference on the data pointed by memBlock.

      If the reference was the last one, it will free the resources allocated for memBlock.

      Parameters:
      memBlock - a pointer to reference counted data
      Since:
      2.58
    • atomicRcBoxReleaseFull

      public static void atomicRcBoxReleaseFull(MemorySegment memBlock)

      Atomically releases a reference on the data pointed by memBlock.

      If the reference was the last one, it will call clearFunc to clear the contents of memBlock, and then will free the resources allocated for memBlock.

      Note that implementing weak references via clearFunc is not thread-safe: clearing a pointer to the memory from the callback can race with another thread trying to access it as memBlock already has a reference count of 0 when the callback is called and will be freed.

      Parameters:
      memBlock - a pointer to reference counted data
      Since:
      2.58
    • atomicRefCountCompare

      public static boolean atomicRefCountCompare(MemorySegment arc, int val)
      Atomically compares the current value of arc with val.
      Parameters:
      arc - the address of an atomic reference count variable
      val - the value to compare
      Returns:
      true if the reference count is the same as the given value
      Since:
      2.58
    • atomicRefCountDec

      public static boolean atomicRefCountDec(MemorySegment arc)

      Atomically decreases the reference count.

      If true is returned, the reference count reached 0. After this point, arc is an undefined state and must be reinitialized with g_atomic_ref_count_init() to be used again.

      Parameters:
      arc - the address of an atomic reference count variable
      Returns:
      true if the reference count reached 0, and false otherwise
      Since:
      2.58
    • atomicRefCountInc

      public static void atomicRefCountInc(MemorySegment arc)
      Atomically increases the reference count.
      Parameters:
      arc - the address of an atomic reference count variable
      Since:
      2.58
    • atomicRefCountInit

      public static void atomicRefCountInit(Out<Integer> arc)
      Initializes a reference count variable to 1.
      Parameters:
      arc - the address of an atomic reference count variable
      Since:
      2.58
    • base64Decode

      public static byte[] base64Decode(String text)
      Decode a sequence of Base-64 encoded text into binary data. Note that the returned binary data is not necessarily zero-terminated, so it should not be used as a character string.
      Parameters:
      text - zero-terminated string with base64 text to decode
      Returns:
      newly allocated buffer containing the binary data that text represents. The returned buffer must be freed with g_free().
      Since:
      2.12
    • base64DecodeInplace

      public static MemorySegment base64DecodeInplace(@Nullable Out<byte[]> text)
      Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.
      Parameters:
      text - zero-terminated string with base64 text to decode
      Returns:
      The binary data that text responds. This pointer is the same as the input text.
      Since:
      2.20
    • base64DecodeStep

      public static long base64DecodeStep(@Nullable byte @Nullable [] in, @Nullable byte @Nullable [] out, Out<Integer> state, Out<Integer> save)

      Incrementally decode a sequence of binary data from its Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.

      The output buffer must be large enough to fit all the data that will be written to it. Since base64 encodes 3 bytes in 4 chars you need at least: (len / 4) * 3 + 3 bytes (+ 3 may be needed in case of non-zero state).

      Parameters:
      in - binary input data
      out - output buffer
      state - Saved state between steps, initialize to 0
      save - Saved state between steps, initialize to 0
      Returns:
      The number of bytes of output that was written
      Since:
      2.12
    • base64Encode

      public static String base64Encode(@Nullable byte @Nullable [] data)
      Encode a sequence of binary data into its Base-64 stringified representation.
      Parameters:
      data - the binary data to encode
      Returns:
      a newly allocated, zero-terminated Base-64 encoded string representing data. The returned string must be freed with g_free().
      Since:
      2.12
    • base64EncodeClose

      public static long base64EncodeClose(boolean breakLines, @Nullable byte @Nullable [] out, Out<Integer> state, Out<Integer> save)

      Flush the status from a sequence of calls to g_base64_encode_step().

      The output buffer must be large enough to fit all the data that will be written to it. It will need up to 4 bytes, or up to 5 bytes if line-breaking is enabled.

      The out array will not be automatically nul-terminated.

      Parameters:
      breakLines - whether to break long lines
      out - pointer to destination buffer
      state - Saved state from g_base64_encode_step()
      save - Saved state from g_base64_encode_step()
      Returns:
      The number of bytes of output that was written
      Since:
      2.12
    • base64EncodeStep

      public static long base64EncodeStep(@Nullable byte @Nullable [] in, boolean breakLines, @Nullable byte @Nullable [] out, Out<Integer> state, Out<Integer> save)

      Incrementally encode a sequence of binary data into its Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.

      When all of the data has been converted you must call g_base64_encode_close() to flush the saved state.

      The output buffer must be large enough to fit all the data that will be written to it. Due to the way base64 encodes you will need at least: (len / 3 + 1) * 4 + 4 bytes (+ 4 may be needed in case of non-zero state). If you enable line-breaking you will need at least: ((len / 3 + 1) * 4 + 4) / 76 + 1 bytes of extra space.

      breakLines is typically used when putting base64-encoded data in emails. It breaks the lines at 76 columns instead of putting all of the text on the same line. This avoids problems with long lines in the email system. Note however that it breaks the lines with LF characters, not CR LF sequences, so the result cannot be passed directly to SMTP or certain other protocols.

      Parameters:
      in - the binary data to encode
      breakLines - whether to break long lines
      out - pointer to destination buffer
      state - Saved state between steps, initialize to 0
      save - Saved state between steps, initialize to 0
      Returns:
      The number of bytes of output that was written
      Since:
      2.12
    • basename

      @Deprecated public static String basename(String fileName)
      Deprecated.
      Use g_path_get_basename() instead, but notice that g_path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.
      Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.
      Parameters:
      fileName - the name of the file
      Returns:
      the name of the file without any leading directory components
    • bitLock

      public static void bitLock(@Nullable MemorySegment address, int lockBit)

      Sets the indicated lockBit in address. If the bit is already set, this call will block until g_bit_unlock() unsets the corresponding bit.

      Attempting to lock on two different bits within the same integer is not supported and will very probably cause deadlocks.

      The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

      This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

      Parameters:
      address - a pointer to an integer
      lockBit - a bit value between 0 and 31
      Since:
      2.24
    • bitLockAndGet

      public static void bitLockAndGet(@Nullable MemorySegment address, int lockBit, @Nullable Out<Integer> outVal)

      Sets the indicated lockBit in address and atomically returns the new value.

      This is like bitLock(MemorySegment, int), except it can atomically return the new value at address (right after obtaining the lock). Thus the value returned in outVal always has the lockBit set.

      Parameters:
      address - a pointer to an integer
      lockBit - a bit value between 0 and 31
      outVal - return location for the new value of the integer
      Since:
      2.86
    • bitNthLsf

      public static int bitNthLsf(int mask, int nthBit)
      Find the position of the first bit set in mask, searching from (but not including) nthBit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nthBit to -1.
      Parameters:
      mask - a gulong containing flags
      nthBit - the index of the bit to start the search from
      Returns:
      the index of the first bit set which is higher than nthBit, or -1 if no higher bits are set
    • bitNthMsf

      public static int bitNthMsf(int mask, int nthBit)
      Find the position of the first bit set in mask, searching from (but not including) nthBit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nthBit to -1 or GLIB_SIZEOF_LONG * 8.
      Parameters:
      mask - a gulong containing flags
      nthBit - the index of the bit to start the search from
      Returns:
      the index of the first bit set which is lower than nthBit, or -1 if no lower bits are set
    • bitStorage

      public static int bitStorage(int number)
      Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.
      Parameters:
      number - a guint
      Returns:
      the number of bits used to hold number
    • bitTrylock

      public static boolean bitTrylock(@Nullable MemorySegment address, int lockBit)

      Sets the indicated lockBit in address, returning true if successful. If the bit is already set, returns false immediately.

      Attempting to lock on two different bits within the same integer is not supported.

      The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

      This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

      Parameters:
      address - a pointer to an integer
      lockBit - a bit value between 0 and 31
      Returns:
      true if the lock was acquired
      Since:
      2.24
    • bitUnlock

      public static void bitUnlock(@Nullable MemorySegment address, int lockBit)

      Clears the indicated lockBit in address. If another thread is currently blocked in g_bit_lock() on this same bit then it will be woken up.

      This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

      Parameters:
      address - a pointer to an integer
      lockBit - a bit value between 0 and 31
      Since:
      2.24
    • bitUnlockAndSet

      public static void bitUnlockAndSet(@Nullable MemorySegment address, int lockBit, int newVal, int preserveMask)

      This is like bitUnlock(MemorySegment, int) but also atomically sets address to val.

      If preserveMask is not zero, then the preserveMask bits will be preserved in address and are not set to val.

      Note that the lockBit bit will always be unset regardless of val, preserveMask and the currently set value in address.

      Parameters:
      address - a pointer to an integer
      lockBit - a bit value between 0 and 31
      newVal - the new value to set
      preserveMask - mask for bits from address to preserve
      Since:
      2.86
    • blowChunks

      @Deprecated public static void blowChunks()
      Deprecated.
    • buildFilename

      public static String buildFilename(String firstElement, Object... varargs)

      Creates a filename from a series of elements using the correct separator for the current platform.

      On Unix, this function behaves identically to g_build_path (G_DIR_SEPARATOR_S, first_element, ....).

      On Windows, it takes into account that either the backslash (\\ or slash (/) can be used as separator in filenames, but otherwise behaves as on UNIX. When file pathname separators need to be inserted, the one that last previously occurred in the parameters (reading from left to right) is used.

      No attempt is made to force the resulting filename to be an absolute path. If the first element is a relative path, the result will be a relative path.

      If you are building a path programmatically you may want to use GPathBuf instead.

      Parameters:
      firstElement - the first element in the path
      varargs - remaining elements in path, terminated by null
      Returns:
      the newly allocated path
    • buildFilenamev

      public static String buildFilenamev(@Nullable String @Nullable [] args)

      Creates a filename from a vector of elements using the correct separator for the current platform.

      This function behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

      If you are building a path programmatically you may want to use GPathBuf instead.

      Parameters:
      args - null-terminated array of strings containing the path elements.
      Returns:
      the newly allocated path
      Since:
      2.8
    • buildPath

      public static String buildPath(String separator, String firstElement, Object... varargs)

      Creates a path from a series of elements using separator as the separator between elements.

      At the boundary between two elements, any trailing occurrences of separator in the first element, or leading occurrences of separator in the second element are removed and exactly one copy of the separator is inserted.

      Empty elements are ignored.

      The number of leading copies of the separator on the result is the same as the number of leading copies of the separator on the first non-empty element.

      The number of trailing copies of the separator on the result is the same as the number of trailing copies of the separator on the last non-empty element. (Determination of the number of trailing copies is done without stripping leading copies, so if the separator is ABA, then ABABA has 1 trailing copy.)

      However, if there is only a single non-empty element, and there are no characters in that element not part of the leading or trailing separators, then the result is exactly the original value of that element.

      Other than for determination of the number of leading and trailing copies of the separator, elements consisting only of copies of the separator are ignored.

      Parameters:
      separator - a string used to separate the elements of the path.
      firstElement - the first element in the path
      varargs - remaining elements in path, terminated by null
      Returns:
      the newly allocated path
    • buildPathv

      public static String buildPathv(String separator, @Nullable String @Nullable [] args)

      Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of variadic arguments.

      This function is mainly meant for language bindings.

      Parameters:
      separator - a string used to separate the elements of the path.
      args - null-terminated array of strings containing the path elements.
      Returns:
      a newly-allocated string that must be freed with g_free().
      Since:
      2.8
    • canonicalizeFilename

      public static String canonicalizeFilename(String filename, @Nullable String relativeTo)

      Gets the canonical file name from filename. All triple slashes are turned into single slashes, and all .. and .s resolved against relativeTo.

      Symlinks are not followed, and the returned path is guaranteed to be absolute.

      If filename is an absolute path, relativeTo is ignored. Otherwise, relativeTo will be prepended to filename to make it absolute. relativeTo must be an absolute path, or null. If relativeTo is null, it'll fallback to g_get_current_dir().

      This function never fails, and will canonicalize file paths even if they don't exist.

      No file system I/O is done.

      Parameters:
      filename - the name of the file
      relativeTo - the relative directory, or null to use the current working directory
      Returns:
      a newly allocated string with the canonical file path
      Since:
      2.58
    • chdir

      public static int chdir(String path)

      A wrapper for the POSIX chdir() function. The function changes the current directory of the process to path.

      See your C library manual for more details about chdir().

      Parameters:
      path - a pathname in the GLib file name encoding (UTF-8 on Windows)
      Returns:
      0 on success, -1 if an error occurred.
      Since:
      2.8
    • checkVersion

      public static @Nullable String checkVersion(int requiredMajor, int requiredMinor, int requiredMicro)

      Checks that the GLib library in use is compatible with the given version.

      Generally you would pass in the constants GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION as the three arguments to this function; that produces a check that the library in use is compatible with the version of GLib the application or module was compiled against.

      Compatibility is defined by two things: first the version of the running library is newer than the version @required_major.required_minor.@required_micro. Second the running library must be binary compatible with the version @required_major.@required_minor.@required_micro (same major version.)

      Parameters:
      requiredMajor - the required major version
      requiredMinor - the required minor version
      requiredMicro - the required micro version
      Returns:
      null if the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.
      Since:
      2.6
    • childWatchAdd

      public static int childWatchAdd(int priority, Pid pid, @Nullable ChildWatchFunc function)

      Sets a function to be called when the child indicated by pid exits, at the priority priority.

      If you obtain pid from spawnAsync(String, String[], String[], Set, SpawnChildSetupFunc, Pid) or spawnAsyncWithPipes(String, String[], String[], Set, SpawnChildSetupFunc, Pid, Out, Out, Out) you will need to pass GLib.SpawnFlags.DO_NOT_REAP_CHILD as a flag to the spawn function for the child watching to work.

      In many programs, you will want to call spawnCheckWaitStatus(int) in the callback to determine whether or not the child exited successfully.

      Also, note that on platforms where GLib.Pid must be explicitly closed (see spawnClosePid(Pid)) pid must not be closed while the source is still active. Typically, you should invoke spawnClosePid(Pid) in the callback function for the source.

      GLib supports only a single callback per process ID. On POSIX platforms, the same restrictions mentioned for childWatchSourceNew(Pid) apply to this function.

      This internally creates a main loop source using childWatchSourceNew(Pid) and attaches it to the main loop context using Source.attach(MainContext). You can do these steps manually if you need greater control.

      Parameters:
      priority - the priority of the idle source; typically this will be in the range between GLib.PRIORITY_DEFAULT_IDLE and GLib.PRIORITY_HIGH_IDLE
      pid - process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)
      function - function to call
      Returns:
      the ID (greater than 0) of the event source
      Since:
      2.4
    • childWatchSourceNew

      public static Source childWatchSourceNew(Pid pid)

      Creates a new child watch source.

      The source will not initially be associated with any GLib.MainContext and must be added to one with Source.attach(MainContext) before it will be executed.

      Note that child watch sources can only be used in conjunction with g_spawn... when the GLib.SpawnFlags.DO_NOT_REAP_CHILD flag is used.

      Note that on platforms where GLib.Pid must be explicitly closed (see spawnClosePid(Pid)) pid must not be closed while the source is still active. Typically, you will want to call spawnClosePid(Pid) in the callback function for the source.

      On POSIX platforms, the following restrictions apply to this API due to limitations in POSIX process interfaces:

      • pid must be a child of this process.
      • pid must be positive.
      • The application must not call waitpid() with a non-positive first argument, for instance in another thread.
      • The application must not wait for pid to exit by any other mechanism, including waitpid(pid, ...) or a second child-watch source for the same pid.
      • The application must not ignore SIGCHLD.
      • Before 2.78, the application could not send a signal (kill()) to the watched pid in a race free manner. Since 2.78, you can do that while the associated GLib.MainContext is acquired.
      • Before 2.78, even after destroying the GLib.Source, you could not be sure that pid wasn’t already reaped. Hence, it was also not safe to kill() or waitpid() on the process ID after the child watch source was gone. Destroying the source before it fired made it impossible to reliably reap the process.

      If any of those conditions are not met, this and related APIs will not work correctly. This can often be diagnosed via a GLib warning stating that ECHILD was received by waitpid().

      Calling waitpid() for specific processes other than pid remains a valid thing to do.

      Parameters:
      pid - process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)
      Returns:
      the newly-created child watch source
      Since:
      2.4
    • chmod

      public static int chmod(String filename, int mode)

      A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object.

      On Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the FAT-style READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.

      See your C library manual for more details about chmod().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      mode - as in chmod()
      Returns:
      0 if the operation succeeded, -1 on error
      Since:
      2.8
    • clearHandleId

      public static void clearHandleId(MemorySegment tagPtr, @Nullable ClearHandleFunc clearFunc)

      Clears a numeric handler, such as a GLib.Source ID.

      The tagPtr must be a valid pointer to the variable holding the handler.

      If the ID is zero then this function does nothing. Otherwise, clearFunc is called with the ID as a parameter, and the tag is set to zero.

      A macro is also included that allows this function to be used without pointer casts.

      Parameters:
      tagPtr - a pointer to the handler ID
      clearFunc - the function to call to clear the handler
      Since:
      2.56
    • clearList

      public static void clearList(Out<List<MemorySegment>> listPtr)

      Clears a pointer to a GList, freeing it and, optionally, freeing its elements using destroy.

      listPtr must be a valid pointer. If listPtr points to a null GList, this does nothing.

      Parameters:
      listPtr - a GList return location
      Since:
      2.64
    • clearPointer

      public static void clearPointer(Out<MemorySegment> pp)

      Clears a reference to a variable.

      pp must not be null.

      If the reference is null then this function does nothing. Otherwise, the variable is destroyed using destroy and the pointer is set to null.

      A macro is also included that allows this function to be used without pointer casts. This will mask any warnings about incompatible function types or calling conventions, so you must ensure that your destroy function is compatible with being called as GLib.DestroyNotify using the standard calling convention for the platform that GLib was compiled for; otherwise the program will experience undefined behaviour.

      Examples of this kind of undefined behaviour include using many Windows Win32 APIs, as well as many if not all OpenGL and Vulkan calls on 32-bit Windows, which typically use the __stdcall calling convention rather than the __cdecl calling convention.

      The affected functions can be used by wrapping them in a GLib.DestroyNotify that is declared with the standard calling convention:

      // Wrapper needed to avoid mismatched calling conventions on Windows
      static void
      destroy_sync (void *sync)
      {
        glDeleteSync (sync);
      }
      
      // …
      
      g_clear_pointer (&sync, destroy_sync);
      
      Parameters:
      pp - a pointer to a variable, struct member etc. holding a pointer
      Since:
      2.34
    • clearSlist

      public static void clearSlist(SList<MemorySegment>[] slistPtr)

      Clears a pointer to a GSList, freeing it and, optionally, freeing its elements using destroy.

      slistPtr must be a valid pointer. If slistPtr points to a null GSList, this does nothing.

      Parameters:
      slistPtr - a GSList return location
      Since:
      2.64
    • close

      public static boolean close(int fd) throws GErrorException

      This wraps the close() call. In case of error, errno will be preserved, but the error will also be stored as a GError in error. In case of success, errno is undefined.

      Besides using GError, there is another major reason to prefer this function over the call provided by the system; on Unix, it will attempt to correctly handle EINTR, which has platform-specific semantics.

      It is a bug to call this function with an invalid file descriptor.

      On POSIX platforms since GLib 2.76, this function is async-signal safe if (and only if) error is null and fd is a valid open file descriptor. This makes it safe to call from a signal handler or a GSpawnChildSetupFunc under those conditions. See signal(7) and signal-safety(7) for more details.

      Parameters:
      fd - A file descriptor
      Returns:
      true on success, false if there was an error.
      Throws:
      GErrorException - see GError
      Since:
      2.36
    • computeChecksumForBytes

      public static @Nullable String computeChecksumForBytes(ChecksumType checksumType, byte[] data)

      Computes the checksum for a binary data. This is a convenience wrapper for g_checksum_new(), g_checksum_get_string() and g_checksum_free().

      The hexadecimal string returned will be in lower case.

      Parameters:
      checksumType - a GChecksumType
      data - binary blob to compute the digest of
      Returns:
      the digest of the binary data as a string in hexadecimal, or null if g_checksum_new() fails for checksumType. The returned string should be freed with g_free() when done using it.
      Since:
      2.34
    • computeChecksumForData

      public static @Nullable String computeChecksumForData(ChecksumType checksumType, @Nullable byte @Nullable [] data)

      Computes the checksum for a binary data of length. This is a convenience wrapper for g_checksum_new(), g_checksum_get_string() and g_checksum_free().

      The hexadecimal string returned will be in lower case.

      Parameters:
      checksumType - a GChecksumType
      data - binary blob to compute the digest of
      Returns:
      the digest of the binary data as a string in hexadecimal, or null if g_checksum_new() fails for checksumType. The returned string should be freed with g_free() when done using it.
      Since:
      2.16
    • computeChecksumForString

      public static @Nullable String computeChecksumForString(ChecksumType checksumType, String str, long length)

      Computes the checksum of a string.

      The hexadecimal string returned will be in lower case.

      Parameters:
      checksumType - a GChecksumType
      str - the string to compute the checksum of
      length - the length of the string, or -1 if the string is null-terminated.
      Returns:
      the checksum as a hexadecimal string, or null if g_checksum_new() fails for checksumType. The returned string should be freed with g_free() when done using it.
      Since:
      2.16
    • computeHmacForBytes

      public static String computeHmacForBytes(ChecksumType digestType, byte[] key, byte[] data)

      Computes the HMAC for a binary data. This is a convenience wrapper for g_hmac_new(), g_hmac_get_string() and g_hmac_unref().

      The hexadecimal string returned will be in lower case.

      Parameters:
      digestType - a GChecksumType to use for the HMAC
      key - the key to use in the HMAC
      data - binary blob to compute the HMAC of
      Returns:
      the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with g_free() when done using it.
      Since:
      2.50
    • computeHmacForData

      public static String computeHmacForData(ChecksumType digestType, @Nullable byte @Nullable [] key, @Nullable byte @Nullable [] data)

      Computes the HMAC for a binary data of length. This is a convenience wrapper for g_hmac_new(), g_hmac_get_string() and g_hmac_unref().

      The hexadecimal string returned will be in lower case.

      Parameters:
      digestType - a GChecksumType to use for the HMAC
      key - the key to use in the HMAC
      data - binary blob to compute the HMAC of
      Returns:
      the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with g_free() when done using it.
      Since:
      2.30
    • computeHmacForString

      public static String computeHmacForString(ChecksumType digestType, @Nullable byte @Nullable [] key, String str, long length)

      Computes the HMAC for a string.

      The hexadecimal string returned will be in lower case.

      Parameters:
      digestType - a GChecksumType to use for the HMAC
      key - the key to use in the HMAC
      str - the string to compute the HMAC for
      length - the length of the string, or -1 if the string is nul-terminated
      Returns:
      the HMAC as a hexadecimal string. The returned string should be freed with g_free() when done using it.
      Since:
      2.30
    • convert

      public static byte[] convert(@Nullable byte @Nullable [] str, String toCodeset, String fromCodeset, @Nullable Out<Long> bytesRead) throws GErrorException

      Converts a string from one character set to another.

      Note that you should use g_iconv() for streaming conversions. Despite the fact that bytesRead can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to g_convert(), g_convert_with_iconv() or g_convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

      Using extensions such as "//TRANSLIT" may not work (or may not work well) on many platforms. Consider using g_str_to_ascii() instead.

      Parameters:
      str - the string to convert.
      toCodeset - name of character set into which to convert str
      fromCodeset - character set of str.
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
      Returns:
      If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with g_free(). Otherwise null and error will be set.
      Throws:
      GErrorException - see GError
    • convertErrorQuark

      public static Quark convertErrorQuark()
    • convertWithFallback

      public static byte[] convertWithFallback(@Nullable byte @Nullable [] str, String toCodeset, String fromCodeset, String fallback, @Nullable Out<Long> bytesRead) throws GErrorException

      Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output. Note that it is not guaranteed that the specification for the fallback sequences in fallback will be honored. Some systems may do an approximate conversion from fromCodeset to toCodeset in their iconv() functions, in which case GLib will simply return that approximate conversion.

      Note that you should use g_iconv() for streaming conversions. Despite the fact that bytesRead can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to g_convert(), g_convert_with_iconv() or g_convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

      Parameters:
      str - the string to convert.
      toCodeset - name of character set into which to convert str
      fromCodeset - character set of str.
      fallback - UTF-8 string to use in place of characters not present in the target encoding. (The string must be representable in the target encoding). If null, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input.
      Returns:
      If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with g_free(). Otherwise null and error will be set.
      Throws:
      GErrorException - see GError
    • convertWithIconv

      public static byte[] convertWithIconv(@Nullable byte @Nullable [] str, @Nullable IConv converter, @Nullable Out<Long> bytesRead) throws GErrorException

      Converts a string from one character set to another.

      Note that you should use g_iconv() for streaming conversions. Despite the fact that bytesRead can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to g_convert(), g_convert_with_iconv() or g_convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

      Characters which are valid in the input character set, but which have no representation in the output character set will result in a ConvertError.ILLEGAL_SEQUENCE error. This is in contrast to the iconv() specification, which leaves this behaviour implementation defined. Note that this is the same error code as is returned for an invalid byte sequence in the input character set. To get defined behaviour for conversion of unrepresentable characters, use g_convert_with_fallback().

      Parameters:
      str - the string to convert.
      converter - conversion descriptor from g_iconv_open()
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
      Returns:
      If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with g_free(). Otherwise null and error will be set.
      Throws:
      GErrorException - see GError
    • creat

      public static int creat(String filename, int mode)

      A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessary.

      On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements creat() and file descriptors. The actual Windows API for opening files is different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

      Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

      See your C library manual for more details about creat().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      mode - as in creat()
      Returns:
      a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().
      Since:
      2.8
    • datalistClear

      public static void datalistClear(Data[] datalist)
      Frees all the data elements of the datalist. The data elements' destroy functions are called if they have been set.
      Parameters:
      datalist - a datalist.
    • datalistForeach

      public static void datalistForeach(Data[] datalist, @Nullable DataForeachFunc func)

      Calls the given function for each data element of the datalist. The function is called with each data element's GQuark id and data, together with the given userData parameter. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

      func can make changes to datalist, but the iteration will not reflect changes made during the g_datalist_foreach() call, other than skipping over elements that are removed.

      Parameters:
      datalist - a datalist.
      func - the function to call for each data element.
    • datalistGetData

      public static @Nullable MemorySegment datalistGetData(Data[] datalist, String key)
      Gets a data element, using its string identifier. This is slower than g_datalist_id_get_data() because it compares strings.
      Parameters:
      datalist - a datalist.
      key - the string identifying a data element.
      Returns:
      the data element, or null if it is not found.
    • datalistGetFlags

      public static int datalistGetFlags(Data[] datalist)
      Gets flags values packed in together with the datalist. See g_datalist_set_flags().
      Parameters:
      datalist - pointer to the location that holds a list
      Returns:
      the flags of the datalist
      Since:
      2.8
    • datalistIdDupData

      public static @Nullable MemorySegment datalistIdDupData(Data[] datalist, Quark keyId, @Nullable DuplicateFunc dupFunc)

      This is a variant of g_datalist_id_get_data() which returns a 'duplicate' of the value. dupFunc defines the meaning of 'duplicate' in this context, it could e.g. take a reference on a ref-counted object.

      If the keyId is not set in the datalist then dupFunc will be called with a null argument.

      Note that dupFunc is called while the datalist is locked, so it is not allowed to read or modify the datalist.

      This function can be useful to avoid races when multiple threads are using the same datalist and the same key.

      Parameters:
      datalist - location of a datalist
      keyId - the GQuark identifying a data element
      dupFunc - function to duplicate the old value
      Returns:
      the result of calling dupFunc on the value associated with keyId in datalist, or null if not set. If dupFunc is null, the value is returned unmodified.
      Since:
      2.34
    • datalistIdGetData

      public static @Nullable MemorySegment datalistIdGetData(Data[] datalist, Quark keyId)
      Retrieves the data element corresponding to keyId.
      Parameters:
      datalist - a datalist.
      keyId - the GQuark identifying a data element.
      Returns:
      the data element, or null if it is not found.
    • datalistIdRemoveMultiple

      public static void datalistIdRemoveMultiple(Data[] datalist, @Nullable Quark @Nullable [] keys)

      Removes multiple keys from a datalist.

      This is more efficient than calling g_datalist_id_remove_data() multiple times in a row.

      Before 2.80, nKeys had to be not larger than 16. Since 2.84, performance is improved for larger number of keys.

      Parameters:
      datalist - a datalist
      keys - keys to remove
      Since:
      2.74
    • datalistIdRemoveNoNotify

      public static @Nullable MemorySegment datalistIdRemoveNoNotify(Data[] datalist, Quark keyId)
      Removes an element, without calling its destroy notification function.
      Parameters:
      datalist - a datalist.
      keyId - the GQuark identifying a data element.
      Returns:
      the data previously stored at keyId, or null if none.
    • datalistIdReplaceData

      public static boolean datalistIdReplaceData(Data[] datalist, Quark keyId, @Nullable MemorySegment oldval, @Nullable MemorySegment newval)

      Compares the member that is associated with keyId in datalist to oldval, and if they are the same, replace oldval with newval.

      This is like a typical atomic compare-and-exchange operation, for a member of datalist.

      If the previous value was replaced then ownership of the old value (oldval) is passed to the caller, including the registered destroy notify for it (passed out in oldDestroy). Its up to the caller to free this as they wish, which may or may not include using oldDestroy as sometimes replacement should not destroy the object in the normal way.

      Parameters:
      datalist - location of a datalist
      keyId - the GQuark identifying a data element
      oldval - the old value to compare against
      newval - the new value to replace it with
      Returns:
      true if the existing value for keyId was replaced by newval, false otherwise.
      Since:
      2.34
    • datalistIdSetDataFull

      public static void datalistIdSetDataFull(Data[] datalist, Quark keyId, @Nullable MemorySegment data)
      Sets the data corresponding to the given GQuark id, and the function to be called when the element is removed from the datalist. Any previous data with the same key is removed, and its destroy function is called.
      Parameters:
      datalist - a datalist.
      keyId - the GQuark to identify the data element.
      data - the data element or null to remove any previous element corresponding to keyId.
    • datalistInit

      public static void datalistInit(Data[] datalist)
      Resets the datalist to null. It does not free any memory or call any destroy functions.
      Parameters:
      datalist - a pointer to a pointer to a datalist.
    • datalistSetFlags

      public static void datalistSetFlags(Data[] datalist, int flags)
      Turns on flag values for a data list. This function is used to keep a small number of boolean flags in an object with a data list without using any additional space. It is not generally useful except in circumstances where space is very tight. (It is used in the base GObject type, for example.)
      Parameters:
      datalist - pointer to the location that holds a list
      flags - the flags to turn on. The values of the flags are restricted by G_DATALIST_FLAGS_MASK (currently 3; giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.
      Since:
      2.8
    • datalistUnsetFlags

      public static void datalistUnsetFlags(Data[] datalist, int flags)
      Turns off flag values for a data list. See g_datalist_unset_flags()
      Parameters:
      datalist - pointer to the location that holds a list
      flags - the flags to turn off. The values of the flags are restricted by G_DATALIST_FLAGS_MASK (currently 3: giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.
      Since:
      2.8
    • datasetDestroy

      public static void datasetDestroy(MemorySegment datasetLocation)
      Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.
      Parameters:
      datasetLocation - the location identifying the dataset.
    • datasetForeach

      public static void datasetForeach(MemorySegment datasetLocation, @Nullable DataForeachFunc func)

      Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unless datasetLocation can be protected from any modifications during invocation of this function, it should not be called.

      func can make changes to the dataset, but the iteration will not reflect changes made during the g_dataset_foreach() call, other than skipping over elements that are removed.

      Parameters:
      datasetLocation - the location identifying the dataset.
      func - the function to call for each data element.
    • datasetIdGetData

      public static @Nullable MemorySegment datasetIdGetData(MemorySegment datasetLocation, Quark keyId)
      Gets the data element corresponding to a GQuark.
      Parameters:
      datasetLocation - the location identifying the dataset.
      keyId - the GQuark id to identify the data element.
      Returns:
      the data element corresponding to the GQuark, or null if it is not found.
    • datasetIdRemoveNoNotify

      public static @Nullable MemorySegment datasetIdRemoveNoNotify(MemorySegment datasetLocation, Quark keyId)
      Removes an element, without calling its destroy notification function.
      Parameters:
      datasetLocation - the location identifying the dataset.
      keyId - the GQuark ID identifying the data element.
      Returns:
      the data previously stored at keyId, or null if none.
    • datasetIdSetDataFull

      public static void datasetIdSetDataFull(MemorySegment datasetLocation, Quark keyId, @Nullable MemorySegment data)
      Sets the data element associated with the given GQuark id, and also the function to call when the data element is destroyed. Any previous data with the same key is removed, and its destroy function is called.
      Parameters:
      datasetLocation - the location identifying the dataset.
      keyId - the GQuark id to identify the data element.
      data - the data element.
    • dcgettext

      public static String dcgettext(@Nullable String domain, String msgid, int category)
      This is a variant of g_dgettext() that allows specifying a locale category instead of always using LC_MESSAGES. See g_dgettext() for more information about how this functions differs from calling dcgettext() directly.
      Parameters:
      domain - the translation domain to use, or null to use the domain set with textdomain()
      msgid - message to translate
      category - a locale category
      Returns:
      the translated string for the given locale category
      Since:
      2.26
    • dgettext

      public static String dgettext(@Nullable String domain, String msgid)

      This function is a wrapper of dgettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

      The advantage of using this function over dgettext() proper is that libraries using this function (like GTK) will not use translations if the application using the library does not have translations for the current locale. This results in a consistent English-only interface instead of one having partial translations. For this feature to work, the call to textdomain() and setlocale() should precede any g_dgettext() invocations. For GTK, it means calling textdomain() before gtk_init or its variants.

      This function disables translations if and only if upon its first call all the following conditions hold:

      • domain is not null

      • textdomain() has been called to set a default text domain

      • there is no translations available for the default text domain and the current locale

      • current locale is not "C" or any English locales (those starting with "en_")

      Note that this behavior may not be desired for example if an application has its untranslated messages in a language other than English. In those cases the application should call textdomain() after initializing GTK.

      Applications should normally not use this function directly, but use the _() macro for translations.

      Parameters:
      domain - the translation domain to use, or null to use the domain set with textdomain()
      msgid - message to translate
      Returns:
      The translated string
      Since:
      2.18
    • directEqual

      public static boolean directEqual(@Nullable MemorySegment v1, @Nullable MemorySegment v2)

      Compares two gpointer arguments and returns true if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using opaque pointers compared by pointer value as keys in a GHashTable.

      This equality function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

      Parameters:
      v1 - a key
      v2 - a key to compare with v1
      Returns:
      true if the two keys match.
    • directHash

      public static int directHash(@Nullable MemorySegment v)

      Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as the hashFunc parameter, when using opaque pointers compared by pointer value as keys in a GHashTable.

      This hash function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

      Parameters:
      v - a gpointer key
      Returns:
      a hash value corresponding to the key.
    • dngettext

      public static String dngettext(@Nullable String domain, String msgid, String msgidPlural, int n)

      This function is a wrapper of dngettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

      See g_dgettext() for details of how this differs from dngettext() proper.

      Parameters:
      domain - the translation domain to use, or null to use the domain set with textdomain()
      msgid - message to translate
      msgidPlural - plural form of the message
      n - the quantity for which translation is needed
      Returns:
      The translated string
      Since:
      2.18
    • doubleEqual

      public static boolean doubleEqual(MemorySegment v1, MemorySegment v2)
      Compares the two gdouble values being pointed to and returns true if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-null pointers to doubles as keys in a GHashTable.
      Parameters:
      v1 - a pointer to a gdouble key
      v2 - a pointer to a gdouble key to compare with v1
      Returns:
      true if the two keys match.
      Since:
      2.22
    • doubleHash

      public static int doubleHash(MemorySegment v)
      Converts a pointer to a gdouble to a hash value. It can be passed to g_hash_table_new() as the hashFunc parameter, It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-null pointers to doubles as keys in a GHashTable.
      Parameters:
      v - a pointer to a gdouble key
      Returns:
      a hash value corresponding to the key.
      Since:
      2.22
    • dpgettext

      public static String dpgettext(@Nullable String domain, String msgctxtid, long msgidoffset)

      This function is a variant of g_dgettext() which supports a disambiguating message context. GNU gettext uses the '\004' character to separate the message context and message id in msgctxtid. If 0 is passed as msgidoffset, this function will fall back to trying to use the deprecated convention of using "|" as a separation character.

      This uses g_dgettext() internally. See that functions for differences with dgettext() proper.

      Applications should normally not use this function directly, but use the C_() macro for translations with context.

      Parameters:
      domain - the translation domain to use, or null to use the domain set with textdomain()
      msgctxtid - a combined message context and message id, separated by a \004 character
      msgidoffset - the offset of the message id in msgctxid
      Returns:
      The translated string
      Since:
      2.16
    • dpgettext2

      public static String dpgettext2(@Nullable String domain, String context, String msgid)

      This function is a variant of g_dgettext() which supports a disambiguating message context. GNU gettext uses the '\004' character to separate the message context and message id in msgctxtid.

      This uses g_dgettext() internally. See that functions for differences with dgettext() proper.

      This function differs from C_() in that it is not a macro and thus you may use non-string-literals as context and msgid arguments.

      Parameters:
      domain - the translation domain to use, or null to use the domain set with textdomain()
      context - the message context
      msgid - the message
      Returns:
      The translated string
      Since:
      2.18
    • environGetenv

      public static @Nullable String environGetenv(@Nullable String @Nullable [] envp, String variable)
      Returns the value of the environment variable variable in the provided list envp.
      Parameters:
      envp - an environment list (eg, as returned from g_get_environ()), or null for an empty environment list
      variable - the environment variable to get
      Returns:
      the value of the environment variable, or null if the environment variable is not set in envp. The returned string is owned by envp, and will be freed if variable is set or unset again.
      Since:
      2.32
    • environSetenv

      public static String[] environSetenv(@Nullable String @Nullable [] envp, String variable, String value, boolean overwrite)
      Sets the environment variable variable in the provided list envp to value.
      Parameters:
      envp - an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), or null for an empty environment list
      variable - the environment variable to set, must not contain '='
      value - the value for to set the variable to
      overwrite - whether to change the variable if it already exists
      Returns:
      the updated environment list. Free it using g_strfreev().
      Since:
      2.32
    • environUnsetenv

      public static String[] environUnsetenv(@Nullable String @Nullable [] envp, String variable)
      Removes the environment variable variable from the provided environment envp.
      Parameters:
      envp - an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), or null for an empty environment list
      variable - the environment variable to remove, must not contain '='
      Returns:
      the updated environment list. Free it using g_strfreev().
      Since:
      2.32
    • fileErrorFromErrno

      public static FileError fileErrorFromErrno(int errNo)

      Gets a GFileError constant based on the passed-in errNo.

      For example, if you pass in EEXIST this function returns FileError.EXIST. Unlike errno values, you can portably assume that all GFileError values will exist.

      Normally a GFileError value goes into a GError returned from a function that manipulates files. So you would use g_file_error_from_errno() when constructing a GError.

      Parameters:
      errNo - an "errno" value
      Returns:
      GFileError corresponding to the given errNo
    • fileErrorQuark

      public static Quark fileErrorQuark()
    • fileGetContents

      public static boolean fileGetContents(String filename, @Nullable Out<byte[]> contents) throws GErrorException

      Reads an entire file into allocated memory, with good error checking.

      If the call was successful, it returns true and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be nul-terminated, so for text files you can pass null for the length argument. If the call was not successful, it returns false and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration. In the error case, contents is set to null and length is set to zero.

      Parameters:
      filename - name of a file to read contents from, in the GLib file name encoding
      contents - location to store an allocated string, use g_free() to free the returned string
      Returns:
      true on success, false if an error occurred
      Throws:
      GErrorException - see GError
    • fileOpenTmp

      public static int fileOpenTmp(@Nullable String tmpl, Out<String> nameUsed) throws GErrorException

      Opens a file for writing in the preferred directory for temporary files (as returned by g_get_tmp_dir()).

      tmpl should be a string in the GLib file name encoding containing a sequence of six 'X' characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is null, a default template is used.

      Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

      Upon success, and if nameUsed is non-null, the actual name used is returned in nameUsed. This string should be freed with g_free() when not needed any longer. The returned name is in the GLib file name encoding.

      Parameters:
      tmpl - Template for file name, as in g_mkstemp(), basename only, or null for a default template
      nameUsed - location to store actual name used, or null
      Returns:
      A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and error will be set.
      Throws:
      GErrorException - see GError
    • fileReadLink

      public static String fileReadLink(String filename) throws GErrorException

      Reads the contents of the symbolic link filename like the POSIX readlink() function.

      The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to convert it to UTF-8.

      The returned string may also be a relative path. Use g_build_filename() to convert it to an absolute path:

      g_autoptr(GError) local_error = NULL;
      g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);
      
      if (local_error != NULL)
        g_error ("Error reading link: %s", local_error->message);
      
      if (!g_path_is_absolute (link_target))
        {
          g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
          g_free (link_target);
          link_target = g_steal_pointer (&absolute_link_target);
        }
      
      Parameters:
      filename - the symbolic link
      Returns:
      A newly-allocated string with the contents of the symbolic link, or null if an error occurred.
      Throws:
      GErrorException - see GError
      Since:
      2.4
    • fileSetContents

      public static boolean fileSetContents(String filename, @Nullable byte @Nullable [] contents) throws GErrorException
      Writes all of contents to a file named filename. This is a convenience wrapper around calling g_file_set_contents_full() with flags set to G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING and mode set to 0666.
      Parameters:
      filename - name of a file to write contents to, in the GLib file name encoding
      contents - string to write to the file
      Returns:
      true on success, false if an error occurred
      Throws:
      GErrorException - see GError
      Since:
      2.8
    • fileSetContentsFull

      public static boolean fileSetContentsFull(String filename, @Nullable byte @Nullable [] contents, Set<FileSetContentsFlags> flags, int mode) throws GErrorException

      Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

      flags control the properties of the write operation: whether it’s atomic, and what the tradeoff is between returning quickly or being resilient to system crashes.

      As this function performs file I/O, it is recommended to not call it anywhere where blocking would cause problems, such as in the main loop of a graphical application. In particular, if flags has any value other than FileSetContentsFlags.NONE then this function may call fsync().

      If FileSetContentsFlags.CONSISTENT is set in flags, the operation is atomic in the sense that it is first written to a temporary file which is then renamed to the final name.

      Notes:

      • On UNIX, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.

      • On UNIX, if filename already exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and if FileSetContentsFlags.CONSISTENT is set in flags, the fsync() call (or equivalent) will be used to ensure atomic replacement: filename will contain either its old contents or contents, even in the face of system power loss, the disk being unsafely removed, etc.

      • On UNIX, if filename does not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leave filename empty or full of NUL bytes, depending on the underlying filesystem, unless FileSetContentsFlags.DURABLE and FileSetContentsFlags.CONSISTENT are set in flags.

      • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.

      • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

      If the call was successful, it returns true. If the call was not successful, it returns false and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration.

      Note that the name for the temporary file is constructed by appending up to 7 characters to filename.

      If the file didn’t exist before and is created, it will be given the permissions from mode. Otherwise, the permissions of the existing file will remain unchanged.

      Parameters:
      filename - name of a file to write contents to, in the GLib file name encoding
      contents - string to write to the file
      flags - flags controlling the safety vs speed of the operation
      mode - file mode, as passed to open(); typically this will be 0666
      Returns:
      true on success, false if an error occurred
      Throws:
      GErrorException - see GError
      Since:
      2.66
    • fileSetContentsFull

      public static boolean fileSetContentsFull(String filename, @Nullable byte @Nullable [] contents, FileSetContentsFlags flags, int mode) throws GErrorException

      Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

      flags control the properties of the write operation: whether it’s atomic, and what the tradeoff is between returning quickly or being resilient to system crashes.

      As this function performs file I/O, it is recommended to not call it anywhere where blocking would cause problems, such as in the main loop of a graphical application. In particular, if flags has any value other than FileSetContentsFlags.NONE then this function may call fsync().

      If FileSetContentsFlags.CONSISTENT is set in flags, the operation is atomic in the sense that it is first written to a temporary file which is then renamed to the final name.

      Notes:

      • On UNIX, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.

      • On UNIX, if filename already exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and if FileSetContentsFlags.CONSISTENT is set in flags, the fsync() call (or equivalent) will be used to ensure atomic replacement: filename will contain either its old contents or contents, even in the face of system power loss, the disk being unsafely removed, etc.

      • On UNIX, if filename does not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leave filename empty or full of NUL bytes, depending on the underlying filesystem, unless FileSetContentsFlags.DURABLE and FileSetContentsFlags.CONSISTENT are set in flags.

      • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.

      • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

      If the call was successful, it returns true. If the call was not successful, it returns false and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration.

      Note that the name for the temporary file is constructed by appending up to 7 characters to filename.

      If the file didn’t exist before and is created, it will be given the permissions from mode. Otherwise, the permissions of the existing file will remain unchanged.

      Parameters:
      filename - name of a file to write contents to, in the GLib file name encoding
      contents - string to write to the file
      flags - flags controlling the safety vs speed of the operation
      mode - file mode, as passed to open(); typically this will be 0666
      Returns:
      true on success, false if an error occurred
      Throws:
      GErrorException - see GError
      Since:
      2.66
    • fileTest

      public static boolean fileTest(String filename, Set<FileTest> test)

      Returns true if any of the tests in the bitfield test are true. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return true if the file exists; the check whether it's a directory doesn't matter since the existence test is true. With the current set of available tests, there's no point passing in more than one test at a time.

      Apart from FileTest.IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will return true for both FileTest.IS_SYMLINK and FileTest.IS_REGULAR.

      Note, that for a dangling symbolic link g_file_test() will return true for FileTest.IS_SYMLINK and false for all other flags.

      You should never use g_file_test() to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before you actually perform the operation, see TOCTOU.

      For example, you might think you could use FileTest.IS_SYMLINK to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn't work!

       // DON'T DO THIS
       if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
         {
           fd = g_open (filename, O_WRONLY);
           // write to fd
         }
      
       // DO THIS INSTEAD
       fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
       if (fd == -1)
         {
           // check error
           if (errno == ELOOP)
             // file is a symlink and can be ignored
           else
             // handle errors as before
         }
       else
         {
           // write to fd
         }
      

      Another thing to note is that FileTest.EXISTS and FileTest.IS_EXECUTABLE are implemented using the access() system call. This usually doesn't matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

      On Windows, there are no symlinks, so testing for FileTest.IS_SYMLINK will always return false. Testing for FileTest.IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

      Parameters:
      filename - a filename to test in the GLib file name encoding
      test - bitfield of GFileTest flags
      Returns:
      whether a test was true
    • fileTest

      public static boolean fileTest(String filename, FileTest... test)

      Returns true if any of the tests in the bitfield test are true. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return true if the file exists; the check whether it's a directory doesn't matter since the existence test is true. With the current set of available tests, there's no point passing in more than one test at a time.

      Apart from FileTest.IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will return true for both FileTest.IS_SYMLINK and FileTest.IS_REGULAR.

      Note, that for a dangling symbolic link g_file_test() will return true for FileTest.IS_SYMLINK and false for all other flags.

      You should never use g_file_test() to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before you actually perform the operation, see TOCTOU.

      For example, you might think you could use FileTest.IS_SYMLINK to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn't work!

       // DON'T DO THIS
       if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
         {
           fd = g_open (filename, O_WRONLY);
           // write to fd
         }
      
       // DO THIS INSTEAD
       fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
       if (fd == -1)
         {
           // check error
           if (errno == ELOOP)
             // file is a symlink and can be ignored
           else
             // handle errors as before
         }
       else
         {
           // write to fd
         }
      

      Another thing to note is that FileTest.EXISTS and FileTest.IS_EXECUTABLE are implemented using the access() system call. This usually doesn't matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

      On Windows, there are no symlinks, so testing for FileTest.IS_SYMLINK will always return false. Testing for FileTest.IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

      Parameters:
      filename - a filename to test in the GLib file name encoding
      test - bitfield of GFileTest flags
      Returns:
      whether a test was true
    • filenameDisplayBasename

      public static String filenameDisplayBasename(String filename)

      Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display.

      If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

      You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.

      This function is preferred over g_filename_display_name() if you know the whole path, as it allows translation.

      Parameters:
      filename - an absolute pathname in the GLib file name encoding
      Returns:
      a newly allocated string containing a rendition of the basename of the filename in valid UTF-8
      Since:
      2.6
    • filenameDisplayName

      public static String filenameDisplayName(String filename)

      Converts a filename into a valid UTF-8 string. The conversion is not necessarily reversible, so you should keep the original around and use the return value of this function only for display purposes. Unlike g_filename_to_utf8(), the result is guaranteed to be non-null even if the filename actually isn't in the GLib file name encoding.

      If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

      If you know the whole pathname of the file you should use g_filename_display_basename(), since that allows location-based translation of filenames.

      Parameters:
      filename - a pathname hopefully in the GLib file name encoding
      Returns:
      a newly allocated string containing a rendition of the filename in valid UTF-8
      Since:
      2.6
    • filenameFromUri

      public static String filenameFromUri(String uri, @Nullable Out<String> hostname) throws GErrorException

      Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

      Since GLib 2.78, the query string and fragment can be present in the URI, but are not part of the resulting filename. We take inspiration from https://url.spec.whatwg.org/file-state, but we don't support the entire standard.

      Parameters:
      uri - a uri describing a filename (escaped, encoded in ASCII).
      hostname - Location to store hostname for the URI. If there is no hostname in the URI, null will be stored in this location.
      Returns:
      a newly-allocated string holding the resulting filename, or null on an error.
      Throws:
      GErrorException - see GError
    • filenameFromUtf8

      public static String filenameFromUtf8(String utf8string, long len, @Nullable Out<Long> bytesRead, @Nullable Out<Long> bytesWritten) throws GErrorException

      Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

      The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertError.ILLEGAL_SEQUENCE. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertError.EMBEDDED_NUL is set and the function returns null.

      Parameters:
      utf8string - a UTF-8 encoded string.
      len - the length of the string, or -1 if the string is nul-terminated.
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
      bytesWritten - the number of bytes stored in the output buffer (not including the terminating nul).
      Returns:
      The converted string, or null on an error.
      Throws:
      GErrorException - see GError
    • filenameToUri

      public static String filenameToUri(String filename, @Nullable String hostname) throws GErrorException
      Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.
      Parameters:
      filename - an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windows
      hostname - A UTF-8 encoded hostname, or null for none.
      Returns:
      a newly-allocated string holding the resulting URI, or null on an error.
      Throws:
      GErrorException - see GError
    • filenameToUtf8

      public static String filenameToUtf8(String opsysstring, long len, @Nullable Out<Long> bytesRead, @Nullable Out<Long> bytesWritten) throws GErrorException

      Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

      The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertError.ILLEGAL_SEQUENCE. If the source encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertError.EMBEDDED_NUL is set and the function returns null. Use g_convert() to produce output that may contain embedded nul characters.

      Parameters:
      opsysstring - a string in the encoding for filenames
      len - the length of the string, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
      bytesWritten - the number of bytes stored in the output buffer (not including the terminating nul).
      Returns:
      The converted string, or null on an error.
      Throws:
      GErrorException - see GError
    • findProgramInPath

      public static @Nullable String findProgramInPath(String program)

      Locates the first executable named program in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or null if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and null otherwise.

      On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

      On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

      Parameters:
      program - a program name in the GLib file name encoding
      Returns:
      a newly-allocated string with the absolute path, or null
    • fopen

      public static @Nullable MemorySegment fopen(String filename, String mode)

      A wrapper for the stdio fopen() function. The fopen() function opens a file and associates a new stream with it.

      Because file descriptors are specific to the C library on Windows, and a file descriptor is part of the FILE struct, the FILE* returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the FILE* returned by this function cannot be passed to C library functions like fprintf() or fread().

      See your C library manual for more details about fopen().

      As close() and fclose() are part of the C library, this implies that it is currently impossible to close a file if the application C library and the C library used by GLib are different. Convenience functions like g_file_set_contents_full() avoid this problem.

      Since GLib 2.86, the e option is supported in mode on all platforms. On Unix platforms it will set O_CLOEXEC on the opened file descriptor. On Windows platforms it will be converted to the N modifier. It is recommended to set e unconditionally, unless you know the returned file should be shared between this process and a new fork.

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      mode - a string describing the mode in which the file should be opened
      Returns:
      A FILE* if the file was successfully opened, or null if an error occurred
      Since:
      2.6
    • formatSize

      public static String formatSize(long size)

      Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (kB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.2 MB". The returned string is UTF-8, and may use a non-breaking space to separate the number and units, to ensure they aren’t separated when line wrapped.

      The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).

      This string should be freed with g_free() when not needed any longer.

      See g_format_size_full() for more options about how the size might be formatted.

      Parameters:
      size - a size in bytes
      Returns:
      a newly-allocated formatted string containing a human readable file size
      Since:
      2.30
    • formatSizeForDisplay

      @Deprecated public static String formatSizeForDisplay(long size)
      Deprecated.
      This function is broken due to its use of SI suffixes to denote IEC units. Use g_format_size() instead.

      Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.1 MB".

      The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).

      This string should be freed with g_free() when not needed any longer.

      Parameters:
      size - a size in bytes
      Returns:
      a newly-allocated formatted string containing a human readable file size
      Since:
      2.16
    • formatSizeFull

      public static String formatSizeFull(long size, Set<FormatSizeFlags> flags)

      Formats a size.

      This function is similar to g_format_size() but allows for flags that modify the output. See GFormatSizeFlags.

      Parameters:
      size - a size in bytes
      flags - GFormatSizeFlags to modify the output
      Returns:
      a newly-allocated formatted string containing a human readable file size
      Since:
      2.30
    • formatSizeFull

      public static String formatSizeFull(long size, FormatSizeFlags... flags)

      Formats a size.

      This function is similar to g_format_size() but allows for flags that modify the output. See GFormatSizeFlags.

      Parameters:
      size - a size in bytes
      flags - GFormatSizeFlags to modify the output
      Returns:
      a newly-allocated formatted string containing a human readable file size
      Since:
      2.30
    • fprintf

      public static int fprintf(MemorySegment file, String format, Object... varargs)

      An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.

      glib/gprintf.h must be explicitly included in order to use this function.

      Parameters:
      file - the stream to write to
      format - a standard printf() format string, but notice string precision pitfalls
      varargs - the arguments to insert in the output
      Returns:
      the number of bytes printed
      Since:
      2.2
    • free

      public static void free(@Nullable MemorySegment mem)

      Frees the memory pointed to by mem.

      If you know the allocated size of mem, calling g_free_sized() may be faster, depending on the libc implementation in use.

      Starting from GLib 2.78, this may happen automatically in case a GCC compatible compiler is used with some optimization level and the allocated size is known at compile time (see documentation of __builtin_object_size() to understand its caveats).

      If mem is null it simply returns, so there is no need to check mem against null before calling this function.

      Parameters:
      mem - the memory to free
    • freeSized

      public static void freeSized(@Nullable MemorySegment mem, long size)

      Frees the memory pointed to by mem, assuming it is has the given size.

      If mem is null this is a no-op (and size is ignored).

      It is an error if size doesn’t match the size passed when mem was allocated. size is passed to this function to allow optimizations in the allocator. If you don’t know the allocation size, use g_free() instead.

      In case a GCC compatible compiler is used, this function may be used automatically via g_free() if the allocated size is known at compile time, since GLib 2.78.

      Parameters:
      mem - the memory to free
      size - size of mem, in bytes
      Since:
      2.76
    • freopen

      public static @Nullable MemorySegment freopen(String filename, String mode, @Nullable MemorySegment stream)

      A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.

      See your C library manual for more details about freopen().

      Since GLib 2.86, the e option is supported in mode on all platforms. See the documentation for fopen(String, String) for more details.

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      mode - a string describing the mode in which the file should be opened
      stream - an existing stream which will be reused, or null
      Returns:
      A FILE* if the file was successfully opened, or null if an error occurred.
      Since:
      2.6
    • fsync

      public static int fsync(int fd)

      A wrapper for the POSIX fsync() function. On Windows, _commit() will be used. On macOS, fcntl(F_FULLFSYNC) will be used. The fsync() function is used to synchronize a file's in-core state with that of the disk.

      This wrapper will handle retrying on EINTR.

      See the C library manual for more details about fsync().

      Parameters:
      fd - a file descriptor
      Returns:
      0 on success, or -1 if an error occurred. The return value can be used exactly like the return value from fsync().
      Since:
      2.64
    • getApplicationName

      public static @Nullable String getApplicationName()
      Gets a human-readable name for the application, as set by g_set_application_name(). This name should be localized if possible, and is intended for display to the user. Contrast with g_get_prgname(), which gets a non-localized name. If g_set_application_name() has not been called, returns the result of g_get_prgname() (which may be null if g_set_prgname() has also not been called).
      Returns:
      human-readable application name. May return null
      Since:
      2.2
    • getCharset

      public static boolean getCharset(@Nullable Out<String> charset)

      Obtains the character set for the current locale; you might use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8() are nice shortcuts, though.)

      On Windows the character set returned by this function is the so-called system default ANSI code-page. That is the character set used by the "narrow" versions of C library and Win32 functions that handle file names. It might be different from the character set used by the C library's current locale.

      On Linux, the character set is found by consulting nl_langinfo() if available. If not, the environment variables LC_ALL, LC_CTYPE, LANG and CHARSET are queried in order. nl_langinfo() returns the C locale if no locale has been loaded by setlocale().

      The return value is true if the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().

      The string returned in charset is not allocated, and should not be freed.

      Parameters:
      charset - return location for character set name, or null.
      Returns:
      true if the returned charset is UTF-8
    • getCodeset

      public static String getCodeset()
      Gets the character set for the current locale.
      Returns:
      a newly allocated string containing the name of the character set. This string must be freed with g_free().
    • getConsoleCharset

      public static boolean getConsoleCharset(@Nullable Out<String> charset)

      Obtains the character set used by the console attached to the process, which is suitable for printing output to the terminal.

      Usually this matches the result returned by g_get_charset(), but in environments where the locale's character set does not match the encoding of the console this function tries to guess a more suitable value instead.

      On Windows the character set returned by this function is the output code page used by the console associated with the calling process. If the codepage can't be determined (for example because there is no console attached) UTF-8 is assumed.

      The return value is true if the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().

      The string returned in charset is not allocated, and should not be freed.

      Parameters:
      charset - return location for character set name, or null.
      Returns:
      true if the returned charset is UTF-8
      Since:
      2.62
    • getCurrentDir

      public static String getCurrentDir()

      Gets the current directory.

      The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

      Since GLib 2.40, this function will return the value of the "PWD" environment variable if it is set and it happens to be the same as the current directory. This can make a difference in the case that the current directory is the target of a symbolic link.

      Returns:
      the current directory
    • getCurrentTime

      @Deprecated public static void getCurrentTime(TimeVal result)
      Deprecated.
      GLib.TimeVal is not year-2038-safe. Use getRealTime() instead.

      Queries the system wall-clock time.

      This is equivalent to the UNIX gettimeofday() function, but portable.

      You may find getRealTime() to be more convenient.

      Parameters:
      result - GLib.TimeVal structure in which to store current time
    • getEnviron

      public static String[] getEnviron()

      Gets the list of environment variables for the current process.

      The list is null terminated and each item in the list is of the form 'NAME=VALUE'.

      This is equivalent to direct access to the 'environ' global variable, except portable.

      The return value is freshly allocated and it should be freed with g_strfreev() when it is no longer needed.

      Returns:
      the list of environment variables
      Since:
      2.28
    • getFilenameCharsets

      public static boolean getFilenameCharsets(@Nullable Out<String[]> filenameCharsets)

      Determines the preferred character sets used for filenames. The first character set from the charsets is the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, see g_filename_display_name().

      On Unix, the character sets are determined by consulting the environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES. On Windows, the character set used in the GLib API is always UTF-8 and said environment variables have no effect.

      G_FILENAME_ENCODING may be set to a comma-separated list of character set names. The special token @locale is taken to mean the character set for the current locale. If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the character set of the current locale is taken as the filename encoding. If neither environment variable is set, UTF-8 is taken as the filename encoding, but the character set of the current locale is also put in the list of encodings.

      The returned charsets belong to GLib and must not be freed.

      Note that on Unix, regardless of the locale character set or G_FILENAME_ENCODING value, the actual file names present on a system might be in any random encoding or just gibberish.

      Parameters:
      filenameCharsets - return location for the null-terminated list of encoding names
      Returns:
      true if the filename encoding is UTF-8.
      Since:
      2.6
    • getHomeDir

      public static String getHomeDir()

      Gets the current user's home directory.

      As with most UNIX tools, this function will return the value of the HOME environment variable if it is set to an existing absolute path name, falling back to the passwd file in the case that it is unset.

      If the path given in HOME is non-absolute, does not exist, or is not a directory, the result is undefined.

      Before version 2.36 this function would ignore the HOME environment variable, taking the value from the passwd database instead. This was changed to increase the compatibility of GLib with other programs (and the XDG basedir specification) and to increase testability of programs based on GLib (by making it easier to run them from test frameworks).

      If your program has a strong requirement for either the new or the old behaviour (and if you don't wish to increase your GLib dependency to ensure that the new behaviour is in effect) then you should either directly check the HOME environment variable yourself or unset it before calling any functions in GLib.

      Returns:
      the current user's home directory
    • getHostName

      public static String getHostName()

      Return a name for the machine.

      The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

      The encoding of the returned string is UTF-8.

      Returns:
      the host name of the machine.
      Since:
      2.8
    • getLanguageNames

      public static String[] getLanguageNames()

      Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

      For example, if LANGUAGE=de:en_US, then the returned list is "de", "en_US", "en", "C".

      This function consults the environment variables LANGUAGE, LC_ALL, LC_MESSAGES and LANG to find the list of locales specified by the user.

      Returns:
      a null-terminated array of strings owned by GLib that must not be modified or freed.
      Since:
      2.6
    • getLanguageNamesWithCategory

      public static String[] getLanguageNamesWithCategory(String categoryName)

      Computes a list of applicable locale names with a locale category name, which can be used to construct the fallback locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

      This function consults the environment variables LANGUAGE, LC_ALL, categoryName, and LANG to find the list of locales specified by the user.

      g_get_language_names() returns g_get_language_names_with_category("LC_MESSAGES").

      Parameters:
      categoryName - a locale category name
      Returns:
      a null-terminated array of strings owned by the thread g_get_language_names_with_category was called from. It must not be modified or freed. It must be copied if planned to be used in another thread.
      Since:
      2.58
    • getLocaleVariants

      public static String[] getLocaleVariants(String locale)

      Returns a list of derived variants of locale, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable. This function handles territory, charset and extra locale modifiers. See setlocale(3) for information about locales and their format.

      locale itself is guaranteed to be returned in the output.

      For example, if locale is fr_BE, then the returned list is fr_BE, fr. If locale is en_GB.UTF-8@euro, then the returned list is en_GB.UTF-8@euro, en_GB.UTF-8, en_GB@euro, en_GB, en.UTF-8@euro, en.UTF-8, en@euro, en.

      If you need the list of variants for the current locale, use g_get_language_names().

      Parameters:
      locale - a locale identifier
      Returns:
      a newly allocated array of newly allocated strings with the locale variants. Free with g_strfreev().
      Since:
      2.28
    • getMonotonicTime

      public static long getMonotonicTime()

      Queries the system monotonic time in microseconds.

      The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.

      We try to use the clock that corresponds as closely as possible to the passage of time as measured by system calls such as poll() but it may not always be possible to do this.

      A more accurate version of this function exists. getMonotonicTimeNs() returns the time in nanoseconds.

      Returns:
      the monotonic time, in microseconds
      Since:
      2.28
    • getMonotonicTimeNs

      public static long getMonotonicTimeNs()

      Queries the system monotonic time in nanoseconds.

      The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.

      We try to use the clock that corresponds as closely as possible to the passage of time as measured by system calls such as poll() but it may not always be possible to do this.

      Another version of this function exists. getMonotonicTime() returns the time in microseconds. If you want to support older GLib versions, it is an alternative.

      Returns:
      the monotonic time, in nanoseconds
      Since:
      2.88
    • getNumProcessors

      public static int getNumProcessors()
      Determine the approximate number of threads that the system will schedule simultaneously for this process. This is intended to be used as a parameter to g_thread_pool_new() for CPU bound tasks and similar cases.
      Returns:
      Number of schedulable threads, always greater than 0
      Since:
      2.36
    • getOsInfo

      public static @Nullable String getOsInfo(String keyName)

      Get information about the operating system.

      On Linux this comes from the /etc/os-release file. On other systems, it may come from a variety of sources. You can either use the standard key names like G_OS_INFO_KEY_NAME or pass any UTF-8 string key name. For example, /etc/os-release provides a number of other less commonly used values that may be useful. No key is guaranteed to be provided, so the caller should always check if the result is null.

      Parameters:
      keyName - a key for the OS info being requested, for example G_OS_INFO_KEY_NAME.
      Returns:
      The associated value for the requested key or null if this information is not provided.
      Since:
      2.64
    • getPrgname

      public static @Nullable String getPrgname()

      Gets the name of the program. This name should not be localized, in contrast to g_get_application_name().

      If you are using GApplication the program name is set in g_application_run(). In case of GDK or GTK it is set in gdk_init(), which is called by gtk_init() and the GtkApplication::startup handler. The program name is found by taking the last component of argv[0].

      Returns:
      the name of the program, or null if it has not been set yet. The returned string belongs to GLib and must not be modified or freed.
    • getRealName

      public static String getRealName()
      Gets the real name of the user. This usually comes from the user's entry in the passwd file. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string "Unknown" is returned.
      Returns:
      the user's real name.
    • getRealTime

      public static long getRealTime()

      Queries the system wall-clock time.

      This is equivalent to the UNIX gettimeofday() function, but portable.

      You should only use this call if you are actually interested in the real wall-clock time. getMonotonicTime() is probably more useful for measuring intervals.

      Returns:
      the number of microseconds since January 1, 1970 UTC
      Since:
      2.28
    • getSystemConfigDirs

      public static String[] getSystemConfigDirs()

      Returns an ordered list of base directories in which to access system-wide configuration information.

      On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the list of directories retrieved will be XDG_CONFIG_DIRS.

      On Windows it follows XDG Base Directory Specification if XDG_CONFIG_DIRS is defined. If XDG_CONFIG_DIRS is undefined, the directory that contains application data for all users is used instead. A typical path is C:\\Documents and Settings\\All Users\\Application Data. This folder is used for application data that is not user specific. For example, an application can store a spell-check dictionary, a database of clip art, or a log file in the FOLDERID_ProgramData folder. This information will not roam and is available to anyone using the computer.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a null-terminated array of strings owned by GLib that must not be modified or freed.
      Since:
      2.6
    • getSystemDataDirs

      public static String[] getSystemDataDirs()

      Returns an ordered list of base directories in which to access system-wide application data.

      On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification In this case the list of directories retrieved will be XDG_DATA_DIRS.

      On Windows it follows XDG Base Directory Specification if XDG_DATA_DIRS is defined. If XDG_DATA_DIRS is undefined, the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for FOLDERID_ProgramData and FOLDERID_PublicDocuments.

      Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

      Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.

      The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.

      Note that on Windows the returned list can vary depending on where this function is called.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a null-terminated array of strings owned by GLib that must not be modified or freed.
      Since:
      2.6
    • getTmpDir

      public static String getTmpDir()

      Gets the directory to use for temporary files.

      On UNIX, this is taken from the TMPDIR environment variable. If the variable is not set, P_tmpdir is used, as defined by the system C library. Failing that, a hard-coded default of "/tmp" is returned.

      On Windows, the TEMP environment variable is used, with the root directory of the Windows installation (eg: "C:\") used as a default.

      The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never null or the empty string.

      Returns:
      the directory to use for temporary files.
    • getUserCacheDir

      public static String getUserCacheDir()

      Returns a base directory in which to store non-essential, cached data specific to particular user.

      On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_CACHE_HOME.

      On Windows it follows XDG Base Directory Specification if XDG_CACHE_HOME is defined. If XDG_CACHE_HOME is undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path is C:\\Documents and Settings\\username\\Local Settings\\Temporary Internet Files. See the documentation for FOLDERID_InternetCache.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a string owned by GLib that must not be modified or freed.
      Since:
      2.6
    • getUserConfigDir

      public static String getUserConfigDir()

      Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.

      On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_CONFIG_HOME.

      On Windows it follows XDG Base Directory Specification if XDG_CONFIG_HOME is defined. If XDG_CONFIG_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for FOLDERID_LocalAppData. Note that in this case on Windows it will be the same as what g_get_user_data_dir() returns.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a string owned by GLib that must not be modified or freed.
      Since:
      2.6
    • getUserDataDir

      public static String getUserDataDir()

      Returns a base directory in which to access application data such as icons that is customized for a particular user.

      On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_DATA_HOME.

      On Windows it follows XDG Base Directory Specification if XDG_DATA_HOME is defined. If XDG_DATA_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for FOLDERID_LocalAppData. Note that in this case on Windows it will be the same as what g_get_user_config_dir() returns.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a string owned by GLib that must not be modified or freed.
      Since:
      2.6
    • getUserName

      public static String getUserName()
      Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.
      Returns:
      the user name of the current user.
    • getUserRuntimeDir

      public static String getUserRuntimeDir()

      Returns a directory that is unique to the current user on the local system.

      This is determined using the mechanisms described in the XDG Base Directory Specification. This is the directory specified in the XDG_RUNTIME_DIR environment variable. In the case that this variable is not set, we return the value of g_get_user_cache_dir(), after verifying that it exists.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a string owned by GLib that must not be modified or freed.
      Since:
      2.28
    • getUserSpecialDir

      public static @Nullable String getUserSpecialDir(UserDirectory directory)

      Returns the full path of a special directory using its logical id.

      On UNIX this is done using the XDG special user directories. For compatibility with existing practise, UserDirectory.DIRECTORY_DESKTOP falls back to $HOME/Desktop when XDG special user directories have not been set up.

      Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

      Parameters:
      directory - the logical id of special directory
      Returns:
      the path to the specified special directory, or null if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.
      Since:
      2.14
    • getUserStateDir

      public static String getUserStateDir()

      Returns a base directory in which to store state files specific to particular user.

      On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_STATE_HOME.

      On Windows it follows XDG Base Directory Specification if XDG_STATE_HOME is defined. If XDG_STATE_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for FOLDERID_LocalAppData. Note that in this case on Windows it will be the same as what g_get_user_data_dir() returns.

      The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

      Returns:
      a string owned by GLib that must not be modified or freed.
      Since:
      2.72
    • getenv

      public static @Nullable String getenv(String variable)

      Returns the value of an environment variable.

      On UNIX, the name and value are byte strings which might or might not be in some consistent character set and encoding. On Windows, they are in UTF-8. On Windows, in case the environment variable's value contains references to other environment variables, they are expanded.

      Parameters:
      variable - the environment variable to get
      Returns:
      the value of the environment variable, or null if the environment variable is not found. The returned string may be overwritten by the next call to g_getenv(), g_setenv() or g_unsetenv().
    • hostnameIsAsciiEncoded

      public static boolean hostnameIsAsciiEncoded(String hostname)

      Tests if hostname contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returns true, you should decode the hostname with g_hostname_to_unicode() before displaying it to the user.

      Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for g_hostname_is_non_ascii() and g_hostname_is_ascii_encoded() to both return true for a name.

      Parameters:
      hostname - a hostname
      Returns:
      true if hostname contains any ASCII-encoded segments.
      Since:
      2.22
    • hostnameIsIpAddress

      public static boolean hostnameIsIpAddress(String hostname)

      Tests if hostname is the string form of an IPv4 or IPv6 address. (Eg, "192.168.0.1".)

      Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).

      Parameters:
      hostname - a hostname (or IP address in string form)
      Returns:
      true if hostname is an IP address
      Since:
      2.22
    • hostnameIsNonAscii

      public static boolean hostnameIsNonAscii(String hostname)

      Tests if hostname contains Unicode characters. If this returns true, you need to encode the hostname with g_hostname_to_ascii() before using it in non-IDN-aware contexts.

      Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for g_hostname_is_non_ascii() and g_hostname_is_ascii_encoded() to both return true for a name.

      Parameters:
      hostname - a hostname
      Returns:
      true if hostname contains any non-ASCII characters
      Since:
      2.22
    • hostnameToAscii

      public static @Nullable String hostnameToAscii(String hostname)
      Converts hostname to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.
      Parameters:
      hostname - a valid UTF-8 or ASCII hostname
      Returns:
      an ASCII hostname, which must be freed, or null if hostname is in some way invalid.
      Since:
      2.22
    • hostnameToUnicode

      public static @Nullable String hostnameToUnicode(String hostname)

      Converts hostname to its canonical presentation form; a UTF-8 string in Unicode normalization form C, containing no uppercase letters, no forbidden characters, and no ASCII-encoded segments, and not ending with a trailing dot.

      Of course if hostname is not an internationalized hostname, then the canonical presentation form will be entirely ASCII.

      Parameters:
      hostname - a valid UTF-8 or ASCII hostname
      Returns:
      a UTF-8 hostname, which must be freed, or null if hostname is in some way invalid.
      Since:
      2.22
    • iconv

      public static long iconv(@Nullable IConv converter, String[] inbuf, Out<Long> inbytesLeft, String[] outbuf, Out<Long> outbytesLeft)

      Same as the standard UNIX routine iconv(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.

      GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

      Note that the behaviour of iconv() for characters which are valid in the input character set, but which have no representation in the output character set, is implementation defined. This function may return success (with a positive number of non-reversible conversions as replacement characters were used), or it may return -1 and set an error such as EILSEQ, in such a situation.

      See iconv(3posix) and iconv(3) for more details about behavior when an error occurs.

      Parameters:
      converter - conversion descriptor from g_iconv_open()
      inbuf - bytes to convert
      inbytesLeft - inout parameter, bytes remaining to convert in inbuf
      outbuf - converted output bytes
      outbytesLeft - inout parameter, bytes available to fill in outbuf
      Returns:
      count of non-reversible conversions, or -1 on error
    • idleAdd

      public static int idleAdd(int priority, @Nullable SourceFunc function)

      Adds a function to be called whenever there are no higher priority events pending.

      If the function returns GLib.SOURCE_REMOVE it is automatically removed from the list of event sources and will not be called again.

      See main loop memory management for details on how to handle the return value and memory management of data.

      This internally creates a main loop source using idleSourceNew() and attaches it to the global GLib.MainContext using Source.attach(MainContext), so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

      Parameters:
      priority - the priority of the idle source; typically this will be in the range between GLib.PRIORITY_DEFAULT_IDLE and GLib.PRIORITY_HIGH_IDLE
      function - function to call
      Returns:
      the ID (greater than 0) of the event source
    • idleRemoveByData

      public static boolean idleRemoveByData(@Nullable MemorySegment data)
      Removes the idle function with the given data.
      Parameters:
      data - the data for the idle source’s callback.
      Returns:
      true if an idle source was found and removed, false otherwise
    • idleSourceNew

      public static Source idleSourceNew()

      Creates a new idle source.

      The source will not initially be associated with any GLib.MainContext and must be added to one with Source.attach(MainContext) before it will be executed. Note that the default priority for idle sources is GLib.PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of GLib.PRIORITY_DEFAULT.

      Returns:
      the newly-created idle source
    • int64Equal

      public static boolean int64Equal(MemorySegment v1, MemorySegment v2)
      Compares the two gint64 values being pointed to and returns true if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-null pointers to 64-bit integers as keys in a GHashTable.
      Parameters:
      v1 - a pointer to a gint64 key
      v2 - a pointer to a gint64 key to compare with v1
      Returns:
      true if the two keys match.
      Since:
      2.22
    • int64Hash

      public static int int64Hash(MemorySegment v)

      Converts a pointer to a gint64 to a hash value.

      It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-null pointers to 64-bit integer values as keys in a GHashTable.

      Parameters:
      v - a pointer to a gint64 key
      Returns:
      a hash value corresponding to the key.
      Since:
      2.22
    • intEqual

      public static boolean intEqual(MemorySegment v1, MemorySegment v2)

      Compares the two gint values being pointed to and returns true if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-null pointers to integers as keys in a GHashTable.

      Note that this function acts on pointers to gint, not on gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use g_direct_equal() instead.

      Parameters:
      v1 - a pointer to a gint key
      v2 - a pointer to a gint key to compare with v1
      Returns:
      true if the two keys match.
    • intHash

      public static int intHash(MemorySegment v)

      Converts a pointer to a gint to a hash value. It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-null pointers to integer values as keys in a GHashTable.

      Note that this function acts on pointers to gint, not on gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use g_direct_hash() instead.

      Parameters:
      v - a pointer to a gint key
      Returns:
      a hash value corresponding to the key.
    • internStaticString

      public static String internStaticString(@Nullable String string)

      Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). g_intern_static_string() does not copy the string, therefore string must not be freed or modified.

      This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

      Parameters:
      string - a static string
      Returns:
      a canonical representation for the string
      Since:
      2.10
    • internString

      public static String internString(@Nullable String string)

      Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

      This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

      Parameters:
      string - a string
      Returns:
      a canonical representation for the string
      Since:
      2.10
    • ioAddWatch

      public static int ioAddWatch(IOChannel channel, int priority, Set<IOCondition> condition, @Nullable IOFunc func)

      Adds the GIOChannel into the default main loop context with the given priority.

      This internally creates a main loop source using g_io_create_watch() and attaches it to the main loop context with g_source_attach(). You can do these steps manually if you need greater control.

      Parameters:
      channel - a GIOChannel
      priority - the priority of the GIOChannel source
      condition - the condition to watch for
      func - the function to call when the condition is satisfied
      Returns:
      the event source id
    • ioAddWatch

      public static int ioAddWatch(IOChannel channel, int priority, IOCondition condition, @Nullable IOFunc func)

      Adds the GIOChannel into the default main loop context with the given priority.

      This internally creates a main loop source using g_io_create_watch() and attaches it to the main loop context with g_source_attach(). You can do these steps manually if you need greater control.

      Parameters:
      channel - a GIOChannel
      priority - the priority of the GIOChannel source
      condition - the condition to watch for
      func - the function to call when the condition is satisfied
      Returns:
      the event source id
    • ioCreateWatch

      public static Source ioCreateWatch(IOChannel channel, Set<IOCondition> condition)

      Creates a GSource that's dispatched when condition is met for the given channel. For example, if condition is IOCondition.IN, the source will be dispatched when there's data available for reading.

      The callback function invoked by the GSource should be added with g_source_set_callback(), but it has type GIOFunc (not GSourceFunc).

      g_io_add_watch() is a simpler interface to this same functionality, for the case where you want to add the source to the default main loop context at the default priority.

      On Windows, polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

      Parameters:
      channel - a GIOChannel to watch
      condition - conditions to watch for
      Returns:
      a new GSource
    • ioCreateWatch

      public static Source ioCreateWatch(IOChannel channel, IOCondition... condition)

      Creates a GSource that's dispatched when condition is met for the given channel. For example, if condition is IOCondition.IN, the source will be dispatched when there's data available for reading.

      The callback function invoked by the GSource should be added with g_source_set_callback(), but it has type GIOFunc (not GSourceFunc).

      g_io_add_watch() is a simpler interface to this same functionality, for the case where you want to add the source to the default main loop context at the default priority.

      On Windows, polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

      Parameters:
      channel - a GIOChannel to watch
      condition - conditions to watch for
      Returns:
      a new GSource
    • listenv

      public static String[] listenv()

      Gets the names of all variables set in the environment.

      Programs that want to be portable to Windows should typically use this function and g_getenv() instead of using the environ array from the C library directly. On Windows, the strings in the environ array are in system codepage encoding, while in most of the typical use cases for environment variables in GLib-using programs you want the UTF-8 encoding that this function and g_getenv() provide.

      Returns:
      a null-terminated list of strings which must be freed with g_strfreev().
      Since:
      2.8
    • localeFromUtf8

      public static byte[] localeFromUtf8(String utf8string, long len, @Nullable Out<Long> bytesRead) throws GErrorException

      Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale. On Windows this means the system codepage.

      The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertError.ILLEGAL_SEQUENCE. Use g_convert() to convert input that may contain embedded nul characters.

      Parameters:
      utf8string - a UTF-8 encoded string
      len - the length of the string, or -1 if the string is nul-terminated.
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
      Returns:
      A newly-allocated buffer containing the converted string, or null on an error, and error will be set.
      Throws:
      GErrorException - see GError
    • localeToUtf8

      public static String localeToUtf8(@Nullable byte @Nullable [] opsysstring, @Nullable Out<Long> bytesRead, @Nullable Out<Long> bytesWritten) throws GErrorException

      Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.

      If the source encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertError.EMBEDDED_NUL is set and the function returns null. If the source encoding is UTF-8, an embedded nul character is treated with the ConvertError.ILLEGAL_SEQUENCE error for backward compatibility with earlier versions of this library. Use g_convert() to produce output that may contain embedded nul characters.

      Parameters:
      opsysstring - a string in the encoding of the current locale. On Windows this means the system codepage.
      bytesRead - location to store the number of bytes in the input string that were successfully converted, or null. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
      bytesWritten - the number of bytes stored in the output buffer (not including the terminating nul).
      Returns:
      The converted string, or null on an error.
      Throws:
      GErrorException - see GError
    • log

      public static void log(@Nullable String logDomain, Set<LogLevelFlags> logLevel, String format, Object... varargs)

      Logs an error or debugging message.

      If the log level has been set as fatal, GLib.BREAKPOINT is called to terminate the program. See the documentation for GLib.BREAKPOINT for details of the debugging options this provides.

      If logDefaultHandler(String, Set, String, MemorySegment) is used as the log handler function, a new-line character will automatically be appended to ..., and need not be entered manually.

      If structured logging is enabled this will output via the structured log writer function (see logSetWriterFunc(LogWriterFunc)).

      Parameters:
      logDomain - the log domain, usually G_LOG_DOMAIN, or NULL for the default
      logLevel - the log level, either from GLib.LogLevelFlags or a user-defined level
      format - the message format. See the printf() documentation
      varargs - the parameters to insert into the format string
    • log

      public static void log(@Nullable String logDomain, LogLevelFlags logLevel, String format, Object... varargs)

      Logs an error or debugging message.

      If the log level has been set as fatal, GLib.BREAKPOINT is called to terminate the program. See the documentation for GLib.BREAKPOINT for details of the debugging options this provides.

      If logDefaultHandler(String, Set, String, MemorySegment) is used as the log handler function, a new-line character will automatically be appended to ..., and need not be entered manually.

      If structured logging is enabled this will output via the structured log writer function (see logSetWriterFunc(LogWriterFunc)).

      Parameters:
      logDomain - the log domain, usually G_LOG_DOMAIN, or NULL for the default
      logLevel - the log level, either from GLib.LogLevelFlags or a user-defined level
      format - the message format. See the printf() documentation
      varargs - the parameters to insert into the format string
    • logDefaultHandler

      public static void logDefaultHandler(@Nullable String logDomain, Set<LogLevelFlags> logLevel, @Nullable String message, @Nullable MemorySegment unusedData)

      The default log handler set up by GLib; logSetDefaultHandler(LogFunc) allows to install an alternate default log handler.

      This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls GLib.BREAKPOINT. It automatically prints a new-line character after the message, so one does not need to be manually included in message.

      The behavior of this log handler can be influenced by a number of environment variables:

      • G_MESSAGES_PREFIXED: A :-separated list of log levels for which messages should be prefixed by the program name and PID of the application.
      • G_MESSAGES_DEBUG: A space-separated list of log domains for which debug and informational messages are printed. By default these messages are not printed. If you need to set the allowed domains at runtime, use logWriterDefaultSetDebugDomains(String).
      • DEBUG_INVOCATION: If set to 1, this is equivalent to G_MESSAGES_DEBUG=all. DEBUG_INVOCATION is a standard environment variable set by systemd to prompt debug output. (Since: 2.84)

      stderr is used for levels GLib.LogLevelFlags.LEVEL_ERROR, GLib.LogLevelFlags.LEVEL_CRITICAL, GLib.LogLevelFlags.LEVEL_WARNING and GLib.LogLevelFlags.LEVEL_MESSAGE. stdout is used for the rest, unless stderr was requested by logWriterDefaultSetUseStderr(boolean).

      This has no effect if structured logging is enabled; see Using Structured Logging.

      Parameters:
      logDomain - the log domain of the message, or NULL for the default "" application domain
      logLevel - the level of the message
      message - the message
      unusedData - data passed from log(String, Set, String, Object...) which is unused
    • logDefaultHandler

      public static void logDefaultHandler(@Nullable String logDomain, LogLevelFlags logLevel, @Nullable String message, @Nullable MemorySegment unusedData)

      The default log handler set up by GLib; logSetDefaultHandler(LogFunc) allows to install an alternate default log handler.

      This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls GLib.BREAKPOINT. It automatically prints a new-line character after the message, so one does not need to be manually included in message.

      The behavior of this log handler can be influenced by a number of environment variables:

      • G_MESSAGES_PREFIXED: A :-separated list of log levels for which messages should be prefixed by the program name and PID of the application.
      • G_MESSAGES_DEBUG: A space-separated list of log domains for which debug and informational messages are printed. By default these messages are not printed. If you need to set the allowed domains at runtime, use logWriterDefaultSetDebugDomains(String).
      • DEBUG_INVOCATION: If set to 1, this is equivalent to G_MESSAGES_DEBUG=all. DEBUG_INVOCATION is a standard environment variable set by systemd to prompt debug output. (Since: 2.84)

      stderr is used for levels GLib.LogLevelFlags.LEVEL_ERROR, GLib.LogLevelFlags.LEVEL_CRITICAL, GLib.LogLevelFlags.LEVEL_WARNING and GLib.LogLevelFlags.LEVEL_MESSAGE. stdout is used for the rest, unless stderr was requested by logWriterDefaultSetUseStderr(boolean).

      This has no effect if structured logging is enabled; see Using Structured Logging.

      Parameters:
      logDomain - the log domain of the message, or NULL for the default "" application domain
      logLevel - the level of the message
      message - the message
      unusedData - data passed from log(String, Set, String, Object...) which is unused
    • logGetAlwaysFatal

      public static Set<LogLevelFlags> logGetAlwaysFatal()

      Gets the current fatal mask.

      This is mostly used by custom log writers to make fatal messages (fatal-warnings, fatal-criticals) work as expected, when using the G_DEBUG environment variable (see Running GLib Applications).

      An example usage is shown below:

      static GLogWriterOutput
      my_custom_log_writer_fn (GLogLevelFlags log_level,
                               const GLogField *fields,
                               gsize n_fields,
                               gpointer user_data)
      {
      
         // abort if the message was fatal
         if (log_level & g_log_get_always_fatal ())
           g_abort ();
      
         // custom log handling code
         ...
         ...
      
         // success
         return G_LOG_WRITER_HANDLED;
      }
      
      Returns:
      the current fatal mask
      Since:
      2.86
    • logGetDebugEnabled

      public static boolean logGetDebugEnabled()

      Return whether debug output from the GLib logging system is enabled.

      Note that this should not be used to conditionalise calls to GLib.debug or other logging functions; it should only be used from GLib.LogWriterFunc implementations.

      Note also that the value of this does not depend on G_MESSAGES_DEBUG, nor DEBUG_INVOCATION, nor logWriterDefaultSetDebugDomains(String); see the docs for logSetDebugEnabled(boolean).

      Returns:
      TRUE if debug output is enabled, FALSE otherwise
      Since:
      2.72
    • logRemoveHandler

      public static void logRemoveHandler(String logDomain, int handlerId)

      Removes the log handler.

      This has no effect if structured logging is enabled; see Using Structured Logging.

      Parameters:
      logDomain - the log domain
      handlerId - the ID of the handler, which was returned in logSetHandler(String, Set, LogFunc)
    • logSetAlwaysFatal

      public static Set<LogLevelFlags> logSetAlwaysFatal(Set<LogLevelFlags> fatalMask)

      Sets the message levels which are always fatal, in any log domain.

      When a message with any of these levels is logged the program terminates. You can only set the levels defined by GLib to be fatal. GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

      You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

      Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

      Structured log messages (using logStructured(String, Set, Object...) and logStructuredArray(Set, LogField[])) are fatal only if the default log writer is used; otherwise it is up to the writer function to determine which log messages are fatal. See Using Structured Logging.

      Parameters:
      fatalMask - the mask containing bits set for each level of error which is to be fatal
      Returns:
      the old fatal mask
    • logSetAlwaysFatal

      public static Set<LogLevelFlags> logSetAlwaysFatal(LogLevelFlags... fatalMask)

      Sets the message levels which are always fatal, in any log domain.

      When a message with any of these levels is logged the program terminates. You can only set the levels defined by GLib to be fatal. GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

      You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

      Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

      Structured log messages (using logStructured(String, Set, Object...) and logStructuredArray(Set, LogField[])) are fatal only if the default log writer is used; otherwise it is up to the writer function to determine which log messages are fatal. See Using Structured Logging.

      Parameters:
      fatalMask - the mask containing bits set for each level of error which is to be fatal
      Returns:
      the old fatal mask
    • logSetDebugEnabled

      public static void logSetDebugEnabled(boolean enabled)

      Enable or disable debug output from the GLib logging system for all domains.

      This value interacts disjunctively with G_MESSAGES_DEBUG, DEBUG_INVOCATION and logWriterDefaultSetDebugDomains(String) — if any of them would allow a debug message to be outputted, it will be.

      Note that this should not be used from within library code to enable debug output — it is intended for external use.

      Parameters:
      enabled - TRUE to enable debug output, FALSE otherwise
      Since:
      2.72
    • logSetDefaultHandler

      public static @Nullable LogFunc logSetDefaultHandler(@Nullable LogFunc logFunc)

      Installs a default log handler which is used if no log handler has been set for the particular log domain and log level combination.

      By default, GLib uses logDefaultHandler(String, Set, String, MemorySegment) as default log handler.

      This has no effect if structured logging is enabled; see Using Structured Logging.

      Parameters:
      logFunc - the log handler function
      Returns:
      the previous default log handler
      Since:
      2.6
    • logSetFatalMask

      public static Set<LogLevelFlags> logSetFatalMask(String logDomain, Set<LogLevelFlags> fatalMask)

      Sets the log levels which are fatal in the given domain.

      GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

      This has no effect on structured log messages (using logStructured(String, Set, Object...) or logStructuredArray(Set, LogField[])). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using logSetWriterFunc(LogWriterFunc). See Using Structured Logging.

      This function is mostly intended to be used with GLib.LogLevelFlags.LEVEL_CRITICAL. You should typically not set GLib.LogLevelFlags.LEVEL_WARNING, GLib.LogLevelFlags.LEVEL_MESSAGE, GLib.LogLevelFlags.LEVEL_INFO or GLib.LogLevelFlags.LEVEL_DEBUG as fatal except inside of test programs.

      Parameters:
      logDomain - the log domain
      fatalMask - the new fatal mask
      Returns:
      the old fatal mask for the log domain
    • logSetFatalMask

      public static Set<LogLevelFlags> logSetFatalMask(String logDomain, LogLevelFlags... fatalMask)

      Sets the log levels which are fatal in the given domain.

      GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

      This has no effect on structured log messages (using logStructured(String, Set, Object...) or logStructuredArray(Set, LogField[])). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using logSetWriterFunc(LogWriterFunc). See Using Structured Logging.

      This function is mostly intended to be used with GLib.LogLevelFlags.LEVEL_CRITICAL. You should typically not set GLib.LogLevelFlags.LEVEL_WARNING, GLib.LogLevelFlags.LEVEL_MESSAGE, GLib.LogLevelFlags.LEVEL_INFO or GLib.LogLevelFlags.LEVEL_DEBUG as fatal except inside of test programs.

      Parameters:
      logDomain - the log domain
      fatalMask - the new fatal mask
      Returns:
      the old fatal mask for the log domain
    • logSetHandler

      public static int logSetHandler(@Nullable String logDomain, Set<LogLevelFlags> logLevels, @Nullable LogFunc logFunc)

      Like logSetHandler(String, Set, LogFunc), but takes a destroy notify for the userData.

      This has no effect if structured logging is enabled; see Using Structured Logging.

      The log_domain parameter can be set to NULL or an empty string to use the default application domain.

      Parameters:
      logDomain - the log domain application domain
      logLevels - the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the GLib.LogLevelFlags.FLAG_FATAL and GLib.LogLevelFlags.FLAG_RECURSION bit flags.
      logFunc - the log handler function
      Returns:
      the ID of the new handler
      Since:
      2.46
    • logSetHandler

      public static int logSetHandler(@Nullable String logDomain, LogLevelFlags logLevels, @Nullable LogFunc logFunc)

      Like logSetHandler(String, Set, LogFunc), but takes a destroy notify for the userData.

      This has no effect if structured logging is enabled; see Using Structured Logging.

      The log_domain parameter can be set to NULL or an empty string to use the default application domain.

      Parameters:
      logDomain - the log domain application domain
      logLevels - the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the GLib.LogLevelFlags.FLAG_FATAL and GLib.LogLevelFlags.FLAG_RECURSION bit flags.
      logFunc - the log handler function
      Returns:
      the ID of the new handler
      Since:
      2.46
    • logSetWriterFunc

      public static void logSetWriterFunc(@Nullable LogWriterFunc func)

      Set a writer function which will be called to format and write out each log message.

      Each program should set a writer function, or the default writer (logWriterDefault(Set, LogField[], MemorySegment)) will be used.

      Libraries must not call this function — only programs are allowed to install a writer function, as there must be a single, central point where log messages are formatted and outputted.

      There can only be one writer function. It is an error to set more than one.

      Parameters:
      func - log writer function, which must not be NULL
      Since:
      2.50
    • logStructured

      public static void logStructured(String logDomain, Set<LogLevelFlags> logLevel, Object... varargs)

      Log a message with structured data.

      The message will be passed through to the log writer set by the application using logSetWriterFunc(LogWriterFunc). If the message is fatal (i.e. its log level is GLib.LogLevelFlags.LEVEL_ERROR), the program will be aborted by calling GLib.BREAKPOINT at the end of this function. If the log writer returns GLib.LogWriterOutput.UNHANDLED (failure), no other fallback writers will be tried. See the documentation for GLib.LogWriterFunc for information on chaining writers.

      The structured data is provided as key–value pairs, where keys are UTF-8 strings, and values are arbitrary pointers — typically pointing to UTF-8 strings, but that is not a requirement. To pass binary (non-nul-terminated) structured data, use logStructuredArray(Set, LogField[]). The keys for structured data should follow the systemd journal fields specification. It is suggested that custom keys are namespaced according to the code which sets them. For example, custom keys from GLib all have a GLIB_ prefix.

      Note that keys that expect UTF-8 strings (specifically "MESSAGE" and "GLIB_DOMAIN") must be passed as nul-terminated UTF-8 strings until GLib version 2.74.1 because the default log handler did not consider the length of the GLogField. Starting with GLib 2.74.1 this is fixed and non-nul-terminated UTF-8 strings can be passed with their correct length, with the exception of "GLIB_DOMAIN" which was only fixed with GLib 2.82.3.

      The logDomain will be converted into a GLIB_DOMAIN field. logLevel will be converted into a PRIORITY field. The format string will have its placeholders substituted for the provided values and be converted into a MESSAGE field.

      Other fields you may commonly want to pass into this function:

      Note that CODE_FILE, CODE_LINE and CODE_FUNC are automatically set by the logging macros, GLib.DEBUGHERE, GLib.message, GLib.warning, GLib.critical, GLib.error, etc, if the symbol G_LOG_USE_STRUCTURED is defined before including glib.h.

      For example:

      g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
                        "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
                        "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
                        "MESSAGE", "This is a debug message about pointer %p and integer %u.",
                        some_pointer, some_integer);
      

      Note that each MESSAGE_ID must be uniquely and randomly generated. If adding a MESSAGE_ID, consider shipping a message catalog with your software.

      To pass a user data pointer to the log writer function which is specific to this logging call, you must use logStructuredArray(Set, LogField[]) and pass the pointer as a field with GLogField.length set to zero, otherwise it will be interpreted as a string.

      For example:

      const GLogField fields[] = {
        { "MESSAGE", "This is a debug message.", -1 },
        { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
        { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
        { "MY_APPLICATION_STATE", state_object, 0 },
      };
      g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
      

      Note also that, even if no other structured fields are specified, there must always be a MESSAGE key before the format string. The MESSAGE-format pair has to be the last of the key-value pairs, and MESSAGE is the only field for which printf()-style formatting is supported.

      The default writer function for stdout and stderr will automatically append a new-line character after the message, so you should not add one manually to the format string.

      Parameters:
      logDomain - log domain, usually G_LOG_DOMAIN
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      varargs - key-value pairs of structured data to add to the log entry, followed by the key MESSAGE, followed by a printf()-style message format, followed by parameters to insert in the format string
      Since:
      2.50
    • logStructured

      public static void logStructured(String logDomain, LogLevelFlags logLevel, Object... varargs)

      Log a message with structured data.

      The message will be passed through to the log writer set by the application using logSetWriterFunc(LogWriterFunc). If the message is fatal (i.e. its log level is GLib.LogLevelFlags.LEVEL_ERROR), the program will be aborted by calling GLib.BREAKPOINT at the end of this function. If the log writer returns GLib.LogWriterOutput.UNHANDLED (failure), no other fallback writers will be tried. See the documentation for GLib.LogWriterFunc for information on chaining writers.

      The structured data is provided as key–value pairs, where keys are UTF-8 strings, and values are arbitrary pointers — typically pointing to UTF-8 strings, but that is not a requirement. To pass binary (non-nul-terminated) structured data, use logStructuredArray(Set, LogField[]). The keys for structured data should follow the systemd journal fields specification. It is suggested that custom keys are namespaced according to the code which sets them. For example, custom keys from GLib all have a GLIB_ prefix.

      Note that keys that expect UTF-8 strings (specifically "MESSAGE" and "GLIB_DOMAIN") must be passed as nul-terminated UTF-8 strings until GLib version 2.74.1 because the default log handler did not consider the length of the GLogField. Starting with GLib 2.74.1 this is fixed and non-nul-terminated UTF-8 strings can be passed with their correct length, with the exception of "GLIB_DOMAIN" which was only fixed with GLib 2.82.3.

      The logDomain will be converted into a GLIB_DOMAIN field. logLevel will be converted into a PRIORITY field. The format string will have its placeholders substituted for the provided values and be converted into a MESSAGE field.

      Other fields you may commonly want to pass into this function:

      Note that CODE_FILE, CODE_LINE and CODE_FUNC are automatically set by the logging macros, GLib.DEBUGHERE, GLib.message, GLib.warning, GLib.critical, GLib.error, etc, if the symbol G_LOG_USE_STRUCTURED is defined before including glib.h.

      For example:

      g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
                        "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
                        "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
                        "MESSAGE", "This is a debug message about pointer %p and integer %u.",
                        some_pointer, some_integer);
      

      Note that each MESSAGE_ID must be uniquely and randomly generated. If adding a MESSAGE_ID, consider shipping a message catalog with your software.

      To pass a user data pointer to the log writer function which is specific to this logging call, you must use logStructuredArray(Set, LogField[]) and pass the pointer as a field with GLogField.length set to zero, otherwise it will be interpreted as a string.

      For example:

      const GLogField fields[] = {
        { "MESSAGE", "This is a debug message.", -1 },
        { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
        { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
        { "MY_APPLICATION_STATE", state_object, 0 },
      };
      g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
      

      Note also that, even if no other structured fields are specified, there must always be a MESSAGE key before the format string. The MESSAGE-format pair has to be the last of the key-value pairs, and MESSAGE is the only field for which printf()-style formatting is supported.

      The default writer function for stdout and stderr will automatically append a new-line character after the message, so you should not add one manually to the format string.

      Parameters:
      logDomain - log domain, usually G_LOG_DOMAIN
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      varargs - key-value pairs of structured data to add to the log entry, followed by the key MESSAGE, followed by a printf()-style message format, followed by parameters to insert in the format string
      Since:
      2.50
    • logStructuredArray

      public static void logStructuredArray(Set<LogLevelFlags> logLevel, @Nullable LogField @Nullable [] fields)

      Log a message with structured data.

      The message will be passed through to the log writer set by the application using logSetWriterFunc(LogWriterFunc). If the message is fatal (i.e. its log level is GLib.LogLevelFlags.LEVEL_ERROR), the program will be aborted at the end of this function.

      See logStructured(String, Set, Object...) for more documentation.

      This assumes that logLevel is already present in fields (typically as the PRIORITY field).

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data to add to the log message
      Since:
      2.50
    • logStructuredArray

      public static void logStructuredArray(LogLevelFlags logLevel, @Nullable LogField @Nullable [] fields)

      Log a message with structured data.

      The message will be passed through to the log writer set by the application using logSetWriterFunc(LogWriterFunc). If the message is fatal (i.e. its log level is GLib.LogLevelFlags.LEVEL_ERROR), the program will be aborted at the end of this function.

      See logStructured(String, Set, Object...) for more documentation.

      This assumes that logLevel is already present in fields (typically as the PRIORITY field).

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data to add to the log message
      Since:
      2.50
    • logStructuredStandard

      public static void logStructuredStandard(String logDomain, Set<LogLevelFlags> logLevel, String file, String line, String func, String messageFormat, Object... varargs)
    • logStructuredStandard

      public static void logStructuredStandard(String logDomain, LogLevelFlags logLevel, String file, String line, String func, String messageFormat, Object... varargs)
    • logVariant

      public static void logVariant(@Nullable String logDomain, Set<LogLevelFlags> logLevel, Variant fields)

      Log a message with structured data, accepting the data within a GLib.Variant.

      This version is especially useful for use in other languages, via introspection.

      The only mandatory item in the fields dictionary is the "MESSAGE" which must contain the text shown to the user.

      The values in the fields dictionary are likely to be of type G_VARIANT_TYPE_STRING. Array of bytes (G_VARIANT_TYPE_BYTESTRING) is also supported. In this case the message is handled as binary and will be forwarded to the log writer as such. The size of the array should not be higher than G_MAXSSIZE. Otherwise it will be truncated to this size. For other types Variant.print(boolean) will be used to convert the value into a string.

      For more details on its usage and about the parameters, see logStructured(String, Set, Object...).

      Parameters:
      logDomain - log domain, usually G_LOG_DOMAIN
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - a dictionary (GLib.Variant of the type G_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.
      Since:
      2.50
    • logVariant

      public static void logVariant(@Nullable String logDomain, LogLevelFlags logLevel, Variant fields)

      Log a message with structured data, accepting the data within a GLib.Variant.

      This version is especially useful for use in other languages, via introspection.

      The only mandatory item in the fields dictionary is the "MESSAGE" which must contain the text shown to the user.

      The values in the fields dictionary are likely to be of type G_VARIANT_TYPE_STRING. Array of bytes (G_VARIANT_TYPE_BYTESTRING) is also supported. In this case the message is handled as binary and will be forwarded to the log writer as such. The size of the array should not be higher than G_MAXSSIZE. Otherwise it will be truncated to this size. For other types Variant.print(boolean) will be used to convert the value into a string.

      For more details on its usage and about the parameters, see logStructured(String, Set, Object...).

      Parameters:
      logDomain - log domain, usually G_LOG_DOMAIN
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - a dictionary (GLib.Variant of the type G_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.
      Since:
      2.50
    • logWriterDefault

      public static LogWriterOutput logWriterDefault(Set<LogLevelFlags> logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and output it to the default log destination for the platform.

      On Linux, this is typically the systemd journal, falling back to stdout or stderr if running from the terminal or if output is being redirected to a file.

      Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.

      This is suitable for use as a GLib.LogWriterFunc, and is the default writer used if no other is set using logSetWriterFunc(LogWriterFunc).

      As with logDefaultHandler(String, Set, String, MemorySegment), this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or set at runtime by logWriterDefaultSetDebugDomains(String).

      logWriterDefault(Set, LogField[], MemorySegment) uses the mask set by logSetAlwaysFatal(Set) to determine which messages are fatal. When using a custom writer function instead it is up to the writer function to determine which log messages are fatal.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.50
    • logWriterDefault

      public static LogWriterOutput logWriterDefault(LogLevelFlags logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and output it to the default log destination for the platform.

      On Linux, this is typically the systemd journal, falling back to stdout or stderr if running from the terminal or if output is being redirected to a file.

      Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.

      This is suitable for use as a GLib.LogWriterFunc, and is the default writer used if no other is set using logSetWriterFunc(LogWriterFunc).

      As with logDefaultHandler(String, Set, String, MemorySegment), this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or set at runtime by logWriterDefaultSetDebugDomains(String).

      logWriterDefault(Set, LogField[], MemorySegment) uses the mask set by logSetAlwaysFatal(Set) to determine which messages are fatal. When using a custom writer function instead it is up to the writer function to determine which log messages are fatal.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.50
    • logWriterDefaultSetDebugDomains

      public static void logWriterDefaultSetDebugDomains(@Nullable String domains)

      Reset the list of domains to be logged, that might be initially set by the G_MESSAGES_DEBUG or DEBUG_INVOCATION environment variables.

      This function is thread-safe.

      Parameters:
      domains - NULL-terminated array with domains to be printed. NULL or an array with no values means none. Array with a single value "all" means all.
      Since:
      2.80
    • logWriterDefaultSetUseStderr

      public static void logWriterDefaultSetUseStderr(boolean useStderr)

      Configure whether the built-in log functions will output all log messages to stderr.

      The built-in log functions are logDefaultHandler(String, Set, String, MemorySegment) for the old-style API, and both logWriterDefault(Set, LogField[], MemorySegment) and logWriterStandardStreams(Set, LogField[], MemorySegment) for the structured API.

      By default, log messages of levels GLib.LogLevelFlags.LEVEL_INFO and GLib.LogLevelFlags.LEVEL_DEBUG are sent to stdout, and other log messages are sent to stderr. This is problematic for applications that intend to reserve stdout for structured output such as JSON or XML.

      This function sets global state. It is not thread-aware, and should be called at the very start of a program, before creating any other threads or creating objects that could create worker threads of their own.

      Parameters:
      useStderr - If TRUE, use stderr for log messages that would normally have appeared on stdout
      Since:
      2.68
    • logWriterDefaultWouldDrop

      public static boolean logWriterDefaultWouldDrop(Set<LogLevelFlags> logLevel, @Nullable String logDomain)

      Check whether logWriterDefault(Set, LogField[], MemorySegment) and logDefaultHandler(String, Set, String, MemorySegment) would ignore a message with the given domain and level.

      As with logDefaultHandler(String, Set, String, MemorySegment), this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or by logWriterDefaultSetDebugDomains(String).

      This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:

      if (g_log_writer_default_would_drop (log_level, log_domain))
        return G_LOG_WRITER_HANDLED;
      ]|
      
      or to skip an expensive computation if it is only needed for a debugging
      message, and `G_MESSAGES_DEBUG` and `DEBUG_INVOCATION` are not set:
      
      ```c
      if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
        {
          g_autofree gchar *result = expensive_computation (my_object);
      
          g_debug ("my_object result: `s`", result);
        }
      

      @param logLevel log level, either from GLib.LogLevelFlags, or a user-defined level @param logDomain log domain @return TRUE if the log message would be dropped by GLib’s default log handlers @since 2.68

    • logWriterDefaultWouldDrop

      public static boolean logWriterDefaultWouldDrop(LogLevelFlags logLevel, @Nullable String logDomain)

      Check whether logWriterDefault(Set, LogField[], MemorySegment) and logDefaultHandler(String, Set, String, MemorySegment) would ignore a message with the given domain and level.

      As with logDefaultHandler(String, Set, String, MemorySegment), this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or by logWriterDefaultSetDebugDomains(String).

      This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:

      if (g_log_writer_default_would_drop (log_level, log_domain))
        return G_LOG_WRITER_HANDLED;
      ]|
      
      or to skip an expensive computation if it is only needed for a debugging
      message, and `G_MESSAGES_DEBUG` and `DEBUG_INVOCATION` are not set:
      
      ```c
      if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
        {
          g_autofree gchar *result = expensive_computation (my_object);
      
          g_debug ("my_object result: `s`", result);
        }
      

      @param logLevel log level, either from GLib.LogLevelFlags, or a user-defined level @param logDomain log domain @return TRUE if the log message would be dropped by GLib’s default log handlers @since 2.68

    • logWriterFormatFields

      public static String logWriterFormatFields(Set<LogLevelFlags> logLevel, @Nullable LogField @Nullable [] fields, boolean useColor)

      Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).

      This will include the values of all fields it knows how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the documentation for logStructured(String, Set, Object...)). It does not include values from unknown fields.

      The returned string does not have a trailing new-line character. It is encoded in the character set of the current locale, which is not necessarily UTF-8.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      useColor - TRUE to use ANSI color escape sequences when formatting the message, FALSE to not
      Returns:
      string containing the formatted log message, in the character set of the current locale
      Since:
      2.50
    • logWriterFormatFields

      public static String logWriterFormatFields(LogLevelFlags logLevel, @Nullable LogField @Nullable [] fields, boolean useColor)

      Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).

      This will include the values of all fields it knows how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the documentation for logStructured(String, Set, Object...)). It does not include values from unknown fields.

      The returned string does not have a trailing new-line character. It is encoded in the character set of the current locale, which is not necessarily UTF-8.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      useColor - TRUE to use ANSI color escape sequences when formatting the message, FALSE to not
      Returns:
      string containing the formatted log message, in the character set of the current locale
      Since:
      2.50
    • logWriterIsJournald

      public static boolean logWriterIsJournald(int outputFd)

      Check whether the given outputFd file descriptor is a connection to the systemd journal, or something else (like a log file or stdout or stderr).

      Invalid file descriptors are accepted and return FALSE, which allows for the following construct without needing any additional error handling:

      is_journald = g_log_writer_is_journald (fileno (stderr));
      
      Parameters:
      outputFd - output file descriptor to check
      Returns:
      TRUE if outputFd points to the journal, FALSE otherwise
      Since:
      2.50
    • logWriterJournald

      public static LogWriterOutput logWriterJournald(Set<LogLevelFlags> logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and send it to the systemd journal as a set of key–value pairs.

      All fields are sent to the journal, but if a field has length zero (indicating program-specific data) then only its key will be sent.

      This is suitable for use as a GLib.LogWriterFunc.

      If GLib has been compiled without systemd support, this function is still defined, but will always return GLib.LogWriterOutput.UNHANDLED.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.50
    • logWriterJournald

      public static LogWriterOutput logWriterJournald(LogLevelFlags logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and send it to the systemd journal as a set of key–value pairs.

      All fields are sent to the journal, but if a field has length zero (indicating program-specific data) then only its key will be sent.

      This is suitable for use as a GLib.LogWriterFunc.

      If GLib has been compiled without systemd support, this function is still defined, but will always return GLib.LogWriterOutput.UNHANDLED.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.50
    • logWriterStandardStreams

      public static LogWriterOutput logWriterStandardStreams(Set<LogLevelFlags> logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and print it to either stdout or stderr, depending on its log level.

      GLib.LogLevelFlags.LEVEL_INFO and GLib.LogLevelFlags.LEVEL_DEBUG messages are sent to stdout, or to stderr if requested by logWriterDefaultSetUseStderr(boolean); all other log levels are sent to stderr. Only fields which are understood by this function are included in the formatted string which is printed.

      If the output stream supports ANSI color escape sequences, they will be used in the output.

      A trailing new-line character is added to the log message when it is printed.

      This is suitable for use as a GLib.LogWriterFunc.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.50
    • logWriterStandardStreams

      public static LogWriterOutput logWriterStandardStreams(LogLevelFlags logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and print it to either stdout or stderr, depending on its log level.

      GLib.LogLevelFlags.LEVEL_INFO and GLib.LogLevelFlags.LEVEL_DEBUG messages are sent to stdout, or to stderr if requested by logWriterDefaultSetUseStderr(boolean); all other log levels are sent to stderr. Only fields which are understood by this function are included in the formatted string which is printed.

      If the output stream supports ANSI color escape sequences, they will be used in the output.

      A trailing new-line character is added to the log message when it is printed.

      This is suitable for use as a GLib.LogWriterFunc.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.50
    • logWriterSupportsColor

      public static boolean logWriterSupportsColor(int outputFd)

      Check whether the given outputFd file descriptor supports ANSI color escape sequences.

      If so, they can safely be used when formatting log messages.

      Parameters:
      outputFd - output file descriptor to check
      Returns:
      TRUE if ANSI color escapes are supported, FALSE otherwise
      Since:
      2.50
    • logWriterSyslog

      public static LogWriterOutput logWriterSyslog(Set<LogLevelFlags> logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and send it to the syslog daemon. Only fields which are understood by this function are included in the formatted string which is printed.

      Log facility will be defined via the SYSLOG_FACILITY field and accepts the following values: "auth", "daemon", and "user". If SYSLOG_FACILITY is not specified, LOG_USER facility will be used.

      This is suitable for use as a GLib.LogWriterFunc.

      If syslog is not supported, this function is still defined, but will always return GLib.LogWriterOutput.UNHANDLED.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.80
    • logWriterSyslog

      public static LogWriterOutput logWriterSyslog(LogLevelFlags logLevel, @Nullable LogField @Nullable [] fields, @Nullable MemorySegment userData)

      Format a structured log message and send it to the syslog daemon. Only fields which are understood by this function are included in the formatted string which is printed.

      Log facility will be defined via the SYSLOG_FACILITY field and accepts the following values: "auth", "daemon", and "user". If SYSLOG_FACILITY is not specified, LOG_USER facility will be used.

      This is suitable for use as a GLib.LogWriterFunc.

      If syslog is not supported, this function is still defined, but will always return GLib.LogWriterOutput.UNHANDLED.

      Parameters:
      logLevel - log level, either from GLib.LogLevelFlags, or a user-defined level
      fields - key–value pairs of structured data forming the log message
      userData - user data passed to logSetWriterFunc(LogWriterFunc)
      Returns:
      GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise
      Since:
      2.80
    • lstat

      public static int lstat(String filename, StatBuf buf)

      A wrapper for the POSIX lstat() function. The lstat() function is like stat() except that in the case of symbolic links, it returns information about the symbolic link itself and not the file that it refers to. If the system does not support symbolic links g_lstat() is identical to g_stat().

      See your C library manual for more details about lstat().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      buf - a pointer to a stat struct, which will be filled with the file information
      Returns:
      0 if the information was successfully retrieved, -1 if an error occurred
      Since:
      2.6
    • mainCurrentSource

      public static @Nullable Source mainCurrentSource()
      Returns the currently firing source for this thread.
      Returns:
      the currently firing source, or NULL if none is firing
      Since:
      2.12
    • mainDepth

      public static int mainDepth()

      Returns the depth of the stack of calls to MainContext.dispatch() on any GMainContext in the current thread.

      That is, when called from the top level, it gives 0. When called from within a callback from MainContext.iteration(boolean) (or MainLoop.run(), etc.) it returns 1. When called from within a callback to a recursive call to MainContext.iteration(boolean), it returns 2. And so forth.

      This function is useful in a situation like the following: Imagine an extremely simple ‘garbage collected’ system.

      static GList *free_list;
      
      gpointer
      allocate_memory (gsize size)
      {
        gpointer result = g_malloc (size);
        free_list = g_list_prepend (free_list, result);
        return result;
      }
      
      void
      free_allocated_memory (void)
      {
        GList *l;
        for (l = free_list; l; l = l->next);
          g_free (l->data);
        g_list_free (free_list);
        free_list = NULL;
       }
      
      [...]
      
      while (TRUE);
       {
         g_main_context_iteration (NULL, TRUE);
         free_allocated_memory();
        }
      

      This works from an application, however, if you want to do the same thing from a library, it gets more difficult, since you no longer control the main loop. You might think you can simply use an idle function to make the call to free_allocated_memory(), but that doesn’t work, since the idle function could be called from a recursive callback. This can be fixed by using mainDepth()

      gpointer
      allocate_memory (gsize size)
      {
        FreeListBlock *block = g_new (FreeListBlock, 1);
        block->mem = g_malloc (size);
        block->depth = g_main_depth ();
        free_list = g_list_prepend (free_list, block);
        return block->mem;
      }
      
      void
      free_allocated_memory (void)
      {
        GList *l;
        
        int depth = g_main_depth ();
        for (l = free_list; l; );
          {
            GList *next = l->next;
            FreeListBlock *block = l->data;
            if (block->depth > depth)
              {
                g_free (block->mem);
                g_free (block);
                free_list = g_list_delete_link (free_list, l);
              }
                    
            l = next;
          }
        }
      

      There is a temptation to use mainDepth() to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item’s callback return immediately and do nothing if mainDepth() returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you’ll find yourself adding these checks all over your code, since there are doubtless many, many things that the user could do. Instead, you can use the following techniques:

      1. Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.

      2. Avoid main loop recursion in situations where you can’t handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.

      Returns:
      the main loop recursion level in the current thread
    • malloc

      public static @Nullable MemorySegment malloc(long nBytes)

      Allocates nBytes bytes of memory. If nBytes is 0 it returns null.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Parameters:
      nBytes - the number of bytes to allocate
      Returns:
      a pointer to the allocated memory
    • malloc0

      public static @Nullable MemorySegment malloc0(long nBytes)

      Allocates nBytes bytes of memory, initialized to 0's. If nBytes is 0 it returns null.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Parameters:
      nBytes - the number of bytes to allocate
      Returns:
      a pointer to the allocated memory
    • malloc0N

      public static @Nullable MemorySegment malloc0N(long nBlocks, long nBlockBytes)

      This function is similar to g_malloc0(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Parameters:
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      Returns:
      a pointer to the allocated memory
      Since:
      2.24
    • mallocN

      public static @Nullable MemorySegment mallocN(long nBlocks, long nBlockBytes)

      This function is similar to g_malloc(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Parameters:
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      Returns:
      a pointer to the allocated memory
      Since:
      2.24
    • markupCollectAttributes

      public static boolean markupCollectAttributes(String elementName, String[] attributeNames, String[] attributeValues, GError[] error, Set<MarkupCollectType> firstType, String firstAttr, Object... varargs)

      Collects the attributes of the element from the data passed to the GMarkupParser start_element function, dealing with common error conditions and supporting boolean values.

      This utility function is not required to write a parser but can save a lot of typing.

      The elementName, attributeNames, attributeValues and error parameters passed to the start_element callback should be passed unmodified to this function.

      Following these arguments is a list of "supported" attributes to collect. It is an error to specify multiple attributes with the same name. If any attribute not in the list appears in the attributeNames array then an unknown attribute error will result.

      The GMarkupCollectType field allows specifying the type of collection to perform and if a given attribute must appear or is optional.

      The attribute name is simply the name of the attribute to collect.

      The pointer should be of the appropriate type (see the descriptions under GMarkupCollectType) and may be null in case a particular attribute is to be allowed but ignored.

      This function deals with issuing errors for missing attributes (of type MarkupError.MISSING_ATTRIBUTE), unknown attributes (of type MarkupError.UNKNOWN_ATTRIBUTE) and duplicate attributes (of type MarkupError.INVALID_CONTENT) as well as parse errors for boolean-valued attributes (again of type MarkupError.INVALID_CONTENT). In all of these cases false will be returned and error will be set as appropriate.

      Parameters:
      elementName - the current tag name
      attributeNames - the attribute names
      attributeValues - the attribute values
      error - a pointer to a GError or null
      firstType - the GMarkupCollectType of the first attribute
      firstAttr - the name of the first attribute
      varargs - a pointer to the storage location of the first attribute (or null), followed by more types names and pointers, ending with MarkupCollectType.INVALID
      Returns:
      true if successful
      Since:
      2.16
    • markupCollectAttributes

      public static boolean markupCollectAttributes(String elementName, String[] attributeNames, String[] attributeValues, GError[] error, MarkupCollectType firstType, String firstAttr, Object... varargs)

      Collects the attributes of the element from the data passed to the GMarkupParser start_element function, dealing with common error conditions and supporting boolean values.

      This utility function is not required to write a parser but can save a lot of typing.

      The elementName, attributeNames, attributeValues and error parameters passed to the start_element callback should be passed unmodified to this function.

      Following these arguments is a list of "supported" attributes to collect. It is an error to specify multiple attributes with the same name. If any attribute not in the list appears in the attributeNames array then an unknown attribute error will result.

      The GMarkupCollectType field allows specifying the type of collection to perform and if a given attribute must appear or is optional.

      The attribute name is simply the name of the attribute to collect.

      The pointer should be of the appropriate type (see the descriptions under GMarkupCollectType) and may be null in case a particular attribute is to be allowed but ignored.

      This function deals with issuing errors for missing attributes (of type MarkupError.MISSING_ATTRIBUTE), unknown attributes (of type MarkupError.UNKNOWN_ATTRIBUTE) and duplicate attributes (of type MarkupError.INVALID_CONTENT) as well as parse errors for boolean-valued attributes (again of type MarkupError.INVALID_CONTENT). In all of these cases false will be returned and error will be set as appropriate.

      Parameters:
      elementName - the current tag name
      attributeNames - the attribute names
      attributeValues - the attribute values
      error - a pointer to a GError or null
      firstType - the GMarkupCollectType of the first attribute
      firstAttr - the name of the first attribute
      varargs - a pointer to the storage location of the first attribute (or null), followed by more types names and pointers, ending with MarkupCollectType.INVALID
      Returns:
      true if successful
      Since:
      2.16
    • markupErrorQuark

      public static Quark markupErrorQuark()
    • markupEscapeText

      public static String markupEscapeText(String text, long length)

      Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.

      Note that this function doesn't protect whitespace and line endings from being processed according to the XML rules for normalization of line endings and attribute values.

      Note also that this function will produce character references in the range of &x1; ... &x1f; for all control sequences except for tabstop, newline and carriage return. The character references in this range are not valid XML 1.0, but they are valid XML 1.1 and will be accepted by the GMarkup parser.

      Parameters:
      text - some valid UTF-8 text
      length - length of text in bytes, or -1 if the text is nul-terminated
      Returns:
      a newly allocated string with the escaped text
    • markupPrintfEscaped

      public static String markupPrintfEscaped(String format, Object... varargs)

      Formats arguments according to format, escaping all string and character arguments in the fashion of g_markup_escape_text(). This is useful when you want to insert literal strings into XML-style markup output, without having to worry that the strings might themselves contain markup.

      const char *store = "Fortnum & Mason";
      const char *item = "Tea";
      char *output;
      
      output = g_markup_printf_escaped ("<purchase>"
                                        "<store>%s</store>"
                                        "<item>%s</item>"
                                        "</purchase>",
                                        store, item);
      
      Parameters:
      format - printf() style format string
      varargs - the arguments to insert in the format string
      Returns:
      newly allocated result from formatting operation. Free with g_free().
      Since:
      2.4
    • memIsSystemMalloc

      @Deprecated public static boolean memIsSystemMalloc()
      Deprecated.
      GLib always uses the system malloc, so this function always returns true.
      Checks whether the allocator used by g_malloc() is the system's malloc implementation. If it returns true memory allocated with malloc() can be used interchangeably with memory allocated using g_malloc(). This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.
      Returns:
      if true, malloc() and g_malloc() can be mixed.
    • memProfile

      @Deprecated public static void memProfile()
      Deprecated.
      Use other memory profiling tools instead
      GLib used to support some tools for memory profiling, but this no longer works. There are many other useful tools for memory profiling these days which can be used instead.
    • memSetVtable

      @Deprecated public static void memSetVtable(MemVTable vtable)
      Deprecated.
      This function now does nothing. Use other memory profiling tools instead
      This function used to let you override the memory allocation function. However, its use was incompatible with the use of global constructors in GLib and GIO, because those use the GLib allocators before main is reached. Therefore this function is now deprecated and is just a stub.
      Parameters:
      vtable - table of memory allocation routines.
    • memdup

      @Deprecated public static @Nullable MemorySegment memdup(@Nullable MemorySegment mem, int byteSize)
      Deprecated.
      Use memdup2(MemorySegment, long) instead, as it accepts a gsize argument for byteSize, avoiding the possibility of overflow in a gsizeguint conversion
      Allocates byteSize bytes of memory, and copies byteSize bytes into it from mem. If mem is NULL it returns NULL.
      Parameters:
      mem - the memory to copy
      byteSize - the number of bytes to copy
      Returns:
      a pointer to the newly-allocated copy of the memory
    • memdup2

      public static @Nullable MemorySegment memdup2(@Nullable MemorySegment mem, long byteSize)

      Allocates byteSize bytes of memory, and copies byteSize bytes into it from mem. If mem is NULL it returns NULL.

      This replaces memdup(MemorySegment, int), which was prone to integer overflows when converting the argument from a gsize to a guint.

      Parameters:
      mem - the memory to copy
      byteSize - the number of bytes to copy
      Returns:
      a pointer to the newly-allocated copy of the memory
      Since:
      2.68
    • mkdir

      public static int mkdir(String filename, int mode)

      A wrapper for the POSIX mkdir() function. The mkdir() function attempts to create a directory with the given name and permissions. The mode argument is ignored on Windows.

      See your C library manual for more details about mkdir().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      mode - permissions to use for the newly created directory
      Returns:
      0 if the directory was successfully created, -1 if an error occurred
      Since:
      2.6
    • mkdirWithParents

      public static int mkdirWithParents(String pathname, int mode)
      Create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.
      Parameters:
      pathname - a pathname in the GLib file name encoding
      mode - permissions to use for newly created directories
      Returns:
      0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.
      Since:
      2.8
    • mkdtemp

      public static @Nullable String mkdtemp(String tmpl)

      Creates a temporary directory in the current directory.

      See the mkdtemp() documentation on most UNIX-like systems.

      The parameter is a string that should follow the rules for mkdtemp() templates, i.e. contain the string "XXXXXX". g_mkdtemp() is slightly more flexible than mkdtemp() in that the sequence does not have to occur at the very end of the template. The X string will be modified to form the name of a directory that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

      If you are going to be creating a temporary directory inside the directory returned by g_get_tmp_dir(), you might want to use g_dir_make_tmp() instead.

      Parameters:
      tmpl - template directory name
      Returns:
      A pointer to tmpl, which has been modified to hold the directory name. In case of errors, null is returned and errno will be set.
      Since:
      2.30
    • mkdtempFull

      public static @Nullable String mkdtempFull(String tmpl, int mode)

      Creates a temporary directory in the current directory.

      See the mkdtemp() documentation on most UNIX-like systems.

      The parameter is a string that should follow the rules for mkdtemp() templates, i.e. contain the string "XXXXXX". g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the sequence does not have to occur at the very end of the template and you can pass a mode. The X string will be modified to form the name of a directory that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

      If you are going to be creating a temporary directory inside the directory returned by g_get_tmp_dir(), you might want to use g_dir_make_tmp() instead.

      Parameters:
      tmpl - template directory name
      mode - permissions to create the temporary directory with
      Returns:
      A pointer to tmpl, which has been modified to hold the directory name. In case of errors, null is returned, and errno will be set.
      Since:
      2.30
    • mkstemp

      public static int mkstemp(String tmpl)

      Opens a temporary file in the current directory.

      See the mkstemp() documentation on most UNIX-like systems.

      The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template. The X string will be modified to form the name of a file that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

      Parameters:
      tmpl - template filename
      Returns:
      A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and errno will be set.
    • mkstempFull

      public static int mkstempFull(String tmpl, int flags, int mode)

      Opens a temporary file in the current directory.

      See the mkstemp() documentation on most UNIX-like systems.

      The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp_full() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template and you can pass a mode and additional flags. The X string will be modified to form the name of a file that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

      Parameters:
      tmpl - template filename
      flags - flags to pass to an open() call in addition to O_EXCL and O_CREAT, which are passed automatically
      mode - permissions to create the temporary file with
      Returns:
      A file handle (as from open()) to the file opened for reading and writing. The file handle should be closed with close(). In case of errors, -1 is returned and errno will be set.
      Since:
      2.22
    • nullifyPointer

      public static void nullifyPointer(MemorySegment nullifyLocation)
      Set the pointer at the specified location to null.
      Parameters:
      nullifyLocation - the memory address of the pointer.
    • numberParserErrorQuark

      public static Quark numberParserErrorQuark()
    • onErrorQuery

      public static void onErrorQuery(String prgName)

      Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.

      #include <glib.h>
      
      static void
      log_handler (const gchar   *log_domain,
                   GLogLevelFlags log_level,
                   const gchar   *message,
                   gpointer       user_data)
      {
        g_log_default_handler (log_domain, log_level, message, user_data);
      
        g_on_error_query (MY_PROGRAM_NAME);
      }
      
      int
      main (int argc, char *argv[])
      {
        g_log_set_handler (MY_LOG_DOMAIN,
                           G_LOG_LEVEL_WARNING |
                           G_LOG_LEVEL_ERROR |
                           G_LOG_LEVEL_CRITICAL,
                           log_handler,
                           NULL);
        ...
      

      If "Exit" is selected, the application terminates with a call to _exit(0).

      If "

      invalid reference
      S
      tack" trace is selected, g_on_error_stack_trace() is called.

      This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

      If "

      invalid reference
      P
      roceed" is selected, the function returns.

      This function may cause different actions on non-UNIX platforms.

      On Windows consider using the G_DEBUGGER environment variable (see Running GLib Applications) and calling g_on_error_stack_trace() instead.

      Parameters:
      prgName -

      the program name, needed by gdb for the "

      invalid reference
      S
      tack trace"
      option. If `prgName` is `null`, g_get_prgname() is called to get
      the program name (which will work correctly if gdk_init() or
      gtk_init() has been called)
      
    • onErrorStackTrace

      public static void onErrorStackTrace(@Nullable String prgName)

      Invokes gdb, which attaches to the current process and shows a stack trace. Called by g_on_error_query() when the "

      invalid reference
      S
      tack trace"

      option is selected. You can get the current process's program name with g_get_prgname(), assuming that you have called gtk_init() or gdk_init().

      This function may cause different actions on non-UNIX platforms.

      When running on Windows, this function is not called by g_on_error_query(). If called directly, it will raise an exception, which will crash the program. If the G_DEBUGGER environment variable is set, a debugger will be invoked to attach and handle that exception (see Running GLib Applications).

      Parameters:
      prgName -

      the program name, needed by gdb for the "

      invalid reference
      S
      tack trace" option, or `NULL` to use a default string
    • open

      public static int open(String filename, int flags, int mode)

      A wrapper for the POSIX open() function. The open() function is used to convert a pathname into a file descriptor.

      On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements open() and file descriptors. The actual Win32 API for opening files is quite different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

      Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

      See your C library manual for more details about open().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      flags - as in open()
      mode - as in open()
      Returns:
      a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from open().
      Since:
      2.6
    • optionErrorQuark

      public static Quark optionErrorQuark()
    • parseDebugString

      public static int parseDebugString(@Nullable String string, @Nullable DebugKey @Nullable [] keys)

      Parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK to parse the debug options passed on the command line or through environment variables.

      If string is equal to "all", all flags are set. Any flags specified along with "all" in string are inverted; thus, "all,foo,bar" or "foo,bar,all" sets all flags except those corresponding to "foo" and "bar".

      If string is equal to "help", all the available keys in keys are printed out to standard error.

      Parameters:
      string - a list of debug options separated by colons, spaces, or commas, or null.
      keys - pointer to an array of GDebugKey which associate strings with bit flags.
      Returns:
      the combined set of bit flags.
    • pathGetBasename

      public static String pathGetBasename(String fileName)

      Gets the last component of the filename.

      If fileName ends with a directory separator it gets the component before the last slash. If fileName consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If fileName is empty, it gets ".".

      Parameters:
      fileName - the name of the file
      Returns:
      a newly allocated string containing the last component of the filename
    • pathGetDirname

      public static String pathGetDirname(String fileName)

      Gets the directory components of a file name. For example, the directory component of /usr/bin/test is /usr/bin. The directory component of / is /.

      If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

      Parameters:
      fileName - the name of the file
      Returns:
      the directory components of the file
    • pathIsAbsolute

      public static boolean pathIsAbsolute(String fileName)

      Returns true if the given fileName is an absolute file name. Note that this is a somewhat vague concept on Windows.

      On POSIX systems, an absolute file name is well-defined. It always starts from the single root directory. For example "/usr/local".

      On Windows, the concepts of current drive and drive-specific current directory introduce vagueness. This function interprets as an absolute file name one that either begins with a directory separator such as "\Users\tml" or begins with the root on a drive, for example "C:\Windows". The first case also includes UNC paths such as "\\\\myserver\docs\foo". In all cases, either slashes or backslashes are accepted.

      Note that a file name relative to the current drive root does not truly specify a file uniquely over time and across processes, as the current drive is a per-process value and can be changed.

      File names relative the current directory on some specific drive, such as "D:foo/bar", are not interpreted as absolute by this function, but they obviously are not relative to the normal current directory as returned by getcwd() or g_get_current_dir() either. Such paths should be avoided, or need to be handled using Windows-specific code.

      Parameters:
      fileName - a file name
      Returns:
      true if fileName is absolute
    • pathSkipRoot

      public static @Nullable String pathSkipRoot(String fileName)
      Returns a pointer into fileName after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If fileName is not an absolute path it returns null.
      Parameters:
      fileName - a file name
      Returns:
      a pointer into fileName after the root component
    • patternMatch

      @Deprecated public static boolean patternMatch(PatternSpec pspec, int stringLength, String string, @Nullable String stringReversed)

      Matches a string against a compiled pattern.

      Passing the correct length of the string given is mandatory. The reversed string can be omitted by passing NULL, this is more efficient if the reversed version of the string to be matched is not at hand, as g_pattern_match() will only construct it if the compiled pattern requires reverse matches.

      Note that, if the user code will (possibly) match a string against a multitude of patterns containing wildcards, chances are high that some patterns will require a reversed string. In this case, it’s more efficient to provide the reversed string to avoid multiple constructions thereof in the various calls to g_pattern_match().

      Note also that the reverse of a UTF-8 encoded string can in general not be obtained by strreverse(String). This works only if the string does not contain any multibyte characters. GLib offers the utf8Strreverse(String, long) function to reverse UTF-8 encoded strings.

      Parameters:
      pspec - a GPatternSpec
      stringLength - the length of string (in bytes, i.e. strlen(), not utf8Strlen(String, long))
      string - the UTF-8 encoded string to match
      stringReversed - the reverse of string
      Returns:
      true if string matches pspec
    • patternMatchSimple

      public static boolean patternMatchSimple(String pattern, String string)

      Matches a string against a pattern given as a string.

      If this function is to be called in a loop, it’s more efficient to compile the pattern once with PatternSpec(String) and call PatternSpec.matchString(String) repeatedly.

      Parameters:
      pattern - the UTF-8 encoded pattern
      string - the UTF-8 encoded string to match
      Returns:
      true if string matches pspec
    • patternMatchString

      @Deprecated public static boolean patternMatchString(PatternSpec pspec, String string)
      Deprecated.

      Matches a string against a compiled pattern.

      If the string is to be matched against more than one pattern, consider using PatternSpec.match(long, String, String) instead while supplying the reversed string.

      Parameters:
      pspec - a GPatternSpec
      string - the UTF-8 encoded string to match
      Returns:
      true if string matches pspec
    • pointerBitLock

      public static void pointerBitLock(MemorySegment address, int lockBit)

      This is equivalent to g_bit_lock, but working on pointers (or other pointer-sized values).

      For portability reasons, you may only lock on the bottom 32 bits of the pointer.

      While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

      Parameters:
      address - a pointer to a gpointer-sized value
      lockBit - a bit value between 0 and 31
      Since:
      2.30
    • pointerBitLockAndGet

      public static void pointerBitLockAndGet(MemorySegment address, int lockBit, @Nullable Out<Long> outPtr)

      This is equivalent to g_bit_lock, but working on pointers (or other pointer-sized values).

      For portability reasons, you may only lock on the bottom 32 bits of the pointer.

      Parameters:
      address - a pointer to a gpointer-sized value
      lockBit - a bit value between 0 and 31
      outPtr - returns the set pointer atomically. This is the value after setting the lock, it thus always has the lock bit set, while previously address had the lockbit unset. You may also use g_pointer_bit_lock_mask_ptr() to clear the lock bit.
      Since:
      2.80
    • pointerBitLockMaskPtr

      public static @Nullable MemorySegment pointerBitLockMaskPtr(@Nullable MemorySegment ptr, int lockBit, boolean set, long preserveMask, @Nullable MemorySegment preservePtr)
      This mangles ptr as g_pointer_bit_lock() and g_pointer_bit_unlock() do.
      Parameters:
      ptr - the pointer to mask
      lockBit - the bit to set/clear. If set to G_MAXUINT, the lockbit is taken from preservePtr or ptr (depending on preserveMask).
      set - whether to set (lock) the bit or unset (unlock). This has no effect, if lockBit is set to G_MAXUINT.
      preserveMask - if non-zero, a bit-mask for preservePtr. The preserveMask bits from preservePtr are set in the result. Note that the lockBit bit will be always set according to set, regardless of preserveMask and preservePtr (unless lockBit is G_MAXUINT).
      preservePtr - if preserveMask is non-zero, the bits from this pointer are set in the result.
      Returns:
      the mangled pointer.
      Since:
      2.80
    • pointerBitTrylock

      public static boolean pointerBitTrylock(MemorySegment address, int lockBit)

      This is equivalent to g_bit_trylock(), but working on pointers (or other pointer-sized values).

      For portability reasons, you may only lock on the bottom 32 bits of the pointer.

      While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

      Parameters:
      address - a pointer to a gpointer-sized value
      lockBit - a bit value between 0 and 31
      Returns:
      true if the lock was acquired
      Since:
      2.30
    • pointerBitUnlock

      public static void pointerBitUnlock(MemorySegment address, int lockBit)

      This is equivalent to g_bit_unlock, but working on pointers (or other pointer-sized values).

      For portability reasons, you may only lock on the bottom 32 bits of the pointer.

      While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

      Parameters:
      address - a pointer to a gpointer-sized value
      lockBit - a bit value between 0 and 31
      Since:
      2.30
    • pointerBitUnlockAndSet

      public static void pointerBitUnlockAndSet(MemorySegment address, int lockBit, @Nullable MemorySegment ptr, long preserveMask)

      This is equivalent to g_pointer_bit_unlock() and atomically setting the pointer value.

      Note that the lock bit will be cleared from the pointer. If the unlocked pointer that was set is not identical to ptr, an assertion fails. In other words, ptr must have lockBit unset. This also means, you usually can only use this on the lowest bits.

      Parameters:
      address - a pointer to a gpointer-sized value
      lockBit - a bit value between 0 and 31
      ptr - the new pointer value to set
      preserveMask - if non-zero, those bits of the current pointer in address are preserved. Note that the lockBit bit will be always unset regardless of ptr, preserveMask and the currently set value in address.
      Since:
      2.80
    • poll

      public static int poll(PollFD fds, int nfds, int timeout)

      Polls fds, as with the poll() system call, but portably. (On systems that don't have poll(), it is emulated using select().) This is used internally by GMainContext, but it can be called directly if you need to block until a file descriptor is ready, but don't want to run the full main loop.

      Each element of fds is a GPollFD describing a single file descriptor to poll. The fd field indicates the file descriptor, and the events field indicates the events to poll for. On return, the revents fields will be filled with the events that actually occurred.

      On POSIX systems, the file descriptors in fds can be any sort of file descriptor, but the situation is much more complicated on Windows. If you need to use g_poll() in code that has to run on Windows, the easiest solution is to construct all of your GPollFDs with g_io_channel_win32_make_pollfd().

      Parameters:
      fds - file descriptors to poll
      nfds - the number of file descriptors in fds
      timeout - amount of time to wait, in milliseconds, or -1 to wait forever
      Returns:
      the number of entries in fds whose revents fields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.
      Since:
      2.20
    • prefixError

      public static void prefixError(Out<GError> err, String format, Object... varargs)

      Formats a string according to format and prefix it to an existing error message. If err is null (ie: no error variable) then do nothing.

      If *err is null (ie: an error variable is present but there is no error condition) then also do nothing.

      Parameters:
      err - a return location for a GError
      format - printf()-style format string
      varargs - arguments to format
      Since:
      2.16
    • prefixErrorLiteral

      public static void prefixErrorLiteral(Out<GError> err, String prefix)
      Prefixes prefix to an existing error message. If err or *err is null (i.e.: no error variable) then do nothing.
      Parameters:
      err - a return location for a GError, or null
      prefix - string to prefix err with
      Since:
      2.70
    • print

      public static void print(String format, Object... varargs)

      Outputs a formatted message via the print handler.

      The default print handler outputs the encoded message to stdout, without appending a trailing new-line character. Typically, format should end with its own new-line character.

      This function should not be used from within libraries for debugging messages, since it may be redirected by applications to special purpose message windows or even files. Instead, libraries should use log(String, Set, String, Object...), logStructured(String, Set, Object...), or the convenience macros GLib.message, GLib.warning and GLib.error.

      Parameters:
      format - the message format. See the printf() documentation
      varargs - the parameters to insert into the format string
    • printerr

      public static void printerr(String format, Object... varargs)

      Outputs a formatted message via the error message handler.

      The default handler outputs the encoded message to stderr, without appending a trailing new-line character. Typically, format should end with its own new-line character.

      This function should not be used from within libraries. Instead log(String, Set, String, Object...) or logStructured(String, Set, Object...) should be used, or the convenience macros GLib.message, GLib.warning and GLib.error.

      Parameters:
      format - the message format. See the printf() documentation
      varargs - the parameters to insert into the format string
    • printf

      public static int printf(String format, Object... varargs)

      An implementation of the standard printf() function which supports positional parameters, as specified in the Single Unix Specification.

      As with the standard printf(), this does not automatically append a trailing new-line character to the message, so typically format should end with its own new-line character.

      glib/gprintf.h must be explicitly included in order to use this function.

      Parameters:
      format - a standard printf() format string, but notice string precision pitfalls
      varargs - the arguments to insert in the output
      Returns:
      the number of bytes printed
      Since:
      2.2
    • propagateError

      public static void propagateError(Out<GError> dest, GError src)

      If dest is null, free src; otherwise, moves src into *dest. The error variable dest points to must be null.

      src must be non-null.

      Note that src is no longer valid after this call. If you want to keep using the same GError*, you need to set it to null after calling this function on it.

      Parameters:
      dest - error return location
      src - error to move into the return location
    • propagatePrefixedError

      public static void propagatePrefixedError(GError[] dest, GError src, String format, Object... varargs)
      If dest is null, free src; otherwise, moves src into *dest. *dest must be null. After the move, add a prefix as with g_prefix_error().
      Parameters:
      dest - error return location
      src - error to move into the return location
      format - printf()-style format string
      varargs - arguments to format
      Since:
      2.16
    • qsortWithData

      @Deprecated public static void qsortWithData(MemorySegment pbase, int totalElems, long size, @Nullable CompareDataFunc compareFunc)
      Deprecated.
      total_elems is too small to represent larger arrays; use sortArray(MemorySegment[], long, CompareDataFunc) instead

      This is just like the standard C qsort() function, but the comparison routine accepts a user data argument (like qsort_r()).

      Unlike qsort(), this is guaranteed to be a stable sort (since GLib 2.32).

      Parameters:
      pbase - start of array to sort
      totalElems - elements in the array
      size - size of each element
      compareFunc - function to compare elements
    • quarkFromStaticString

      public static Quark quarkFromStaticString(@Nullable String string)

      Gets the GQuark identifying the given (static) string. If the string does not currently have an associated GQuark, a new GQuark is created, linked to the given string.

      Note that this function is identical to g_quark_from_string() except that if a new GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will continue to exist until the program terminates. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK theme engines).

      This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

      Parameters:
      string - a string
      Returns:
      the GQuark identifying the string, or 0 if string is null
    • quarkFromString

      public static Quark quarkFromString(@Nullable String string)

      Gets the GQuark identifying the given string. If the string does not currently have an associated GQuark, a new GQuark is created, using a copy of the string.

      This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

      Parameters:
      string - a string
      Returns:
      the GQuark identifying the string, or 0 if string is null
    • quarkToString

      public static String quarkToString(Quark quark)
      Gets the string associated with the given GQuark.
      Parameters:
      quark - a GQuark.
      Returns:
      the string associated with the GQuark
    • quarkTryString

      public static Quark quarkTryString(@Nullable String string)

      Gets the GQuark associated with the given string, or 0 if string is null or it has no associated GQuark.

      If you want the GQuark to be created if it doesn't already exist, use g_quark_from_string() or g_quark_from_static_string().

      This function must not be used before library constructors have finished running.

      Parameters:
      string - a string
      Returns:
      the GQuark associated with the string, or 0 if string is null or there is no GQuark associated with it
    • randomDouble

      public static double randomDouble()
      Returns a random gdouble equally distributed over the range [0..1).
      Returns:
      a random number
    • randomDoubleRange

      public static double randomDoubleRange(double begin, double end)
      Returns a random gdouble equally distributed over the range [end).
      Parameters:
      begin - lower closed bound of the interval
      end - upper open bound of the interval
      Returns:
      a random number
    • randomInt

      public static int randomInt()
      Return a random guint32 equally distributed over the range [0..2^32-1].
      Returns:
      a random number
    • randomIntRange

      public static int randomIntRange(int begin, int end)
      Returns a random gint32 equally distributed over the range end-1.
      Parameters:
      begin - lower closed bound of the interval
      end - upper open bound of the interval
      Returns:
      a random number
    • randomSetSeed

      public static void randomSetSeed(int seed)
      Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.
      Parameters:
      seed - a value to reinitialize the global random number generator
    • rcBoxAcquire

      public static MemorySegment rcBoxAcquire(MemorySegment memBlock)
      Acquires a reference on the data pointed by memBlock.
      Parameters:
      memBlock - a pointer to reference counted data
      Returns:
      a pointer to the data, with its reference count increased
      Since:
      2.58
    • rcBoxAlloc

      public static MemorySegment rcBoxAlloc(long blockSize)

      Allocates blockSize bytes of memory, and adds reference counting semantics to it.

      The data will be freed when its reference count drops to zero.

      The allocated data is guaranteed to be suitably aligned for any built-in type.

      Parameters:
      blockSize - the size of the allocation, must be greater than 0
      Returns:
      a pointer to the allocated memory
      Since:
      2.58
    • rcBoxAlloc0

      public static MemorySegment rcBoxAlloc0(long blockSize)

      Allocates blockSize bytes of memory, and adds reference counting semantics to it.

      The contents of the returned data is set to zero.

      The data will be freed when its reference count drops to zero.

      The allocated data is guaranteed to be suitably aligned for any built-in type.

      Parameters:
      blockSize - the size of the allocation, must be greater than 0
      Returns:
      a pointer to the allocated memory
      Since:
      2.58
    • rcBoxDup

      public static MemorySegment rcBoxDup(long blockSize, MemorySegment memBlock)
      Allocates a new block of data with reference counting semantics, and copies blockSize bytes of memBlock into it.
      Parameters:
      blockSize - the number of bytes to copy, must be greater than 0
      memBlock - the memory to copy
      Returns:
      a pointer to the allocated memory
      Since:
      2.58
    • rcBoxGetSize

      public static long rcBoxGetSize(MemorySegment memBlock)
      Retrieves the size of the reference counted data pointed by memBlock.
      Parameters:
      memBlock - a pointer to reference counted data
      Returns:
      the size of the data, in bytes
      Since:
      2.58
    • rcBoxRelease

      public static void rcBoxRelease(MemorySegment memBlock)

      Releases a reference on the data pointed by memBlock.

      If the reference was the last one, it will free the resources allocated for memBlock.

      Parameters:
      memBlock - a pointer to reference counted data
      Since:
      2.58
    • rcBoxReleaseFull

      public static void rcBoxReleaseFull(MemorySegment memBlock)

      Releases a reference on the data pointed by memBlock.

      If the reference was the last one, it will call clearFunc to clear the contents of memBlock, and then will free the resources allocated for memBlock.

      Parameters:
      memBlock - a pointer to reference counted data
      Since:
      2.58
    • realloc

      public static @Nullable MemorySegment realloc(@Nullable MemorySegment mem, long nBytes)

      Reallocates the memory pointed to by mem, so that it now has space for nBytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be null, in which case it's considered to have zero-length. nBytes may be 0, in which case null will be returned and mem will be freed unless it is null.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Parameters:
      mem - the memory to reallocate
      nBytes - new size of the memory in bytes
      Returns:
      the new address of the allocated memory
    • reallocN

      public static @Nullable MemorySegment reallocN(@Nullable MemorySegment mem, long nBlocks, long nBlockBytes)

      This function is similar to g_realloc(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

      If the allocation fails (because the system is out of memory), the program is terminated.

      Parameters:
      mem - the memory to reallocate
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      Returns:
      the new address of the allocated memory
      Since:
      2.24
    • refCountCompare

      public static boolean refCountCompare(MemorySegment rc, int val)
      Compares the current value of rc with val.
      Parameters:
      rc - the address of a reference count variable
      val - the value to compare
      Returns:
      true if the reference count is the same as the given value
      Since:
      2.58
    • refCountDec

      public static boolean refCountDec(Out<Integer> rc)

      Decreases the reference count.

      If true is returned, the reference count reached 0. After this point, rc is an undefined state and must be reinitialized with g_ref_count_init() to be used again.

      Parameters:
      rc - the address of a reference count variable
      Returns:
      true if the reference count reached 0, and false otherwise
      Since:
      2.58
    • refCountInc

      public static void refCountInc(Out<Integer> rc)
      Increases the reference count.
      Parameters:
      rc - the address of a reference count variable
      Since:
      2.58
    • refCountInit

      public static void refCountInit(Out<Integer> rc)
      Initializes a reference count variable to 1.
      Parameters:
      rc - the address of a reference count variable
      Since:
      2.58
    • refStringAcquire

      public static String refStringAcquire(String str)
      Acquires a reference on a string.
      Parameters:
      str - a reference counted string
      Returns:
      the given string, with its reference count increased
      Since:
      2.58
    • refStringEqual

      public static boolean refStringEqual(String str1, String str2)

      Compares two ref-counted strings for byte-by-byte equality.

      It can be passed to HashTable.new_(HashFunc, EqualFunc) as the key equality function, and behaves exactly the same as strEqual(MemorySegment, MemorySegment) (or strcmp()), but can return slightly faster as it can check the string lengths before checking all the bytes.

      Parameters:
      str1 - a reference counted string
      str2 - a reference counted string
      Returns:
      TRUE if the strings are equal, otherwise FALSE
      Since:
      2.84
    • refStringLength

      public static long refStringLength(String str)
      Retrieves the length of str.
      Parameters:
      str - a reference counted string
      Returns:
      the length of the given string, in bytes
      Since:
      2.58
    • refStringNew

      public static String refStringNew(String str)
      Creates a new reference counted string and copies the contents of str into it.
      Parameters:
      str - a NUL-terminated string
      Returns:
      the newly created reference counted string
      Since:
      2.58
    • refStringNewIntern

      public static String refStringNewIntern(String str)

      Creates a new reference counted string and copies the content of str into it.

      If you call this function multiple times with the same str, or with the same contents of str, it will return a new reference, instead of creating a new string.

      Parameters:
      str - a NUL-terminated string
      Returns:
      the newly created reference counted string, or a new reference to an existing string
      Since:
      2.58
    • refStringNewLen

      public static String refStringNewLen(String str, long len)

      Creates a new reference counted string and copies the contents of str into it, up to len bytes.

      Since this function does not stop at nul bytes, it is the caller's responsibility to ensure that str has at least len addressable bytes.

      Parameters:
      str - a string
      len - length of str to use, or -1 if str is nul-terminated
      Returns:
      the newly created reference counted string
      Since:
      2.58
    • refStringRelease

      public static void refStringRelease(String str)
      Releases a reference on a string; if it was the last reference, the resources allocated by the string are freed as well.
      Parameters:
      str - a reference counted string
      Since:
      2.58
    • reloadUserSpecialDirsCache

      public static void reloadUserSpecialDirsCache()

      Resets the cache used for g_get_user_special_dir(), so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.

      Due to thread safety issues this may cause leaking of strings that were previously returned from g_get_user_special_dir() that can't be freed. We ensure to only leak the data for the directories that actually changed value though.

      Since:
      2.22
    • remove

      public static int remove(String filename)

      A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.

      See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.

      If this function fails on Windows you can't infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      Returns:
      0 if the file was successfully removed, -1 if an error occurred
      Since:
      2.6
    • rename

      public static int rename(String oldfilename, String newfilename)

      A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.

      See your C library manual for more details about how rename() works on your system. It is not possible in general on Windows to rename a file that is open to some process.

      Parameters:
      oldfilename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      newfilename - a pathname in the GLib file name encoding
      Returns:
      0 if the renaming succeeded, -1 if an error occurred
      Since:
      2.6
    • returnIfFailWarning

      public static void returnIfFailWarning(@Nullable String logDomain, String prettyFunction, @Nullable String expression)
      Internal function used to print messages from the public GLib.returnIfFail and GLib.returnValIfFail macros.
      Parameters:
      logDomain - log domain
      prettyFunction - function containing the assertion
      expression - expression which failed
    • rmdir

      public static int rmdir(String filename)

      A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.

      See your C library manual for more details about how rmdir() works on your system.

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      Returns:
      0 if the directory was successfully removed, -1 if an error occurred
      Since:
      2.6
    • setApplicationName

      public static void setApplicationName(String applicationName)

      Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user. Contrast with g_set_prgname(), which sets a non-localized name. g_set_prgname() will be called automatically by gtk_init(), but g_set_application_name() will not.

      Note that for thread safety reasons, this function can only be called once.

      The application name will be used in contexts such as error messages, or when displaying an application's name in the task list.

      Parameters:
      applicationName - localized name of the application
      Since:
      2.2
    • setError

      public static void setError(Out<GError> err, Quark domain, int code, String format, Object... varargs)
      Does nothing if err is null; if err is non-null, then *err must be null. A new GError is created and assigned to *err.
      Parameters:
      err - a return location for a GError
      domain - error domain
      code - error code
      format - printf()-style format
      varargs - args for format
    • setErrorLiteral

      public static void setErrorLiteral(Out<GError> err, Quark domain, int code, String message)
      Does nothing if err is null; if err is non-null, then *err must be null. A new GError is created and assigned to *err. Unlike g_set_error(), message is not a printf()-style format string. Use this function if message contains text you don't have control over, that could include printf() escape sequences.
      Parameters:
      err - a return location for a GError
      domain - error domain
      code - error code
      message - error message
      Since:
      2.18
    • setPrgname

      public static void setPrgname(String prgname)

      Sets the name of the program. This name should not be localized, in contrast to g_set_application_name().

      If you are using GApplication the program name is set in g_application_run(). In case of GDK or GTK it is set in gdk_init(), which is called by gtk_init() and the GtkApplication::startup handler. By default, the program name is found by taking the last component of argv[0].

      Since GLib 2.72, this function can be called multiple times and is fully thread safe. Prior to GLib 2.72, this function could only be called once per process.

      See the GTK documentation for requirements on integrating g_set_prgname() with GTK applications.

      Parameters:
      prgname - the name of the program.
    • setPrintHandler

      public static @Nullable PrintFunc setPrintHandler(@Nullable PrintFunc func)

      Sets the print handler to func, or resets it to the default GLib handler if NULL.

      Any messages passed to print(String, Object...) will be output via the new handler. The default handler outputs the encoded message to stdout. By providing your own handler you can redirect the output, to a GTK widget or a log file for example.

      Since 2.76 this functions always returns a valid GLib.PrintFunc, and never returns NULL. If no custom print handler was set, it will return the GLib default print handler and that can be re-used to decorate its output and/or to write to stderr in all platforms. Before GLib 2.76, this was NULL.

      Parameters:
      func - the new print handler or NULL to reset to the default
      Returns:
      the old print handler
    • setPrinterrHandler

      public static @Nullable PrintFunc setPrinterrHandler(@Nullable PrintFunc func)

      Sets the handler for printing error messages to func, or resets it to the default GLib handler if NULL.

      Any messages passed to printerr(String, Object...) will be output via the new handler. The default handler outputs the encoded message to stderr. By providing your own handler you can redirect the output, to a GTK widget or a log file for example.

      Since 2.76 this functions always returns a valid GLib.PrintFunc, and never returns NULL. If no custom error print handler was set, it will return the GLib default error print handler and that can be re-used to decorate its output and/or to write to stderr in all platforms. Before GLib 2.76, this was NULL.

      Parameters:
      func - he new error message handler or NULL to reset to the default
      Returns:
      the old error message handler
    • setenv

      public static boolean setenv(String variable, String value, boolean overwrite)

      Sets an environment variable. On UNIX, both the variable's name and value can be arbitrary byte strings, except that the variable's name cannot contain '='. On Windows, they should be in UTF-8.

      Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.

      You should be mindful of the fact that environment variable handling in UNIX is not thread-safe, and your program may crash if one thread calls g_setenv() while another thread is calling getenv(). (And note that many functions, such as gettext(), call getenv() internally.) This function is only safe to use at the very start of your program, before creating any other threads (or creating objects that create worker threads of their own).

      If you need to set up the environment for a child process, you can use g_get_environ() to get an environment array, modify that with g_environ_setenv() and g_environ_unsetenv(), and then pass that array directly to execvpe(), g_spawn_async(), or the like.

      Parameters:
      variable - the environment variable to set, must not contain '='.
      value - the value for to set the variable to.
      overwrite - whether to change the variable if it already exists.
      Returns:
      false if the environment variable couldn't be set.
      Since:
      2.4
    • shellErrorQuark

      public static Quark shellErrorQuark()
    • shellParseArgv

      public static boolean shellParseArgv(String commandLine, @Nullable Out<String[]> argvp) throws GErrorException

      Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported).

      The results are defined to be the same as those you would get from a UNIX98 /bin/sh, as long as the input contains none of the unsupported shell expansions. If the input does contain such expansions, they are passed through literally.

      Possible errors are those from the G_SHELL_ERROR domain.

      In particular, if commandLine is an empty string (or a string containing only whitespace), ShellError.EMPTY_STRING will be returned. It’s guaranteed that argvp will be a non-empty array if this function returns successfully.

      Free the returned vector with g_strfreev().

      Parameters:
      commandLine - command line to parse
      argvp - return location for array of args
      Returns:
      true on success, false if error set
      Throws:
      GErrorException - see GError
    • shellQuote

      public static String shellQuote(String unquotedString)

      Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquotedString.

      If you pass a filename to the shell, for example, you should first quote it with this function.

      The return value must be freed with g_free().

      The quoting style used is undefined (single or double quotes may be used).

      Parameters:
      unquotedString - a literal string
      Returns:
      quoted string
    • shellUnquote

      public static String shellUnquote(String quotedString) throws GErrorException

      Unquotes a string as the shell (/bin/sh) would.

      This function only handles quotes; if a string contains file globs, arithmetic operators, variables, backticks, redirections, or other special-to-the-shell features, the result will be different from the result a real shell would produce (the variables, backticks, etc. will be passed through literally instead of being expanded).

      This function is guaranteed to succeed if applied to the result of g_shell_quote(). If it fails, it returns null and sets the error.

      The quotedString need not actually contain quoted or escaped text; g_shell_unquote() simply goes through the string and unquotes/unescapes anything that the shell would. Both single and double quotes are handled, as are escapes including escaped newlines.

      The return value must be freed with g_free().

      Possible errors are in the G_SHELL_ERROR domain.

      Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even \\' - if you want a ' in the quoted text, you have to do something like 'foo'\\''bar'. Double quotes allow $, ```, ", \\, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.

      Parameters:
      quotedString - shell-quoted string
      Returns:
      an unquoted string
      Throws:
      GErrorException - see GError
    • sliceAlloc

      public static @Nullable MemorySegment sliceAlloc(long blockSize)

      Allocates a block of memory from the libc allocator.

      The block address handed out can be expected to be aligned to at least 1 * sizeof (void*).

      Since GLib 2.76 this always uses the system malloc() implementation internally.

      Parameters:
      blockSize - the number of bytes to allocate
      Returns:
      a pointer to the allocated memory block, which will be null if and only if memSize is 0
      Since:
      2.10
    • sliceAlloc0

      public static @Nullable MemorySegment sliceAlloc0(long blockSize)

      Allocates a block of memory via g_slice_alloc() and initializes the returned memory to 0.

      Since GLib 2.76 this always uses the system malloc() implementation internally.

      Parameters:
      blockSize - the number of bytes to allocate
      Returns:
      a pointer to the allocated block, which will be null if and only if memSize is 0
      Since:
      2.10
    • sliceCopy

      public static @Nullable MemorySegment sliceCopy(long blockSize, @Nullable MemorySegment memBlock)

      Allocates a block of memory from the slice allocator and copies blockSize bytes into it from memBlock.

      memBlock must be non-null if blockSize is non-zero.

      Since GLib 2.76 this always uses the system malloc() implementation internally.

      Parameters:
      blockSize - the number of bytes to allocate
      memBlock - the memory to copy
      Returns:
      a pointer to the allocated memory block, which will be null if and only if memSize is 0
      Since:
      2.14
    • sliceFree1

      public static void sliceFree1(long blockSize, @Nullable MemorySegment memBlock)

      Frees a block of memory.

      The memory must have been allocated via g_slice_alloc() or g_slice_alloc0() and the blockSize has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

      If memBlock is null, this function does nothing.

      Since GLib 2.76 this always uses the system free_sized() implementation internally.

      Parameters:
      blockSize - the size of the block
      memBlock - a pointer to the block to free
      Since:
      2.10
    • sliceFreeChainWithOffset

      public static void sliceFreeChainWithOffset(long blockSize, @Nullable MemorySegment memChain, long nextOffset)

      Frees a linked list of memory blocks of structure type type.

      The memory blocks must be equal-sized, allocated via g_slice_alloc() or g_slice_alloc0() and linked together by a next pointer (similar to GSList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

      If memChain is null, this function does nothing.

      Since GLib 2.76 this always uses the system free_sized() implementation internally.

      Parameters:
      blockSize - the size of the blocks
      memChain - a pointer to the first block of the chain
      nextOffset - the offset of the next field in the blocks
      Since:
      2.10
    • sliceGetConfig

      public static long sliceGetConfig(SliceConfig ckey)
    • sliceGetConfigState

      public static MemorySegment sliceGetConfigState(SliceConfig ckey, long address, MemorySegment nValues)
    • sliceSetConfig

      public static void sliceSetConfig(SliceConfig ckey, long value)
    • snprintf

      public static int snprintf(String string, int n, String format, Object... varargs)

      A safer form of the standard sprintf() function. The output is guaranteed to not exceed n characters (including the terminating nul character), so it is easy to ensure that a buffer overflow cannot occur.

      See also strdupPrintf(String, Object...).

      In versions of GLib prior to 1.2.3, this function may return -1 if the output was truncated, and the truncated string may not be nul-terminated. In versions prior to 1.3.12, this function returns the length of the output string.

      The return value of g_snprintf() conforms to the snprintf() function as standardized in ISO C99. Note that this is different from traditional snprintf(), which returns the length of the output string.

      The format string may contain positional parameters, as specified in the Single Unix Specification.

      Parameters:
      string - the buffer to hold the output
      n - the maximum number of bytes to produce (including the terminating nul character)
      format - a standard printf() format string, but notice string precision pitfalls
      varargs - the arguments to insert in the output
      Returns:
      the number of bytes which would be produced if the buffer was large enough
    • sortArray

      public static void sortArray(@Nullable MemorySegment @Nullable [] array, long elementSize, @Nullable CompareDataFunc compareFunc)

      This is just like the standard C qsort() function, but the comparison routine accepts a user data argument (like qsort_r()).

      Unlike qsort(), this is guaranteed to be a stable sort.

      Parameters:
      array - start of array to sort
      elementSize - size of each element
      compareFunc - function to compare elements
      Since:
      2.82
    • spacedPrimesClosest

      public static int spacedPrimesClosest(int num)

      Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a GHashTable.

      The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

      Parameters:
      num - a guint
      Returns:
      the smallest prime number from a built-in array of primes which is larger than num
    • spawnAsync

      public static boolean spawnAsync(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid) throws GErrorException

      Executes a child program asynchronously.

      See g_spawn_async_with_pipes_and_fds() for a full description; this function simply calls the g_spawn_async_with_pipes() without any pipes, which in turn calls g_spawn_async_with_pipes_and_fds().

      You should call g_spawn_close_pid() on the returned child process reference when you don't need it any more.

      If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use GdkAppLaunchContext, GAppLaunchContext, or set the DISPLAY environment variable.

      Note that the returned childPid on Windows is a handle to the child process and not its identifier. Process handles and process identifiers are different concepts on Windows.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's
      argv - child's argument vector
      envp - child's environment, or null to inherit parent's
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      childPid - return location for child process reference, or null
      Returns:
      true on success, false if error is set
      Throws:
      GErrorException - see GError
    • spawnAsync

      public static boolean spawnAsync(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid) throws GErrorException

      Executes a child program asynchronously.

      See g_spawn_async_with_pipes_and_fds() for a full description; this function simply calls the g_spawn_async_with_pipes() without any pipes, which in turn calls g_spawn_async_with_pipes_and_fds().

      You should call g_spawn_close_pid() on the returned child process reference when you don't need it any more.

      If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use GdkAppLaunchContext, GAppLaunchContext, or set the DISPLAY environment variable.

      Note that the returned childPid on Windows is a handle to the child process and not its identifier. Process handles and process identifiers are different concepts on Windows.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's
      argv - child's argument vector
      envp - child's environment, or null to inherit parent's
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      childPid - return location for child process reference, or null
      Returns:
      true on success, false if error is set
      Throws:
      GErrorException - see GError
    • spawnAsyncWithFds

      public static boolean spawnAsyncWithFds(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, int stdinFd, int stdoutFd, int stderrFd) throws GErrorException

      Executes a child program asynchronously.

      Identical to g_spawn_async_with_pipes_and_fds() but with n_fds set to zero, so no FD assignments are used.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's, in the GLib file name encoding
      argv - child's argument vector, in the GLib file name encoding; it must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's, in the GLib file name encoding
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      childPid - return location for child process ID, or null
      stdinFd - file descriptor to use for child's stdin, or -1
      stdoutFd - file descriptor to use for child's stdout, or -1
      stderrFd - file descriptor to use for child's stderr, or -1
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
      Since:
      2.58
    • spawnAsyncWithFds

      public static boolean spawnAsyncWithFds(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, int stdinFd, int stdoutFd, int stderrFd) throws GErrorException

      Executes a child program asynchronously.

      Identical to g_spawn_async_with_pipes_and_fds() but with n_fds set to zero, so no FD assignments are used.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's, in the GLib file name encoding
      argv - child's argument vector, in the GLib file name encoding; it must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's, in the GLib file name encoding
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      childPid - return location for child process ID, or null
      stdinFd - file descriptor to use for child's stdin, or -1
      stdoutFd - file descriptor to use for child's stdout, or -1
      stderrFd - file descriptor to use for child's stderr, or -1
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
      Since:
      2.58
    • spawnAsyncWithPipes

      public static boolean spawnAsyncWithPipes(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, @Nullable Out<Integer> standardInput, @Nullable Out<Integer> standardOutput, @Nullable Out<Integer> standardError) throws GErrorException
      Identical to g_spawn_async_with_pipes_and_fds() but with n_fds set to zero, so no FD assignments are used.
      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's, in the GLib file name encoding
      argv - child's argument vector, in the GLib file name encoding; it must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's, in the GLib file name encoding
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      childPid - return location for child process ID, or null
      standardInput - return location for file descriptor to write to child's stdin, or null
      standardOutput - return location for file descriptor to read child's stdout, or null
      standardError - return location for file descriptor to read child's stderr, or null
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
    • spawnAsyncWithPipes

      public static boolean spawnAsyncWithPipes(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, @Nullable Out<Integer> standardInput, @Nullable Out<Integer> standardOutput, @Nullable Out<Integer> standardError) throws GErrorException
      Identical to g_spawn_async_with_pipes_and_fds() but with n_fds set to zero, so no FD assignments are used.
      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's, in the GLib file name encoding
      argv - child's argument vector, in the GLib file name encoding; it must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's, in the GLib file name encoding
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      childPid - return location for child process ID, or null
      standardInput - return location for file descriptor to write to child's stdin, or null
      standardOutput - return location for file descriptor to read child's stdout, or null
      standardError - return location for file descriptor to read child's stderr, or null
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
    • spawnAsyncWithPipesAndFds

      public static boolean spawnAsyncWithPipesAndFds(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, int stdinFd, int stdoutFd, int stderrFd, @Nullable int @Nullable [] sourceFds, @Nullable int @Nullable [] targetFds, @Nullable Pid childPidOut, @Nullable Out<Integer> stdinPipeOut, @Nullable Out<Integer> stdoutPipeOut, @Nullable Out<Integer> stderrPipeOut) throws GErrorException

      Executes a child program asynchronously (your program will not block waiting for the child to exit).

      The child program is specified by the only argument that must be provided, argv. argv should be a null-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path. If flags contains the SpawnFlags.SEARCH_PATH flag, the PATH environment variable is used to search for the executable. If flags contains the SpawnFlags.SEARCH_PATH_FROM_ENVP flag, the PATH variable from envp is used to search for the executable. If both the SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP flags are set, the PATH variable from envp takes precedence over the environment variable.

      If the program name is not a full path and SpawnFlags.SEARCH_PATH flag is not used, then the program will be run from the current directory (or workingDirectory, if specified); this might be unexpected or even dangerous in some cases when the current directory is world-writable.

      On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in these arguments will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft's tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

      At least currently, mingw doesn't support wmain(), so if you use mingw to develop the spawned program, it should call g_win32_get_command_line() to get arguments in UTF-8.

      On Windows the low-level child process creation API CreateProcess() doesn't use argument vectors, but a command line. The C runtime library's spawn*() family of functions (which g_spawn_async_with_pipes() eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when you have argument vector elements that contain spaces or double quotes. The spawn*() functions don't do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

      The returned childPid on Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.

      envp is a null-terminated array of strings, where each string has the form KEY=VALUE. This will become the child's environment. If envp is null, the child inherits its parent's environment.

      flags should be the bitwise OR of any flags you want to affect the function's behaviour. The SpawnFlags.DO_NOT_REAP_CHILD means that the child will not automatically be reaped; you must use a child watch (g_child_watch_add()) to be notified about the death of the child process, otherwise it will stay around as a zombie process until this process exits. Eventually you must call g_spawn_close_pid() on the childPid, in order to free resources which may be associated with the child process. (On Unix, using a child watch is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling g_spawn_close_pid() is equivalent to calling CloseHandle() on the process handle returned in childPid). See g_child_watch_add().

      Open UNIX file descriptors marked as FD_CLOEXEC will be automatically closed in the child process. SpawnFlags.LEAVE_DESCRIPTORS_OPEN means that other open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. SpawnFlags.SEARCH_PATH means that argv[0] need not be an absolute path, it will be looked for in the PATH environment variable. SpawnFlags.SEARCH_PATH_FROM_ENVP means need not be an absolute path, it will be looked for in the PATH variable from envp. If both SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP are used, the value from envp takes precedence over the environment.

      SpawnFlags.CHILD_INHERITS_STDIN means that the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null). SpawnFlags.STDIN_FROM_DEV_NULL explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdinPipeOut argument is ignored.

      SpawnFlags.STDOUT_TO_DEV_NULL means that the child's standard output will be discarded (by default, it goes to the same location as the parent's standard output). SpawnFlags.CHILD_INHERITS_STDOUT explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdoutPipeOut argument is ignored.

      SpawnFlags.STDERR_TO_DEV_NULL means that the child's standard error will be discarded (by default, it goes to the same location as the parent's standard error). SpawnFlags.CHILD_INHERITS_STDERR explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stderrPipeOut argument is ignored.

      It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both stdoutFd and stderrFd, and include it in sourceFds too).

      sourceFds and targetFds allow zero or more FDs from this process to be remapped to different FDs in the spawned process. If nFds is greater than zero, sourceFds and targetFds must both be non-null and the same length. Each FD in sourceFds is remapped to the FD number at the same index in targetFds. The source and target FD may be equal to simply propagate an FD to the spawned process. FD remappings are processed after standard FDs, so any target FDs which equal stdinFd, stdoutFd or stderrFd will overwrite them in the spawned process.

      sourceFds is supported on Windows since 2.72.

      SpawnFlags.FILE_AND_ARGV_ZERO means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to execute, and passes all of argv to the child.

      childSetup and userData are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, childSetup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent.

      On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). There is no sensible thing childSetup could be used for on Windows so it is ignored and not called.

      If non-null, childPid will on Unix be filled with the child's process ID. You can use the process ID to send signals to the child, or to use g_child_watch_add() (or waitpid()) if you specified the SpawnFlags.DO_NOT_REAP_CHILD flag. On Windows, childPid will be filled with a handle to the child process only if you specified the SpawnFlags.DO_NOT_REAP_CHILD flag. You can then access the child process using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). You should close the handle with CloseHandle() or g_spawn_close_pid() when you no longer need it.

      If non-null, the stdinPipeOut, stdoutPipeOut, stderrPipeOut locations will be filled with file descriptors for writing to the child's standard input or reading from its standard output or standard error. The caller of g_spawn_async_with_pipes() must close these file descriptors when they are no longer in use. If these parameters are null, the corresponding pipe won't be created.

      If stdinPipeOut is null, the child's standard input is attached to /dev/null unless SpawnFlags.CHILD_INHERITS_STDIN is set.

      If stderrPipeOut is NULL, the child's standard error goes to the same location as the parent's standard error unless SpawnFlags.STDERR_TO_DEV_NULL is set.

      If stdoutPipeOut is NULL, the child's standard output goes to the same location as the parent's standard output unless SpawnFlags.STDOUT_TO_DEV_NULL is set.

      error can be null to ignore errors, or non-null to report errors. If an error is set, the function returns false. Errors are reported even if they occur in the child (for example if the executable in @argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

      If an error occurs, childPid, stdinPipeOut, stdoutPipeOut, and stderrPipeOut will not be filled with valid values.

      If childPid is not null and an error does not occur then the returned process reference must be closed using g_spawn_close_pid().

      On modern UNIX platforms, GLib can use an efficient process launching codepath driven internally by posix_spawn(). This has the advantage of avoiding the fork-time performance costs of cloning the parent process address space, and avoiding associated memory overcommit checks that are not relevant in the context of immediately executing a distinct process. This optimized codepath will be used provided that the following conditions are met:

      1. SpawnFlags.DO_NOT_REAP_CHILD is set
      2. SpawnFlags.LEAVE_DESCRIPTORS_OPEN is set
      3. SpawnFlags.SEARCH_PATH_FROM_ENVP is not set
      4. workingDirectory is null
      5. childSetup is null
      6. The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.

      If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use GdkAppLaunchContext, GAppLaunchContext, or set the DISPLAY environment variable.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's, in the GLib file name encoding
      argv - child's argument vector, in the GLib file name encoding; it must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's, in the GLib file name encoding
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      stdinFd - file descriptor to use for child's stdin, or -1
      stdoutFd - file descriptor to use for child's stdout, or -1
      stderrFd - file descriptor to use for child's stderr, or -1
      sourceFds - array of FDs from the parent process to make available in the child process
      targetFds - array of FDs to remap sourceFds to in the child process
      childPidOut - return location for child process ID, or null
      stdinPipeOut - return location for file descriptor to write to child's stdin, or null
      stdoutPipeOut - return location for file descriptor to read child's stdout, or null
      stderrPipeOut - return location for file descriptor to read child's stderr, or null
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
      Since:
      2.68
    • spawnAsyncWithPipesAndFds

      public static boolean spawnAsyncWithPipesAndFds(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, int stdinFd, int stdoutFd, int stderrFd, @Nullable int @Nullable [] sourceFds, @Nullable int @Nullable [] targetFds, @Nullable Pid childPidOut, @Nullable Out<Integer> stdinPipeOut, @Nullable Out<Integer> stdoutPipeOut, @Nullable Out<Integer> stderrPipeOut) throws GErrorException

      Executes a child program asynchronously (your program will not block waiting for the child to exit).

      The child program is specified by the only argument that must be provided, argv. argv should be a null-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path. If flags contains the SpawnFlags.SEARCH_PATH flag, the PATH environment variable is used to search for the executable. If flags contains the SpawnFlags.SEARCH_PATH_FROM_ENVP flag, the PATH variable from envp is used to search for the executable. If both the SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP flags are set, the PATH variable from envp takes precedence over the environment variable.

      If the program name is not a full path and SpawnFlags.SEARCH_PATH flag is not used, then the program will be run from the current directory (or workingDirectory, if specified); this might be unexpected or even dangerous in some cases when the current directory is world-writable.

      On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in these arguments will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft's tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

      At least currently, mingw doesn't support wmain(), so if you use mingw to develop the spawned program, it should call g_win32_get_command_line() to get arguments in UTF-8.

      On Windows the low-level child process creation API CreateProcess() doesn't use argument vectors, but a command line. The C runtime library's spawn*() family of functions (which g_spawn_async_with_pipes() eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when you have argument vector elements that contain spaces or double quotes. The spawn*() functions don't do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

      The returned childPid on Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.

      envp is a null-terminated array of strings, where each string has the form KEY=VALUE. This will become the child's environment. If envp is null, the child inherits its parent's environment.

      flags should be the bitwise OR of any flags you want to affect the function's behaviour. The SpawnFlags.DO_NOT_REAP_CHILD means that the child will not automatically be reaped; you must use a child watch (g_child_watch_add()) to be notified about the death of the child process, otherwise it will stay around as a zombie process until this process exits. Eventually you must call g_spawn_close_pid() on the childPid, in order to free resources which may be associated with the child process. (On Unix, using a child watch is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling g_spawn_close_pid() is equivalent to calling CloseHandle() on the process handle returned in childPid). See g_child_watch_add().

      Open UNIX file descriptors marked as FD_CLOEXEC will be automatically closed in the child process. SpawnFlags.LEAVE_DESCRIPTORS_OPEN means that other open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. SpawnFlags.SEARCH_PATH means that argv[0] need not be an absolute path, it will be looked for in the PATH environment variable. SpawnFlags.SEARCH_PATH_FROM_ENVP means need not be an absolute path, it will be looked for in the PATH variable from envp. If both SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP are used, the value from envp takes precedence over the environment.

      SpawnFlags.CHILD_INHERITS_STDIN means that the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null). SpawnFlags.STDIN_FROM_DEV_NULL explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdinPipeOut argument is ignored.

      SpawnFlags.STDOUT_TO_DEV_NULL means that the child's standard output will be discarded (by default, it goes to the same location as the parent's standard output). SpawnFlags.CHILD_INHERITS_STDOUT explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdoutPipeOut argument is ignored.

      SpawnFlags.STDERR_TO_DEV_NULL means that the child's standard error will be discarded (by default, it goes to the same location as the parent's standard error). SpawnFlags.CHILD_INHERITS_STDERR explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stderrPipeOut argument is ignored.

      It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both stdoutFd and stderrFd, and include it in sourceFds too).

      sourceFds and targetFds allow zero or more FDs from this process to be remapped to different FDs in the spawned process. If nFds is greater than zero, sourceFds and targetFds must both be non-null and the same length. Each FD in sourceFds is remapped to the FD number at the same index in targetFds. The source and target FD may be equal to simply propagate an FD to the spawned process. FD remappings are processed after standard FDs, so any target FDs which equal stdinFd, stdoutFd or stderrFd will overwrite them in the spawned process.

      sourceFds is supported on Windows since 2.72.

      SpawnFlags.FILE_AND_ARGV_ZERO means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to execute, and passes all of argv to the child.

      childSetup and userData are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, childSetup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent.

      On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). There is no sensible thing childSetup could be used for on Windows so it is ignored and not called.

      If non-null, childPid will on Unix be filled with the child's process ID. You can use the process ID to send signals to the child, or to use g_child_watch_add() (or waitpid()) if you specified the SpawnFlags.DO_NOT_REAP_CHILD flag. On Windows, childPid will be filled with a handle to the child process only if you specified the SpawnFlags.DO_NOT_REAP_CHILD flag. You can then access the child process using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). You should close the handle with CloseHandle() or g_spawn_close_pid() when you no longer need it.

      If non-null, the stdinPipeOut, stdoutPipeOut, stderrPipeOut locations will be filled with file descriptors for writing to the child's standard input or reading from its standard output or standard error. The caller of g_spawn_async_with_pipes() must close these file descriptors when they are no longer in use. If these parameters are null, the corresponding pipe won't be created.

      If stdinPipeOut is null, the child's standard input is attached to /dev/null unless SpawnFlags.CHILD_INHERITS_STDIN is set.

      If stderrPipeOut is NULL, the child's standard error goes to the same location as the parent's standard error unless SpawnFlags.STDERR_TO_DEV_NULL is set.

      If stdoutPipeOut is NULL, the child's standard output goes to the same location as the parent's standard output unless SpawnFlags.STDOUT_TO_DEV_NULL is set.

      error can be null to ignore errors, or non-null to report errors. If an error is set, the function returns false. Errors are reported even if they occur in the child (for example if the executable in @argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

      If an error occurs, childPid, stdinPipeOut, stdoutPipeOut, and stderrPipeOut will not be filled with valid values.

      If childPid is not null and an error does not occur then the returned process reference must be closed using g_spawn_close_pid().

      On modern UNIX platforms, GLib can use an efficient process launching codepath driven internally by posix_spawn(). This has the advantage of avoiding the fork-time performance costs of cloning the parent process address space, and avoiding associated memory overcommit checks that are not relevant in the context of immediately executing a distinct process. This optimized codepath will be used provided that the following conditions are met:

      1. SpawnFlags.DO_NOT_REAP_CHILD is set
      2. SpawnFlags.LEAVE_DESCRIPTORS_OPEN is set
      3. SpawnFlags.SEARCH_PATH_FROM_ENVP is not set
      4. workingDirectory is null
      5. childSetup is null
      6. The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.

      If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use GdkAppLaunchContext, GAppLaunchContext, or set the DISPLAY environment variable.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's, in the GLib file name encoding
      argv - child's argument vector, in the GLib file name encoding; it must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's, in the GLib file name encoding
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      stdinFd - file descriptor to use for child's stdin, or -1
      stdoutFd - file descriptor to use for child's stdout, or -1
      stderrFd - file descriptor to use for child's stderr, or -1
      sourceFds - array of FDs from the parent process to make available in the child process
      targetFds - array of FDs to remap sourceFds to in the child process
      childPidOut - return location for child process ID, or null
      stdinPipeOut - return location for file descriptor to write to child's stdin, or null
      stdoutPipeOut - return location for file descriptor to read child's stdout, or null
      stderrPipeOut - return location for file descriptor to read child's stderr, or null
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
      Since:
      2.68
    • spawnCheckExitStatus

      @Deprecated public static boolean spawnCheckExitStatus(int waitStatus) throws GErrorException
      Deprecated.
      Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.

      An old name for g_spawn_check_wait_status(), deprecated because its name is misleading.

      Despite the name of the function, waitStatus must be the wait status as returned by g_spawn_sync(), g_subprocess_get_status(), waitpid(), etc. On Unix platforms, it is incorrect for it to be the exit status as passed to exit() or returned by g_subprocess_get_exit_status() or WEXITSTATUS().

      Parameters:
      waitStatus - A status as returned from g_spawn_sync()
      Returns:
      true if child exited successfully, false otherwise (and error will be set)
      Throws:
      GErrorException - see GError
      Since:
      2.34
    • spawnCheckWaitStatus

      public static boolean spawnCheckWaitStatus(int waitStatus) throws GErrorException

      Set error if waitStatus indicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal).

      The g_spawn_sync() and g_child_watch_add() family of APIs return the status of subprocesses encoded in a platform-specific way. On Unix, this is guaranteed to be in the same format waitpid() returns, and on Windows it is guaranteed to be the result of GetExitCodeProcess().

      Prior to the introduction of this function in GLib 2.34, interpreting waitStatus required use of platform-specific APIs, which is problematic for software using GLib as a cross-platform layer.

      Additionally, many programs simply want to determine whether or not the child exited successfully, and either propagate a GError or print a message to standard error. In that common case, this function can be used. Note that the error message in error will contain human-readable information about the wait status.

      The domain and code of error have special semantics in the case where the process has an "exit code", as opposed to being killed by a signal. On Unix, this happens if WIFEXITED() would be true of waitStatus. On Windows, it is always the case.

      The special semantics are that the actual exit code will be the code set in error, and the domain will be G_SPAWN_EXIT_ERROR. This allows you to differentiate between different exit codes.

      If the process was terminated by some means other than an exit status (for example if it was killed by a signal), the domain will be G_SPAWN_ERROR and the code will be SpawnError.FAILED.

      This function just offers convenience; you can of course also check the available platform via a macro such as G_OS_UNIX, and use WIFEXITED() and WEXITSTATUS() on waitStatus directly. Do not attempt to scan or parse the error message string; it may be translated and/or change in future versions of GLib.

      Prior to version 2.70, g_spawn_check_exit_status() provides the same functionality, although under a misleading name.

      Parameters:
      waitStatus - A platform-specific wait status as returned from g_spawn_sync()
      Returns:
      true if child exited successfully, false otherwise (and error will be set)
      Throws:
      GErrorException - see GError
      Since:
      2.70
    • spawnClosePid

      public static void spawnClosePid(Pid pid)
      On some platforms, notably Windows, the GPid type represents a resource which must be closed to prevent resource leaking. g_spawn_close_pid() is provided for this purpose. It should be used on all platforms, even though it doesn't do anything under UNIX.
      Parameters:
      pid - The process reference to close
    • spawnCommandLineAsync

      public static boolean spawnCommandLineAsync(String commandLine) throws GErrorException

      A simple version of g_spawn_async() that parses a command line with g_shell_parse_argv() and passes it to g_spawn_async().

      Runs a command line in the background. Unlike g_spawn_async(), the SpawnFlags.SEARCH_PATH flag is enabled, other flags are not. Note that SpawnFlags.SEARCH_PATH can have security implications, so consider using g_spawn_async() directly if appropriate. Possible errors are those from g_shell_parse_argv() and g_spawn_async().

      The same concerns on Windows apply as for g_spawn_command_line_sync().

      Parameters:
      commandLine - a command line
      Returns:
      true on success, false if error is set
      Throws:
      GErrorException - see GError
    • spawnCommandLineSync

      public static boolean spawnCommandLineSync(String commandLine, @Nullable Out<byte[]> standardOutput, @Nullable Out<byte[]> standardError, @Nullable Out<Integer> waitStatus) throws GErrorException

      A simple version of g_spawn_sync() with little-used parameters removed, taking a command line instead of an argument vector.

      See g_spawn_sync() for full details.

      The commandLine argument will be parsed by g_shell_parse_argv().

      Unlike g_spawn_sync(), the SpawnFlags.SEARCH_PATH flag is enabled. Note that SpawnFlags.SEARCH_PATH can have security implications, so consider using g_spawn_sync() directly if appropriate.

      Possible errors are those from g_spawn_sync() and those from g_shell_parse_argv().

      If waitStatus is non-null, the platform-specific status of the child is stored there; see the documentation of g_spawn_check_wait_status() for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

      On Windows, please note the implications of g_shell_parse_argv() parsing commandLine. Parsing is done according to Unix shell rules, not Windows command interpreter rules. Space is a separator, and backslashes are special. Thus you cannot simply pass a commandLine containing canonical Windows paths, like "c:\\program files\\app\\app.exe", as the backslashes will be eaten, and the space will act as a separator. You need to enclose such paths with single quotes, like "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".

      Parameters:
      commandLine - a command line
      standardOutput - return location for child output
      standardError - return location for child errors
      waitStatus - return location for child wait status, as returned by waitpid()
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
    • spawnErrorQuark

      public static Quark spawnErrorQuark()
    • spawnExitErrorQuark

      public static Quark spawnExitErrorQuark()
    • spawnSync

      public static boolean spawnSync(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Out<byte[]> standardOutput, @Nullable Out<byte[]> standardError, @Nullable Out<Integer> waitStatus) throws GErrorException

      Executes a child synchronously (waits for the child to exit before returning).

      All output from the child is stored in standardOutput and standardError, if those parameters are non-null. Note that you must set the SpawnFlags.STDOUT_TO_DEV_NULL and SpawnFlags.STDERR_TO_DEV_NULL flags when passing null for standardOutput and standardError.

      If waitStatus is non-null, the platform-specific status of the child is stored there; see the documentation of g_spawn_check_wait_status() for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

      Note that it is invalid to pass SpawnFlags.DO_NOT_REAP_CHILD in flags, and on POSIX platforms, the same restrictions as for g_child_watch_source_new() apply.

      If an error occurs, no data is returned in standardOutput, standardError, or waitStatus.

      This function calls g_spawn_async_with_pipes() internally; see that function for full details on the other parameters and details on how these functions work on Windows.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's
      argv - child's argument vector, which must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      standardOutput - return location for child output, or null
      standardError - return location for child error messages, or null
      waitStatus - return location for child wait status, as returned by waitpid(), or null
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
    • spawnSync

      public static boolean spawnSync(@Nullable String workingDirectory, @Nullable String @Nullable [] argv, @Nullable String @Nullable [] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Out<byte[]> standardOutput, @Nullable Out<byte[]> standardError, @Nullable Out<Integer> waitStatus) throws GErrorException

      Executes a child synchronously (waits for the child to exit before returning).

      All output from the child is stored in standardOutput and standardError, if those parameters are non-null. Note that you must set the SpawnFlags.STDOUT_TO_DEV_NULL and SpawnFlags.STDERR_TO_DEV_NULL flags when passing null for standardOutput and standardError.

      If waitStatus is non-null, the platform-specific status of the child is stored there; see the documentation of g_spawn_check_wait_status() for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

      Note that it is invalid to pass SpawnFlags.DO_NOT_REAP_CHILD in flags, and on POSIX platforms, the same restrictions as for g_child_watch_source_new() apply.

      If an error occurs, no data is returned in standardOutput, standardError, or waitStatus.

      This function calls g_spawn_async_with_pipes() internally; see that function for full details on the other parameters and details on how these functions work on Windows.

      Parameters:
      workingDirectory - child's current working directory, or null to inherit parent's
      argv - child's argument vector, which must be non-empty and null-terminated
      envp - child's environment, or null to inherit parent's
      flags - flags from GSpawnFlags
      childSetup - function to run in the child just before exec()
      standardOutput - return location for child output, or null
      standardError - return location for child error messages, or null
      waitStatus - return location for child wait status, as returned by waitpid(), or null
      Returns:
      true on success, false if an error was set
      Throws:
      GErrorException - see GError
    • sprintf

      public static int sprintf(String string, String format, Object... varargs)

      An implementation of the standard sprintf() function which supports positional parameters, as specified in the Single Unix Specification.

      Note that it is usually better to use snprintf(String, int, String, Object...), to avoid the risk of buffer overflow.

      glib/gprintf.h must be explicitly included in order to use this function.

      See also strdupPrintf(String, Object...).

      Parameters:
      string - A pointer to a memory buffer to contain the resulting string. It is up to the caller to ensure that the allocated buffer is large enough to hold the formatted result.
      format - a standard printf() format string, but notice string precision pitfalls
      varargs - the arguments to insert in the output
      Returns:
      the number of bytes printed
      Since:
      2.2
    • stat

      public static int stat(String filename, StatBuf buf)

      A wrapper for the POSIX stat() function. The stat() function returns information about a file. On Windows the stat() function in the C library checks only the FAT-style READONLY attribute and does not look at the ACL at all. Thus on Windows the protection bits in the stMode field are a fabrication of little use.

      On Windows the Microsoft C libraries have several variants of the stat struct and stat() function with names like _stat(), _stat32(), _stat32i64() and _stat64i32(). The one used here is for 32-bit code the one with 32-bit size and time fields, specifically called _stat32().

      In Microsoft's compiler, by default struct stat means one with 64-bit time fields while in MinGW struct stat is the legacy one with 32-bit fields. To hopefully clear up this messs, the gstdio.h header defines a type GStatBuf which is the appropriate struct type depending on the platform and/or compiler being used. On POSIX it is just struct stat, but note that even on POSIX platforms, stat() might be a macro.

      See your C library manual for more details about stat().

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      buf - a pointer to a stat struct, which will be filled with the file information
      Returns:
      0 if the information was successfully retrieved, -1 if an error occurred
      Since:
      2.6
    • stpcpy

      public static String stpcpy(String dest, String src)
      Copies a nul-terminated string into the destination buffer, including the trailing nul byte, and returns a pointer to the trailing nul byte in dest. The return value is useful for concatenating multiple strings without having to repeatedly scan for the end.
      Parameters:
      dest - destination buffer
      src - source string
      Returns:
      a pointer to the trailing nul byte in dest
    • strEqual

      public static boolean strEqual(MemorySegment v1, MemorySegment v2)

      Compares two strings for byte-by-byte equality and returns true if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-null strings as keys in a GHashTable.

      This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-null strings. For a null-safe string comparison function, see g_strcmp0().

      Parameters:
      v1 - a key
      v2 - a key to compare with v1
      Returns:
      true if the two keys match
    • strHasPrefix

      public static boolean strHasPrefix(String str, String prefix)
      Looks whether the string str begins with prefix.
      Parameters:
      str - a string to look in
      prefix - the prefix to look for
      Returns:
      true if str begins with prefix, false otherwise
      Since:
      2.2
    • strHasSuffix

      public static boolean strHasSuffix(String str, String suffix)
      Looks whether a string ends with suffix.
      Parameters:
      str - a string to look in
      suffix - the suffix to look for
      Returns:
      true if str ends with suffix, false otherwise
      Since:
      2.2
    • strHash

      public static int strHash(MemorySegment v)

      Converts a string to a hash value.

      This function implements the widely used "djb" hash apparently posted by Daniel Bernstein to comp.lang.c some time ago. The 32 bit unsigned hash value starts at 5381 and for each byte 'c' in the string, is updated: hash = hash * 33 + c. This function uses the signed value of each byte.

      It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-null strings as keys in a GHashTable.

      Note that this function may not be a perfect fit for all use cases. For example, it produces some hash collisions with strings as short as 2.

      Parameters:
      v - a string key
      Returns:
      a hash value corresponding to the key
    • strIsAscii

      public static boolean strIsAscii(String str)
      Determines if a string is pure ASCII. A string is pure ASCII if it contains no bytes with the high bit set.
      Parameters:
      str - a string
      Returns:
      true if str is ASCII
      Since:
      2.40
    • strMatchString

      public static boolean strMatchString(String searchTerm, String potentialHit, boolean acceptAlternates)

      Checks if a search conducted for searchTerm should match potentialHit.

      This function calls strTokenizeAndFold(String, String, Out) on both searchTerm and potentialHit. ASCII alternates are never taken for searchTerm but will be taken for potentialHit according to the value of acceptAlternates.

      A hit occurs when each folded token in searchTerm is a prefix of a folded token from potentialHit.

      Depending on how you're performing the search, it will typically be faster to call g_str_tokenize_and_fold() on each string in your corpus and build an index on the returned folded tokens, then call g_str_tokenize_and_fold() on the search term and perform lookups into that index.

      As some examples, searching for ‘fred’ would match the potential hit ‘Smith, Fred’ and also ‘Frédéric’. Searching for ‘Fréd’ would match ‘Frédéric’ but not ‘Frederic’ (due to the one-directional nature of accent matching). Searching ‘fo’ would match ‘Foo’ and ‘Bar Foo Baz’, but not ‘SFO’ (because no word has ‘fo’ as a prefix).

      Parameters:
      searchTerm - the search term from the user
      potentialHit - the text that may be a hit
      acceptAlternates - if true, ASCII alternates are accepted
      Returns:
      true if potentialHit is a hit
      Since:
      2.40
    • strToAscii

      public static String strToAscii(String str, @Nullable String fromLocale)

      Transliterate str to plain ASCII.

      For best results, str should be in composed normalised form.

      This function performs a reasonably good set of character replacements. The particular set of replacements that is done may change by version or even by runtime environment.

      If the source language of str is known, it can used to improve the accuracy of the translation by passing it as fromLocale. It should be a valid POSIX locale string (of the form language[_territory][.codeset][@modifier]).

      If fromLocale is null then the current locale is used.

      If you want to do translation for no specific locale, and you want it to be done independently of the currently locale, specify "C" for fromLocale.

      Parameters:
      str - a string, in UTF-8
      fromLocale - the source locale, if known
      Returns:
      a string in plain ASCII
      Since:
      2.40
    • strTokenizeAndFold

      public static String[] strTokenizeAndFold(String string, @Nullable String translitLocale, @Nullable Out<String[]> asciiAlternates)

      Tokenizes string and performs folding on each token.

      A token is a non-empty sequence of alphanumeric characters in the source string, separated by non-alphanumeric characters. An "alphanumeric" character for this purpose is one that matches unicharIsalnum(int) or unicharIsmark(int).

      Each token is then (Unicode) normalised and case-folded. If asciiAlternates is non-NULL and some of the returned tokens contain non-ASCII characters, ASCII alternatives will be generated.

      The number of ASCII alternatives that are generated and the method for doing so is unspecified, but translitLocale (if specified) may improve the transliteration if the language of the source string is known.

      Parameters:
      string - a string to tokenize
      translitLocale - the language code (like 'de' or 'en_GB') from which string originates
      asciiAlternates - a return location for ASCII alternates
      Returns:
      the folded tokens
      Since:
      2.40
    • strcanon

      public static String strcanon(String string, String validChars, byte substitutor)

      For each character in string, if the character is not in validChars, replaces the character with substitutor.

      Modifies string in place, and return string itself, not a copy. The return value is to allow nesting such as:

      g_ascii_strup (g_strcanon (str, "abc", '?'))
      

      In order to modify a copy, you may use strdup(String):

      reformatted = g_strcanon (g_strdup (const_str), "abc", '?');
      …
      g_free (reformatted);
      
      Parameters:
      string - a nul-terminated array of bytes
      validChars - bytes permitted in string
      substitutor - replacement character for disallowed bytes
      Returns:
      the modified string
    • strcasecmp

      @Deprecated public static int strcasecmp(String s1, String s2)
      Deprecated.
      See strncasecmp(String, String, int) for a discussion of why this function is deprecated and how to replace it.
      A case-insensitive string comparison, corresponding to the standard strcasecmp() function on platforms which support it.
      Parameters:
      s1 - string to compare with s2
      s2 - string to compare with s1
      Returns:
      0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2
    • strchomp

      public static String strchomp(String string)

      Removes trailing whitespace from a string.

      This function doesn't allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

      The pointer to string is returned to allow the nesting of functions.

      Also see strchug(String) and GLib.strstrip.

      Parameters:
      string - a string to remove the trailing whitespace from
      Returns:
      the modified string
    • strchug

      public static String strchug(String string)

      Removes leading whitespace from a string, by moving the rest of the characters forward.

      This function doesn't allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

      The pointer to string is returned to allow the nesting of functions.

      Also see strchomp(String) and GLib.strstrip.

      Parameters:
      string - a string to remove the leading whitespace from
      Returns:
      the modified string
    • strcmp0

      public static int strcmp0(@Nullable String str1, @Nullable String str2)

      Compares str1 and str2 like strcmp().

      Handles NULL gracefully by sorting it before non-NULL strings. Comparing two NULL pointers returns 0.

      Parameters:
      str1 - a string
      str2 - another string
      Returns:
      an integer less than, equal to, or greater than zero, if str1 is <, == or > than str2
      Since:
      2.16
    • strcompress

      public static String strcompress(String source)

      Makes a copy of a string replacing C string-style escape sequences with their one byte equivalent:

      strescape(String, String) does the reverse conversion.

      Parameters:
      source - a string to compress
      Returns:
      a newly-allocated copy of source with all escaped character compressed
    • strconcat

      public static String strconcat(String string1, Object... varargs)

      Concatenates all of the given strings into one long string.

      The variable argument list must end with NULL. If you forget the NULL, g_strconcat() will start appending random memory junk to your string.

      Note that this function is usually not the right function to use to assemble a translated message from pieces, since proper translation often requires the pieces to be reordered.

      Parameters:
      string1 - the first string to add, which must not be NULL
      varargs - a NULL-terminated list of strings to append to the string
      Returns:
      a newly-allocated string containing all the string arguments
    • strdelimit

      public static String strdelimit(String string, @Nullable String delimiters, byte newDelimiter)

      Converts any delimiter characters in string to newDelimiter.

      Any characters in string which are found in delimiters are changed to the newDelimiter character. Modifies string in place, and returns string itself, not a copy.

      The return value is to allow nesting such as:

      g_ascii_strup (g_strdelimit (str, "abc", '?'))
      

      In order to modify a copy, you may use strdup(String):

      reformatted = g_strdelimit (g_strdup (const_str), "abc", '?');
      …
      g_free (reformatted);
      
      Parameters:
      string - the string to convert
      delimiters - a string containing the current delimiters, or NULL to use the standard delimiters defined in GLib.STR_DELIMITERS
      newDelimiter - the new delimiter character
      Returns:
      the modified string
    • strdown

      @Deprecated public static String strdown(String string)
      Deprecated.
      This function is totally broken for the reasons discussed in the strncasecmp(String, String, int) docs — use asciiStrdown(String, long) or utf8Strdown(String, long) instead.
      Converts a string to lower case.
      Parameters:
      string - the string to convert
      Returns:
      the string
    • strdup

      public static String strdup(@Nullable String str)
      Duplicates a string. If str is NULL it returns NULL.
      Parameters:
      str - the string to duplicate
      Returns:
      a newly-allocated copy of str
    • strdupPrintf

      public static @Nullable String strdupPrintf(String format, Object... varargs)

      Similar to the standard C sprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result.

      The returned string is guaranteed to be non-NULL, unless format contains %lc or %ls conversions, which can fail if no multibyte representation is available for the given character.

      Parameters:
      format - a standard printf() format string, but notice string precision pitfalls
      varargs - the parameters to insert into the format string
      Returns:
      a newly-allocated string holding the result
    • strdupv

      public static @Nullable String @Nullable [] strdupv(@Nullable String @Nullable [] strArray)

      Copies an array of strings. The copy is a deep copy; each string is also copied.

      If called on a NULL value, g_strdupv() simply returns NULL.

      Parameters:
      strArray - an array of strings to copy
      Returns:
      a newly-allocated array of strings. Use strfreev(MemorySegment) to free it.
    • strerror

      public static String strerror(int errnum)

      Returns a string corresponding to the given error code, e.g. "no such process".

      Unlike strerror(), this always returns a string in UTF-8 encoding, and the pointer is guaranteed to remain valid for the lifetime of the process. If the error code is unknown, it returns a string like “Unknown error <code\>”.

      Note that the string may be translated according to the current locale.

      The value of errno will not be changed by this function. However, it may be changed by intermediate function calls, so you should save its value as soon as the call returns:

      int saved_errno;
      
      ret = read (blah);
      saved_errno = errno;
      
      g_strerror (saved_errno);
      
      Parameters:
      errnum - the system error number. See the standard C errno documentation
      Returns:
      the string describing the error code
    • strescape

      public static String strescape(String source, @Nullable String exceptions)

      It replaces the following special characters in the string source with their corresponding C escape sequence:

      Symbol Escape
      U+0008 Backspace \\b
      U+000C Form Feed \\f
      U+000A Line Feed \\n
      U+000D Carriage Return \\r
      U+0009 Horizontal Tabulation \\t
      U+000B Vertical Tabulation \\v

      It also inserts a backslash (\\) before any backslash or a double quote ("). Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a backslash followed by their octal representation. Characters supplied in exceptions are not escaped.

      strcompress(String) does the reverse conversion.

      Parameters:
      source - a string to escape
      exceptions - a string of characters not to escape in source
      Returns:
      a newly-allocated copy of source with special characters escaped
    • strfreev

      public static void strfreev(@Nullable MemorySegment strArray)

      Frees an array of strings, as well as each string it contains.

      If strArray is NULL, this function simply returns.

      Parameters:
      strArray - an array of strings to free
    • stripContext

      public static String stripContext(String msgid, String msgval)
      An auxiliary function for gettext() support (see Q_()).
      Parameters:
      msgid - a string
      msgval - another string
      Returns:
      msgval, unless msgval is identical to msgid and contains a '|' character, in which case a pointer to the substring of msgid after the first '|' character is returned.
      Since:
      2.4
    • strjoin

      public static String strjoin(@Nullable String separator, Object... varargs)
      Joins a number of strings together to form one long string, with the optional separator inserted between each of them.
      Parameters:
      separator - a string to insert between each of the strings
      varargs - a NULL-terminated list of strings to join
      Returns:
      a newly-allocated string containing all of the strings joined together, with separator between them
    • strjoinv

      public static String strjoinv(@Nullable String separator, @Nullable String @Nullable [] strArray)

      Joins an array of strings together to form one long string, with the optional separator inserted between each of them.

      If strArray has no items, the return value will be an empty string. If strArray contains a single item, separator will not appear in the resulting string.

      Parameters:
      separator - a string to insert between each of the strings
      strArray - an array of strings to join
      Returns:
      a newly-allocated string containing all of the strings joined together, with separator between them
    • strlcat

      public static long strlcat(String dest, String src, long destSize)

      Portability wrapper that calls strlcat() on systems which have it, and emulates it otherwise. Appends nul-terminated src string to dest, guaranteeing nul-termination for dest. The total size of dest won't exceed destSize.

      At most destSize - 1 characters will be copied. Unlike strncat(), destSize is the full size of dest, not the space left over. This function does not allocate memory. It always nul-terminates (unless destSize == 0 or there were no nul characters in the destSize characters of dest to start with).

      Caveat: this is supposedly a more secure alternative to strcat() or strncat(), but for real security strconcat(String, Object...) is harder to mess up.

      Parameters:
      dest - destination buffer, already containing one nul-terminated string
      src - source buffer
      destSize - length of dest buffer in bytes (not length of existing string inside dest)
      Returns:
      size of attempted result, which is MIN (dest_size, strlen (original dest)) + strlen (src), so if retval >= destSize, truncation occurred
    • strlcpy

      public static long strlcpy(String dest, String src, long destSize)

      Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise. Copies src to dest; dest is guaranteed to be nul-terminated; src must be nul-terminated; destSize is the buffer size, not the number of bytes to copy.

      At most destSize - 1 characters will be copied. Always nul-terminates (unless destSize is 0). This function does not allocate memory. Unlike strncpy(), this function doesn't pad dest (so it's often faster). It returns the size of the attempted result, strlen (src), so if retval >= destSize, truncation occurred.

      Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(), but if you really want to avoid screwups, strdup(String) is an even better idea.

      Parameters:
      dest - destination buffer
      src - source buffer
      destSize - length of dest in bytes
      Returns:
      length of src
    • strncasecmp

      @Deprecated public static int strncasecmp(String s1, String s2, int n)
      Deprecated.

      The problem with g_strncasecmp() is that it does the comparison by calling toupper()/tolower(). These functions are locale-specific and operate on single bytes. However, it is impossible to handle things correctly from an internationalization standpoint by operating on bytes, since characters may be multibyte. Thus g_strncasecmp() is broken if your string is guaranteed to be ASCII, since it is locale-sensitive, and it's broken if your string is localized, since it doesn't work on many encodings at all, including UTF-8, EUC-JP, etc.

      There are therefore two replacement techniques: asciiStrncasecmp(String, String, long), which only works on ASCII and is not locale-sensitive, and utf8Casefold(String, long) followed by strcmp() on the resulting strings, which is good for case-insensitive sorting of UTF-8.

      A case-insensitive string comparison, corresponding to the standard strncasecmp() function on platforms which support it. It is similar to strcasecmp(String, String) except it only compares the first n characters of the strings.
      Parameters:
      s1 - string to compare with s2
      s2 - string to compare with s1
      n - the maximum number of characters to compare
      Returns:
      0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2
    • strndup

      public static @Nullable String strndup(@Nullable String str, long n)

      Duplicates the first n bytes of a string, returning a newly-allocated buffer n + 1 bytes long which will always be nul-terminated. If str is less than n bytes long the buffer is padded with nuls. If str is NULL it returns NULL.

      To copy a number of characters from a UTF-8 encoded string, use utf8Strncpy(String, String, long) instead.

      Parameters:
      str - the string to duplicate
      n - the maximum number of bytes to copy from str
      Returns:
      a newly-allocated buffer containing the first n bytes of str
    • strnfill

      public static String strnfill(long length, byte fillChar)
      Creates a new string length bytes long filled with fillChar.
      Parameters:
      length - the length of the new string
      fillChar - the byte to fill the string with
      Returns:
      a newly-allocated string filled with fillChar
    • strreverse

      public static String strreverse(String string)

      Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".

      Note that g_strreverse() doesn't work on UTF-8 strings containing multibyte characters. For that purpose, use utf8Strreverse(String, long).

      Parameters:
      string - the string to reverse
      Returns:
      the string, reversed in place
    • strrstr

      public static @Nullable String strrstr(String haystack, String needle)

      Searches the string haystack for the last occurrence of the string needle.

      The fact that this function returns gchar * rather than const gchar * is a historical artifact.

      Parameters:
      haystack - a string to search in
      needle - the string to search for
      Returns:
      a pointer to the found occurrence, or NULL if not found
    • strrstrLen

      public static @Nullable String strrstrLen(String haystack, long haystackLen, String needle)

      Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystackLen.

      The fact that this function returns gchar * rather than const gchar * is a historical artifact.

      Parameters:
      haystack - a string to search in
      haystackLen - the maximum length of haystack in bytes. A length of -1 can be used to mean "search the entire string", like strrstr(String, String)
      needle - the string to search for
      Returns:
      a pointer to the found occurrence, or NULL if not found
    • strsignal

      public static String strsignal(int signum)

      Returns a string describing the given signal, e.g. "Segmentation fault". If the signal is unknown, it returns “unknown signal (<signum\>)”.

      You should use this function in preference to strsignal(), because it returns a string in UTF-8 encoding, and since not all platforms support the strsignal() function.

      Parameters:
      signum - the signal number. See the signal documentation
      Returns:
      the string describing the signal
    • strsplit

      public static String[] strsplit(String string, String delimiter, int maxTokens)

      Splits a string into a maximum of maxTokens pieces, using the given delimiter. If maxTokens is reached, the remainder of string is appended to the last token.

      As an example, the result of g_strsplit (":a:bc::d:", ":", -1) is an array containing the six strings "", "a", "bc", "", "d" and "".

      As a special case, the result of splitting the empty string "" is an empty array, not an array containing a single string. The reason for this special case is that being able to represent an empty array is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you'll need to check for the empty string before calling g_strsplit().

      Parameters:
      string - a string to split
      delimiter - a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unless maxTokens is reached.
      maxTokens - the maximum number of pieces to split string into If this is less than 1, the string is split completely
      Returns:
      a newly-allocated array of strings, freed with strfreev(MemorySegment)
    • strsplitSet

      public static String[] strsplitSet(String string, @Nullable byte @Nullable [] delimiters, int maxTokens)

      Splits string into a number of tokens not containing any of the bytes in delimiters.

      A token is the (possibly empty) longest string that does not contain any of the bytes in delimiters. Note that separators will only be single bytes from delimiters. If maxTokens is reached, the remainder is appended to the last token.

      For example, the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is an array containing the three strings "abc", "def", and "ghi".

      The result of g_strsplit_set (":def/ghi:/x", ":/", -1) is an array containing the five strings "", "def", "ghi", "", "x".

      As a special case, the result of splitting the empty string "" is an empty array, not an array containing a single string. The reason for this special case is that being able to represent an empty array is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you'll need to check for the empty string before calling g_strsplit_set().

      Note that this function works on bytes not characters, so it can't be used to delimit UTF-8 strings for anything but ASCII characters.

      Parameters:
      string - a string to split
      delimiters - a nul-terminated byte array containing bytes that are used to split the string; can be empty (just a nul byte), which will result in no string splitting
      maxTokens - the maximum number of tokens to split string into. If this is less than 1, the string is split completely
      Returns:
      a newly-allocated array of strings. Use strfreev(MemorySegment) to free it.
      Since:
      2.4
    • strstrLen

      public static @Nullable String strstrLen(String haystack, long haystackLen, String needle)

      Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystackLen or a nul terminator byte (whichever is reached first).

      A length of -1 can be used to mean “search the entire string”, like strstr().

      The fact that this function returns gchar * rather than const gchar * is a historical artifact.

      Parameters:
      haystack - a string to search in
      haystackLen - the maximum length of haystack in bytes, or -1 to search it entirely
      needle - the string to search for
      Returns:
      a pointer to the found occurrence, or NULL if not found
    • strtod

      public static double strtod(String nptr, @Nullable Out<String> endptr)

      Converts a string to a floating point value.

      It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with asciiStrtod(String, Out), and returns the best match.

      This function should seldom be used. The normal situation when reading numbers not for human consumption is to use asciiStrtod(String, Out). Only when you know that you must expect both locale formatted and C formatted numbers should you use this. Make sure that you don't pass strings such as comma separated lists of values, since the commas may be interpreted as a decimal point in some locales, causing unexpected results.

      Parameters:
      nptr - the string to convert to a numeric value
      endptr - if non-NULL, it returns the character after the last character used in the conversion
      Returns:
      the converted value
    • strup

      @Deprecated public static String strup(String string)
      Deprecated.
      This function is totally broken for the reasons discussed in the strncasecmp(String, String, int) docs — use asciiStrup(String, long) or utf8Strup(String, long) instead.
      Converts a string to upper case.
      Parameters:
      string - the string to convert
      Returns:
      the string
    • strvContains

      public static boolean strvContains(@Nullable String @Nullable [] strv, String str)
      Checks if an array of strings contains the string str according to strEqual(MemorySegment, MemorySegment). strv must not be NULL.
      Parameters:
      strv - an array of strings to search in
      str - the string to search for
      Returns:
      true if str is an element of strv
      Since:
      2.44
    • strvEqual

      public static boolean strvEqual(@Nullable String @Nullable [] strv1, @Nullable String @Nullable [] strv2)

      Checks if two arrays of strings contain exactly the same elements in exactly the same order.

      Elements are compared using strEqual(MemorySegment, MemorySegment). To match independently of order, sort the arrays first (using qsortWithData(MemorySegment, int, long, CompareDataFunc) or similar).

      Two empty arrays are considered equal. Neither strv1 nor strv2 may be NULL.

      Parameters:
      strv1 - an array of strings to compare to strv2
      strv2 - an array of strings to compare to strv1
      Returns:
      true if strv1 and strv2 are equal
      Since:
      2.60
    • strvGetType

      public static Type strvGetType()
    • strvLength

      public static int strvLength(@Nullable String @Nullable [] strArray)
      Returns the length of an array of strings. strArray must not be NULL.
      Parameters:
      strArray - an array of strings
      Returns:
      length of strArray
      Since:
      2.6
    • testAddDataFunc

      public static void testAddDataFunc(String testpath, @Nullable MemorySegment testData, @Nullable TestDataFunc testFunc)

      Creates a new test case.

      This function is similar to testCreateCase(String, long, MemorySegment, TestFixtureFunc, TestFixtureFunc, TestFixtureFunc). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions of testpath. The testData argument will be passed as first argument to testFunc.

      If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or testTrapSubprocess(String, long, Set).

      No component of testpath may start with a dot (.) if the GLib.TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

      Parameters:
      testpath - a /-separated name for the test
      testData - data for the testFunc
      testFunc - the test function to invoke for this test
      Since:
      2.16
    • testAddDataFuncFull

      public static void testAddDataFuncFull(String testpath, @Nullable MemorySegment testData, @Nullable TestDataFunc testFunc)

      Creates a new test case.

      In contrast to testAddDataFunc(String, MemorySegment, TestDataFunc), this function is freeing testData after the test run is complete.

      Parameters:
      testpath - a /-separated name for the test
      testData - data for testFunc
      testFunc - the test function to invoke for this test
      Since:
      2.34
    • testAddFunc

      public static void testAddFunc(String testpath, @Nullable TestFunc testFunc)

      Creates a new test case.

      This function is similar to testCreateCase(String, long, MemorySegment, TestFixtureFunc, TestFixtureFunc, TestFixtureFunc). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions of testpath.

      If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or testTrapSubprocess(String, long, Set).

      No component of testpath may start with a dot (.) if the GLib.TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

      Parameters:
      testpath - a /-separated name for the test
      testFunc - the test function to invoke for this test
      Since:
      2.16
    • testAddVtable

      public static void testAddVtable(String testpath, long dataSize, @Nullable MemorySegment testData, @Nullable TestFixtureFunc dataSetup, @Nullable TestFixtureFunc dataTest, @Nullable TestFixtureFunc dataTeardown)
    • testAssertExpectedMessagesInternal

      public static void testAssertExpectedMessagesInternal(String domain, String file, int line, String func)
    • testBug

      public static void testBug(String bugUriSnippet)

      Adds a message to test reports that associates a bug URI with a test case.

      Bug URIs are constructed from a base URI set with testBugBase(String) and bugUriSnippet. If testBugBase(String) has not been called, it is assumed to be the empty string, so a full URI can be provided to testBug(String) instead.

      See also testSummary(String).

      Since GLib 2.70, the base URI is not prepended to bugUriSnippet if it is already a valid URI.

      Parameters:
      bugUriSnippet - Bug specific bug tracker URI or URI portion.
      Since:
      2.16
    • testBugBase

      public static void testBugBase(String uriPattern)

      Specifies the base URI for bug reports.

      The base URI is used to construct bug report messages for testMessage(String, Object...) when testBug(String) is called. Calling this function outside of a test case sets the default base URI for all test cases. Calling it from within a test case changes the base URI for the scope of the test case only. Bug URIs are constructed by appending a bug specific URI portion to uriPattern, or by replacing the special string %s within uriPattern if that is present.

      If testBugBase(String) is not called, bug URIs are formed solely from the value provided by testBug(String).

      Parameters:
      uriPattern - the base pattern for bug URIs
      Since:
      2.16
    • testBuildFilename

      public static String testBuildFilename(TestFileType fileType, String firstPath, Object... varargs)

      Creates the pathname to a data file that is required for a test.

      This function is conceptually similar to buildFilename(String, Object...) except that the first argument has been replaced with a GLib.TestFileType argument.

      The data file should either have been distributed with the module containing the test (GLib.TestFileType.dist or built as part of the buildcsystem of that module (GLib.TestFileType.built).

      In order for this function to work in srcdir != builddir situations, the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to have been defined. As of 2.38, this is done by the glib.mk that is included in GLib. Please ensure that your copy is up to date before using this function.

      In case neither variable is set, this function will fall back to using the dirname portion of argv[0], possibly removing ".libs". This allows for casual running of tests directly from the commandline in the srcdir == builddir case and should also support running of installed tests, assuming the data files have been installed in the same relative path as the test binary.

      Parameters:
      fileType - the type of file (built vs. distributed)
      firstPath - the first segment of the pathname
      varargs - NULL-terminated additional path segments
      Returns:
      the path of the file, to be freed using free(MemorySegment)
      Since:
      2.38
    • testCreateCase

      public static TestCase testCreateCase(String testName, long dataSize, @Nullable MemorySegment testData, @Nullable TestFixtureFunc dataSetup, @Nullable TestFixtureFunc dataTest, @Nullable TestFixtureFunc dataTeardown)

      Creates a new GLib.TestCase.

      This API is fairly low level, and calling GLib.testAdd or testAddFunc(String, TestFunc) is preferable.

      When this test is executed, a fixture structure of size dataSize will be automatically allocated and filled with zeros. Then dataSetup is called to initialize the fixture. After fixture setup, the actual test function dataTest is called. Once the test run completes, the fixture structure is torn down by calling dataTeardown and after that the memory is automatically released by the test framework.

      Splitting up a test run into fixture setup, test function and fixture teardown is most useful if the same fixture type is used for multiple tests. In this cases, testCreateCase(String, long, MemorySegment, TestFixtureFunc, TestFixtureFunc, TestFixtureFunc) will be called with the same type of fixture (the dataSize argument), but varying testName and dataTest arguments.

      Parameters:
      testName - the name for the test case
      dataSize - the size of the fixture data structure
      testData - test data argument for the test functions
      dataSetup - the function to set up the fixture data
      dataTest - the actual test function
      dataTeardown - the function to teardown the fixture data
      Returns:
      a newly allocated test case
      Since:
      2.16
    • testCreateSuite

      public static TestSuite testCreateSuite(String suiteName)
      Creates a new test suite with the name suiteName.
      Parameters:
      suiteName - a name for the suite
      Returns:
      a newly allocated test suite
      Since:
      2.16
    • testDisableCrashReporting

      public static void testDisableCrashReporting()

      Attempts to disable system crash reporting infrastructure.

      This function should be called before exercising code paths that are expected or intended to crash, to avoid wasting resources in system-wide crash collection infrastructure such as systemd-coredump or abrt.

      Since:
      2.78
    • testExpectMessage

      public static void testExpectMessage(@Nullable String logDomain, Set<LogLevelFlags> logLevel, String pattern)

      Indicates that a message with the given logDomain and logLevel, with text matching pattern, is expected to be logged.

      When this message is logged, it will not be printed, and the test case will not abort.

      This API may only be used with the old logging API (log(String, Set, String, Object...) without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See Testing for Messages.

      Use GLib.testAssertExpectedMessages to assert that all previously-expected messages have been seen and suppressed.

      You can call this multiple times in a row, if multiple messages are expected as a result of a single call. (The messages must appear in the same order as the calls to testExpectMessage(String, Set, String).)

      For example:

      // g_main_context_push_thread_default() should fail if the
      // context is already owned by another thread.
      g_test_expect_message (G_LOG_DOMAIN,
                             G_LOG_LEVEL_CRITICAL,
                             "assertion*acquired_context*failed");
      g_main_context_push_thread_default (bad_context);
      g_test_assert_expected_messages ();
      

      Note that you cannot use this to test GLib.error messages, since GLib.error intentionally never returns even if the program doesn’t abort; use testTrapSubprocess(String, long, Set) in this case.

      If messages at GLib.LogLevelFlags.LEVEL_DEBUG are emitted, but not explicitly expected via testExpectMessage(String, Set, String) then they will be ignored.

      Parameters:
      logDomain - the log domain of the message
      logLevel - the log level of the message
      pattern - a glob-style pattern (see GLib.PatternSpec)
      Since:
      2.34
    • testExpectMessage

      public static void testExpectMessage(@Nullable String logDomain, LogLevelFlags logLevel, String pattern)

      Indicates that a message with the given logDomain and logLevel, with text matching pattern, is expected to be logged.

      When this message is logged, it will not be printed, and the test case will not abort.

      This API may only be used with the old logging API (log(String, Set, String, Object...) without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See Testing for Messages.

      Use GLib.testAssertExpectedMessages to assert that all previously-expected messages have been seen and suppressed.

      You can call this multiple times in a row, if multiple messages are expected as a result of a single call. (The messages must appear in the same order as the calls to testExpectMessage(String, Set, String).)

      For example:

      // g_main_context_push_thread_default() should fail if the
      // context is already owned by another thread.
      g_test_expect_message (G_LOG_DOMAIN,
                             G_LOG_LEVEL_CRITICAL,
                             "assertion*acquired_context*failed");
      g_main_context_push_thread_default (bad_context);
      g_test_assert_expected_messages ();
      

      Note that you cannot use this to test GLib.error messages, since GLib.error intentionally never returns even if the program doesn’t abort; use testTrapSubprocess(String, long, Set) in this case.

      If messages at GLib.LogLevelFlags.LEVEL_DEBUG are emitted, but not explicitly expected via testExpectMessage(String, Set, String) then they will be ignored.

      Parameters:
      logDomain - the log domain of the message
      logLevel - the log level of the message
      pattern - a glob-style pattern (see GLib.PatternSpec)
      Since:
      2.34
    • testFail

      public static void testFail()

      Indicates that a test failed.

      This function can be called multiple times from the same test. You can use this function if your test failed in a recoverable way.

      Do not use this function if the failure of a test could cause other tests to malfunction.

      Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

      If not called from inside a test, this function does nothing.

      Note that unlike testSkip(String) and testIncomplete(String), this function does not log a message alongside the test failure. If details of the test failure are available, either log them with testMessage(String, Object...) before testFail(), or use testFailPrintf(String, Object...) instead.

      Since:
      2.30
    • testFailPrintf

      public static void testFailPrintf(String format, Object... varargs)

      Indicates that a test failed and records a message.

      Also see testFail().

      The message is formatted as if by strdupPrintf(String, Object...).

      Parameters:
      format - the format string
      varargs - printf-like arguments to format
      Since:
      2.70
    • testFailed

      public static boolean testFailed()

      Returns whether a test has already failed.

      This will be the case when testFail(), testIncomplete(String) or testSkip(String) have been called, but also if an assertion has failed.

      This can be useful to return early from a test if continuing after a failed assertion might be harmful.

      The return value of this function is only meaningful if it is called from inside a test function.

      Returns:
      true if the test has failed
      Since:
      2.38
    • testGetDir

      public static String testGetDir(TestFileType fileType)

      Gets the pathname of the directory containing test files of the type specified by fileType.

      This is approximately the same as calling g_test_build_filename("."), but you don't need to free the return value.

      Parameters:
      fileType - the type of file (built vs. distributed)
      Returns:
      the path of the directory, owned by GLib
      Since:
      2.38
    • testGetFilename

      public static String testGetFilename(TestFileType fileType, String firstPath, Object... varargs)

      Gets the pathname to a data file that is required for a test.

      This is the same as testBuildFilename(TestFileType, String, Object...) with two differences. The first difference is that you must only use this function from within a testcase function. The second difference is that you need not free the return value — it will be automatically freed when the testcase finishes running.

      It is safe to use this function from a thread inside of a testcase but you must ensure that all such uses occur before the main testcase function returns (ie: it is best to ensure that all threads have been joined).

      Parameters:
      fileType - the type of file (built vs. distributed)
      firstPath - the first segment of the pathname
      varargs - NULL-terminated additional path segments
      Returns:
      the path, automatically freed at the end of the testcase
      Since:
      2.38
    • testGetPath

      public static String testGetPath()

      Gets the test path for the test currently being run.

      In essence, it will be the same string passed as the first argument to e.g. GLib.testAdd when the test was added.

      This function returns a valid string only within a test function.

      Note that this is a test path, not a file system path.

      Returns:
      the test path for the test currently being run
      Since:
      2.68
    • testGetRoot

      public static TestSuite testGetRoot()
      Gets the toplevel test suite for the test path API.
      Returns:
      the toplevel test suite
      Since:
      2.16
    • testIncomplete

      public static void testIncomplete(@Nullable String msg)

      Indicates that a test failed because of some incomplete functionality.

      This function can be called multiple times from the same test.

      Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

      If not called from inside a test, this function does nothing.

      Parameters:
      msg - explanation
      Since:
      2.38
    • testIncompletePrintf

      public static void testIncompletePrintf(String format, Object... varargs)

      Indicates that a test failed because of some incomplete functionality.

      Equivalent to testIncomplete(String), but the explanation is formatted as if by strdupPrintf(String, Object...).

      Parameters:
      format - the format string
      varargs - printf-like arguments to format
      Since:
      2.70
    • testInit

      public static void testInit(MemorySegment argc, String[] argv, Object... varargs)

      Initializes the GLib testing framework.

      This includes seeding the test random number generator, setting the program name, and parsing test-related commandline args.

      This should be called before calling any other g_test_*() functions.

      The following arguments are understood:

      • -l: List test cases available in a test executable.

      • --seed=SEED: Provide a random seed to reproduce test runs using random numbers.

      • --verbose: Run tests verbosely.

      • -q, --quiet: Run tests quietly.

      • -p PATH: Execute all tests matching the given path.

      • -s PATH: Skip all tests matching the given path. This can also be used to force a test to run that would otherwise be skipped (ie, a test whose name contains "/subprocess").

      • -m {perf|slow|thorough|quick|undefined|no-undefined}: Execute tests according to these test modes:

        perf: Performance tests, may take long and report results (off by default).

        slow, thorough: Slow and thorough tests, may take quite long and maximize coverage (off by default).

        quick: Quick tests, should run really quickly and give good coverage (the default).

        undefined: Tests for undefined behaviour, may provoke programming errors under testTrapSubprocess(String, long, Set) or testExpectMessage(String, Set, String) to check that appropriate assertions or warnings are given (the default).

        no-undefined: Avoid tests for undefined behaviour.

      • --debug-log: Debug test logging output.

      Any parsed arguments are removed from argv, and argc is adjust accordingly.

      The following options are supported:

      • G_TEST_OPTION_NO_PRGNAME: Causes g_test_init() to not call setPrgname(String). Since. 2.84
      • G_TEST_OPTION_ISOLATE_DIRS: Creates a unique temporary directory for each unit test and sets XDG directories to point there for the duration of the unit test. See GLib.TEST_OPTION_ISOLATE_DIRS.
      • G_TEST_OPTION_NONFATAL_ASSERTIONS: This has the same effect as testSetNonfatalAssertions(). Since 2.84

      Since 2.58, if tests are compiled with G_DISABLE_ASSERT defined, g_test_init() will print an error and exit. This is to prevent no-op tests from being executed, as GLib.assert_ is commonly (erroneously) used in unit tests, and is a no-op when compiled with G_DISABLE_ASSERT. Ensure your tests are compiled without G_DISABLE_ASSERT defined.

      Parameters:
      argc - address of the argc parameter of main()
      argv - address of the argv parameter of main()
      varargs - NULL-terminated list of special options
      Since:
      2.16
    • testLogSetFatalHandler

      public static void testLogSetFatalHandler(@Nullable TestLogFatalFunc logFunc)

      Installs a non-error fatal log handler which can be used to decide whether log messages which are counted as fatal abort the program.

      The use case here is that you are running a test case that depends on particular libraries or circumstances and cannot prevent certain known critical or warning messages. So you install a handler that compares the domain and message to precisely not abort in such a case.

      Note that the handler is reset at the beginning of any test case, so you have to set it inside each test function which needs the special behavior.

      This handler has no effect on g_error messages.

      This handler also has no effect on structured log messages (using logStructured(String, Set, Object...) or logStructuredArray(Set, LogField[])). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using logSetWriterFunc(LogWriterFunc).See Using Structured Logging.

      Parameters:
      logFunc - the log handler function.
      Since:
      2.22
    • testLogTypeName

      public static String testLogTypeName(TestLogType logType)
    • testMaximizedResult

      public static void testMaximizedResult(double maximizedQuantity, String format, Object... varargs)

      Reports the result of a performance or measurement test.

      The test should generally strive to maximize the reported quantities (larger values are better than smaller ones), this and maximizedQuantity can determine sorting order for test result reports.

      Parameters:
      maximizedQuantity - the reported value
      format - the format string of the report message
      varargs - printf-like arguments to format
      Since:
      2.16
    • testMessage

      public static void testMessage(String format, Object... varargs)
      Adds a message to the test report.
      Parameters:
      format - the format string
      varargs - printf-like arguments to format
      Since:
      2.16
    • testMinimizedResult

      public static void testMinimizedResult(double minimizedQuantity, String format, Object... varargs)

      Reports the result of a performance or measurement test.

      The test should generally strive to minimize the reported quantities (smaller values are better than larger ones), this and minimizedQuantity can determine sorting order for test result reports.

      Parameters:
      minimizedQuantity - the reported value
      format - the format string of the report message
      varargs - printf-like arguments to format
      Since:
      2.16
    • testQueueDestroy

      public static void testQueueDestroy(@Nullable MemorySegment destroyData)

      Enqueues a callback destroyFunc to be executed during the next test case teardown phase.

      This is most useful to auto destroy allocated test resources at the end of a test run. Resources are released in reverse queue order, that means enqueueing callback A before callback B will cause B() to be called before A() during teardown.

      Parameters:
      destroyData - destroy callback data
      Since:
      2.16
    • testQueueFree

      public static void testQueueFree(@Nullable MemorySegment gfreePointer)

      Enqueues a pointer to be released with free(MemorySegment) during the next teardown phase.

      This is equivalent to calling testQueueDestroy(MemorySegment) with a destroy callback of free(MemorySegment).

      Parameters:
      gfreePointer - the pointer to be stored
      Since:
      2.16
    • testRandDouble

      public static double testRandDouble()

      Gets a reproducible random floating point number.

      See testRandInt() for details on test case random numbers.

      Returns:
      a random number from the seeded random number generator
      Since:
      2.16
    • testRandDoubleRange

      public static double testRandDoubleRange(double rangeStart, double rangeEnd)

      Gets a reproducible random floating point number out of a specified range.

      See testRandInt() for details on test case random numbers.

      Parameters:
      rangeStart - the minimum value returned by this function
      rangeEnd - the minimum value not returned by this function
      Returns:
      a number with rangeStart <= number < rangeEnd
      Since:
      2.16
    • testRandInt

      public static int testRandInt()

      Gets a reproducible random integer number.

      The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the --seed option is given when starting test programs.

      For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make --seed effective for all test cases.

      Returns:
      a random number from the seeded random number generator
      Since:
      2.16
    • testRandIntRange

      public static int testRandIntRange(int begin, int end)

      Gets a reproducible random integer number out of a specified range.

      See testRandInt() for details on test case random numbers.

      Parameters:
      begin - the minimum value returned by this function
      end - the smallest value not to be returned by this function
      Returns:
      a number with begin <= number < end
      Since:
      2.16
    • testRun

      public static int testRun()

      Runs all tests under the toplevel suite.

      The toplevel suite can be retrieved with testGetRoot().

      Similar to testRunSuite(TestSuite), the test cases to be run are filtered according to test path arguments (-p testpath and -s testpath) as parsed by testInit(MemorySegment, String[], Object...). testRunSuite(TestSuite) or testRun() may only be called once in a program.

      In general, the tests and sub-suites within each suite are run in the order in which they are defined. However, note that prior to GLib 2.36, there was a bug in the g_test_add_* functions which caused them to create multiple suites with the same name, meaning that if you created tests "/foo/simple", "/bar/simple", and "/foo/using-bar" in that order, they would get run in that order (since testRun() would run the first "/foo" suite, then the "/bar" suite, then the second "/foo" suite). As of 2.36, this bug is fixed, and adding the tests in that order would result in a running order of "/foo/simple", "/foo/using-bar", "/bar/simple". If this new ordering is sub-optimal (because it puts more-complicated tests before simpler ones, making it harder to figure out exactly what has failed), you can fix it by changing the test paths to group tests by suite in a way that will result in the desired running order. Eg, "/simple/foo", "/simple/bar", "/complex/foo-using-bar".

      However, you should never make the actual result of a test depend on the order that tests are run in. If you need to ensure that some particular code runs before or after a given test case, use GLib.testAdd, which lets you specify setup and teardown functions.

      If all tests are skipped or marked as incomplete (expected failures), this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.

      Returns:
      0 on success, 1 on failure (assuming it returns at all), 0 or 77 if all tests were skipped or marked as incomplete
      Since:
      2.16
    • testRunSuite

      public static int testRunSuite(TestSuite suite)

      Executes the tests within suite and all nested test suites.

      The test suites to be executed are filtered according to test path arguments (-p testpath and -s testpath) as parsed by testInit(MemorySegment, String[], Object...). See the testRun() documentation for more information on the order that tests are run in.

      testRunSuite(TestSuite) or testRun() may only be called once in a program.

      Parameters:
      suite - a test suite
      Returns:
      0 on success
      Since:
      2.16
    • testSetNonfatalAssertions

      public static void testSetNonfatalAssertions()

      Changes the behaviour of the various assertion macros.

      The g_assert_*() macros, g_test_assert_expected_messages() and the various g_test_trap_assert_*() macros are changed to not abort to program.

      Instead, they will call testFail() and continue. (This also changes the behavior of testFail() so that it will not cause the test program to abort after completing the failed test.)

      Note that the GLib.assertNotReached and GLib.assert_ macros are not affected by this.

      This function can only be called after testInit(MemorySegment, String[], Object...).

      Since:
      2.38
    • testSkip

      public static void testSkip(@Nullable String msg)

      Indicates that a test was skipped.

      Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

      If not called from inside a test, this function does nothing.

      Parameters:
      msg - explanation
      Since:
      2.38
    • testSkipPrintf

      public static void testSkipPrintf(String format, Object... varargs)

      Indicates that a test was skipped.

      Equivalent to testSkip(String), but the explanation is formatted as if by strdupPrintf(String, Object...).

      Parameters:
      format - the format string
      varargs - printf-like arguments to format
      Since:
      2.70
    • testSubprocess

      public static boolean testSubprocess()
      Returns true if the test program is running under testTrapSubprocess(String, long, Set).
      Returns:
      true if the test program is running under testTrapSubprocess(String, long, Set)
      Since:
      2.38
    • testSummary

      public static void testSummary(String summary)

      Sets the summary for a test.

      This may be included in test report output, and is useful documentation for anyone reading the source code or modifying a test in future. It must be a single line, and it should summarise what the test checks, and how.

      This should be called at the top of a test function.

      For example:

      static void
      test_array_sort (void)
      {
        g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
                        "including testing zero length and one-element arrays.");
      
        // ...
      }
      

      See also testBug(String).

      Parameters:
      summary - summary of the test purpose
      Since:
      2.62
    • testTimerElapsed

      public static double testTimerElapsed()
      Gets the number of seconds since the last start of the timer with testTimerStart().
      Returns:
      the time since the last start of the timer in seconds
      Since:
      2.16
    • testTimerLast

      public static double testTimerLast()
      Reports the last result of testTimerElapsed().
      Returns:
      the last result of testTimerElapsed()
      Since:
      2.16
    • testTimerStart

      public static void testTimerStart()

      Starts a timing test.

      Call testTimerElapsed() when the task is supposed to be done. Call this function again to restart the timer.

      Since:
      2.16
    • testTrapAssertions

      public static void testTrapAssertions(String domain, String file, int line, String func, long assertionFlags, String pattern)
    • testTrapFork

      @Deprecated public static boolean testTrapFork(long usecTimeout, Set<TestTrapFlags> testTrapFlags)
      Deprecated.
      This function is implemented only on Unix platforms, is not always reliable due to problems inherent in fork-without-exec and doesn't set close-on-exec flag on its file descriptors. Use funcGLib.testTrapSubprocess] instead.

      Forks the current test program to execute a test case that might not return or that might abort.

      If usecTimeout is non-0, the forked test case is aborted and considered failing if its run time exceeds it.

      The forking behavior can be configured with GLib.TestTrapFlags flags.

      In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.

        static void
        test_fork_patterns (void)
        {
          if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
            {
              g_print ("some stdout text: somagic17
      ");
              g_printerr ("some stderr text: semagic43
      ");
              exit (0); // successful test run
            }
          g_test_trap_assert_passed ();
          g_test_trap_assert_stdout ("*somagic17*");
          g_test_trap_assert_stderr ("*semagic43*");
        }
      
      Parameters:
      usecTimeout - timeout for the forked test in microseconds
      testTrapFlags - flags to modify forking behaviour
      Returns:
      true for the forked child and false for the executing parent process.
      Since:
      2.16
    • testTrapFork

      @Deprecated public static boolean testTrapFork(long usecTimeout, TestTrapFlags... testTrapFlags)
      Deprecated.
      This function is implemented only on Unix platforms, is not always reliable due to problems inherent in fork-without-exec and doesn't set close-on-exec flag on its file descriptors. Use funcGLib.testTrapSubprocess] instead.

      Forks the current test program to execute a test case that might not return or that might abort.

      If usecTimeout is non-0, the forked test case is aborted and considered failing if its run time exceeds it.

      The forking behavior can be configured with GLib.TestTrapFlags flags.

      In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.

        static void
        test_fork_patterns (void)
        {
          if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
            {
              g_print ("some stdout text: somagic17
      ");
              g_printerr ("some stderr text: semagic43
      ");
              exit (0); // successful test run
            }
          g_test_trap_assert_passed ();
          g_test_trap_assert_stdout ("*somagic17*");
          g_test_trap_assert_stderr ("*semagic43*");
        }
      
      Parameters:
      usecTimeout - timeout for the forked test in microseconds
      testTrapFlags - flags to modify forking behaviour
      Returns:
      true for the forked child and false for the executing parent process.
      Since:
      2.16
    • testTrapHasPassed

      public static boolean testTrapHasPassed()
      Checks the result of the last testTrapSubprocess(String, long, Set) call.
      Returns:
      true if the last test subprocess terminated successfully
      Since:
      2.16
    • testTrapHasSkipped

      public static boolean testTrapHasSkipped()
      Checks the result of the last testTrapSubprocess(String, long, Set) call.
      Returns:
      true if the last test subprocess was skipped
      Since:
      2.88
    • testTrapReachedTimeout

      public static boolean testTrapReachedTimeout()
      Checks the result of the last testTrapSubprocess(String, long, Set) call.
      Returns:
      true if the last test subprocess got killed due to a timeout
      Since:
      2.16
    • testTrapSubprocess

      public static void testTrapSubprocess(@Nullable String testPath, long usecTimeout, Set<TestSubprocessFlags> testFlags)

      Respawns the test program to run only testPath in a subprocess.

      This is equivalent to calling testTrapSubprocessWithEnvp(String, String[], long, Set) with envp set to NULL. See the documentation for that function for full details.

      Parameters:
      testPath - test to run in a subprocess
      usecTimeout - timeout for the subprocess test in microseconds.
      testFlags - flags to modify subprocess behaviour
      Since:
      2.38
    • testTrapSubprocess

      public static void testTrapSubprocess(@Nullable String testPath, long usecTimeout, TestSubprocessFlags... testFlags)

      Respawns the test program to run only testPath in a subprocess.

      This is equivalent to calling testTrapSubprocessWithEnvp(String, String[], long, Set) with envp set to NULL. See the documentation for that function for full details.

      Parameters:
      testPath - test to run in a subprocess
      usecTimeout - timeout for the subprocess test in microseconds.
      testFlags - flags to modify subprocess behaviour
      Since:
      2.38
    • testTrapSubprocessWithEnvp

      public static void testTrapSubprocessWithEnvp(@Nullable String testPath, @Nullable String @Nullable [] envp, long usecTimeout, Set<TestSubprocessFlags> testFlags)

      Respawns the test program to run only testPath in a subprocess with a given environment.

      This can be used for a test case that might not return, or that might abort.

      If testPath is NULL then the same test is re-run in a subprocess. You can use testSubprocess() to determine whether the test is in a subprocess or not.

      testPath can also be the name of the parent test, followed by "/subprocess/" and then a name for the specific subtest (or just ending with "/subprocess" if the test only has one child test); tests with names of this form will automatically be skipped in the parent process.

      If envp is NULL, the parent process’ environment will be inherited.

      If usecTimeout is non-0, the test subprocess is aborted and considered failing if its run time exceeds it.

      The subprocess behavior can be configured with GLib.TestSubprocessFlags flags.

      You can use methods such as GLib.testTrapAssertPassed, GLib.testTrapAssertFailed, and GLib.testTrapAssertStderr to check the results of the subprocess. (But note that GLib.testTrapAssertStdout and GLib.testTrapAssertStderr cannot be used if testFlags specifies that the child should inherit the parent stdout/stderr.)

      If your main () needs to behave differently in the subprocess, you can call testSubprocess() (after calling testInit(MemorySegment, String[], Object...)) to see whether you are in a subprocess.

      Internally, this function tracks the child process using childWatchSourceNew(Pid), so your process must not ignore SIGCHLD, and must not attempt to watch or wait for the child process via another mechanism.

      The following example tests that calling my_object_new(1000000) will abort with an error message.

        static void
        test_create_large_object (void)
        {
          if (g_test_subprocess ())
            {
              my_object_new (1000000);
              return;
            }
      
          // Reruns this same test in a subprocess
          g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
          g_test_trap_assert_failed ();
          g_test_trap_assert_stderr ("*ERROR*too large*");
        }
      
        static void
        test_different_username (void)
        {
          if (g_test_subprocess ())
            {
              // Code under test goes here
              g_message ("Username is now simulated as %s", g_getenv ("USER"));
              return;
            }
      
          // Reruns this same test in a subprocess
          g_auto(GStrv) envp = g_get_environ ();
          envp = g_environ_setenv (g_steal_pointer (&envp), "USER", "charlie", TRUE);
          g_test_trap_subprocess_with_envp (NULL, envp, 0, G_TEST_SUBPROCESS_DEFAULT);
          g_test_trap_assert_passed ();
          g_test_trap_assert_stdout ("Username is now simulated as charlie");
        }
      
        int
        main (int argc, char **argv)
        {
          g_test_init (&argc, &argv, NULL);
      
          g_test_add_func ("/myobject/create-large-object",
                           test_create_large_object);
          g_test_add_func ("/myobject/different-username",
                           test_different_username);
          return g_test_run ();
        }
      
      Parameters:
      testPath - test to run in a subprocess
      envp - environment to run the test in
      usecTimeout - timeout for the subprocess test in microseconds
      testFlags - flags to modify subprocess behaviour
      Since:
      2.80
    • testTrapSubprocessWithEnvp

      public static void testTrapSubprocessWithEnvp(@Nullable String testPath, @Nullable String @Nullable [] envp, long usecTimeout, TestSubprocessFlags... testFlags)

      Respawns the test program to run only testPath in a subprocess with a given environment.

      This can be used for a test case that might not return, or that might abort.

      If testPath is NULL then the same test is re-run in a subprocess. You can use testSubprocess() to determine whether the test is in a subprocess or not.

      testPath can also be the name of the parent test, followed by "/subprocess/" and then a name for the specific subtest (or just ending with "/subprocess" if the test only has one child test); tests with names of this form will automatically be skipped in the parent process.

      If envp is NULL, the parent process’ environment will be inherited.

      If usecTimeout is non-0, the test subprocess is aborted and considered failing if its run time exceeds it.

      The subprocess behavior can be configured with GLib.TestSubprocessFlags flags.

      You can use methods such as GLib.testTrapAssertPassed, GLib.testTrapAssertFailed, and GLib.testTrapAssertStderr to check the results of the subprocess. (But note that GLib.testTrapAssertStdout and GLib.testTrapAssertStderr cannot be used if testFlags specifies that the child should inherit the parent stdout/stderr.)

      If your main () needs to behave differently in the subprocess, you can call testSubprocess() (after calling testInit(MemorySegment, String[], Object...)) to see whether you are in a subprocess.

      Internally, this function tracks the child process using childWatchSourceNew(Pid), so your process must not ignore SIGCHLD, and must not attempt to watch or wait for the child process via another mechanism.

      The following example tests that calling my_object_new(1000000) will abort with an error message.

        static void
        test_create_large_object (void)
        {
          if (g_test_subprocess ())
            {
              my_object_new (1000000);
              return;
            }
      
          // Reruns this same test in a subprocess
          g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
          g_test_trap_assert_failed ();
          g_test_trap_assert_stderr ("*ERROR*too large*");
        }
      
        static void
        test_different_username (void)
        {
          if (g_test_subprocess ())
            {
              // Code under test goes here
              g_message ("Username is now simulated as %s", g_getenv ("USER"));
              return;
            }
      
          // Reruns this same test in a subprocess
          g_auto(GStrv) envp = g_get_environ ();
          envp = g_environ_setenv (g_steal_pointer (&envp), "USER", "charlie", TRUE);
          g_test_trap_subprocess_with_envp (NULL, envp, 0, G_TEST_SUBPROCESS_DEFAULT);
          g_test_trap_assert_passed ();
          g_test_trap_assert_stdout ("Username is now simulated as charlie");
        }
      
        int
        main (int argc, char **argv)
        {
          g_test_init (&argc, &argv, NULL);
      
          g_test_add_func ("/myobject/create-large-object",
                           test_create_large_object);
          g_test_add_func ("/myobject/different-username",
                           test_different_username);
          return g_test_run ();
        }
      
      Parameters:
      testPath - test to run in a subprocess
      envp - environment to run the test in
      usecTimeout - timeout for the subprocess test in microseconds
      testFlags - flags to modify subprocess behaviour
      Since:
      2.80
    • timeoutAdd

      public static int timeoutAdd(int priority, int interval, @Nullable SourceFunc function)

      Sets a function to be called at regular intervals, with the given priority.

      The function is called repeatedly until it returns GLib.SOURCE_REMOVE, at which point the timeout is automatically destroyed and the function will not be called again. The notify function is called when the timeout is destroyed. The first call to the function will be at the end of the first interval.

      Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to ‘catch up’ time lost in delays).

      See main loop memory management for details on how to handle the return value and memory management of data.

      This internally creates a main loop source using timeoutSourceNew(int) and attaches it to the global GLib.MainContext using Source.attach(MainContext), so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

      The interval given is in terms of monotonic time, not wall clock time. See getMonotonicTime().

      Parameters:
      priority - the priority of the timeout source; typically this will be in the range between GLib.PRIORITY_DEFAULT and GLib.PRIORITY_HIGH
      interval - the time between calls to the function, in milliseconds
      function - function to call
      Returns:
      the ID (greater than 0) of the event source
    • timeoutAddSeconds

      public static int timeoutAddSeconds(int priority, int interval, @Nullable SourceFunc function)

      Sets a function to be called at regular intervals, with priority.

      The function is called repeatedly until it returns GLib.SOURCE_REMOVE, at which point the timeout is automatically destroyed and the function will not be called again.

      Unlike timeoutAdd(int, int, SourceFunc), this function operates at whole second granularity. The initial starting point of the timer is determined by the implementation and the implementation is expected to group multiple timers together so that they fire all at the same time. To allow this grouping, the interval to the first timer is rounded and can deviate up to one second from the specified interval. Subsequent timer iterations will generally run at the specified interval.

      Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval

      See main loop memory management for details on how to handle the return value and memory management of data.

      If you want timing more precise than whole seconds, use timeoutAdd(int, int, SourceFunc) instead.

      The grouping of timers to fire at the same time results in a more power and CPU efficient behavior so if your timer is in multiples of seconds and you don’t require the first timer exactly one second from now, the use of timeoutAddSeconds(int, int, SourceFunc) is preferred over timeoutAdd(int, int, SourceFunc).

      This internally creates a main loop source using timeoutSourceNewSeconds(int) and attaches it to the main loop context using Source.attach(MainContext). You can do these steps manually if you need greater control.

      It is safe to call this function from any thread.

      The interval given is in terms of monotonic time, not wall clock time. See getMonotonicTime().

      Parameters:
      priority - the priority of the timeout source; typically this will be in the range between GLib.PRIORITY_DEFAULT and GLib.PRIORITY_HIGH
      interval - the time between calls to the function, in seconds
      function - function to call
      Returns:
      the ID (greater than 0) of the event source
      Since:
      2.14
    • timeoutSourceNew

      public static Source timeoutSourceNew(int interval)

      Creates a new timeout source.

      The source will not initially be associated with any GLib.MainContext and must be added to one with Source.attach(MainContext) before it will be executed.

      The interval given is in terms of monotonic time, not wall clock time. See getMonotonicTime().

      Parameters:
      interval - the timeout interval in milliseconds
      Returns:
      the newly-created timeout source
    • timeoutSourceNewSeconds

      public static Source timeoutSourceNewSeconds(int interval)

      Creates a new timeout source.

      The source will not initially be associated with any GLib.MainContext and must be added to one with Source.attach(MainContext) before it will be executed.

      The scheduling granularity/accuracy of this timeout source will be in seconds.

      The interval given is in terms of monotonic time, not wall clock time. See getMonotonicTime().

      Parameters:
      interval - the timeout interval in seconds
      Returns:
      the newly-created timeout source
      Since:
      2.14
    • tryMalloc

      public static @Nullable MemorySegment tryMalloc(long nBytes)
      Attempts to allocate nBytes, and returns null on failure. Contrast with g_malloc(), which aborts the program on failure.
      Parameters:
      nBytes - number of bytes to allocate.
      Returns:
      the allocated memory, or null.
    • tryMalloc0

      public static @Nullable MemorySegment tryMalloc0(long nBytes)
      Attempts to allocate nBytes, initialized to 0's, and returns null on failure. Contrast with g_malloc0(), which aborts the program on failure.
      Parameters:
      nBytes - number of bytes to allocate
      Returns:
      the allocated memory, or null
      Since:
      2.8
    • tryMalloc0N

      public static @Nullable MemorySegment tryMalloc0N(long nBlocks, long nBlockBytes)
      This function is similar to g_try_malloc0(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.
      Parameters:
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      Returns:
      the allocated memory, or null
      Since:
      2.24
    • tryMallocN

      public static @Nullable MemorySegment tryMallocN(long nBlocks, long nBlockBytes)
      This function is similar to g_try_malloc(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.
      Parameters:
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      Returns:
      the allocated memory, or null.
      Since:
      2.24
    • tryRealloc

      public static @Nullable MemorySegment tryRealloc(@Nullable MemorySegment mem, long nBytes)

      Attempts to realloc mem to a new size, nBytes, and returns null on failure. Contrast with g_realloc(), which aborts the program on failure.

      If mem is null, behaves the same as g_try_malloc().

      Parameters:
      mem - previously-allocated memory, or null.
      nBytes - number of bytes to allocate.
      Returns:
      the allocated memory, or null.
    • tryReallocN

      public static @Nullable MemorySegment tryReallocN(@Nullable MemorySegment mem, long nBlocks, long nBlockBytes)
      This function is similar to g_try_realloc(), allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.
      Parameters:
      mem - previously-allocated memory, or null.
      nBlocks - the number of blocks to allocate
      nBlockBytes - the size of each block in bytes
      Returns:
      the allocated memory, or null.
      Since:
      2.24
    • ucs4ToUtf16

      public static MemorySegment ucs4ToUtf16(@Nullable int @Nullable [] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) throws GErrorException

      Convert a string from UCS-4 to UTF-16.

      A nul character (U+0000) will be added to the result after the converted text.

      Parameters:
      str - a UCS-4 encoded string
      itemsRead - location to store number of bytes read, or NULL to ignore. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.
      itemsWritten - location to store number of gunichar2 written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.
      Returns:
      a pointer to a newly allocated UTF-16 string. This value must be freed with free(MemorySegment).
      Throws:
      GErrorException - see GError
    • ucs4ToUtf8

      public static String ucs4ToUtf8(@Nullable int @Nullable [] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) throws GErrorException

      Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8.

      The result will be terminated with a nul byte.

      Parameters:
      str - a UCS-4 encoded string
      itemsRead - location to store number of characters read, or NULL to ignore. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.
      itemsWritten - location to store number of bytes written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.
      Returns:
      a pointer to a newly allocated UTF-8 string. This value must be freed with free(MemorySegment).
      Throws:
      GErrorException - see GError
    • unicharBreakType

      public static UnicodeBreakType unicharBreakType(int c)
      Determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use g_utf8_get_char()). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally you would use a function such as pango_break() instead of caring about break types yourself.
      Parameters:
      c - a Unicode character
      Returns:
      the break type of c
    • unicharCombiningClass

      public static int unicharCombiningClass(int uc)
      Determines the canonical combining class of a Unicode character.
      Parameters:
      uc - a Unicode character
      Returns:
      the combining class of the character
      Since:
      2.14
    • unicharCompose

      public static boolean unicharCompose(int a, int b, Out<Integer> ch)

      Performs a single composition step of the Unicode canonical composition algorithm.

      This function includes algorithmic Hangul Jamo composition, but it is not exactly the inverse of g_unichar_decompose(). No composition can have either of a or b equal to zero. To be precise, this function composes if and only if there exists a Primary Composite P which is canonically equivalent to the sequence <b>. See the Unicode Standard for the definition of Primary Composite.

      If a and b do not compose a new character, ch is set to zero.

      See UAX#15 for details.

      Parameters:
      a - a Unicode character
      b - a Unicode character
      ch - return location for the composed character
      Returns:
      true if the characters could be composed
      Since:
      2.30
    • unicharDecompose

      public static boolean unicharDecompose(int ch, Out<Integer> a, Out<Integer> b)

      Performs a single decomposition step of the Unicode canonical decomposition algorithm.

      This function does not include compatibility decompositions. It does, however, include algorithmic Hangul Jamo decomposition, as well as 'singleton' decompositions which replace a character by a single other character. In the case of singletons *b will be set to zero.

      If ch is not decomposable, *a is set to ch and *b is set to zero.

      Note that the way Unicode decomposition pairs are defined, it is guaranteed that b would not decompose further, but a may itself decompose. To get the full canonical decomposition for ch, one would need to recursively call this function on a. Or use g_unichar_fully_decompose().

      See UAX#15 for details.

      Parameters:
      ch - a Unicode character
      a - return location for the first component of ch
      b - return location for the second component of ch
      Returns:
      true if the character could be decomposed
      Since:
      2.30
    • unicharDigitValue

      public static int unicharDigitValue(int c)
      Determines the numeric value of a character as a decimal digit.
      Parameters:
      c - a Unicode character
      Returns:
      If c is a decimal digit (according to g_unichar_isdigit()), its numeric value. Otherwise, -1.
    • unicharFullyDecompose

      public static long unicharFullyDecompose(int ch, boolean compat, @Nullable Out<Integer> result, long resultLen)

      Computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, pass true for compat; for canonical decomposition pass false for compat.

      The decomposed sequence is placed in result. Only up to resultLen characters are written into result. The length of the full decomposition (irrespective of resultLen) is returned by the function. For canonical decomposition, currently all decompositions are of length at most 4, but this may change in the future (very unlikely though). At any rate, Unicode does guarantee that a buffer of length 18 is always enough for both compatibility and canonical decompositions, so that is the size recommended. This is provided as G_UNICHAR_MAX_DECOMPOSITION_LENGTH.

      See UAX#15 for details.

      Parameters:
      ch - a Unicode character.
      compat - whether perform canonical or compatibility decomposition
      result - location to store decomposed result, or null
      resultLen - length of result
      Returns:
      the length of the full decomposition.
      Since:
      2.30
    • unicharGetMirrorChar

      public static boolean unicharGetMirrorChar(int ch, Out<Integer> mirroredCh)

      In Unicode, some characters are "mirrored". This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.

      If ch has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of ch's glyph and mirroredCh is set, it puts that character in the address pointed to by mirroredCh. Otherwise the original character is put.

      Parameters:
      ch - a Unicode character
      mirroredCh - location to store the mirrored character
      Returns:
      true if ch has a mirrored character, false otherwise
      Since:
      2.4
    • unicharGetScript

      public static UnicodeScript unicharGetScript(int ch)

      Looks up the GUnicodeScript for a particular character (as defined by Unicode Standard Annex \24). No check is made for ch being a valid Unicode character; if you pass in invalid character, the result is undefined.

      This function is equivalent to pango_script_for_unichar() and the two are interchangeable.

      Parameters:
      ch - a Unicode character
      Returns:
      the GUnicodeScript for the character.
      Since:
      2.14
    • unicharIsalnum

      public static boolean unicharIsalnum(int c)
      Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is an alphanumeric character
    • unicharIsalpha

      public static boolean unicharIsalpha(int c)
      Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is an alphabetic character
    • unicharIscntrl

      public static boolean unicharIscntrl(int c)
      Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is a control character
    • unicharIsdefined

      public static boolean unicharIsdefined(int c)
      Determines if a given character is assigned in the Unicode standard.
      Parameters:
      c - a Unicode character
      Returns:
      true if the character has an assigned value
    • unicharIsdigit

      public static boolean unicharIsdigit(int c)
      Determines whether a character is numeric (i.e. a digit). This covers ASCII 0-9 and also digits in other languages/scripts. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is a digit
    • unicharIsgraph

      public static boolean unicharIsgraph(int c)
      Determines whether a character is printable and not a space (returns false for control characters, format characters, and spaces). g_unichar_isprint() is similar, but returns true for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is printable unless it's a space
    • unicharIslower

      public static boolean unicharIslower(int c)
      Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is a lowercase letter
    • unicharIsmark

      public static boolean unicharIsmark(int c)

      Determines whether a character is a mark (non-spacing mark, combining mark, or enclosing mark in Unicode speak). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

      Note: in most cases where isalpha characters are allowed, ismark characters should be allowed to as they are essential for writing most European languages as well as many non-Latin scripts.

      Parameters:
      c - a Unicode character
      Returns:
      true if c is a mark character
      Since:
      2.14
    • unicharIsprint

      public static boolean unicharIsprint(int c)
      Determines whether a character is printable. Unlike g_unichar_isgraph(), returns true for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is printable
    • unicharIspunct

      public static boolean unicharIspunct(int c)
      Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with g_utf8_get_char().
      Parameters:
      c - a Unicode character
      Returns:
      true if c is a punctuation or symbol character
    • unicharIsspace

      public static boolean unicharIsspace(int c)

      Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

      (Note: don't use this to do word breaking; you have to use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)

      Parameters:
      c - a Unicode character
      Returns:
      true if c is a space character
    • unicharIstitle

      public static boolean unicharIstitle(int c)
      Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.
      Parameters:
      c - a Unicode character
      Returns:
      true if the character is titlecase
    • unicharIsupper

      public static boolean unicharIsupper(int c)
      Determines if a character is uppercase.
      Parameters:
      c - a Unicode character
      Returns:
      true if c is an uppercase character
    • unicharIswide

      public static boolean unicharIswide(int c)
      Determines if a character is typically rendered in a double-width cell.
      Parameters:
      c - a Unicode character
      Returns:
      true if the character is wide
    • unicharIswideCjk

      public static boolean unicharIswideCjk(int c)

      Determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to g_unichar_iswide(), then it is also reported wide with this function, but the converse is not necessarily true. See the Unicode Standard Annex #11 for details.

      If a character passes the g_unichar_iswide() test then it will also pass this test, but not the other way around. Note that some characters may pass both this test and g_unichar_iszerowidth().

      Parameters:
      c - a Unicode character
      Returns:
      true if the character is wide in legacy East Asian locales
      Since:
      2.12
    • unicharIsxdigit

      public static boolean unicharIsxdigit(int c)
      Determines if a character is a hexadecimal digit.
      Parameters:
      c - a Unicode character.
      Returns:
      true if the character is a hexadecimal digit
    • unicharIszerowidth

      public static boolean unicharIszerowidth(int c)

      Determines if a given character typically takes zero width when rendered. The return value is true for all non-spacing and enclosing marks (e.g., combining accents), format characters, zero-width space, but not U+00AD SOFT HYPHEN.

      A typical use of this function is with one of g_unichar_iswide() or g_unichar_iswide_cjk() to determine the number of cells a string occupies when displayed on a grid display (terminals). However, note that not all terminals support zero-width rendering of zero-width marks.

      Parameters:
      c - a Unicode character
      Returns:
      true if the character has zero width
      Since:
      2.14
    • unicharToUtf8

      public static int unicharToUtf8(int c, @Nullable Out<String> outbuf)
      Converts a single character to UTF-8.
      Parameters:
      c - a Unicode character code
      outbuf - output buffer, must have at least 6 bytes of space. If NULL, the length will be computed and returned and nothing will be written to outbuf.
      Returns:
      number of bytes written, guaranteed to be in the range [1, 6]
    • unicharTolower

      public static int unicharTolower(int c)
      Converts a character to lower case.
      Parameters:
      c - a Unicode character.
      Returns:
      the result of converting c to lower case. If c is not an upperlower or titlecase character, or has no lowercase equivalent c is returned unchanged.
    • unicharTotitle

      public static int unicharTotitle(int c)
      Converts a character to the titlecase.
      Parameters:
      c - a Unicode character
      Returns:
      the result of converting c to titlecase. If c is not an uppercase or lowercase character, c is returned unchanged.
    • unicharToupper

      public static int unicharToupper(int c)
      Converts a character to uppercase.
      Parameters:
      c - a Unicode character
      Returns:
      the result of converting c to uppercase. If c is not a lowercase or titlecase character, or has no upper case equivalent c is returned unchanged.
    • unicharType

      public static UnicodeType unicharType(int c)
      Classifies a Unicode character by type.
      Parameters:
      c - a Unicode character
      Returns:
      the type of the character.
    • unicharValidate

      public static boolean unicharValidate(int ch)

      Checks whether ch is a valid Unicode character.

      Some possible integer values of ch will not be valid. U+0000 is considered a valid character, though it’s normally a string terminator.

      Parameters:
      ch - a Unicode character
      Returns:
      TRUE if ch is a valid Unicode character
    • unicharXdigitValue

      public static int unicharXdigitValue(int c)
      Determines the numeric value of a character as a hexadecimal digit.
      Parameters:
      c - a Unicode character
      Returns:
      If c is a hex digit (according to g_unichar_isxdigit()), its numeric value. Otherwise, -1.
    • unicodeCanonicalDecomposition

      @Deprecated public static MemorySegment unicodeCanonicalDecomposition(int ch, MemorySegment resultLen)
      Deprecated.
      Use the more flexible g_unichar_fully_decompose() instead.
      Computes the canonical decomposition of a Unicode character.
      Parameters:
      ch - a Unicode character.
      resultLen - location to store the length of the return value.
      Returns:
      a newly allocated string of Unicode characters. resultLen is set to the resulting length of the string.
    • unicodeCanonicalOrdering

      public static void unicodeCanonicalOrdering(@Nullable int @Nullable [] string)
      Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.
      Parameters:
      string - a UCS-4 encoded string.
    • unlink

      public static int unlink(String filename)

      A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.

      See your C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      Returns:
      0 if the name was successfully deleted, -1 if an error occurred
      Since:
      2.6
    • unsetenv

      public static void unsetenv(String variable)

      Removes an environment variable from the environment.

      Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.

      You should be mindful of the fact that environment variable handling in UNIX is not thread-safe, and your program may crash if one thread calls g_unsetenv() while another thread is calling getenv(). (And note that many functions, such as gettext(), call getenv() internally.) This function is only safe to use at the very start of your program, before creating any other threads (or creating objects that create worker threads of their own).

      If you need to set up the environment for a child process, you can use g_get_environ() to get an environment array, modify that with g_environ_setenv() and g_environ_unsetenv(), and then pass that array directly to execvpe(), g_spawn_async(), or the like.

      Parameters:
      variable - the environment variable to remove, must not contain '='
      Since:
      2.4
    • usleep

      public static void usleep(int microseconds)

      Pauses the current thread for the given number of microseconds.

      There are 1 million microseconds per second (represented by the G_USEC_PER_SEC macro). g_usleep() may have limited precision, depending on hardware and operating system; don't rely on the exact length of the sleep.

      Parameters:
      microseconds - number of microseconds to pause
    • utf16ToUcs4

      public static MemorySegment utf16ToUcs4(@Nullable short @Nullable [] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) throws GErrorException

      Convert a string from UTF-16 to UCS-4.

      The result will be nul-terminated.

      Parameters:
      str - a UTF-16 encoded string
      itemsRead - location to store number of gunichar2 read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.
      itemsWritten - location to store number of characters written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.
      Returns:
      a pointer to a newly allocated UCS-4 string. This value must be freed with free(MemorySegment).
      Throws:
      GErrorException - see GError
    • utf16ToUtf8

      public static String utf16ToUtf8(@Nullable short @Nullable [] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) throws GErrorException

      Convert a string from UTF-16 to UTF-8.

      The result will be terminated with a nul byte.

      Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. convert(byte[], String, String, Out) can be used to convert a byte buffer of UTF-16 data of ambiguous endianness.

      Further note that this function does not validate the result string; it may (for example) include embedded nul characters. The only validation done by this function is to ensure that the input can be correctly interpreted as UTF-16, i.e. it doesn’t contain unpaired surrogates or partial character sequences.

      Parameters:
      str - a UTF-16 encoded string
      itemsRead - location to store number of gunichar2 read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.
      itemsWritten - location to store number of bytes written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.
      Returns:
      a pointer to a newly allocated UTF-8 string. This value must be freed with free(MemorySegment).
      Throws:
      GErrorException - see GError
    • utf8Casefold

      public static String utf8Casefold(String str, long len)

      Converts a string into a form that is independent of case. The result will not correspond to any particular case, but can be compared for equality or ordered with the results of calling g_utf8_casefold() on other strings.

      Note that calling g_utf8_casefold() followed by g_utf8_collate() is only an approximation to the correct linguistic case insensitive ordering, though it is a fairly good one. Getting this exactly right would require a more sophisticated collation function that takes case sensitivity into account. GLib does not currently provide such a function.

      Parameters:
      str - a UTF-8 encoded string
      len - length of str, in bytes, or -1 if str is nul-terminated.
      Returns:
      a newly allocated string, that is a case independent form of str.
    • utf8Collate

      public static int utf8Collate(String str1, String str2)

      Compares two strings for ordering using the linguistically correct rules for the current locale. When sorting a large number of strings, it will be significantly faster to obtain collation keys with g_utf8_collate_key() and compare the keys with strcmp() when sorting instead of sorting the original strings.

      If the two strings are not comparable due to being in different collation sequences, the result is undefined. This can happen if the strings are in different language scripts, for example.

      Parameters:
      str1 - a UTF-8 encoded string
      str2 - a UTF-8 encoded string
      Returns:
      < 0 if str1 compares before str2, 0 if they compare equal, > 0 if str1 compares after str2.
    • utf8CollateKey

      public static String utf8CollateKey(String str, long len)

      Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

      The results of comparing the collation keys of two strings with strcmp() will always be the same as comparing the two original keys with g_utf8_collate().

      Note that this function depends on the current locale.

      Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.

      Parameters:
      str - a UTF-8 encoded string.
      len - length of str, in bytes, or -1 if str is nul-terminated.
      Returns:
      a newly allocated string. The contents of the string are only meant to be used when sorting. This string should be freed with g_free() when you are done with it.
    • utf8CollateKeyForFilename

      public static String utf8CollateKeyForFilename(String str, long len)

      Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

      In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".

      Note that this function depends on the current locale.

      Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.

      Parameters:
      str - a UTF-8 encoded string.
      len - length of str, in bytes, or -1 if str is nul-terminated.
      Returns:
      a newly allocated string. The contents of the string are only meant to be used when sorting. This string should be freed with g_free() when you are done with it.
      Since:
      2.8
    • utf8FindNextChar

      public static @Nullable String utf8FindNextChar(String p, @Nullable String end)

      Finds the start of the next UTF-8 character in the string after p.

      p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

      If end is NULL, the return value will never be NULL: if the end of the string is reached, a pointer to the terminating nul byte is returned. If end is non-NULL, the return value will be NULL if the end of the string is reached.

      Parameters:
      p - a pointer to a position within a UTF-8 encoded string
      end - a pointer to the byte following the end of the string, or NULL to indicate that the string is nul-terminated
      Returns:
      a pointer to the found character or NULL if end is set and is reached
    • utf8FindPrevChar

      public static @Nullable String utf8FindPrevChar(String str, String p)

      Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns NULL if no UTF-8 characters are present in str before p.

      p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

      Parameters:
      str - pointer to the beginning of a UTF-8 encoded string
      p - pointer to some position within str
      Returns:
      a pointer to the found character
    • utf8GetChar

      public static int utf8GetChar(String p)

      Converts a sequence of bytes encoded as UTF-8 to a Unicode character.

      If p does not point to a valid UTF-8 encoded character, results are undefined. If you are not sure that the bytes are complete valid Unicode characters, you should use utf8GetCharValidated(String, long) instead.

      Parameters:
      p - a pointer to Unicode character encoded as UTF-8
      Returns:
      the resulting character
    • utf8GetCharValidated

      public static int utf8GetCharValidated(String p, long maxLen)

      Convert a sequence of bytes encoded as UTF-8 to a Unicode character.

      This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.

      Note that utf8GetCharValidated(String, long) returns (gunichar)-2 if maxLen is positive and any of the bytes in the first UTF-8 character sequence are nul.

      Parameters:
      p - a pointer to Unicode character encoded as UTF-8
      maxLen - the maximum number of bytes to read, or -1 if p is nul-terminated
      Returns:
      the resulting character. If p points to a partial sequence at the end of a string that could begin a valid character (or if maxLen is zero), returns (gunichar)-2; otherwise, if p does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.
    • utf8MakeValid

      public static String utf8MakeValid(String str, long len)

      If the provided string is valid UTF-8, return a copy of it. If not, return a copy in which bytes that could not be interpreted as valid Unicode are replaced with the Unicode replacement character (U+FFFD).

      For example, this is an appropriate function to use if you have received a string that was incorrectly declared to be UTF-8, and you need a valid UTF-8 version of it that can be logged or displayed to the user, with the assumption that it is close enough to ASCII or UTF-8 to be mostly readable as-is.

      Parameters:
      str - string to coerce into UTF-8
      len - the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.
      Returns:
      a valid UTF-8 string whose content resembles str
      Since:
      2.52
    • utf8Normalize

      public static @Nullable String utf8Normalize(String str, long len, NormalizeMode mode)

      Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. The string has to be valid UTF-8, otherwise null is returned. You should generally call g_utf8_normalize() before comparing two Unicode strings.

      The normalization mode NormalizeMode.DEFAULT only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. NormalizeMode.ALL also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.

      NormalizeMode.DEFAULT_COMPOSE and NormalizeMode.ALL_COMPOSE are like NormalizeMode.DEFAULT and NormalizeMode.ALL, but returned a result with composed forms rather than a maximally decomposed form. This is often useful if you intend to convert the string to a legacy encoding or pass it to a system with less capable Unicode handling.

      Parameters:
      str - a UTF-8 encoded string.
      len - length of str, in bytes, or -1 if str is nul-terminated.
      mode - the type of normalization to perform.
      Returns:
      a newly allocated string, that is the normalized form of str, or null if str is not valid UTF-8.
    • utf8OffsetToPointer

      public static String utf8OffsetToPointer(String str, int offset)

      Converts from an integer character offset to a pointer to a position within the string.

      Since 2.10, this function allows to pass a negative offset to step backwards. It is usually worth stepping backwards from the end instead of forwards if offset is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.

      Note that this function doesn’t abort when reaching the end of str. Therefore you should be sure that offset is within string boundaries before calling that function. Call utf8Strlen(String, long) when unsure. This limitation exists as this function is called frequently during text rendering and therefore has to be as fast as possible.

      Parameters:
      str - a UTF-8 encoded string
      offset - a character offset within str
      Returns:
      the resulting pointer
    • utf8PointerToOffset

      public static int utf8PointerToOffset(String str, String pos)

      Converts from a pointer to position within a string to an integer character offset.

      Since 2.10, this function allows pos to be before str, and returns a negative offset in this case.

      Parameters:
      str - a UTF-8 encoded string
      pos - a pointer to a position within str
      Returns:
      the resulting character offset
    • utf8PrevChar

      public static String utf8PrevChar(String p)

      Finds the previous UTF-8 character in the string before p.

      p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If p might be the first character of the string, you must use utf8FindPrevChar(String, String) instead.

      Parameters:
      p - a pointer to a position within a UTF-8 encoded string
      Returns:
      a pointer to the found character
    • utf8Strchr

      public static @Nullable String utf8Strchr(String p, long len, int c)

      Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes.

      If len is -1, allow unbounded search.

      Parameters:
      p - a nul-terminated UTF-8 encoded string
      len - the maximum length of p
      c - a Unicode character
      Returns:
      NULL if the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.
    • utf8Strdown

      public static String utf8Strdown(String str, long len)
      Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.
      Parameters:
      str - a UTF-8 encoded string
      len - length of str, in bytes, or -1 if str is nul-terminated.
      Returns:
      a newly allocated string, with all characters converted to lowercase.
    • utf8Strlen

      public static int utf8Strlen(String p, long max)
      Computes the length of the string in characters, not including the terminating nul character. If the max’th byte falls in the middle of a character, the last (partial) character is not counted.
      Parameters:
      p - pointer to the start of a UTF-8 encoded string
      max - the maximum number of bytes to examine. If max is less than 0, then the string is assumed to be nul-terminated. If max is 0, p will not be examined and may be NULL. If max is greater than 0, up to max bytes are examined
      Returns:
      the length of the string in characters
    • utf8Strncpy

      public static String utf8Strncpy(String dest, String src, long n)

      Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes.

      The src string must be valid UTF-8 encoded text. (Use utf8Validate(byte[], Out) on all text before trying to use UTF-8 utility functions with it.)

      Note you must ensure dest is at least 4 * n + 1 to fit the largest possible UTF-8 characters

      Parameters:
      dest - buffer to fill with characters from src
      src - UTF-8 encoded string
      n - character count
      Returns:
      dest
    • utf8Strrchr

      public static @Nullable String utf8Strrchr(String p, long len, int c)

      Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes.

      If len is -1, allow unbounded search.

      Parameters:
      p - a nul-terminated UTF-8 encoded string
      len - the maximum length of p
      c - a Unicode character
      Returns:
      NULL if the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.
    • utf8Strreverse

      public static String utf8Strreverse(String str, long len)

      Reverses a UTF-8 string.

      str must be valid UTF-8 encoded text. (Use utf8Validate(byte[], Out) on all text before trying to use UTF-8 utility functions with it.)

      This function is intended for programmatic uses of reversed strings. It pays no attention to decomposed characters, combining marks, byte order marks, directional indicators (LRM, LRO, etc) and similar characters which might need special handling when reversing a string for display purposes.

      Note that unlike strreverse(String), this function returns newly-allocated memory, which should be freed with free(MemorySegment) when no longer needed.

      Parameters:
      str - a UTF-8 encoded string
      len - the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.
      Returns:
      a newly-allocated string which is the reverse of str
      Since:
      2.2
    • utf8Strup

      public static String utf8Strup(String str, long len)
      Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)
      Parameters:
      str - a UTF-8 encoded string
      len - length of str, in bytes, or -1 if str is nul-terminated.
      Returns:
      a newly allocated string, with all characters converted to uppercase.
    • utf8Substring

      public static String utf8Substring(String str, int startPos, int endPos)

      Copies a substring out of a UTF-8 encoded string. The substring will contain endPos - startPos characters.

      Since GLib 2.72, -1 can be passed to endPos to indicate the end of the string.

      Parameters:
      str - a UTF-8 encoded string
      startPos - a character offset within str
      endPos - another character offset within str, or -1 to indicate the end of the string
      Returns:
      a newly allocated copy of the requested substring. Free with free(MemorySegment) when no longer needed.
      Since:
      2.30
    • utf8ToUcs4

      public static MemorySegment utf8ToUcs4(String str, int len, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) throws GErrorException

      Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4.

      A trailing nul character (U+0000) will be added to the string after the converted text.

      Parameters:
      str - a UTF-8 encoded string
      len - the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.
      itemsRead - location to store number of bytes read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.
      itemsWritten - location to store number of characters written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.
      Returns:
      a pointer to a newly allocated UCS-4 string. This value must be freed with free(MemorySegment).
      Throws:
      GErrorException - see GError
    • utf8ToUcs4Fast

      public static MemorySegment utf8ToUcs4Fast(String str, int len, @Nullable Out<Integer> itemsWritten)

      Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input.

      This function is roughly twice as fast as utf8ToUcs4(String, int, Out, Out) but does no error checking on the input. A trailing nul character (U+0000) will be added to the string after the converted text.

      Parameters:
      str - a UTF-8 encoded string
      len - the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.
      itemsWritten - location to store the number of characters in the result, or NULL.
      Returns:
      a pointer to a newly allocated UCS-4 string. This value must be freed with free(MemorySegment).
    • utf8ToUtf16

      public static MemorySegment utf8ToUtf16(String str, int len, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) throws GErrorException

      Convert a string from UTF-8 to UTF-16.

      A nul character (U+0000) will be added to the result after the converted text.

      Parameters:
      str - a UTF-8 encoded string
      len - the maximum length (number of bytes) of str to use. If len is negative, then the string is nul-terminated.
      itemsRead - location to store number of bytes read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.
      itemsWritten - location to store number of gunichar2 written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.
      Returns:
      a pointer to a newly allocated UTF-16 string. This value must be freed with free(MemorySegment).
      Throws:
      GErrorException - see GError
    • utf8TruncateMiddle

      public static String utf8TruncateMiddle(String string, long truncateLength)

      Cuts off the middle of the string, preserving half of truncateLength characters at the beginning and half at the end.

      If string is already short enough, this returns a copy of string. If truncateLength is 0, an empty string is returned.

      Parameters:
      string - a nul-terminated UTF-8 encoded string
      truncateLength - the new size of string, in characters, including the ellipsis character
      Returns:
      a newly-allocated copy of string ellipsized in the middle
      Since:
      2.78
    • utf8Validate

      public static boolean utf8Validate(@Nullable byte @Nullable [] str, @Nullable Out<byte[]> end)

      Validates UTF-8 encoded text.

      str is the text to validate; if str is nul-terminated, then maxLen can be -1, otherwise maxLen should be the number of bytes to validate.

      If end is non-NULL, then the end of the valid range will be stored there. This is the first byte of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise — either the trailing nul byte, or the first byte beyond maxLen (if it’s positive).

      Note that g_utf8_validate() returns FALSE if maxLen is positive and any of the maxLen bytes are nul.

      Returns TRUE if all of str was valid. Many GLib and GTK routines require valid UTF-8 as input; so data read from a file or the network should be checked with g_utf8_validate() before doing anything else with it.

      Parameters:
      str - a pointer to character data
      end - return location for end of valid data
      Returns:
      TRUE if the text was valid UTF-8
    • utf8ValidateLen

      public static boolean utf8ValidateLen(@Nullable byte @Nullable [] str, @Nullable Out<byte[]> end)

      Validates UTF-8 encoded text.

      As with utf8Validate(byte[], Out), but maxLen must be set, and hence this function will always return FALSE if any of the bytes of str are nul.

      Parameters:
      str - a pointer to character data
      end - return location for end of valid data
      Returns:
      TRUE if the text was valid UTF-8
      Since:
      2.60
    • utime

      public static int utime(String filename, @Nullable MemorySegment utb)

      A wrapper for the POSIX utime() function. The utime() function sets the access and modification timestamps of a file.

      See your C library manual for more details about how utime() works on your system.

      Parameters:
      filename - a pathname in the GLib file name encoding (UTF-8 on Windows)
      utb - a pointer to a struct utimbuf.
      Returns:
      0 if the operation was successful, -1 if an error occurred
      Since:
      2.18
    • uuidStringIsValid

      public static boolean uuidStringIsValid(String str)

      Parses the string str and verify if it is a UUID.

      The function accepts the following syntax:

      • simple forms (e.g. f81d4fae-7dec-11d0-a765-00a0c91e6bf6)

      Note that hyphens are required within the UUID string itself, as per the aforementioned RFC.

      Parameters:
      str - a string representing a UUID
      Returns:
      true if str is a valid UUID, false otherwise.
      Since:
      2.52
    • uuidStringRandom

      public static String uuidStringRandom()
      Generates a random UUID (RFC 4122 version 4) as a string. It has the same randomness guarantees as GRand, so must not be used for cryptographic purposes such as key generation, nonces, salts or one-time pads.
      Returns:
      A string that should be freed with g_free().
      Since:
      2.52
    • variantGetGtype

      public static Type variantGetGtype()
    • warnMessage

      public static void warnMessage(@Nullable String domain, String file, int line, String func, @Nullable String warnexpr)
      Internal function used to print messages from the public GLib.warnIfReached and GLib.warnIfFail macros.
      Parameters:
      domain - log domain
      file - file containing the warning
      line - line number of the warning
      func - function containing the warning
      warnexpr - expression which failed
    • abort

      public static void abort()

      A wrapper for the POSIX abort() function.

      On Windows it is a function that makes extra effort (including a call to abort()) to ensure that a debugger-catchable exception is thrown before the program terminates.

      See your C library manual for more details about abort().

      Since:
      2.50
    • win32GetSystemDataDirsForModule

      public static String[] win32GetSystemDataDirsForModule(@Nullable MemorySegment addressOfFunction)
    • idleAddOnce

      public static int idleAddOnce(SourceOnceFunc function)

      Adds a function to be called whenever there are no higher priority events pending to the default main loop. The function is given the default idle priority, GLib.PRIORITY_DEFAULT_IDLE.

      The function will only be called once and then the source will be automatically removed from the main context.

      This function otherwise behaves like idleAdd(int, SourceFunc).

      Parameters:
      function - function to call
      Returns:
      the ID (greater than 0) of the event source
    • timeoutAddOnce

      public static int timeoutAddOnce(int interval, SourceOnceFunc function)

      Sets a function to be called after interval milliseconds have elapsed, with the default priority, GLib.PRIORITY_DEFAULT.

      The given function is called once and then the source will be automatically removed from the main context.

      This function otherwise behaves like timeoutAdd(int, int, SourceFunc).

      Parameters:
      interval - the time after which the function will be called, in milliseconds (1/1000ths of a second)
      function - function to call
      Returns:
      the ID (greater than 0) of the event source
    • timeoutAddSecondsOnce

      public static int timeoutAddSecondsOnce(int interval, SourceOnceFunc function)
      This function behaves like timeoutAddOnce(int, SourceOnceFunc) but with a range in seconds.
      Parameters:
      interval - the time after which the function will be called, in seconds
      function - function to call
      Returns:
      the ID (greater than 0) of the event source