Class GLib
-
Field Summary
Modifier and TypeFieldDescriptionstatic final int
static final int
static final int
static final int
static final int
static final int
static final int
A good size for a buffer to be passed intoasciiDtostr(java.lang.String, int, double)
.static final int
Evaluates to the initial reference count forgatomicrefcount
.static final int
Specifies one of the possible types of byte order.static final int
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.static final String
The set of lowercase ASCII alphabet characters.static final String
The set of uppercase ASCII alphabet characters.static final String
The set of ASCII digits.static final int
A bitmask that restricts the possible flags passed to g_datalist_set_flags().static final int
Represents an invalidGDateDay
.static final int
Represents an invalid Julian day number.static final int
Represents an invalid year.static final int
The directory separator character.static final String
The directory separator as a string.static final double
The base of natural logarithms.static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final String
Expands to "" on all modern compilers, and to __FUNCTION__ on gcc version 2.x.static final String
Expands to "" on all modern compilers, and to __PRETTY_FUNCTION__ on gcc version 2.x.static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final int
static final int
static final int
Defined to 1 if gcc-style visibility handling is supported.static final int
static final int
static final int
The position of the first bit which is not reserved for internal use be theGHook
implementation, i.e.static final int
The bias by which exponents in double-precision floats are offset.static final int
The bias by which exponents in single-precision floats are offset.static final String
The name of the main group of a desktop entry file, as defined in the Desktop Entry Specification.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string list giving the available application actions.static final String
A key underG_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.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the tooltip for the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean set to true if the application is D-Bus activatable.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the command line to execute.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the generic name of the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the desktop entry has been deleted by the user.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the name of the icon to be displayed for the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings giving the MIME types supported by this desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the specific name of the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the desktop entry should be shown in menus.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings identifying the environments that should not display the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings identifying the environments that should display the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string containing the working directory to run the program in.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification.static final String
A key underG_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.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the program should be run in a terminal window.static final String
A key underG_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.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the type of the desktop entry.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the URL to access.static final String
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file.static final String
The value of theG_KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing applications.static final String
The value of theG_KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing directories.static final String
The value of theG_KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing links to documents.static final int
Specifies one of the possible types of byte order.static final double
The natural logarithm of 10.static final double
The natural logarithm of 2.static final double
Multiplying the base 2 exponent by this number yields the base 10 exponent.static final byte
Defines the log domain.static final int
GLib log levels that are considered fatal by default.static final int
Log levels below1<<G_LOG_LEVEL_USER_SHIFT
are used by GLib.static final int
static final int
The major version number of the GLib library.static final short
static final int
static final long
static final byte
static final short
static final int
static final long
static final byte
static final int
The micro version number of the GLib library.static final short
The minimum value which can be held in agint16
.static final int
The minimum value which can be held in agint32
.static final long
The minimum value which can be held in agint64
.static final byte
The minimum value which can be held in agint8
.static final int
The minor version number of the GLib library.static final String
static final String
If a long option in the main group has this name, it is not treated as a regular option.static final int
Specifies one of the possible types of byte order (currently unused).static final double
The value of pi (ratio of circle's circumference to its diameter).static final double
Pi divided by 2.static final double
Pi divided by 4.static final String
A format specifier that can be used in printf()-style format strings when printing aGPid
.static final String
A format specifier that can be used in printf()-style format strings when printing thefd
member of aGPollFD
.static final int
Use this for default priority event sources.static final int
Use this for default priority idle functions.static final int
Use this for high priority event sources.static final int
Use this for high priority idle functions.static final int
Use this for very low priority background tasks.static final int
Evaluates to the initial reference count forgrefcount
.static final int
The search path separator character.static final String
The search path separator as a string.static final int
static final int
static final int
static final int
static final boolean
Use this macro as the return value of aGLib.SourceFunc
to leave theGLib.Source
in the main loop.static final boolean
Use this macro as the return value of aGLib.SourceFunc
to remove theGLib.Source
from the main loop.static final double
The square root of two.static final String
The standard delimiters, used instrdelimit(java.lang.String, java.lang.String, byte)
.static final int
static final int
static final int
static final int
static final int
static final int
static final String
Creates a unique temporary directory for each unit test and uses g_set_user_dirs() to set XDG directories to point into subdirectories of it for the duration of the unit test.static final long
Evaluates to a time span of one day.static final long
Evaluates to a time span of one hour.static final long
Evaluates to a time span of one millisecond.static final long
Evaluates to a time span of one minute.static final long
Evaluates to a time span of one second.static final int
The maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.static final String
Generic delimiters characters as defined in RFC 3986.static final String
Subcomponent delimiter characters as defined in RFC 3986.static final int
Number of microseconds in one second (1 million).static final int
static final int
A macro that should be defined by the user prior to including the glib.h header.static final int
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
abort()
A wrapper for the POSIX abort() function.static int
A wrapper for the POSIX access() function.static 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.static 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.static void
alignedFree
(@Nullable MemorySegment mem) Frees the memory allocated by g_aligned_alloc().static void
alignedFreeSized
(@Nullable MemorySegment mem, long alignment, long size) Frees the memory pointed to bymem
, assuming it is has the givensize
andalignment
.static int
asciiDigitValue
(byte c) Determines the numeric value of a character as a decimal digit.static String
asciiDtostr
(String buffer, int bufLen, double d) Converts agdouble
to a string, using the '.' as decimal point.static String
asciiFormatd
(String buffer, int bufLen, String format, double d) Converts agdouble
to a string, using the '.' as decimal point.static int
asciiStrcasecmp
(String s1, String s2) Compare two strings, ignoring the case of ASCII characters.static String
asciiStrdown
(String str, long len) Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly matchasciiTolower(byte)
.static boolean
asciiStringToSigned
(String str, int base, long min, long max, @Nullable Out<Long> outNum) A convenience function for converting a string to a signed number.static boolean
asciiStringToUnsigned
(String str, int base, long min, long max, @Nullable Out<Long> outNum) A convenience function for converting a string to an unsigned number.static int
asciiStrncasecmp
(String s1, String s2, long n) Compares1
ands2
, ignoring the case of ASCII characters and any characters after the firstn
in each string.static double
asciiStrtod
(String nptr, @Nullable Out<String> endptr) Converts a string to a floating point value.static long
asciiStrtoll
(String nptr, @Nullable Out<String> endptr, int base) Converts a string to agint64
value.static long
asciiStrtoull
(String nptr, @Nullable Out<String> endptr, int base) Converts a string to aguint64
value.static String
asciiStrup
(String str, long len) Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly matchasciiToupper(byte)
.static byte
asciiTolower
(byte c) Convert a character to ASCII lower case.static byte
asciiToupper
(byte c) Convert a character to ASCII upper case.static int
asciiXdigitValue
(byte c) Determines the numeric value of a character as a hexadecimal digit.static void
assertionMessage
(String domain, String file, int line, String func, String message) static void
assertionMessageCmpint
(String domain, String file, int line, String func, String expr, long arg1, String cmp, long arg2, byte numtype) static void
assertionMessageCmpnum
(String domain, String file, int line, String func, String expr, double arg1, String cmp, double arg2, byte numtype) static void
assertionMessageCmpstr
(String domain, String file, int line, String func, String expr, String arg1, String cmp, String arg2) static void
assertionMessageCmpstrv
(String domain, String file, int line, String func, String expr, String arg1, String arg2, long firstWrongIdx) static void
assertionMessageError
(String domain, String file, int line, String func, String expr, GError error, Quark errorDomain, int errorCode) 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.static void
assertWarning
(String logDomain, String file, int line, String prettyFunction, String expression) static void
Deprecated.It is best to avoid g_atexit().static int
atomicIntAdd
(MemorySegment atomic, int val) Atomically addsval
to the value ofatomic
.static int
atomicIntAnd
(MemorySegment atomic, int val) Performs an atomic bitwise 'and' of the value ofatomic
andval
, storing the result back inatomic
.static boolean
atomicIntCompareAndExchange
(MemorySegment atomic, int oldval, int newval) Comparesatomic
tooldval
and, if equal, sets it tonewval
.static boolean
atomicIntCompareAndExchangeFull
(MemorySegment atomic, int oldval, int newval, Out<Integer> preval) Comparesatomic
tooldval
and, if equal, sets it tonewval
.static boolean
atomicIntDecAndTest
(MemorySegment atomic) Decrements the value ofatomic
by 1.static int
atomicIntExchange
(MemorySegment atomic, int newval) Sets theatomic
tonewval
and returns the old value fromatomic
.static int
atomicIntExchangeAndAdd
(MemorySegment atomic, int val) Deprecated.Use g_atomic_int_add() instead.static int
atomicIntGet
(MemorySegment atomic) Gets the current value ofatomic
.static void
atomicIntInc
(MemorySegment atomic) Increments the value ofatomic
by 1.static int
atomicIntOr
(MemorySegment atomic, int val) Performs an atomic bitwise 'or' of the value ofatomic
andval
, storing the result back inatomic
.static void
atomicIntSet
(MemorySegment atomic, int newval) Sets the value ofatomic
tonewval
.static int
atomicIntXor
(MemorySegment atomic, int val) Performs an atomic bitwise 'xor' of the value ofatomic
andval
, storing the result back inatomic
.static long
atomicPointerAdd
(MemorySegment atomic, long val) Atomically addsval
to the value ofatomic
.static long
atomicPointerAnd
(MemorySegment atomic, long val) Performs an atomic bitwise 'and' of the value ofatomic
andval
, storing the result back inatomic
.static boolean
atomicPointerCompareAndExchange
(MemorySegment atomic, @Nullable MemorySegment oldval, @Nullable MemorySegment newval) Comparesatomic
tooldval
and, if equal, sets it tonewval
.static boolean
atomicPointerCompareAndExchangeFull
(MemorySegment atomic, @Nullable MemorySegment oldval, @Nullable MemorySegment newval, Out<MemorySegment> preval) Comparesatomic
tooldval
and, if equal, sets it tonewval
.static MemorySegment
atomicPointerExchange
(@Nullable MemorySegment atomic, @Nullable MemorySegment newval) Sets theatomic
tonewval
and returns the old value fromatomic
.static MemorySegment
atomicPointerGet
(MemorySegment atomic) Gets the current value ofatomic
.static long
atomicPointerOr
(MemorySegment atomic, long val) Performs an atomic bitwise 'or' of the value ofatomic
andval
, storing the result back inatomic
.static void
atomicPointerSet
(MemorySegment atomic, @Nullable MemorySegment newval) Sets the value ofatomic
tonewval
.static long
atomicPointerXor
(MemorySegment atomic, long val) Performs an atomic bitwise 'xor' of the value ofatomic
andval
, storing the result back inatomic
.static MemorySegment
atomicRcBoxAcquire
(MemorySegment memBlock) Atomically acquires a reference on the data pointed bymemBlock
.static MemorySegment
atomicRcBoxAlloc
(long blockSize) AllocatesblockSize
bytes of memory, and adds atomic reference counting semantics to it.static MemorySegment
atomicRcBoxAlloc0
(long blockSize) AllocatesblockSize
bytes of memory, and adds atomic reference counting semantics to it.static MemorySegment
atomicRcBoxDup
(long blockSize, MemorySegment memBlock) Allocates a new block of data with atomic reference counting semantics, and copiesblockSize
bytes ofmemBlock
into it.static long
atomicRcBoxGetSize
(MemorySegment memBlock) Retrieves the size of the reference counted data pointed bymemBlock
.static void
atomicRcBoxRelease
(MemorySegment memBlock) Atomically releases a reference on the data pointed bymemBlock
.static void
atomicRcBoxReleaseFull
(MemorySegment memBlock) Atomically releases a reference on the data pointed bymemBlock
.static boolean
atomicRefCountCompare
(MemorySegment arc, int val) Atomically compares the current value ofarc
withval
.static boolean
Atomically decreases the reference count.static void
Atomically increases the reference count.static void
Initializes a reference count variable to 1.static byte[]
base64Decode
(String text) Decode a sequence of Base-64 encoded text into binary data.static MemorySegment
base64DecodeInplace
(Out<byte[]> text) Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.static long
base64DecodeStep
(byte[] in, byte[] out, Out<Integer> state, Out<Integer> save) Incrementally decode a sequence of binary data from its Base-64 stringified representation.static String
base64Encode
(@org.jetbrains.annotations.Nullable byte[] data) Encode a sequence of binary data into its Base-64 stringified representation.static long
base64EncodeClose
(boolean breakLines, byte[] out, Out<Integer> state, Out<Integer> save) Flush the status from a sequence of calls to g_base64_encode_step().static long
base64EncodeStep
(byte[] in, boolean breakLines, byte[] out, Out<Integer> state, Out<Integer> save) Incrementally encode a sequence of binary data into its Base-64 stringified representation.static String
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.static void
bitLock
(MemorySegment address, int lockBit) Sets the indicatedlockBit
inaddress
.static int
bitNthLsf
(int mask, int nthBit) Find the position of the first bit set inmask
, searching from (but not including)nthBit
upwards.static int
bitNthMsf
(int mask, int nthBit) Find the position of the first bit set inmask
, searching from (but not including)nthBit
downwards.static int
bitStorage
(int number) Gets the number of bits used to holdnumber
, e.g.static boolean
bitTrylock
(MemorySegment address, int lockBit) Sets the indicatedlockBit
inaddress
, returningtrue
if successful.static void
bitUnlock
(MemorySegment address, int lockBit) Clears the indicatedlockBit
inaddress
.static void
static String
buildFilename
(String firstElement, Object... varargs) Creates a filename from a series of elements using the correct separator for the current platform.static String
buildFilenamev
(String[] args) Creates a filename from a vector of elements using the correct separator for the current platform.static String
Creates a path from a series of elements usingseparator
as the separator between elements.static String
buildPathv
(String separator, String[] args) Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of variadic arguments.static String
canonicalizeFilename
(String filename, @Nullable String relativeTo) Gets the canonical file name fromfilename
.static int
A wrapper for the POSIX chdir() function.static String
checkVersion
(int requiredMajor, int requiredMinor, int requiredMicro) Checks that the GLib library in use is compatible with the given version.static int
childWatchAdd
(int priority, Pid pid, ChildWatchFunc function) Sets a function to be called when the child indicated bypid
exits, at the prioritypriority
.static Source
childWatchSourceNew
(Pid pid) Creates a new child_watch source.static int
A wrapper for the POSIX chmod() function.static void
clearHandleId
(MemorySegment tagPtr, ClearHandleFunc clearFunc) Clears a numeric handler, such as aGSource
ID.static void
clearList
(List<MemorySegment>[] listPtr) Clears a pointer to aGList
, freeing it and, optionally, freeing its elements usingdestroy
.static void
clearPointer
(Out<MemorySegment> pp) Clears a reference to a variable.static void
clearSlist
(SList<MemorySegment>[] slistPtr) Clears a pointer to aGSList
, freeing it and, optionally, freeing its elements usingdestroy
.static boolean
close
(int fd) This wraps the close() call.static int
closefrom
(int lowfd) Close every file descriptor equal to or greater thanlowfd
.static String
computeChecksumForBytes
(ChecksumType checksumType, Bytes data) Computes the checksum for a binarydata
.static String
computeChecksumForData
(ChecksumType checksumType, byte[] data) Computes the checksum for a binarydata
oflength
.static String
computeChecksumForString
(ChecksumType checksumType, String str, long length) Computes the checksum of a string.static String
computeHmacForBytes
(ChecksumType digestType, Bytes key, Bytes data) Computes the HMAC for a binarydata
.static String
computeHmacForData
(ChecksumType digestType, byte[] key, byte[] data) Computes the HMAC for a binarydata
oflength
.static String
computeHmacForString
(ChecksumType digestType, byte[] key, String str, long length) Computes the HMAC for a string.static byte[]
Converts a string from one character set to another.static Quark
static byte[]
convertWithFallback
(byte[] str, String toCodeset, String fromCodeset, String fallback, @Nullable Out<Long> bytesRead) Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output.static byte[]
convertWithIconv
(byte[] str, IConv converter, @Nullable Out<Long> bytesRead) Converts a string from one character set to another.static int
A wrapper for the POSIX creat() function.static void
datalistClear
(Data[] datalist) Frees all the data elements of the datalist.static void
datalistForeach
(Data[] datalist, DataForeachFunc func) Calls the given function for each data element of the datalist.static MemorySegment
datalistGetData
(Data[] datalist, String key) Gets a data element, using its string identifier.static int
datalistGetFlags
(Data[] datalist) Gets flags values packed in together with the datalist.static 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.static MemorySegment
datalistIdGetData
(Data[] datalist, Quark keyId) Retrieves the data element corresponding tokeyId
.static void
datalistIdRemoveMultiple
(Data[] datalist, Quark[] keys) Removes multiple keys from a datalist.static MemorySegment
datalistIdRemoveNoNotify
(Data[] datalist, Quark keyId) Removes an element, without calling its destroy notification function.static boolean
datalistIdReplaceData
(Data[] datalist, Quark keyId, @Nullable MemorySegment oldval, @Nullable MemorySegment newval, @Nullable Out<DestroyNotify> oldDestroy) Compares the member that is associated withkeyId
indatalist
tooldval
, and if they are the same, replaceoldval
withnewval
.static void
datalistIdSetDataFull
(Data[] datalist, Quark keyId, @Nullable MemorySegment data) Sets the data corresponding to the givenGQuark
id, and the function to be called when the element is removed from the datalist.static void
datalistInit
(Data[] datalist) Resets the datalist tonull
.static void
datalistSetFlags
(Data[] datalist, int flags) Turns on flag values for a data list.static void
datalistUnsetFlags
(Data[] datalist, int flags) Turns off flag values for a data list.static void
datasetDestroy
(MemorySegment datasetLocation) Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.static void
datasetForeach
(MemorySegment datasetLocation, DataForeachFunc func) Calls the given function for each data element which is associated with the given location.static MemorySegment
datasetIdGetData
(MemorySegment datasetLocation, Quark keyId) Gets the data element corresponding to aGQuark
.static MemorySegment
datasetIdRemoveNoNotify
(MemorySegment datasetLocation, Quark keyId) Removes an element, without calling its destroy notification function.static void
datasetIdSetDataFull
(MemorySegment datasetLocation, Quark keyId, @Nullable MemorySegment data) Sets the data element associated with the givenGQuark
id, and also the function to call when the data element is destroyed.static String
This is a variant of g_dgettext() that allows specifying a locale category instead of always usingLC_MESSAGES
.static String
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.static boolean
directEqual
(@Nullable MemorySegment v1, @Nullable MemorySegment v2) Compares twogpointer
arguments and returnstrue
if they are equal.static int
directHash
(@Nullable MemorySegment v) Converts a gpointer to a hash value.static String
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.static boolean
doubleEqual
(MemorySegment v1, MemorySegment v2) Compares the twogdouble
values being pointed to and returnstrue
if they are equal.static int
Converts a pointer to agdouble
to a hash value.static String
This function is a variant of g_dgettext() which supports a disambiguating message context.static String
dpgettext2
(@Nullable String domain, String context, String msgid) This function is a variant of g_dgettext() which supports a disambiguating message context.static String
environGetenv
(@Nullable String[] envp, String variable) Returns the value of the environment variablevariable
in the provided listenvp
.static String[]
environSetenv
(@Nullable String[] envp, String variable, String value, boolean overwrite) Sets the environment variablevariable
in the provided listenvp
tovalue
.static String[]
environUnsetenv
(@Nullable String[] envp, String variable) Removes the environment variablevariable
from the provided environmentenvp
.static int
fdwalkSetCloexec
(int lowfd) Mark every file descriptor equal to or greater thanlowfd
to be closed at the nextexecve()
or similar, as if via theFD_CLOEXEC
flag.static FileError
fileErrorFromErrno
(int errNo) Gets aGFileError
constant based on the passed-inerrNo
.static Quark
static boolean
fileGetContents
(String filename, Out<byte[]> contents) Reads an entire file into allocated memory, with good error checking.static String
filenameDisplayBasename
(String filename) Returns the display basename for the particular filename, guaranteed to be valid UTF-8.static String
filenameDisplayName
(String filename) Converts a filename into a valid UTF-8 string.static String
filenameFromUri
(String uri, @Nullable Out<String> hostname) Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.static String
filenameFromUtf8
(String utf8string, long len, @Nullable Out<Long> bytesRead, @Nullable Out<Long> bytesWritten) Converts a string from UTF-8 to the encoding GLib uses for filenames.static String
filenameToUri
(String filename, @Nullable String hostname) Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3.static String
filenameToUtf8
(String opsysstring, long len, @Nullable Out<Long> bytesRead, @Nullable Out<Long> bytesWritten) Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string.static int
fileOpenTmp
(@Nullable String tmpl, Out<String> nameUsed) Opens a file for writing in the preferred directory for temporary files (as returned by g_get_tmp_dir()).static String
fileReadLink
(String filename) Reads the contents of the symbolic linkfilename
like the POSIXreadlink()
function.static boolean
fileSetContents
(String filename, byte[] contents) Writes all ofcontents
to a file namedfilename
.static boolean
fileSetContentsFull
(String filename, byte[] contents, Set<FileSetContentsFlags> flags, int mode) Writes all ofcontents
to a file namedfilename
, with good error checking.static boolean
fileSetContentsFull
(String filename, byte[] contents, FileSetContentsFlags flags, int mode) Writes all ofcontents
to a file namedfilename
, with good error checking.static boolean
Returnstrue
if any of the tests in the bitfieldtest
aretrue
.static boolean
Returnstrue
if any of the tests in the bitfieldtest
aretrue
.static String
findProgramInPath
(String program) Locates the first executable namedprogram
in the user's path, in the same way that execvp() would locate it.static MemorySegment
A wrapper for the stdiofopen()
function.static String
formatSize
(long size) Formats a size (for example the size of a file) into a human readable string.static String
formatSizeForDisplay
(long size) Deprecated.This function is broken due to its use of SI suffixes to denote IEC units.static String
formatSizeFull
(long size, Set<FormatSizeFlags> flags) Formats a size.static String
formatSizeFull
(long size, FormatSizeFlags... flags) Formats a size.static int
fprintf
(MemorySegment file, String format, Object... varargs) An implementation of the standardfprintf()
function which supports positional parameters, as specified in the Single Unix Specification.static void
free
(@Nullable MemorySegment mem) Frees the memory pointed to bymem
.static void
freeSized
(@Nullable MemorySegment mem, long size) Frees the memory pointed to bymem
, assuming it is has the givensize
.static MemorySegment
freopen
(String filename, String mode, @Nullable MemorySegment stream) A wrapper for the POSIX freopen() function.static int
fsync
(int fd) A wrapper for the POSIXfsync()
function.static String
Gets a human-readable name for the application, as set by g_set_application_name().static boolean
getCharset
(@Nullable Out<String> charset) Obtains the character set for the [current locale][setlocale]; you might use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding.static String
Gets the character set for the current locale.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.static String
Gets the current directory.static void
getCurrentTime
(TimeVal result) Deprecated.GTimeVal
is not year-2038-safe.static String
Returns the value of an environment variable.static String[]
Gets the list of environment variables for the current process.static boolean
getFilenameCharsets
(String[] filenameCharsets) Determines the preferred character sets used for filenames.static String
Gets the current user's home directory.static String
Return a name for the machine.static String[]
Computes a list of applicable locale names, which can be used to e.g.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.static String[]
getLocaleVariants
(String locale) Returns a list of derived variants oflocale
, which can be used to e.g.static long
Queries the system monotonic time.static int
Determine the approximate number of threads that the system will schedule simultaneously for this process.static String
Get information about the operating system.static String
Gets the name of the program.static String
Gets the real name of the user.static long
Queries the system wall-clock time.static String[]
Returns an ordered list of base directories in which to access system-wide configuration information.static String[]
Returns an ordered list of base directories in which to access system-wide application data.static String
Gets the directory to use for temporary files.static String
Returns a base directory in which to store non-essential, cached data specific to particular user.static String
Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.static String
Returns a base directory in which to access application data such as icons that is customized for a particular user.static String
Gets the user name of the current user.static String
Returns a directory that is unique to the current user on the local system.static String
getUserSpecialDir
(UserDirectory directory) Returns the full path of a special directory using its logical id.static String
Returns a base directory in which to store state files specific to particular user.static boolean
hostnameIsAsciiEncoded
(String hostname) Tests ifhostname
contains segments with an ASCII-compatible encoding of an Internationalized Domain Name.static boolean
hostnameIsIpAddress
(String hostname) Tests ifhostname
is the string form of an IPv4 or IPv6 address.static boolean
hostnameIsNonAscii
(String hostname) Tests ifhostname
contains Unicode characters.static String
hostnameToAscii
(String hostname) Convertshostname
to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.static String
hostnameToUnicode
(String hostname) Convertshostname
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.static long
iconv
(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.static int
idleAdd
(int priority, SourceFunc function) Adds a function to be called whenever there are no higher priority events pending.static int
idleAddOnce
(SourceOnceFunc function) Adds a function to be called whenever there are no higher priority events pending to the default main loop.static boolean
idleRemoveByData
(@Nullable MemorySegment data) Removes the idle function with the given data.static Source
Creates a new idle source.static boolean
int64Equal
(MemorySegment v1, MemorySegment v2) Compares the twogint64
values being pointed to and returnstrue
if they are equal.static int
Converts a pointer to agint64
to a hash value.static boolean
intEqual
(MemorySegment v1, MemorySegment v2) Compares the twogint
values being pointed to and returnstrue
if they are equal.static String
internStaticString
(@Nullable String string) Returns a canonical representation forstring
.static String
internString
(@Nullable String string) Returns a canonical representation forstring
.static int
Converts a pointer to agint
to a hash value.static int
ioAddWatch
(IOChannel channel, int priority, Set<IOCondition> condition, IOFunc func) Adds theGIOChannel
into the default main loop context with the given priority.static int
ioAddWatch
(IOChannel channel, int priority, IOCondition condition, IOFunc func) Adds theGIOChannel
into the default main loop context with the given priority.static Source
ioCreateWatch
(IOChannel channel, Set<IOCondition> condition) Creates aGSource
that's dispatched whencondition
is met for the givenchannel
.static Source
ioCreateWatch
(IOChannel channel, IOCondition... condition) Creates aGSource
that's dispatched whencondition
is met for the givenchannel
.static void
static String[]
listenv()
Gets the names of all variables set in the environment.static byte[]
localeFromUtf8
(String utf8string, long len, @Nullable Out<Long> bytesRead) 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][setlocale].static String
localeToUtf8
(byte[] opsysstring, @Nullable Out<Long> bytesRead, @Nullable Out<Long> bytesWritten) 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][setlocale] into a UTF-8 string.static void
Logs an error or debugging message.static void
log
(@Nullable String logDomain, LogLevelFlags logLevel, String format, Object... varargs) Logs an error or debugging message.static void
logDefaultHandler
(@Nullable String logDomain, Set<LogLevelFlags> logLevel, @Nullable String message, @Nullable MemorySegment unusedData) The default log handler set up by GLib;logSetDefaultHandler(org.gnome.glib.LogFunc)
allows to install an alternate default log handler.static void
logDefaultHandler
(@Nullable String logDomain, LogLevelFlags logLevel, @Nullable String message, @Nullable MemorySegment unusedData) The default log handler set up by GLib;logSetDefaultHandler(org.gnome.glib.LogFunc)
allows to install an alternate default log handler.static boolean
Return whether debug output from the GLib logging system is enabled.static void
logRemoveHandler
(String logDomain, int handlerId) Removes the log handler.static Set
<LogLevelFlags> logSetAlwaysFatal
(Set<LogLevelFlags> fatalMask) Sets the message levels which are always fatal, in any log domain.static Set
<LogLevelFlags> logSetAlwaysFatal
(LogLevelFlags... fatalMask) Sets the message levels which are always fatal, in any log domain.static void
logSetDebugEnabled
(boolean enabled) Enable or disable debug output from the GLib logging system for all domains.static LogFunc
logSetDefaultHandler
(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.static Set
<LogLevelFlags> logSetFatalMask
(String logDomain, Set<LogLevelFlags> fatalMask) Sets the log levels which are fatal in the given domain.static Set
<LogLevelFlags> logSetFatalMask
(String logDomain, LogLevelFlags... fatalMask) Sets the log levels which are fatal in the given domain.static int
logSetHandler
(@Nullable String logDomain, Set<LogLevelFlags> logLevels, LogFunc logFunc) LikelogSetHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogFunc)
, but takes a destroy notify for theuserData
.static int
logSetHandler
(@Nullable String logDomain, LogLevelFlags logLevels, LogFunc logFunc) LikelogSetHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogFunc)
, but takes a destroy notify for theuserData
.static void
Set a writer function which will be called to format and write out each log message.static void
logStructured
(String logDomain, Set<LogLevelFlags> logLevel, Object... varargs) Log a message with structured data.static void
logStructured
(String logDomain, LogLevelFlags logLevel, Object... varargs) Log a message with structured data.static void
logStructuredArray
(Set<LogLevelFlags> logLevel, LogField[] fields) Log a message with structured data.static void
logStructuredArray
(LogLevelFlags logLevel, LogField[] fields) Log a message with structured data.static void
logStructuredStandard
(String logDomain, Set<LogLevelFlags> logLevel, String file, String line, String func, String messageFormat, Object... varargs) static void
logStructuredStandard
(String logDomain, LogLevelFlags logLevel, String file, String line, String func, String messageFormat, Object... varargs) static void
logVariant
(@Nullable String logDomain, Set<LogLevelFlags> logLevel, Variant fields) Log a message with structured data, accepting the data within aGLib.Variant
.static void
logVariant
(@Nullable String logDomain, LogLevelFlags logLevel, Variant fields) Log a message with structured data, accepting the data within aGLib.Variant
.static LogWriterOutput
logWriterDefault
(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and output it to the default log destination for the platform.static LogWriterOutput
logWriterDefault
(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and output it to the default log destination for the platform.static void
logWriterDefaultSetDebugDomains
(@Nullable String domains) Reset the list of domains to be logged, that might be initially set by theG_MESSAGES_DEBUG
environment variable.static void
logWriterDefaultSetUseStderr
(boolean useStderr) Configure whether the built-in log functions will output all log messages tostderr
.static boolean
logWriterDefaultWouldDrop
(Set<LogLevelFlags> logLevel, @Nullable String logDomain) Check whetherlogWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
andlogDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
would ignore a message with the given domain and level.static boolean
logWriterDefaultWouldDrop
(LogLevelFlags logLevel, @Nullable String logDomain) Check whetherlogWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
andlogDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
would ignore a message with the given domain and level.static String
logWriterFormatFields
(Set<LogLevelFlags> logLevel, LogField[] fields, boolean useColor) Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).static String
logWriterFormatFields
(LogLevelFlags logLevel, LogField[] fields, boolean useColor) Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).static boolean
logWriterIsJournald
(int outputFd) Check whether the givenoutputFd
file descriptor is a connection to the systemd journal, or something else (like a log file orstdout
orstderr
).static LogWriterOutput
logWriterJournald
(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and send it to the systemd journal as a set of key–value pairs.static LogWriterOutput
logWriterJournald
(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and send it to the systemd journal as a set of key–value pairs.static LogWriterOutput
logWriterStandardStreams
(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdout
orstderr
, depending on its log level.static LogWriterOutput
logWriterStandardStreams
(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdout
orstderr
, depending on its log level.static boolean
logWriterSupportsColor
(int outputFd) Check whether the givenoutputFd
file descriptor supports ANSI color escape sequences.static LogWriterOutput
logWriterSyslog
(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and send it to the syslog daemon.static LogWriterOutput
logWriterSyslog
(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and send it to the syslog daemon.static int
A wrapper for the POSIX lstat() function.static Source
Returns the currently firing source for this thread.static int
Returns the depth of the stack of calls toMainContext.dispatch()
on anyGMainContext
in the current thread.static MemorySegment
malloc
(long nBytes) AllocatesnBytes
bytes of memory.static MemorySegment
malloc0
(long nBytes) AllocatesnBytes
bytes of memory, initialized to 0's.static 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.static 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.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 theGMarkupParser
start_element function, dealing with common error conditions and supporting boolean values.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 theGMarkupParser
start_element function, dealing with common error conditions and supporting boolean values.static Quark
static String
markupEscapeText
(String text, long length) Escapes text so that the markup parser will parse it verbatim.static String
markupPrintfEscaped
(String format, Object... varargs) Formats arguments according toformat
, escaping all string and character arguments in the fashion of g_markup_escape_text().static MemorySegment
memdup
(@Nullable MemorySegment mem, int byteSize) Deprecated.Usememdup2(java.lang.foreign.MemorySegment, long)
instead, as it accepts a gsize argument forbyteSize
, avoiding the possibility of overflow in agsize
→guint
conversionstatic MemorySegment
memdup2
(@Nullable MemorySegment mem, long byteSize) AllocatesbyteSize
bytes of memory, and copiesbyteSize
bytes into it frommem
.static boolean
Deprecated.GLib always uses the system malloc, so this function always returnstrue
.static void
Deprecated.Use other memory profiling tools insteadstatic void
memSetVtable
(MemVTable vtable) Deprecated.This function now does nothing.static int
A wrapper for the POSIX mkdir() function.static int
mkdirWithParents
(String pathname, int mode) Create a directory if it doesn't already exist.static String
Creates a temporary directory.static String
mkdtempFull
(String tmpl, int mode) Creates a temporary directory.static int
Opens a temporary file.static int
mkstempFull
(String tmpl, int flags, int mode) Opens a temporary file.static void
nullifyPointer
(MemorySegment nullifyLocation) Set the pointer at the specified location tonull
.static Quark
static void
onErrorQuery
(String prgName) Prompts the user with[E]xit, [H]alt, show [S]tack trace or [P]roceed
.static void
onErrorStackTrace
(String prgName) Invokes gdb, which attaches to the current process and shows a stack trace.static int
A wrapper for the POSIX open() function.static Quark
static int
parseDebugString
(@Nullable String string, DebugKey[] keys) Parses a string containing debugging options into aguint
containing bit flags.static String
pathGetBasename
(String fileName) Gets the last component of the filename.static String
pathGetDirname
(String fileName) Gets the directory components of a file name.static boolean
pathIsAbsolute
(String fileName) Returnstrue
if the givenfileName
is an absolute file name.static String
pathSkipRoot
(String fileName) Returns a pointer intofileName
after the root component, i.e.static boolean
patternMatch
(PatternSpec pspec, int stringLength, String string, @Nullable String stringReversed) Deprecated.static boolean
patternMatchSimple
(String pattern, String string) Matches a string against a pattern given as a string.static boolean
patternMatchString
(PatternSpec pspec, String string) Deprecated.UsePatternSpec.matchString(java.lang.String)
insteadstatic void
pointerBitLock
(MemorySegment address, int lockBit) This is equivalent to g_bit_lock, but working on pointers (or other pointer-sized values).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).static MemorySegment
pointerBitLockMaskPtr
(@Nullable MemorySegment ptr, int lockBit, boolean set, long preserveMask, @Nullable MemorySegment preservePtr) This manglesptr
as g_pointer_bit_lock() and g_pointer_bit_unlock() do.static boolean
pointerBitTrylock
(MemorySegment address, int lockBit) This is equivalent to g_bit_trylock(), but working on pointers (or other pointer-sized values).static void
pointerBitUnlock
(MemorySegment address, int lockBit) This is equivalent to g_bit_unlock, but working on pointers (or other pointer-sized values).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.static int
Pollsfds
, as with the poll() system call, but portably.static void
prefixError
(@Nullable Out<GError> err, String format, Object... varargs) Formats a string according toformat
and prefix it to an existing error message.static void
prefixErrorLiteral
(@Nullable Out<GError> err, String prefix) Prefixesprefix
to an existing error message.static void
Outputs a formatted message via the print handler.static void
Outputs a formatted message via the error message handler.static int
An implementation of the standardprintf()
function which supports positional parameters, as specified in the Single Unix Specification.static void
propagateError
(@Nullable Out<GError> dest, GError src) Ifdest
isnull
, freesrc
; otherwise, movessrc
into *dest
.static void
propagatePrefixedError
(GError[] dest, GError src, String format, Object... varargs) Ifdest
isnull
, freesrc
; otherwise, movessrc
into *dest
.static void
qsortWithData
(MemorySegment pbase, int totalElems, long size, CompareDataFunc compareFunc) Deprecated.total_elems
is too small to represent larger arrays; usesortArray(java.lang.foreign.MemorySegment[], long, org.gnome.glib.CompareDataFunc, java.lang.foreign.MemorySegment)
insteadstatic Quark
quarkFromStaticString
(@Nullable String string) Gets theGQuark
identifying the given (static) string.static Quark
quarkFromString
(@Nullable String string) Gets theGQuark
identifying the given string.static String
quarkToString
(Quark quark) Gets the string associated with the givenGQuark
.static Quark
quarkTryString
(@Nullable String string) Gets theGQuark
associated with the given string, or 0 if string isnull
or it has no associatedGQuark
.static double
Returns a randomgdouble
equally distributed over the range [0..1).static double
randomDoubleRange
(double begin, double end) Returns a randomgdouble
equally distributed over the range [begin
..end
).static int
Return a randomguint32
equally distributed over the range [0..2^32-1].static int
randomIntRange
(int begin, int end) Returns a randomgint32
equally distributed over the rangeend-1
.static void
randomSetSeed
(int seed) Sets the seed for the global random number generator, which is used by the g_random_* functions, toseed
.static MemorySegment
rcBoxAcquire
(MemorySegment memBlock) Acquires a reference on the data pointed bymemBlock
.static MemorySegment
rcBoxAlloc
(long blockSize) AllocatesblockSize
bytes of memory, and adds reference counting semantics to it.static MemorySegment
rcBoxAlloc0
(long blockSize) AllocatesblockSize
bytes of memory, and adds reference counting semantics to it.static MemorySegment
rcBoxDup
(long blockSize, MemorySegment memBlock) Allocates a new block of data with reference counting semantics, and copiesblockSize
bytes ofmemBlock
into it.static long
rcBoxGetSize
(MemorySegment memBlock) Retrieves the size of the reference counted data pointed bymemBlock
.static void
rcBoxRelease
(MemorySegment memBlock) Releases a reference on the data pointed bymemBlock
.static void
rcBoxReleaseFull
(MemorySegment memBlock) Releases a reference on the data pointed bymemBlock
.static MemorySegment
realloc
(@Nullable MemorySegment mem, long nBytes) Reallocates the memory pointed to bymem
, so that it now has space fornBytes
bytes of memory.static 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.static boolean
refCountCompare
(MemorySegment rc, int val) Compares the current value ofrc
withval
.static boolean
Decreases the reference count.static void
Increases the reference count.static void
Initializes a reference count variable to 1.static String
refStringAcquire
(String str) Acquires a reference on a string.static long
refStringLength
(String str) Retrieves the length ofstr
.static String
refStringNew
(String str) Creates a new reference counted string and copies the contents ofstr
into it.static String
refStringNewIntern
(String str) Creates a new reference counted string and copies the content ofstr
into it.static String
refStringNewLen
(String str, long len) Creates a new reference counted string and copies the contents ofstr
into it, up tolen
bytes.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.static void
Resets the cache used for g_get_user_special_dir(), so that the latest on-disk version is used.static int
A wrapper for the POSIX remove() function.static int
A wrapper for the POSIX rename() function.static void
returnIfFailWarning
(@Nullable String logDomain, String prettyFunction, @Nullable String expression) Internal function used to print messages from the publicGLib#returnIfFail
andGLib#returnValIfFail
macros.static int
A wrapper for the POSIX rmdir() function.static void
setApplicationName
(String applicationName) Sets a human-readable name for the application.static boolean
Sets an environment variable.static void
Does nothing iferr
isnull
; iferr
is non-null
, then *err
must benull
.static void
setErrorLiteral
(@Nullable Out<GError> err, Quark domain, int code, String message) Does nothing iferr
isnull
; iferr
is non-null
, then *err
must benull
.static void
setPrgname
(String prgname) Sets the name of the program.static PrintFunc
setPrinterrHandler
(@Nullable PrintFunc func) Sets the handler for printing error messages tofunc
, or resets it to the default GLib handler ifNULL
.static PrintFunc
setPrintHandler
(@Nullable PrintFunc func) Sets the print handler tofunc
, or resets it to the default GLib handler ifNULL
.static Quark
static boolean
shellParseArgv
(String commandLine, @Nullable Out<String[]> argvp) 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.static String
shellQuote
(String unquotedString) Quotes a string so that the shell (/bin/sh) will interpret the quoted string to meanunquotedString
.static String
shellUnquote
(String quotedString) Unquotes a string as the shell (/bin/sh) would.static MemorySegment
sliceAlloc
(long blockSize) Allocates a block of memory from the libc allocator.static MemorySegment
sliceAlloc0
(long blockSize) Allocates a block of memory via g_slice_alloc() and initializes the returned memory to 0.static MemorySegment
sliceCopy
(long blockSize, @Nullable MemorySegment memBlock) Allocates a block of memory from the slice allocator and copiesblockSize
bytes into it frommemBlock
.static void
sliceFree1
(long blockSize, @Nullable MemorySegment memBlock) Frees a block of memory.static void
sliceFreeChainWithOffset
(long blockSize, @Nullable MemorySegment memChain, long nextOffset) Frees a linked list of memory blocks of structure typetype
.static long
sliceGetConfig
(SliceConfig ckey) static MemorySegment
sliceGetConfigState
(SliceConfig ckey, long address, MemorySegment nValues) static void
sliceSetConfig
(SliceConfig ckey, long value) static int
A safer form of the standard sprintf() function.static void
sortArray
(MemorySegment[] array, long elementSize, CompareDataFunc compareFunc, @Nullable MemorySegment userData) static int
spacedPrimesClosest
(int num) Gets the smallest prime number from a built-in array of primes which is larger thannum
.static boolean
spawnAsync
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid) Executes a child program asynchronously.static boolean
spawnAsync
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid) Executes a child program asynchronously.static boolean
spawnAsyncWithFds
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, int stdinFd, int stdoutFd, int stderrFd) Executes a child program asynchronously.static boolean
spawnAsyncWithFds
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, int stdinFd, int stdoutFd, int stderrFd) Executes a child program asynchronously.static boolean
spawnAsyncWithPipes
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, @Nullable Out<Integer> standardInput, @Nullable Out<Integer> standardOutput, @Nullable Out<Integer> standardError) Identical to g_spawn_async_with_pipes_and_fds() but withn_fds
set to zero, so no FD assignments are used.static boolean
spawnAsyncWithPipes
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid, @Nullable Out<Integer> standardInput, @Nullable Out<Integer> standardOutput, @Nullable Out<Integer> standardError) Identical to g_spawn_async_with_pipes_and_fds() but withn_fds
set to zero, so no FD assignments are used.static boolean
spawnAsyncWithPipesAndFds
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, int stdinFd, int stdoutFd, int stderrFd, @org.jetbrains.annotations.Nullable int[] sourceFds, @org.jetbrains.annotations.Nullable int[] targetFds, @Nullable Pid childPidOut, @Nullable Out<Integer> stdinPipeOut, @Nullable Out<Integer> stdoutPipeOut, @Nullable Out<Integer> stderrPipeOut) Executes a child program asynchronously (your program will not block waiting for the child to exit).static boolean
spawnAsyncWithPipesAndFds
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, int stdinFd, int stdoutFd, int stderrFd, @org.jetbrains.annotations.Nullable int[] sourceFds, @org.jetbrains.annotations.Nullable int[] targetFds, @Nullable Pid childPidOut, @Nullable Out<Integer> stdinPipeOut, @Nullable Out<Integer> stdoutPipeOut, @Nullable Out<Integer> stderrPipeOut) Executes a child program asynchronously (your program will not block waiting for the child to exit).static boolean
spawnCheckExitStatus
(int waitStatus) Deprecated.Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.static boolean
spawnCheckWaitStatus
(int waitStatus) Seterror
ifwaitStatus
indicates the child exited abnormally (e.g.static void
spawnClosePid
(Pid pid) On some platforms, notably Windows, theGPid
type represents a resource which must be closed to prevent resource leaking.static boolean
spawnCommandLineAsync
(String commandLine) A simple version of g_spawn_async() that parses a command line with g_shell_parse_argv() and passes it to g_spawn_async().static boolean
spawnCommandLineSync
(String commandLine, @org.jetbrains.annotations.Nullable byte[] standardOutput, @org.jetbrains.annotations.Nullable byte[] standardError, @Nullable Out<Integer> waitStatus) A simple version of g_spawn_sync() with little-used parameters removed, taking a command line instead of an argument vector.static Quark
static Quark
static boolean
spawnSync
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @org.jetbrains.annotations.Nullable byte[] standardOutput, @org.jetbrains.annotations.Nullable byte[] standardError, @Nullable Out<Integer> waitStatus) Executes a child synchronously (waits for the child to exit before returning).static boolean
spawnSync
(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @org.jetbrains.annotations.Nullable byte[] standardOutput, @org.jetbrains.annotations.Nullable byte[] standardError, @Nullable Out<Integer> waitStatus) Executes a child synchronously (waits for the child to exit before returning).static int
An implementation of the standardsprintf()
function which supports positional parameters, as specified in the Single Unix Specification.static int
A wrapper for the POSIX stat() function.static String
Copies a nul-terminated string into the destination buffer, including the trailing nul byte, and returns a pointer to the trailing nul byte indest
.static String
For each character instring
, if the character is not invalidChars
, replaces the character withsubstitutor
.static int
strcasecmp
(String s1, String s2) Deprecated.Seestrncasecmp(java.lang.String, java.lang.String, int)
for a discussion of why this function is deprecated and how to replace it.static String
Removes trailing whitespace from a string.static String
Removes leading whitespace from a string, by moving the rest of the characters forward.static int
Comparesstr1
andstr2
like strcmp().static String
strcompress
(String source) Makes a copy of a string replacing C string-style escape sequences with their one byte equivalent:\\b
→ U+0008 Backspace\\f
→ U+000C Form Feed\\n
→ U+000A Line Feed\\r
→ U+000D Carriage Return\\t
→ U+0009 Horizontal Tabulation\\v
→ U+000B Vertical Tabulation\\
followed by one to three octal digits → the numeric value (mod 255)\\
followed by any other character → the character as is.static String
Concatenates all of the given strings into one long string.static String
strdelimit
(String string, @Nullable String delimiters, byte newDelimiter) Converts any delimiter characters instring
tonewDelimiter
.static String
Deprecated.This function is totally broken for the reasons discussed in thestrncasecmp(java.lang.String, java.lang.String, int)
docs — useasciiStrdown(java.lang.String, long)
orutf8Strdown(java.lang.String, long)
instead.static String
Duplicates a string.static String
strdupPrintf
(String format, Object... varargs) Similar to the standard Csprintf()
function but safer, since it calculates the maximum space required and allocates memory to hold the result.static String[]
Copies an array of strings.static boolean
strEqual
(MemorySegment v1, MemorySegment v2) Compares two strings for byte-by-byte equality and returnstrue
if they are equal.static String
strerror
(int errnum) Returns a string corresponding to the given error code, e.g.static String
It replaces the following special characters in the stringsource
with their corresponding C escape sequence:static void
strfreev
(@Nullable MemorySegment strArray) Frees an array of strings, as well as each string it contains.static int
Converts a string to a hash value.static boolean
strHasPrefix
(String str, String prefix) Looks whether the stringstr
begins withprefix
.static boolean
strHasSuffix
(String str, String suffix) Looks whether a string ends withsuffix
.static String
stripContext
(String msgid, String msgval) An auxiliary function for gettext() support (see Q_()).static boolean
strIsAscii
(String str) Determines if a string is pure ASCII.static String
Joins a number of strings together to form one long string, with the optionalseparator
inserted between each of them.static String
Joins an array of strings together to form one long string, with the optionalseparator
inserted between each of them.static long
Portability wrapper that callsstrlcat()
on systems which have it, and emulates it otherwise.static long
Portability wrapper that callsstrlcpy()
on systems which have it, and emulatesstrlcpy()
otherwise.static boolean
strMatchString
(String searchTerm, String potentialHit, boolean acceptAlternates) Checks if a search conducted forsearchTerm
should matchpotentialHit
.static int
strncasecmp
(String s1, String s2, int n) Deprecated.The problem withg_strncasecmp()
is that it does the comparison by callingtoupper()
/tolower()
.static String
Duplicates the firstn
bytes of a string, returning a newly-allocated buffern
+ 1 bytes long which will always be nul-terminated.static String
strnfill
(long length, byte fillChar) Creates a new stringlength
bytes long filled withfillChar
.static String
strreverse
(String string) Reverses all of the bytes in a string.static String
Searches the stringhaystack
for the last occurrence of the stringneedle
.static String
strrstrLen
(String haystack, long haystackLen, String needle) Searches the stringhaystack
for the last occurrence of the stringneedle
, limiting the length of the search tohaystackLen
.static String
strsignal
(int signum) Returns a string describing the given signal, e.g.static String[]
Splits a string into a maximum ofmaxTokens
pieces, using the givendelimiter
.static String[]
strsplitSet
(String string, String delimiters, int maxTokens) Splitsstring
into a number of tokens not containing any of the characters indelimiters
.static String
Searches the stringhaystack
for the first occurrence of the stringneedle
, limiting the length of the search tohaystackLen
or a nul terminator byte (whichever is reached first).static String
strToAscii
(String str, @Nullable String fromLocale) Transliteratestr
to plain ASCII.static double
Converts a string to a floating point value.static String[]
strTokenizeAndFold
(String string, @Nullable String translitLocale, @Nullable String[] asciiAlternates) Tokenizesstring
and performs folding on each token.static String
Deprecated.This function is totally broken for the reasons discussed in thestrncasecmp(java.lang.String, java.lang.String, int)
docs — useasciiStrup(java.lang.String, long)
orutf8Strup(java.lang.String, long)
instead.static boolean
strvContains
(String[] strv, String str) Checks if an array of strings contains the stringstr
according tostrEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment)
.static boolean
Checks if two arrays of strings contain exactly the same elements in exactly the same order.static Type
static int
strvLength
(String[] strArray) Returns the length of an array of strings.static void
testAddDataFunc
(String testpath, @Nullable MemorySegment testData, TestDataFunc testFunc) Create a new test case, similar to g_test_create_case().static void
testAddDataFuncFull
(String testpath, @Nullable MemorySegment testData, TestDataFunc testFunc) Create a new test case, as with g_test_add_data_func(), but freeingtestData
after the test run is complete.static void
testAddFunc
(String testpath, TestFunc testFunc) Create a new test case, similar to g_test_create_case().static void
testAddVtable
(String testpath, long dataSize, @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) static void
testAssertExpectedMessagesInternal
(String domain, String file, int line, String func) static void
This function adds a message to test reports that associates a bug URI with a test case.static void
testBugBase
(String uriPattern) Specify the base URI for bug reports.static String
testBuildFilename
(TestFileType fileType, String firstPath, Object... varargs) Creates the pathname to a data file that is required for a test.static TestCase
testCreateCase
(String testName, long dataSize, @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) Create a newGTestCase
, namedtestName
.static TestSuite
testCreateSuite
(String suiteName) Create a new test suite with the namesuiteName
.static void
Attempt to disable system crash reporting infrastructure.static void
testExpectMessage
(@Nullable String logDomain, Set<LogLevelFlags> logLevel, String pattern) Indicates that a message with the givenlogDomain
andlogLevel
, with text matchingpattern
, is expected to be logged.static void
testExpectMessage
(@Nullable String logDomain, LogLevelFlags logLevel, String pattern) Indicates that a message with the givenlogDomain
andlogLevel
, with text matchingpattern
, is expected to be logged.static void
testFail()
Indicates that a test failed.static boolean
Returns whether a test has already failed.static void
testFailPrintf
(String format, Object... varargs) Equivalent to g_test_fail(), but also record a message like g_test_skip_printf().static String
testGetDir
(TestFileType fileType) Gets the pathname of the directory containing test files of the type specified byfileType
.static String
testGetFilename
(TestFileType fileType, String firstPath, Object... varargs) Gets the pathname to a data file that is required for a test.static String
Gets the test path for the test currently being run.static TestSuite
Get the toplevel test suite for the test path API.static void
testIncomplete
(@Nullable String msg) Indicates that a test failed because of some incomplete functionality.static void
testIncompletePrintf
(String format, Object... varargs) Equivalent to g_test_incomplete(), but the explanation is formatted as if by g_strdup_printf().static void
testInit
(MemorySegment argc, String[] argv, Object... varargs) Initialize the GLib testing framework, e.g.static void
testLogSetFatalHandler
(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.static String
testLogTypeName
(TestLogType logType) static void
testMaximizedResult
(double maximizedQuantity, String format, Object... varargs) Report the result of a performance or measurement test.static void
testMessage
(String format, Object... varargs) Add a message to the test report.static void
testMinimizedResult
(double minimizedQuantity, String format, Object... varargs) Report the result of a performance or measurement test.static void
testQueueDestroy
(@Nullable MemorySegment destroyData) Enqueues a callbackdestroyFunc
to be executed during the next test case teardown phase.static void
testQueueFree
(@Nullable MemorySegment gfreePointer) Enqueue a pointer to be released with g_free() during the next teardown phase.static double
Get a reproducible random floating point number, see g_test_rand_int() for details on test case random numbers.static double
testRandDoubleRange
(double rangeStart, double rangeEnd) Get a reproducible random floating pointer number out of a specified range, see g_test_rand_int() for details on test case random numbers.static int
Get a reproducible random integer number.static int
testRandIntRange
(int begin, int end) Get a reproducible random integer number out of a specified range, see g_test_rand_int() for details on test case random numbers.static int
testRun()
Runs all tests under the toplevel suite which can be retrieved with g_test_get_root().static int
testRunSuite
(TestSuite suite) Execute the tests withinsuite
and all nestedGTestSuites
.static void
Changes the behaviour of the variousg_assert_*()
macros, g_test_assert_expected_messages() and the variousg_test_trap_assert_*()
macros to not abort to program, but instead call g_test_fail() and continue.static void
Indicates that a test was skipped.static void
testSkipPrintf
(String format, Object... varargs) Equivalent to g_test_skip(), but the explanation is formatted as if by g_strdup_printf().static boolean
Returnstrue
(after g_test_init() has been called) if the test program is running under g_test_trap_subprocess().static void
testSummary
(String summary) Set the summary for a test, which describes what the test checks, and how it goes about checking it.static double
Get the number of seconds since the last start of the timer with g_test_timer_start().static double
Report the last result of g_test_timer_elapsed().static void
Start a timing test.static void
testTrapAssertions
(String domain, String file, int line, String func, long assertionFlags, String pattern) 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.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.static boolean
Check the result of the last g_test_trap_subprocess() call.static boolean
Check the result of the last g_test_trap_subprocess() call.static void
testTrapSubprocess
(@Nullable String testPath, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPath
in a subprocess.static void
testTrapSubprocess
(@Nullable String testPath, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPath
in a subprocess.static void
testTrapSubprocessWithEnvp
(@Nullable String testPath, @Nullable String[] envp, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPath
in a subprocess with the givenenvp
environment.static void
testTrapSubprocessWithEnvp
(@Nullable String testPath, @Nullable String[] envp, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPath
in a subprocess with the givenenvp
environment.static int
timeoutAdd
(int priority, int interval, SourceFunc function) Sets a function to be called at regular intervals, with the given priority.static int
timeoutAddOnce
(int interval, SourceOnceFunc function) Sets a function to be called afterinterval
milliseconds have elapsed, with the default priority,GLib.PRIORITY_DEFAULT
.static int
timeoutAddSeconds
(int priority, int interval, SourceFunc function) Sets a function to be called at regular intervals, withpriority
.static int
timeoutAddSecondsOnce
(int interval, SourceOnceFunc function) This function behaves liketimeoutAddOnce(int, org.gnome.glib.SourceOnceFunc)
but with a range in seconds.static Source
timeoutSourceNew
(int interval) Creates a new timeout source.static Source
timeoutSourceNewSeconds
(int interval) Creates a new timeout source.static MemorySegment
tryMalloc
(long nBytes) Attempts to allocatenBytes
, and returnsnull
on failure.static MemorySegment
tryMalloc0
(long nBytes) Attempts to allocatenBytes
, initialized to 0's, and returnsnull
on failure.static 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.static 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.static MemorySegment
tryRealloc
(@Nullable MemorySegment mem, long nBytes) Attempts to reallocmem
to a new size,nBytes
, and returnsnull
on failure.static 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.static MemorySegment
ucs4ToUtf16
(int[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UCS-4 to UTF-16.static String
ucs4ToUtf8
(int[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from a 32-bit fixed width representation as UCS-4.static UnicodeBreakType
unicharBreakType
(int c) Determines the break type ofc
.static int
unicharCombiningClass
(int uc) Determines the canonical combining class of a Unicode character.static boolean
unicharCompose
(int a, int b, Out<Integer> ch) Performs a single composition step of the Unicode canonical composition algorithm.static boolean
unicharDecompose
(int ch, Out<Integer> a, Out<Integer> b) Performs a single decomposition step of the Unicode canonical decomposition algorithm.static int
unicharDigitValue
(int c) Determines the numeric value of a character as a decimal digit.static long
unicharFullyDecompose
(int ch, boolean compat, @Nullable Out<Integer> result, long resultLen) Computes the canonical or compatibility decomposition of a Unicode character.static boolean
unicharGetMirrorChar
(int ch, Out<Integer> mirroredCh) In Unicode, some characters are "mirrored".static UnicodeScript
unicharGetScript
(int ch) Looks up theGUnicodeScript
for a particular character (as defined by Unicode Standard Annex \\24
).static boolean
unicharIsalnum
(int c) Determines whether a character is alphanumeric.static boolean
unicharIsalpha
(int c) Determines whether a character is alphabetic (i.e.static boolean
unicharIscntrl
(int c) Determines whether a character is a control character.static boolean
unicharIsdefined
(int c) Determines if a given character is assigned in the Unicode standard.static boolean
unicharIsdigit
(int c) Determines whether a character is numeric (i.e.static boolean
unicharIsgraph
(int c) Determines whether a character is printable and not a space (returnsfalse
for control characters, format characters, and spaces).static boolean
unicharIslower
(int c) Determines whether a character is a lowercase letter.static boolean
unicharIsmark
(int c) Determines whether a character is a mark (non-spacing mark, combining mark, or enclosing mark in Unicode speak).static boolean
unicharIsprint
(int c) Determines whether a character is printable.static boolean
unicharIspunct
(int c) Determines whether a character is punctuation or a symbol.static boolean
unicharIsspace
(int c) Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.).static boolean
unicharIstitle
(int c) Determines if a character is titlecase.static boolean
unicharIsupper
(int c) Determines if a character is uppercase.static boolean
unicharIswide
(int c) Determines if a character is typically rendered in a double-width cell.static boolean
unicharIswideCjk
(int c) Determines if a character is typically rendered in a double-width cell under legacy East Asian locales.static boolean
unicharIsxdigit
(int c) Determines if a character is a hexadecimal digit.static boolean
unicharIszerowidth
(int c) Determines if a given character typically takes zero width when rendered.static int
unicharTolower
(int c) Converts a character to lower case.static int
unicharTotitle
(int c) Converts a character to the titlecase.static int
unicharToupper
(int c) Converts a character to uppercase.static int
unicharToUtf8
(int c, @Nullable Out<String> outbuf) Converts a single character to UTF-8.static UnicodeType
unicharType
(int c) Classifies a Unicode character by type.static boolean
unicharValidate
(int ch) Checks whetherch
is a valid Unicode character.static int
unicharXdigitValue
(int c) Determines the numeric value of a character as a hexadecimal digit.static MemorySegment
unicodeCanonicalDecomposition
(int ch, MemorySegment resultLen) Deprecated.Use the more flexible g_unichar_fully_decompose() instead.static void
unicodeCanonicalOrdering
(int[] string) Computes the canonical ordering of a string in-place.static Quark
static int
unixFdAdd
(int fd, Set<IOCondition> condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.static int
unixFdAdd
(int fd, IOCondition condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.static int
unixFdAddFull
(int priority, int fd, Set<IOCondition> condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.static int
unixFdAddFull
(int priority, int fd, IOCondition condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.static Source
unixFdSourceNew
(int fd, Set<IOCondition> condition) Creates aGSource
to watch for a particular I/O condition on a file descriptor.static Source
unixFdSourceNew
(int fd, IOCondition... condition) Creates aGSource
to watch for a particular I/O condition on a file descriptor.static MemorySegment
unixGetPasswdEntry
(String userName) Get thepasswd
file entry for the givenuserName
usinggetpwnam_r()
.static boolean
unixOpenPipe
(int[] fds, int flags) Similar to the UNIX pipe() call, but on modern systems like Linux uses the pipe2() system call, which atomically creates a pipe with the configured flags.static boolean
unixSetFdNonblocking
(int fd, boolean nonblock) Control the non-blocking state of the given file descriptor, according tononblock
.static int
unixSignalAdd
(int priority, int signum, SourceFunc handler) A convenience function for g_unix_signal_source_new(), which attaches to the defaultGMainContext
.static Source
unixSignalSourceNew
(int signum) Create aGSource
that will be dispatched upon delivery of the UNIX signalsignum
.static int
A wrapper for the POSIX unlink() function.static void
Removes an environment variable from the environment.static void
usleep
(int microseconds) Pauses the current thread for the given number of microseconds.static MemorySegment
utf16ToUcs4
(short[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-16 to UCS-4.static String
utf16ToUtf8
(short[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-16 to UTF-8.static String
utf8Casefold
(String str, long len) Converts a string into a form that is independent of case.static int
utf8Collate
(String str1, String str2) Compares two strings for ordering using the linguistically correct rules for the [current locale][setlocale].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().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().static String
utf8FindNextChar
(String p, @Nullable String end) Finds the start of the next UTF-8 character in the string afterp
.static String
utf8FindPrevChar
(String str, String p) Given a positionp
with a UTF-8 encoded stringstr
, find the start of the previous UTF-8 character starting beforep
.static int
Converts a sequence of bytes encoded as UTF-8 to a Unicode character.static int
utf8GetCharValidated
(String p, long maxLen) Convert a sequence of bytes encoded as UTF-8 to a Unicode character.static String
utf8MakeValid
(String str, long len) If the provided string is valid UTF-8, return a copy of it.static 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.static String
utf8OffsetToPointer
(String str, int offset) Converts from an integer character offset to a pointer to a position within the string.static int
utf8PointerToOffset
(String str, String pos) Converts from a pointer to position within a string to an integer character offset.static String
Finds the previous UTF-8 character in the string beforep
.static 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 tolen
bytes.static String
utf8Strdown
(String str, long len) Converts all Unicode characters in the string that have a case to lowercase.static int
utf8Strlen
(String p, long max) Computes the length of the string in characters, not including the terminating nul character.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.static 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 tolen
bytes.static String
utf8Strreverse
(String str, long len) Reverses a UTF-8 string.static String
Converts all Unicode characters in the string that have a case to uppercase.static String
utf8Substring
(String str, int startPos, int endPos) Copies a substring out of a UTF-8 encoded string.static MemorySegment
utf8ToUcs4
(String str, int len, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4.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.static MemorySegment
utf8ToUtf16
(String str, int len, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-8 to UTF-16.static String
utf8TruncateMiddle
(String string, long truncateLength) Cuts off the middle of the string, preserving half oftruncateLength
characters at the beginning and half at the end.static boolean
utf8Validate
(byte[] str, @Nullable Out<String> end) Validates UTF-8 encoded text.static boolean
utf8ValidateLen
(byte[] str, @Nullable Out<String> end) Validates UTF-8 encoded text.static int
utime
(String filename, @Nullable MemorySegment utb) A wrapper for the POSIX utime() function.static boolean
uuidStringIsValid
(String str) Parses the stringstr
and verify if it is a UUID.static String
Generates a random UUID (RFC 4122 version 4) as a string.static Type
static void
warnMessage
(@Nullable String domain, String file, int line, String func, @Nullable String warnexpr) Internal function used to print messages from the publicGLib#warnIfReached
andGLib#warnIfFail
macros.static boolean
win32CheckWindowsVersion
(int major, int minor, int spver, Win32OSType osType) Returns whether the version of the Windows operating system the code is running on is at least the specified major, minor and service pack versions.static String
win32ErrorMessage
(int error) Translate a Win32 error code (as returned by GetLastError() or WSAGetLastError()) into the corresponding message.static int
win32Ftruncate
(int f, int size) static String[]
Gets the command line arguments, on Windows, in the GLib filename encoding (ie: UTF-8).static String
The setlocale() function in the Microsoft C library uses locale names of the form "English_United States.1252" etc.static String
win32GetPackageInstallationDirectory
(@Nullable String package_, @Nullable String dllName) Deprecated.Pass the HMODULE of a DLL or EXE to g_win32_get_package_installation_directory_of_module() instead.static String
win32GetPackageInstallationDirectoryOfModule
(@Nullable MemorySegment hmodule) This function tries to determine the installation directory of a software package based on the location of a DLL of the software package.static String
win32GetPackageInstallationSubdirectory
(@Nullable String package_, @Nullable String dllName, String subdir) Deprecated.Pass the HMODULE of a DLL or EXE to g_win32_get_package_installation_directory_of_module() instead, and then construct a subdirectory pathname with g_build_filename().static String[]
win32GetSystemDataDirsForModule
(@Nullable MemorySegment addressOfFunction) static int
Deprecated.Be aware that for Windows 8.1 and Windows Server 2012 R2 and later, this will return 62 unless the application is manifested for Windows 8.1/Windows Server 2012 R2, for example.static String
win32LocaleFilenameFromUtf8
(String utf8filename) Converts a filename from UTF-8 to the system codepage.
-
Field Details
-
ALLOCATOR_LIST
public static final int ALLOCATOR_LIST- See Also:
-
ALLOCATOR_NODE
public static final int ALLOCATOR_NODE- See Also:
-
ALLOCATOR_SLIST
public static final int ALLOCATOR_SLIST- See Also:
-
ALLOC_AND_FREE
public static final int ALLOC_AND_FREE- See Also:
-
ALLOC_ONLY
public static final int ALLOC_ONLY- See Also:
-
ANALYZER_ANALYZING
public static final int ANALYZER_ANALYZING- See Also:
-
ASCII_DTOSTR_BUF_SIZE
public static final int ASCII_DTOSTR_BUF_SIZEA good size for a buffer to be passed intoasciiDtostr(java.lang.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_INITEvaluates to the initial reference count forgatomicrefcount
.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", };
- See Also:
-
BIG_ENDIAN
public static final int BIG_ENDIANSpecifies one of the possible types of byte order. SeeG_BYTE_ORDER
.- See Also:
-
CSET_A_2_Z
The set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters inGScannerConfig
.- See Also:
-
CSET_DIGITS
The set of ASCII digits. Used for specifying valid identifier characters inGScannerConfig
.- See Also:
-
CSET_a_2_z
The set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters inGScannerConfig
.- See Also:
-
C_STD_VERSION
public static final int C_STD_VERSIONThe 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
andG_CXX_STD_VERSION
- See Also:
-
DATALIST_FLAGS_MASK
public static final int DATALIST_FLAGS_MASKA 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_DAYRepresents an invalidGDateDay
.- See Also:
-
DATE_BAD_JULIAN
public static final int DATE_BAD_JULIANRepresents an invalid Julian day number.- See Also:
-
DATE_BAD_YEAR
public static final int DATE_BAD_YEARRepresents an invalid year.- See Also:
-
DIR_SEPARATOR
public static final int DIR_SEPARATORThe directory separator character. This is '/' on UNIX machines and '\\' under Windows.- See Also:
-
DIR_SEPARATOR_S
The directory separator as a string. This is "/" on UNIX machines and "\\" under Windows.- See Also:
-
E
public static final double EThe base of natural logarithms.- See Also:
-
GINT16_FORMAT
- See Also:
-
GINT16_MODIFIER
- See Also:
-
GINT32_FORMAT
- See Also:
-
GINT32_MODIFIER
- See Also:
-
GINT64_FORMAT
- See Also:
-
GINT64_MODIFIER
- See Also:
-
GINTPTR_FORMAT
- See Also:
-
GINTPTR_MODIFIER
- See Also:
-
GNUC_FUNCTION
Expands to "" on all modern compilers, and to __FUNCTION__ on gcc version 2.x. Don't use it.- See Also:
-
GNUC_PRETTY_FUNCTION
Expands to "" on all modern compilers, and to __PRETTY_FUNCTION__ on gcc version 2.x. Don't use it.- See Also:
-
GSIZE_FORMAT
- See Also:
-
GSIZE_MODIFIER
- See Also:
-
GSSIZE_FORMAT
- See Also:
-
GSSIZE_MODIFIER
- See Also:
-
GUINT16_FORMAT
- See Also:
-
GUINT32_FORMAT
- See Also:
-
GUINT64_FORMAT
- See Also:
-
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_VISIBILITYDefined 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_SHIFTThe position of the first bit which is not reserved for internal use be theGHook
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_BIASThe bias by which exponents in double-precision floats are offset.- See Also:
-
IEEE754_FLOAT_BIAS
public static final int IEEE754_FLOAT_BIASThe bias by which exponents in single-precision floats are offset.- See Also:
-
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.- See Also:
-
KEY_FILE_DESKTOP_KEY_ACTIONS
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string list giving the available application actions.- See Also:
-
KEY_FILE_DESKTOP_KEY_CATEGORIES
A key underG_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.- See Also:
-
KEY_FILE_DESKTOP_KEY_COMMENT
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the tooltip for the desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean set to true if the application is D-Bus activatable.- See Also:
-
KEY_FILE_DESKTOP_KEY_EXEC
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the command line to execute. It is only valid for desktop entries with theApplication
type.- See Also:
-
KEY_FILE_DESKTOP_KEY_GENERIC_NAME
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the generic name of the desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_HIDDEN
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the desktop entry has been deleted by the user.- See Also:
-
KEY_FILE_DESKTOP_KEY_ICON
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the name of the icon to be displayed for the desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_MIME_TYPE
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings giving the MIME types supported by this desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_NAME
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the specific name of the desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings identifying the environments that should not display the desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_NO_DISPLAY
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the desktop entry should be shown in menus.- See Also:
-
KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings identifying the environments that should display the desktop entry.- See Also:
-
KEY_FILE_DESKTOP_KEY_PATH
A key underG_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 theApplication
type.- See Also:
-
KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification.- See Also:
-
KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
A key underG_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.- See Also:
-
KEY_FILE_DESKTOP_KEY_TERMINAL
A key underG_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.- See Also:
-
KEY_FILE_DESKTOP_KEY_TRY_EXEC
A key underG_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 theApplication
type.- See Also:
-
KEY_FILE_DESKTOP_KEY_TYPE
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the type of the desktop entry.Usually
G_KEY_FILE_DESKTOP_TYPE_APPLICATION
,G_KEY_FILE_DESKTOP_TYPE_LINK
, orG_KEY_FILE_DESKTOP_TYPE_DIRECTORY
.- See Also:
-
KEY_FILE_DESKTOP_KEY_URL
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the URL to access. It is only valid for desktop entries with theLink
type.- See Also:
-
KEY_FILE_DESKTOP_KEY_VERSION
A key underG_KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file.- See Also:
-
KEY_FILE_DESKTOP_TYPE_APPLICATION
The value of theG_KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing applications.- See Also:
-
KEY_FILE_DESKTOP_TYPE_DIRECTORY
The value of theG_KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing directories.- See Also:
-
KEY_FILE_DESKTOP_TYPE_LINK
The value of theG_KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing links to documents.- See Also:
-
LITTLE_ENDIAN
public static final int LITTLE_ENDIANSpecifies one of the possible types of byte order. SeeG_BYTE_ORDER
.- See Also:
-
LN10
public static final double LN10The natural logarithm of 10.- See Also:
-
LN2
public static final double LN2The natural logarithm of 2.- See Also:
-
LOG_2_BASE_10
public static final double LOG_2_BASE_10Multiplying the base 2 exponent by this number yields the base 10 exponent.- See Also:
-
LOG_DOMAIN
public static final byte LOG_DOMAINDefines 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
orbloatpad-io
.If undefined, it defaults to the default
null
(or""
) log domain; this is not advisable, as it cannot be filtered against using theG_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_MASKGLib 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_SHIFTLog levels below1<<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_VERSIONThe 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_VERSIONThe 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 MININT16The minimum value which can be held in agint16
.- See Also:
-
MININT32
public static final int MININT32The minimum value which can be held in agint32
.- See Also:
-
MININT64
public static final long MININT64The minimum value which can be held in agint64
.- See Also:
-
MININT8
public static final byte MININT8The minimum value which can be held in agint8
.- See Also:
-
MINOR_VERSION
public static final int MINOR_VERSIONThe 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
- See Also:
-
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 inargv
. The option must be of typeOptionArg.CALLBACK
,OptionArg.STRING_ARRAY
orOptionArg.FILENAME_ARRAY
.Using
G_OPTION_REMAINING
instead of simply scanningargv
for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.- See Also:
-
PDP_ENDIAN
public static final int PDP_ENDIANSpecifies one of the possible types of byte order (currently unused). SeeG_BYTE_ORDER
.- See Also:
-
PI
public static final double PIThe value of pi (ratio of circle's circumference to its diameter).- See Also:
-
PID_FORMAT
A format specifier that can be used in printf()-style format strings when printing aGPid
.- See Also:
-
PI_2
public static final double PI_2Pi divided by 2.- See Also:
-
PI_4
public static final double PI_4Pi divided by 4.- See Also:
-
POLLFD_FORMAT
A format specifier that can be used in printf()-style format strings when printing thefd
member of aGPollFD
.- See Also:
-
PRIORITY_DEFAULT
public static final int PRIORITY_DEFAULTUse this for default priority event sources.In GLib this priority is used when adding timeout functions with
timeoutAdd(int, int, org.gnome.glib.SourceFunc)
. In GDK this priority is used for events from the X server.- See Also:
-
PRIORITY_DEFAULT_IDLE
public static final int PRIORITY_DEFAULT_IDLEUse this for default priority idle functions.In GLib this priority is used when adding idle functions with
idleAdd(int, org.gnome.glib.SourceFunc)
.- See Also:
-
PRIORITY_HIGH
public static final int PRIORITY_HIGHUse 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_IDLEUse this for high priority idle functions.GTK uses
G_PRIORITY_HIGH_IDLE
+ 10 for resizing operations, andG_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_LOWUse 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_INITEvaluates to the initial reference count forgrefcount
.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", };
- See Also:
-
SEARCHPATH_SEPARATOR
public static final int SEARCHPATH_SEPARATORThe search path separator character. This is ':' on UNIX machines and ';' under Windows.- See Also:
-
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_CONTINUEUse this macro as the return value of aGLib.SourceFunc
to leave theGLib.Source
in the main loop.- See Also:
-
SOURCE_REMOVE
public static final boolean SOURCE_REMOVEUse this macro as the return value of aGLib.SourceFunc
to remove theGLib.Source
from the main loop.- See Also:
-
SQRT2
public static final double SQRT2The square root of two.- See Also:
-
STR_DELIMITERS
The standard delimiters, used instrdelimit(java.lang.String, java.lang.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
Creates a unique temporary directory for each unit test and uses g_set_user_dirs() to set 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 g_test_run() is called, so calls to (for example) g_get_user_home_dir() 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.
- g_get_home_dir()
- g_get_user_cache_dir()
- g_get_system_config_dirs()
- g_get_user_config_dir()
- g_get_system_data_dirs()
- g_get_user_data_dir()
- g_get_user_state_dir()
- g_get_user_runtime_dir()
The subdirectories may not be created by the test harness; as with normal calls to functions like g_get_user_cache_dir(), the caller must be prepared to create the directory if it doesn’t exist.
- See Also:
-
TIME_SPAN_DAY
public static final long TIME_SPAN_DAYEvaluates to a time span of one day.- See Also:
-
TIME_SPAN_HOUR
public static final long TIME_SPAN_HOUREvaluates to a time span of one hour.- See Also:
-
TIME_SPAN_MILLISECOND
public static final long TIME_SPAN_MILLISECONDEvaluates to a time span of one millisecond.- See Also:
-
TIME_SPAN_MINUTE
public static final long TIME_SPAN_MINUTEEvaluates to a time span of one minute.- See Also:
-
TIME_SPAN_SECOND
public static final long TIME_SPAN_SECONDEvaluates to a time span of one second.- See Also:
-
UNICHAR_MAX_DECOMPOSITION_LENGTH
public static final int UNICHAR_MAX_DECOMPOSITION_LENGTHThe maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.This is as defined by Unicode 6.1.
- See Also:
-
URI_RESERVED_CHARS_GENERIC_DELIMITERS
-
URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS
-
USEC_PER_SEC
public static final int USEC_PER_SECNumber 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_REQUIREDA 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).- 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:
-
-
Constructor Details
-
GLib
public GLib()
-
-
Method Details
-
javagi$ensureInitialized
public static void javagi$ensureInitialized() -
access
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.
-
alignedAlloc
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 allocatenBlockBytes
- the size of each block in bytesalignment
- the alignment to be enforced, which must be a positive power of 2 and a multiple ofsizeof(void*)
- Returns:
- the allocated memory
-
alignedAlloc0
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 allocatenBlockBytes
- the size of each block in bytesalignment
- the alignment to be enforced, which must be a positive power of 2 and a multiple ofsizeof(void*)
- Returns:
- the allocated, cleared memory
-
alignedFree
Frees the memory allocated by g_aligned_alloc().- Parameters:
mem
- the memory to deallocate
-
alignedFreeSized
public static void alignedFreeSized(@Nullable @Nullable MemorySegment mem, long alignment, long size) Frees the memory pointed to bymem
, assuming it is has the givensize
andalignment
.If
mem
isnull
this is a no-op (andsize
is ignored).It is an error if
size
doesn’t match the size, oralignment
doesn’t match the alignment, passed whenmem
was allocated.size
andalignment
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 freealignment
- alignment ofmem
size
- size ofmem
, in bytes
-
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 toGLib#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
Converts agdouble
to a string, using the '.' as decimal point.This function generates enough precision that converting the string back using
asciiStrtod(java.lang.String, io.github.jwharm.javagi.base.Out<java.lang.String>)
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 thanGLib.ASCII_DTOSTR_BUF_SIZE
bytes, including the terminating nul character, which is always added.- Parameters:
buffer
- a buffer to place the resulting string inbufLen
- the length of the bufferd
- the value to convert- Returns:
- the pointer to the buffer with the converted string
-
asciiFormatd
Converts agdouble
to a string, using the '.' as decimal point. To format the number you pass in aprintf()
-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 agdouble
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(java.lang.String, int, double)
.- Parameters:
buffer
- a buffer to place the resulting string inbufLen
- the length of the bufferformat
- theprintf()
-style format to use for the code to use for convertingd
- the value to convert- Returns:
- the pointer to the buffer with the converted string
-
asciiStrcasecmp
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
ands2
must be non-NULL
.- Parameters:
s1
- string to compare withs2
s2
- string to compare withs1
- Returns:
- 0 if the strings match, a negative value if
s1
<s2
, or a positive value ifs1
>s2
-
asciiStrdown
Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly matchasciiTolower(byte)
.- Parameters:
str
- a stringlen
- length ofstr
in bytes, or-1
ifstr
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 oldstrdown(java.lang.String)
, which modified the string in place.)
-
asciiStringToSigned
public static boolean asciiStringToSigned(String str, int base, long min, long max, @Nullable @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 givenbase
that is within inclusive bounds limited bymin
andmax
. If this is true, then the converted number is stored inoutNum
. 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 beGLib.NumberParserError.INVALID
. If the parsed number is out of bounds -GLib.NumberParserError.OUT_OF_BOUNDS
.See
asciiStrtoll(java.lang.String, io.github.jwharm.javagi.base.Out<java.lang.String>, 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 convertbase
- base of a parsed numbermin
- 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
- seeGError
-
asciiStringToUnsigned
public static boolean asciiStringToUnsigned(String str, int base, long min, long max, @Nullable @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 givenbase
that is within inclusive bounds limited bymin
andmax
. If this is true, then the converted number is stored inoutNum
. 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 beGLib.NumberParserError.INVALID
. If the parsed number is out of bounds -GLib.NumberParserError.OUT_OF_BOUNDS
.See
asciiStrtoull(java.lang.String, io.github.jwharm.javagi.base.Out<java.lang.String>, 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 stringbase
- base of a parsed numbermin
- 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
- seeGError
-
asciiStrncasecmp
Compares1
ands2
, ignoring the case of ASCII characters and any characters after the firstn
in each string. If either string is less thann
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(java.lang.String, java.lang.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 withs2
s2
- string to compare withs1
n
- number of characters to compare- Returns:
- 0 if the strings match, a negative value if
s1
<s2
, or a positive value ifs1
>s2
-
asciiStrtod
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(java.lang.String, int, double)
.If the correct value would cause overflow, plus or minus
HUGE_VAL
is returned (according to the sign of the value), andERANGE
is stored inerrno
. If the correct value would cause underflow, zero is returned andERANGE
is stored inerrno
.This function resets
errno
before callingstrtod()
so that you can reliably detect overflow and underflow.- Parameters:
nptr
- the string to convert to a numeric valueendptr
- if non-NULL
, it returns the character after the last character used in the conversion- Returns:
- the converted value
-
asciiStrtoll
Converts a string to agint64
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
orGLib.MININT64
is returned, andERANGE
is stored inerrno
. If the base is outside the valid range, zero is returned, andEINVAL
is stored inerrno
. If the string conversion fails, zero is returned, andendptr
returnsnptr
(ifendptr
is non-NULL
).- Parameters:
nptr
- the string to convert to a numeric valueendptr
- if non-NULL
, it returns the character after the last character used in the conversionbase
- to be used for the conversion, 2..36 or 0- Returns:
- the converted value, or zero on error
-
asciiStrtoull
Converts a string to aguint64
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 aguint64
. 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, andERANGE
is stored inerrno
. If the base is outside the valid range, zero is returned, andEINVAL
is stored inerrno
. If the string conversion fails, zero is returned, andendptr
returnsnptr
(ifendptr
is non-NULL
).- Parameters:
nptr
- the string to convert to a numeric valueendptr
- if non-NULL
, it returns the character after the last character used in the conversionbase
- to be used for the conversion, 2..36 or 0- Returns:
- the converted value, or zero on error
-
asciiStrup
Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly matchasciiToupper(byte)
.- Parameters:
str
- a stringlen
- length ofstr
in bytes, or-1
ifstr
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 oldstrup(java.lang.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 onEOF
but no need to worry about casting toguchar
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 onEOF
but no need to worry about casting toguchar
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 toGLib#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
-
assertionMessage
-
assertionMessageCmpint
-
assertionMessageCmpnum
-
assertionMessageCmpstr
-
assertionMessageCmpstrv
-
assertionMessageError
-
assertionMessageExpr
public static void assertionMessageExpr(@Nullable @Nullable String domain, String file, int line, String func, @Nullable @Nullable String expr) Internal function used to print messages from the public g_assert() and g_assert_not_reached() macros.- Parameters:
domain
- log domainfile
- file containing the assertionline
- line number of the assertionfunc
- function containing the assertionexpr
- expression which failed
-
atexit
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
Atomically addsval
to the value ofatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
val
- the value to add- Returns:
- the value of
atomic
before the add, signed
-
atomicIntAnd
Performs an atomic bitwise 'and' of the value ofatomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
val
- the value to 'and'- Returns:
- the value of
atomic
before the operation, unsigned
-
atomicIntCompareAndExchange
Comparesatomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
oldval
- the value to compare withnewval
- the value to conditionally replace with- Returns:
true
if the exchange took place
-
atomicIntCompareAndExchangeFull
public static boolean atomicIntCompareAndExchangeFull(MemorySegment atomic, int oldval, int newval, Out<Integer> preval) Comparesatomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
then no change occurs. In any case the value ofatomic
before this operation is stored inpreval
.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 agint
orguint
oldval
- the value to compare withnewval
- the value to conditionally replace withpreval
- the contents ofatomic
before this operation- Returns:
true
if the exchange took place
-
atomicIntDecAndTest
Decrements the value ofatomic
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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
- Returns:
true
if the resultant value is zero
-
atomicIntExchange
Sets theatomic
tonewval
and returns the old value fromatomic
.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 agint
orguint
newval
- the value to replace with- Returns:
- the value of
atomic
before the exchange, signed
-
atomicIntExchangeAndAdd
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 agint
val
- the value to add- Returns:
- the value of
atomic
before the add, signed
-
atomicIntGet
Gets the current value ofatomic
.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
- Returns:
- the value of the integer
-
atomicIntInc
Increments the value ofatomic
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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
-
atomicIntOr
Performs an atomic bitwise 'or' of the value ofatomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
val
- the value to 'or'- Returns:
- the value of
atomic
before the operation, unsigned
-
atomicIntSet
Sets the value ofatomic
tonewval
.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
newval
- a new value to store
-
atomicIntXor
Performs an atomic bitwise 'xor' of the value ofatomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agint
orguint
val
- the value to 'xor'- Returns:
- the value of
atomic
before the operation, unsigned
-
atomicPointerAdd
Atomically addsval
to the value ofatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gssize
togintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.- Parameters:
atomic
- a pointer to agpointer
-sized valueval
- the value to add- Returns:
- the value of
atomic
before the add, signed
-
atomicPointerAnd
Performs an atomic bitwise 'and' of the value ofatomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gsize
toguintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.- Parameters:
atomic
- a pointer to agpointer
-sized valueval
- the value to 'and'- Returns:
- the value of
atomic
before the operation, unsigned
-
atomicPointerCompareAndExchange
public static boolean atomicPointerCompareAndExchange(MemorySegment atomic, @Nullable @Nullable MemorySegment oldval, @Nullable @Nullable MemorySegment newval) Comparesatomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agpointer
-sized valueoldval
- the value to compare withnewval
- the value to conditionally replace with- Returns:
true
if the exchange took place
-
atomicPointerCompareAndExchangeFull
public static boolean atomicPointerCompareAndExchangeFull(MemorySegment atomic, @Nullable @Nullable MemorySegment oldval, @Nullable @Nullable MemorySegment newval, Out<MemorySegment> preval) Comparesatomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
then no change occurs. In any case the value ofatomic
before this operation is stored inpreval
.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 agpointer
-sized valueoldval
- the value to compare withnewval
- the value to conditionally replace withpreval
- the contents ofatomic
before this operation- Returns:
true
if the exchange took place
-
atomicPointerExchange
public static MemorySegment atomicPointerExchange(@Nullable @Nullable MemorySegment atomic, @Nullable @Nullable MemorySegment newval) Sets theatomic
tonewval
and returns the old value fromatomic
.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 agpointer
-sized valuenewval
- the value to replace with- Returns:
- the value of
atomic
before the exchange
-
atomicPointerGet
Gets the current value ofatomic
.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agpointer
-sized value- Returns:
- the value of the pointer
-
atomicPointerOr
Performs an atomic bitwise 'or' of the value ofatomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gsize
toguintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.- Parameters:
atomic
- a pointer to agpointer
-sized valueval
- the value to 'or'- Returns:
- the value of
atomic
before the operation, unsigned
-
atomicPointerSet
Sets the value ofatomic
tonewval
.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.- Parameters:
atomic
- a pointer to agpointer
-sized valuenewval
- a new value to store
-
atomicPointerXor
Performs an atomic bitwise 'xor' of the value ofatomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gsize
toguintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.- Parameters:
atomic
- a pointer to agpointer
-sized valueval
- the value to 'xor'- Returns:
- the value of
atomic
before the operation, unsigned
-
atomicRcBoxAcquire
Atomically acquires a reference on the data pointed bymemBlock
.- Parameters:
memBlock
- a pointer to reference counted data- Returns:
- a pointer to the data, with its reference count increased
-
atomicRcBoxAlloc
AllocatesblockSize
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
-
atomicRcBoxAlloc0
AllocatesblockSize
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
-
atomicRcBoxDup
Allocates a new block of data with atomic reference counting semantics, and copiesblockSize
bytes ofmemBlock
into it.- Parameters:
blockSize
- the number of bytes to copy, must be greater than 0memBlock
- the memory to copy- Returns:
- a pointer to the allocated memory
-
atomicRcBoxGetSize
Retrieves the size of the reference counted data pointed bymemBlock
.- Parameters:
memBlock
- a pointer to reference counted data- Returns:
- the size of the data, in bytes
-
atomicRcBoxRelease
Atomically releases a reference on the data pointed bymemBlock
.If the reference was the last one, it will free the resources allocated for
memBlock
.- Parameters:
memBlock
- a pointer to reference counted data
-
atomicRcBoxReleaseFull
Atomically releases a reference on the data pointed bymemBlock
.If the reference was the last one, it will call
clearFunc
to clear the contents ofmemBlock
, and then will free the resources allocated formemBlock
.- Parameters:
memBlock
- a pointer to reference counted data
-
atomicRefCountCompare
Atomically compares the current value ofarc
withval
.- Parameters:
arc
- the address of an atomic reference count variableval
- the value to compare- Returns:
true
if the reference count is the same as the given value
-
atomicRefCountDec
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, andfalse
otherwise
-
atomicRefCountInc
Atomically increases the reference count.- Parameters:
arc
- the address of an atomic reference count variable
-
atomicRefCountInit
Initializes a reference count variable to 1.- Parameters:
arc
- the address of an atomic reference count variable
-
base64Decode
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().
-
base64DecodeInplace
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 inputtext
.
-
base64DecodeStep
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 dataout
- output bufferstate
- Saved state between steps, initialize to 0save
- Saved state between steps, initialize to 0- Returns:
- The number of bytes of output that was written
-
base64Encode
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().
-
base64EncodeClose
public static long base64EncodeClose(boolean breakLines, byte[] 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 linesout
- pointer to destination bufferstate
- 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
-
base64EncodeStep
public static long base64EncodeStep(byte[] in, boolean breakLines, byte[] 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 withLF
characters, notCR LF
sequences, so the result cannot be passed directly to SMTP or certain other protocols.- Parameters:
in
- the binary data to encodebreakLines
- whether to break long linesout
- pointer to destination bufferstate
- Saved state between steps, initialize to 0save
- Saved state between steps, initialize to 0- Returns:
- The number of bytes of output that was written
-
basename
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
Sets the indicatedlockBit
inaddress
. 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
). Ifbit
is not between 0 and 31 then the result is undefined.This function accesses
address
atomically. All other accesses toaddress
must be atomic in order for this function to work reliably. Whileaddress
has avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.- Parameters:
address
- a pointer to an integerlockBit
- a bit value between 0 and 31
-
bitNthLsf
public static int bitNthLsf(int mask, int nthBit) Find the position of the first bit set inmask
, 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, setnthBit
to -1.- Parameters:
mask
- agulong
containing flagsnthBit
- 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 inmask
, 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, setnthBit
to -1 or GLIB_SIZEOF_LONG * 8.- Parameters:
mask
- agulong
containing flagsnthBit
- 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 holdnumber
, e.g. ifnumber
is 4, 3 bits are needed.- Parameters:
number
- aguint
- Returns:
- the number of bits used to hold
number
-
bitTrylock
Sets the indicatedlockBit
inaddress
, returningtrue
if successful. If the bit is already set, returnsfalse
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
). Ifbit
is not between 0 and 31 then the result is undefined.This function accesses
address
atomically. All other accesses toaddress
must be atomic in order for this function to work reliably. Whileaddress
has avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.- Parameters:
address
- a pointer to an integerlockBit
- a bit value between 0 and 31- Returns:
true
if the lock was acquired
-
bitUnlock
Clears the indicatedlockBit
inaddress
. 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 toaddress
must be atomic in order for this function to work reliably. Whileaddress
has avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.- Parameters:
address
- a pointer to an integerlockBit
- a bit value between 0 and 31
-
blowChunks
public static void blowChunks() -
buildFilename
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 pathvarargs
- remaining elements in path, terminated bynull
- Returns:
- the newly allocated path
-
buildFilenamev
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
-
buildPath
Creates a path from a series of elements usingseparator
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
, thenABABA
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 separator the elements of the path.firstElement
- the first element in the pathvarargs
- remaining elements in path, terminated bynull
- Returns:
- the newly allocated path
-
buildPathv
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 separator 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().
-
canonicalizeFilename
Gets the canonical file name fromfilename
. All triple slashes are turned into single slashes, and all..
and.
s resolved againstrelativeTo
.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 tofilename
to make it absolute.relativeTo
must be an absolute path, ornull
. IfrelativeTo
isnull
, 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 filerelativeTo
- the relative directory, ornull
to use the current working directory- Returns:
- a newly allocated string with the canonical file path
-
chdir
A wrapper for the POSIX chdir() function. The function changes the current directory of the process topath
.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.
-
checkVersion
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 versionrequiredMinor
- the required minor versionrequiredMicro
- 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.
-
childWatchAdd
Sets a function to be called when the child indicated bypid
exits, at the prioritypriority
.If you obtain
pid
fromspawnAsync(java.lang.String, java.lang.String[], java.lang.String[], java.util.Set<org.gnome.glib.SpawnFlags>, org.gnome.glib.SpawnChildSetupFunc, org.gnome.glib.Pid)
orspawnAsyncWithPipes(java.lang.String, java.lang.String[], java.lang.String[], java.util.Set<org.gnome.glib.SpawnFlags>, org.gnome.glib.SpawnChildSetupFunc, org.gnome.glib.Pid, io.github.jwharm.javagi.base.Out<java.lang.Integer>, io.github.jwharm.javagi.base.Out<java.lang.Integer>, io.github.jwharm.javagi.base.Out<java.lang.Integer>)
you will need to passSpawnFlags.DO_NOT_REAP_CHILD
as 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
GPid
must be explicitly closed (seespawnClosePid(org.gnome.glib.Pid)
)pid
must not be closed while the source is still active. Typically, you should invokespawnClosePid(org.gnome.glib.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(org.gnome.glib.Pid)
apply to this function.This internally creates a main loop source using
childWatchSourceNew(org.gnome.glib.Pid)
and attaches it to the main loop context usingSource.attach(org.gnome.glib.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 betweenGLib.PRIORITY_DEFAULT_IDLE
andGLib.PRIORITY_HIGH_IDLE
.pid
- process to watch. On POSIX the positive pid of a child process. On Windows 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.
-
childWatchSourceNew
Creates a new child_watch source.The source will not initially be associated with any
GLib.MainContext
and must be added to one withSource.attach(org.gnome.glib.MainContext)
before it will be executed.Note that child watch sources can only be used in conjunction with
g_spawn...
when theSpawnFlags.DO_NOT_REAP_CHILD
flag is used.Note that on platforms where
GPid
must be explicitly closed (seespawnClosePid(org.gnome.glib.Pid)
)pid
must not be closed while the source is still active. Typically, you will want to callspawnClosePid(org.gnome.glib.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 processpid
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, includingwaitpid(pid, ...)
or a second child-watch source for the samepid
- the application must not ignore
SIGCHLD
- Before 2.78, the application could not send a signal (
kill()
) to the watchedpid
in a race free manner. Since 2.78, you can do that while the associatedGLib.MainContext
is acquired. - Before 2.78, even after destroying the
GLib.Source
, you could not be sure thatpid
wasn't already reaped. Hence, it was also not safe tokill()
orwaitpid()
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 bywaitpid
.Calling
waitpid
for specific processes other thanpid
remains a valid thing to do.- Parameters:
pid
- process to watch. On POSIX the positive pid of a child process. On Windows a handle for a process (which doesn't have to be a child).- Returns:
- the newly-created child watch source
-
chmod
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
-
clearHandleId
Clears a numeric handler, such as aGSource
ID.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 IDclearFunc
- the function to call to clear the handler
-
clearList
Clears a pointer to aGList
, freeing it and, optionally, freeing its elements usingdestroy
.listPtr
must be a valid pointer. IflistPtr
points to a nullGList
, this does nothing.- Parameters:
listPtr
- aGList
return location
-
clearPointer
Clears a reference to a variable.pp
must not benull
.If the reference is
null
then this function does nothing. Otherwise, the variable is destroyed usingdestroy
and the pointer is set tonull
.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 asGLib.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
-
clearSlist
Clears a pointer to aGSList
, freeing it and, optionally, freeing its elements usingdestroy
.slistPtr
must be a valid pointer. IfslistPtr
points to a nullGSList
, this does nothing.- Parameters:
slistPtr
- aGSList
return location
-
close
This wraps the close() call. In case of error,errno
will be preserved, but the error will also be stored as aGError
inerror
. 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 handleEINTR
, 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
isnull
andfd
is a valid open file descriptor. This makes it safe to call from a signal handler or aGSpawnChildSetupFunc
under those conditions. Seesignal(7)
) andsignal-safety(7)
) for more details.- Parameters:
fd
- A file descriptor- Returns:
true
on success,false
if there was an error.- Throws:
GErrorException
- seeGError
-
closefrom
public static int closefrom(int lowfd) Close every file descriptor equal to or greater thanlowfd
.Typically
lowfd
will be 3, to leave standard input, standard output and standard error open.This is the same as Linux
close_range (lowfd, ~0U, 0)
, but portable to other OSs and to older versions of Linux. Equivalently, it is the same as BSDclosefrom (lowfd)
, but portable, and async-signal-safe on all OSs.This function is async-signal safe, making it safe to call from a signal handler or a
GLib.SpawnChildSetupFunc
, as long aslowfd
is non-negative. Seesignal(7)
) andsignal-safety(7)
) for more details.- Parameters:
lowfd
- Minimum fd to close, which must be non-negative- Returns:
- 0 on success, -1 with errno set on error
-
computeChecksumForBytes
Computes the checksum for a binarydata
. 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
- aGChecksumType
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 forchecksumType
. The returned string should be freed with g_free() when done using it.
-
computeChecksumForData
Computes the checksum for a binarydata
oflength
. 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
- aGChecksumType
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 forchecksumType
. The returned string should be freed with g_free() when done using it.
-
computeChecksumForString
Computes the checksum of a string.The hexadecimal string returned will be in lower case.
- Parameters:
checksumType
- aGChecksumType
str
- the string to compute the checksum oflength
- 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 forchecksumType
. The returned string should be freed with g_free() when done using it.
-
computeHmacForBytes
Computes the HMAC for a binarydata
. 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
- aGChecksumType
to use for the HMACkey
- the key to use in the HMACdata
- 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.
-
computeHmacForData
Computes the HMAC for a binarydata
oflength
. 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
- aGChecksumType
to use for the HMACkey
- the key to use in the HMACdata
- 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.
-
computeHmacForString
public static String computeHmacForString(ChecksumType digestType, byte[] key, String str, long length) Computes the HMAC for a string.The hexadecimal string returned will be in lower case.
- Parameters:
digestType
- aGChecksumType
to use for the HMACkey
- the key to use in the HMACstr
- the string to compute the HMAC forlength
- 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.
-
convert
public static byte[] convert(byte[] str, String toCodeset, String fromCodeset, @Nullable @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 convertstr
fromCodeset
- character set ofstr
.bytesRead
- location to store the number of bytes in the input string that were successfully converted, ornull
. Even if the conversion was successful, this may be less thanlen
if there were partial characters at the end of the input. If the errorConvertError.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
anderror
will be set. - Throws:
GErrorException
- seeGError
-
convertErrorQuark
-
convertWithFallback
public static byte[] convertWithFallback(byte[] str, String toCodeset, String fromCodeset, String fallback, @Nullable @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 infallback
will be honored. Some systems may do an approximate conversion fromfromCodeset
totoCodeset
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 convertstr
fromCodeset
- character set ofstr
.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). Ifnull
, 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, ornull
. Even if the conversion was successful, this may be less thanlen
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
anderror
will be set. - Throws:
GErrorException
- seeGError
-
convertWithIconv
public static byte[] convertWithIconv(byte[] str, IConv converter, @Nullable @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, ornull
. Even if the conversion was successful, this may be less thanlen
if there were partial characters at the end of the input. If the errorConvertError.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
anderror
will be set. - Throws:
GErrorException
- seeGError
-
creat
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().
-
datalistClear
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
Calls the given function for each data element of the datalist. The function is called with each data element'sGQuark
id and data, together with the givenuserData
parameter. Note that this function is NOT thread-safe. So unlessdatalist
can be protected from any modifications during invocation of this function, it should not be called.func
can make changes todatalist
, 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
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
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
-
datalistIdDupData
public static MemorySegment datalistIdDupData(Data[] datalist, Quark keyId, @Nullable @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 thendupFunc
will be called with anull
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 datalistkeyId
- theGQuark
identifying a data elementdupFunc
- function to duplicate the old value- Returns:
- the result of calling
dupFunc
on the value associated withkeyId
indatalist
, ornull
if not set. IfdupFunc
isnull
, the value is returned unmodified.
-
datalistIdGetData
Retrieves the data element corresponding tokeyId
.- Parameters:
datalist
- a datalist.keyId
- theGQuark
identifying a data element.- Returns:
- the data element, or
null
if it is not found.
-
datalistIdRemoveMultiple
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. Now it can be larger, but note that GData does a linear search, so an excessive number of keys will perform badly.- Parameters:
datalist
- a datalistkeys
- keys to remove
-
datalistIdRemoveNoNotify
Removes an element, without calling its destroy notification function.- Parameters:
datalist
- a datalist.keyId
- theGQuark
identifying a data element.- Returns:
- the data previously stored at
keyId
, ornull
if none.
-
datalistIdReplaceData
public static boolean datalistIdReplaceData(Data[] datalist, Quark keyId, @Nullable @Nullable MemorySegment oldval, @Nullable @Nullable MemorySegment newval, @Nullable @Nullable Out<DestroyNotify> oldDestroy) Compares the member that is associated withkeyId
indatalist
tooldval
, and if they are the same, replaceoldval
withnewval
.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 inoldDestroy
). Its up to the caller to free this as they wish, which may or may not include usingoldDestroy
as sometimes replacement should not destroy the object in the normal way.- Parameters:
datalist
- location of a datalistkeyId
- theGQuark
identifying a data elementoldval
- the old value to compare againstnewval
- the new value to replace it witholdDestroy
- destroy notify for the existing value- Returns:
true
if the existing value forkeyId
was replaced bynewval
,false
otherwise.
-
datalistIdSetDataFull
public static void datalistIdSetDataFull(Data[] datalist, Quark keyId, @Nullable @Nullable MemorySegment data) Sets the data corresponding to the givenGQuark
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
- theGQuark
to identify the data element.data
- the data element ornull
to remove any previous element corresponding tokeyId
.
-
datalistInit
Resets the datalist tonull
. It does not free any memory or call any destroy functions.- Parameters:
datalist
- a pointer to a pointer to a datalist.
-
datalistSetFlags
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 baseGObject
type, for example.)- Parameters:
datalist
- pointer to the location that holds a listflags
- the flags to turn on. The values of the flags are restricted byG_DATALIST_FLAGS_MASK
(currently 3; giving two possible boolean flags). A value forflags
that doesn't fit within the mask is an error.
-
datalistUnsetFlags
Turns off flag values for a data list. See g_datalist_unset_flags()- Parameters:
datalist
- pointer to the location that holds a listflags
- the flags to turn off. The values of the flags are restricted byG_DATALIST_FLAGS_MASK
(currently 3: giving two possible boolean flags). A value forflags
that doesn't fit within the mask is an error.
-
datasetDestroy
Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.- Parameters:
datasetLocation
- the location identifying the dataset.
-
datasetForeach
Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unlessdatasetLocation
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
Gets the data element corresponding to aGQuark
.- Parameters:
datasetLocation
- the location identifying the dataset.keyId
- theGQuark
id to identify the data element.- Returns:
- the data element corresponding to
the
GQuark
, ornull
if it is not found.
-
datasetIdRemoveNoNotify
Removes an element, without calling its destroy notification function.- Parameters:
datasetLocation
- the location identifying the dataset.keyId
- theGQuark
ID identifying the data element.- Returns:
- the data previously stored at
keyId
, ornull
if none.
-
datasetIdSetDataFull
public static void datasetIdSetDataFull(MemorySegment datasetLocation, Quark keyId, @Nullable @Nullable MemorySegment data) Sets the data element associated with the givenGQuark
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
- theGQuark
id to identify the data element.data
- the data element.
-
dcgettext
This is a variant of g_dgettext() that allows specifying a locale category instead of always usingLC_MESSAGES
. See g_dgettext() for more information about how this functions differs from calling dcgettext() directly.- Parameters:
domain
- the translation domain to use, ornull
to use the domain set with textdomain()msgid
- message to translatecategory
- a locale category- Returns:
- the translated string for the given locale category
-
dgettext
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 notnull
- 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, ornull
to use the domain set with textdomain()msgid
- message to translate- Returns:
- The translated string
-
directEqual
public static boolean directEqual(@Nullable @Nullable MemorySegment v1, @Nullable @Nullable MemorySegment v2) Compares twogpointer
arguments and returnstrue
if they are equal. It can be passed to g_hash_table_new() as thekeyEqualFunc
parameter, when using opaque pointers compared by pointer value as keys in aGHashTable
.This equality function is also appropriate for keys that are integers stored in pointers, such as
GINT_TO_POINTER (n)
.- Parameters:
v1
- a keyv2
- a key to compare withv1
- Returns:
true
if the two keys match.
-
directHash
Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as thehashFunc
parameter, when using opaque pointers compared by pointer value as keys in aGHashTable
.This hash function is also appropriate for keys that are integers stored in pointers, such as
GINT_TO_POINTER (n)
.- Parameters:
v
- agpointer
key- Returns:
- a hash value corresponding to the key.
-
dngettext
public static String dngettext(@Nullable @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, ornull
to use the domain set with textdomain()msgid
- message to translatemsgidPlural
- plural form of the messagen
- the quantity for which translation is needed- Returns:
- The translated string
-
doubleEqual
Compares the twogdouble
values being pointed to and returnstrue
if they are equal. It can be passed to g_hash_table_new() as thekeyEqualFunc
parameter, when using non-null
pointers to doubles as keys in aGHashTable
.- Parameters:
v1
- a pointer to agdouble
keyv2
- a pointer to agdouble
key to compare withv1
- Returns:
true
if the two keys match.
-
doubleHash
Converts a pointer to agdouble
to a hash value. It can be passed to g_hash_table_new() as thehashFunc
parameter, It can be passed to g_hash_table_new() as thehashFunc
parameter, when using non-null
pointers to doubles as keys in aGHashTable
.- Parameters:
v
- a pointer to agdouble
key- Returns:
- a hash value corresponding to the key.
-
dpgettext
public static String dpgettext(@Nullable @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 inmsgctxtid
. If 0 is passed asmsgidoffset
, 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, ornull
to use the domain set with textdomain()msgctxtid
- a combined message context and message id, separated by a \\004 charactermsgidoffset
- the offset of the message id inmsgctxid
- Returns:
- The translated string
-
dpgettext2
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 inmsgctxtid
.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, ornull
to use the domain set with textdomain()context
- the message contextmsgid
- the message- Returns:
- The translated string
-
environGetenv
Returns the value of the environment variablevariable
in the provided listenvp
.- Parameters:
envp
- an environment list (eg, as returned from g_get_environ()), ornull
for an empty environment listvariable
- the environment variable to get- Returns:
- the value of the environment variable, or
null
if the environment variable is not set inenvp
. The returned string is owned byenvp
, and will be freed ifvariable
is set or unset again.
-
environSetenv
public static String[] environSetenv(@Nullable @Nullable String[] envp, String variable, String value, boolean overwrite) Sets the environment variablevariable
in the provided listenvp
tovalue
.- Parameters:
envp
- an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), ornull
for an empty environment listvariable
- the environment variable to set, must not contain '='value
- the value for to set the variable tooverwrite
- whether to change the variable if it already exists- Returns:
- the updated environment list. Free it using g_strfreev().
-
environUnsetenv
Removes the environment variablevariable
from the provided environmentenvp
.- Parameters:
envp
- an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), ornull
for an empty environment listvariable
- the environment variable to remove, must not contain '='- Returns:
- the updated environment list. Free it using g_strfreev().
-
fdwalkSetCloexec
public static int fdwalkSetCloexec(int lowfd) Mark every file descriptor equal to or greater thanlowfd
to be closed at the nextexecve()
or similar, as if via theFD_CLOEXEC
flag.Typically
lowfd
will be 3, to leave standard input, standard output and standard error open after exec.This is the same as Linux
close_range (lowfd, ~0U, CLOSE_RANGE_CLOEXEC)
, but portable to other OSs and to older versions of Linux.This function is async-signal safe, making it safe to call from a signal handler or a
GLib.SpawnChildSetupFunc
, as long aslowfd
is non-negative. Seesignal(7)
) andsignal-safety(7)
) for more details.- Parameters:
lowfd
- Minimum fd to act on, which must be non-negative- Returns:
- 0 on success, -1 with errno set on error
-
fileErrorFromErrno
Gets aGFileError
constant based on the passed-inerrNo
.For example, if you pass in
EEXIST
this function returnsFileError.EXIST
. Unlikeerrno
values, you can portably assume that allGFileError
values will exist.Normally a
GFileError
value goes into aGError
returned from a function that manipulates files. So you would use g_file_error_from_errno() when constructing aGError
.- Parameters:
errNo
- an "errno" value- Returns:
GFileError
corresponding to the givenerrNo
-
fileErrorQuark
-
fileGetContents
Reads an entire file into allocated memory, with good error checking.If the call was successful, it returns
true
and setscontents
to the file contents andlength
to the length of the file contents in bytes. The string stored incontents
will be nul-terminated, so for text files you can passnull
for thelength
argument. If the call was not successful, it returnsfalse
and setserror
. The error domain isG_FILE_ERROR
. Possible error codes are those in theGFileError
enumeration. In the error case,contents
is set tonull
andlength
is set to zero.- Parameters:
filename
- name of a file to read contents from, in the GLib file name encodingcontents
- 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
- seeGError
-
fileOpenTmp
public static int fileOpenTmp(@Nullable @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 isnull
, 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 innameUsed
. 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, ornull
for a default templatenameUsed
- location to store actual name used, ornull
- 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
- seeGError
-
fileReadLink
Reads the contents of the symbolic linkfilename
like the POSIXreadlink()
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
- seeGError
-
fileSetContents
Writes all ofcontents
to a file namedfilename
. This is a convenience wrapper around calling g_file_set_contents_full() withflags
set toG_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING
andmode
set to0666
.- Parameters:
filename
- name of a file to writecontents
to, in the GLib file name encodingcontents
- string to write to the file- Returns:
true
on success,false
if an error occurred- Throws:
GErrorException
- seeGError
-
fileSetContentsFull
public static boolean fileSetContentsFull(String filename, byte[] contents, Set<FileSetContentsFlags> flags, int mode) throws GErrorException Writes all ofcontents
to a file namedfilename
, with good error checking. If a file calledfilename
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 thanFileSetContentsFlags.NONE
then this function may callfsync()
.If
FileSetContentsFlags.CONSISTENT
is set inflags
, 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 tofilename
will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. Iffilename
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 ifFileSetContentsFlags.CONSISTENT
is set inflags
, thefsync()
call (or equivalent) will be used to ensure atomic replacement:filename
will contain either its old contents orcontents
, 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 leavefilename
empty or full of NUL bytes, depending on the underlying filesystem, unlessFileSetContentsFlags.DURABLE
andFileSetContentsFlags.CONSISTENT
are set inflags
.
- 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 returnsfalse
and setserror
. The error domain isG_FILE_ERROR
. Possible error codes are those in theGFileError
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 may be changed tomode
depending onflags
, or they may remain unchanged.- Parameters:
filename
- name of a file to writecontents
to, in the GLib file name encodingcontents
- string to write to the fileflags
- flags controlling the safety vs speed of the operationmode
- file mode, as passed toopen()
; typically this will be0666
- Returns:
true
on success,false
if an error occurred- Throws:
GErrorException
- seeGError
- On UNIX, if
-
fileSetContentsFull
public static boolean fileSetContentsFull(String filename, byte[] contents, FileSetContentsFlags flags, int mode) throws GErrorException Writes all ofcontents
to a file namedfilename
, with good error checking. If a file calledfilename
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 thanFileSetContentsFlags.NONE
then this function may callfsync()
.If
FileSetContentsFlags.CONSISTENT
is set inflags
, 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 tofilename
will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. Iffilename
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 ifFileSetContentsFlags.CONSISTENT
is set inflags
, thefsync()
call (or equivalent) will be used to ensure atomic replacement:filename
will contain either its old contents orcontents
, 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 leavefilename
empty or full of NUL bytes, depending on the underlying filesystem, unlessFileSetContentsFlags.DURABLE
andFileSetContentsFlags.CONSISTENT
are set inflags
.
- 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 returnsfalse
and setserror
. The error domain isG_FILE_ERROR
. Possible error codes are those in theGFileError
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 may be changed tomode
depending onflags
, or they may remain unchanged.- Parameters:
filename
- name of a file to writecontents
to, in the GLib file name encodingcontents
- string to write to the fileflags
- flags controlling the safety vs speed of the operationmode
- file mode, as passed toopen()
; typically this will be0666
- Returns:
true
on success,false
if an error occurred- Throws:
GErrorException
- seeGError
- On UNIX, if
-
fileTest
Returnstrue
if any of the tests in the bitfieldtest
aretrue
. For example,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
will returntrue
if the file exists; the check whether it's a directory doesn't matter since the existence test istrue
. 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 returntrue
for bothFileTest.IS_SYMLINK
andFileTest.IS_REGULAR
.Note, that for a dangling symbolic link g_file_test() will return
true
forFileTest.IS_SYMLINK
andfalse
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
andFileTest.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 returnfalse
. Testing forFileTest.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 thePATHEXT
environment variable.- Parameters:
filename
- a filename to test in the GLib file name encodingtest
- bitfield ofGFileTest
flags- Returns:
- whether a test was
true
-
fileTest
Returnstrue
if any of the tests in the bitfieldtest
aretrue
. For example,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
will returntrue
if the file exists; the check whether it's a directory doesn't matter since the existence test istrue
. 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 returntrue
for bothFileTest.IS_SYMLINK
andFileTest.IS_REGULAR
.Note, that for a dangling symbolic link g_file_test() will return
true
forFileTest.IS_SYMLINK
andfalse
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
andFileTest.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 returnfalse
. Testing forFileTest.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 thePATHEXT
environment variable.- Parameters:
filename
- a filename to test in the GLib file name encodingtest
- bitfield ofGFileTest
flags- Returns:
- whether a test was
true
-
filenameDisplayBasename
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 iffilename
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
-
filenameDisplayName
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 iffilename
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
-
filenameFromUri
public static String filenameFromUri(String uri, @Nullable @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
- seeGError
-
filenameFromUtf8
public static String filenameFromUtf8(String utf8string, long len, @Nullable @Nullable Out<Long> bytesRead, @Nullable @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][setlocale].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 errorConvertError.ILLEGAL_SEQUENCE
. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the errorConvertError.EMBEDDED_NUL
is set and the function returnsnull
.- 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, ornull
. Even if the conversion was successful, this may be less thanlen
if there were partial characters at the end of the input. If the errorConvertError.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
- seeGError
-
filenameToUri
public static String filenameToUri(String filename, @Nullable @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 Windowshostname
- A UTF-8 encoded hostname, ornull
for none.- Returns:
- a newly-allocated string holding the resulting
URI, or
null
on an error. - Throws:
GErrorException
- seeGError
-
filenameToUtf8
public static String filenameToUtf8(String opsysstring, long len, @Nullable @Nullable Out<Long> bytesRead, @Nullable @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][setlocale].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 errorConvertError.ILLEGAL_SEQUENCE
. If the source encoding is not UTF-8 and the conversion output contains a nul character, the errorConvertError.EMBEDDED_NUL
is set and the function returnsnull
. Use g_convert() to produce output that may contain embedded nul characters.- Parameters:
opsysstring
- a string in the encoding for filenameslen
- 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 thelen
parameter is unsafe)bytesRead
- location to store the number of bytes in the input string that were successfully converted, ornull
. Even if the conversion was successful, this may be less thanlen
if there were partial characters at the end of the input. If the errorConvertError.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
- seeGError
-
findProgramInPath
Locates the first executable namedprogram
in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, ornull
if the program is not found in the path. Ifprogram
is already an absolute path, returns a copy ofprogram
ifprogram
exists and is executable, andnull
otherwise. On Windows, ifprogram
does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in thePATHEXT
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
A wrapper for the stdiofopen()
function. Thefopen()
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, theFILE*
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 likefprintf()
orfread()
.See your C library manual for more details about
fopen()
.As
close()
andfclose()
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.- 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, ornull
if an error occurred
-
formatSize
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
-
formatSizeForDisplay
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
-
formatSizeFull
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 bytesflags
-GFormatSizeFlags
to modify the output- Returns:
- a newly-allocated formatted string containing a human readable file size
-
formatSizeFull
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 bytesflags
-GFormatSizeFlags
to modify the output- Returns:
- a newly-allocated formatted string containing a human readable file size
-
fprintf
An implementation of the standardfprintf()
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 toformat
- a standardprintf()
format string, but notice string precision pitfallsvarargs
- the arguments to insert in the output- Returns:
- the number of bytes printed
-
free
Frees the memory pointed to bymem
.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()
](https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html) to understand its caveats).If
mem
isnull
it simply returns, so there is no need to checkmem
againstnull
before calling this function.- Parameters:
mem
- the memory to free
-
freeSized
Frees the memory pointed to bymem
, assuming it is has the givensize
.If
mem
isnull
this is a no-op (andsize
is ignored).It is an error if
size
doesn’t match the size passed whenmem
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 freesize
- size ofmem
, in bytes
-
freopen
public static MemorySegment freopen(String filename, String mode, @Nullable @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().
- 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 openedstream
- an existing stream which will be reused, ornull
- Returns:
- A FILE* if the file was successfully opened, or
null
if an error occurred.
-
fsync
public static int fsync(int fd) A wrapper for the POSIXfsync()
function. On Windows,_commit()
will be used. On macOS,fcntl(F_FULLFSYNC)
will be used. Thefsync()
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().
-
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 benull
if g_set_prgname() has also not been called).- Returns:
- human-readable application
name. May return
null
-
getCharset
Obtains the character set for the [current locale][setlocale]; 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
andCHARSET
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, ornull
.- Returns:
true
if the returned charset is UTF-8
-
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
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, ornull
.- Returns:
true
if the returned charset is UTF-8
-
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.GTimeVal
is not year-2038-safe. UsegetRealTime()
instead.Equivalent to the UNIX gettimeofday() function, but portable.You may find
getRealTime()
to be more convenient.- Parameters:
result
-GTimeVal
structure in which to store current time.
-
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
-
getFilenameCharsets
Determines the preferred character sets used for filenames. The first character set from thecharsets
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
andG_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][setlocale]. IfG_FILENAME_ENCODING
is not set, butG_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 thenull
-terminated list of encoding names- Returns:
true
if the filename encoding is UTF-8.
-
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 thepasswd
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 thepasswd
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
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.
-
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
andLANG
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.
-
getLanguageNamesWithCategory
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
, andLANG
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.
-
getLocaleVariants
Returns a list of derived variants oflocale
, 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. Seesetlocale(3)
for information about locales and their format.locale
itself is guaranteed to be returned in the output.For example, if
locale
isfr_BE
, then the returned list isfr_BE
,fr
. Iflocale
isen_GB.UTF-8@euro
, then the returned list isen_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().
-
getMonotonicTime
public static long getMonotonicTime()Queries the system monotonic time.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.
- Returns:
- the monotonic time, in microseconds
-
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
-
getOsInfo
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 likeG_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 isnull
.- Parameters:
keyName
- a key for the OS info being requested, for exampleG_OS_INFO_KEY_NAME
.- Returns:
- The associated value for the requested key or
null
if this information is not provided.
-
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 theGtkApplication
::startup handler. The program name is found by taking the last component ofargv
[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
Gets the real name of the user. This usually comes from the user's entry in thepasswd
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 call is functionally equivalent to
getCurrentTime(org.gnome.glib.TimeVal)
except that the return value is often more convenient than dealing with aGTimeVal
.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.
-
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. IfXDG_CONFIG_DIRS
is undefined, the directory that contains application data for all users is used instead. A typical path isC:\\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.
-
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. IfXDG_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.
-
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
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. IfXDG_CACHE_HOME
is undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path isC:\\Documents and Settings\\username\\Local Settings\\Temporary Internet Files
. See the documentation forFOLDERID_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.
-
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. IfXDG_CONFIG_HOME
is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation forFOLDERID_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.
-
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. IfXDG_DATA_HOME
is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation forFOLDERID_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.
-
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
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.
-
getUserSpecialDir
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.
-
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. IfXDG_STATE_HOME
is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation forFOLDERID_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.
-
getenv
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
Tests ifhostname
contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returnstrue
, 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
ifhostname
contains any ASCII-encoded segments.
-
hostnameIsIpAddress
Tests ifhostname
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
ifhostname
is an IP address
-
hostnameIsNonAscii
Tests ifhostname
contains Unicode characters. If this returnstrue
, 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
ifhostname
contains any non-ASCII characters
-
hostnameToAscii
Convertshostname
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
ifhostname
is in some way invalid.
-
hostnameToUnicode
Convertshostname
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
ifhostname
is in some way invalid.
-
iconv
public static long iconv(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.- Parameters:
converter
- conversion descriptor from g_iconv_open()inbuf
- bytes to convertinbytesLeft
- inout parameter, bytes remaining to convert ininbuf
outbuf
- converted output bytesoutbytesLeft
- inout parameter, bytes available to fill inoutbuf
- Returns:
- count of non-reversible conversions, or -1 on error
-
idleAdd
Adds a function to be called whenever there are no higher priority events pending.If the function returns
GLib.SOURCE_REMOVE
orfalse
it is automatically removed from the list of event sources and will not be called again.See mainloop 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 globalGLib.MainContext
usingSource.attach(org.gnome.glib.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 betweenGLib.PRIORITY_DEFAULT_IDLE
andGLib.PRIORITY_HIGH_IDLE
.function
- function to call- Returns:
- the ID (greater than 0) of the event source.
-
idleAddOnce
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, org.gnome.glib.SourceFunc)
.- Parameters:
function
- function to call- Returns:
- the ID (greater than 0) of the event source
-
idleRemoveByData
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.
-
idleSourceNew
Creates a new idle source.The source will not initially be associated with any
GLib.MainContext
and must be added to one withSource.attach(org.gnome.glib.MainContext)
before it will be executed. Note that the default priority for idle sources isGLib.PRIORITY_DEFAULT_IDLE
, as compared to other sources which have a default priority ofGLib.PRIORITY_DEFAULT
.- Returns:
- the newly-created idle source
-
int64Equal
Compares the twogint64
values being pointed to and returnstrue
if they are equal. It can be passed to g_hash_table_new() as thekeyEqualFunc
parameter, when using non-null
pointers to 64-bit integers as keys in aGHashTable
.- Parameters:
v1
- a pointer to agint64
keyv2
- a pointer to agint64
key to compare withv1
- Returns:
true
if the two keys match.
-
int64Hash
Converts a pointer to agint64
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 aGHashTable
.- Parameters:
v
- a pointer to agint64
key- Returns:
- a hash value corresponding to the key.
-
intEqual
Compares the twogint
values being pointed to and returnstrue
if they are equal. It can be passed to g_hash_table_new() as thekeyEqualFunc
parameter, when using non-null
pointers to integers as keys in aGHashTable
.Note that this function acts on pointers to
gint
, not ongint
directly: if your hash table's keys are of the formGINT_TO_POINTER (n)
, use g_direct_equal() instead.- Parameters:
v1
- a pointer to agint
keyv2
- a pointer to agint
key to compare withv1
- Returns:
true
if the two keys match.
-
intHash
Converts a pointer to agint
to a hash value. It can be passed to g_hash_table_new() as thehashFunc
parameter, when using non-null
pointers to integer values as keys in aGHashTable
.Note that this function acts on pointers to
gint
, not ongint
directly: if your hash table's keys are of the formGINT_TO_POINTER (n)
, use g_direct_hash() instead.- Parameters:
v
- a pointer to agint
key- Returns:
- a hash value corresponding to the key.
-
internStaticString
Returns a canonical representation forstring
. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). g_intern_static_string() does not copy the string, thereforestring
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
-
internString
Returns a canonical representation forstring
. 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
-
ioAddWatch
public static int ioAddWatch(IOChannel channel, int priority, Set<IOCondition> condition, IOFunc func) Adds theGIOChannel
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
- aGIOChannel
priority
- the priority of theGIOChannel
sourcecondition
- the condition to watch forfunc
- the function to call when the condition is satisfied- Returns:
- the event source id
-
ioAddWatch
Adds theGIOChannel
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
- aGIOChannel
priority
- the priority of theGIOChannel
sourcecondition
- the condition to watch forfunc
- the function to call when the condition is satisfied- Returns:
- the event source id
-
ioCreateWatch
Creates aGSource
that's dispatched whencondition
is met for the givenchannel
. For example, if condition isIOCondition.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 typeGIOFunc
(notGSourceFunc
).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
- aGIOChannel
to watchcondition
- conditions to watch for- Returns:
- a new
GSource
-
ioCreateWatch
Creates aGSource
that's dispatched whencondition
is met for the givenchannel
. For example, if condition isIOCondition.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 typeGIOFunc
(notGSourceFunc
).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
- aGIOChannel
to watchcondition
- conditions to watch for- Returns:
- a new
GSource
-
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().
-
localeFromUtf8
public static byte[] localeFromUtf8(String utf8string, long len, @Nullable @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][setlocale]. 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 errorConvertError.ILLEGAL_SEQUENCE
. Use g_convert() to convert input that may contain embedded nul characters.- Parameters:
utf8string
- a UTF-8 encoded stringlen
- 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, ornull
. Even if the conversion was successful, this may be less thanlen
if there were partial characters at the end of the input. If the errorConvertError.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
- seeGError
-
localeToUtf8
public static String localeToUtf8(byte[] opsysstring, @Nullable @Nullable Out<Long> bytesRead, @Nullable @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][setlocale] 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 returnsnull
. If the source encoding is UTF-8, an embedded nul character is treated with theConvertError.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, ornull
. Even if the conversion was successful, this may be less thanlen
if there were partial characters at the end of the input. If the errorConvertError.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
- seeGError
-
log
public static void log(@Nullable @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 forGLib#BREAKPOINT
for details of the debugging options this provides.If
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.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(org.gnome.glib.LogWriterFunc)
).- Parameters:
logDomain
- the log domain, usuallyG_LOG_DOMAIN
, orNULL
for the defaultlogLevel
- the log level, either fromGLib.LogLevelFlags
or a user-defined levelformat
- the message format. See theprintf()
documentationvarargs
- the parameters to insert into the format string
-
log
public static void log(@Nullable @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 forGLib#BREAKPOINT
for details of the debugging options this provides.If
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.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(org.gnome.glib.LogWriterFunc)
).- Parameters:
logDomain
- the log domain, usuallyG_LOG_DOMAIN
, orNULL
for the defaultlogLevel
- the log level, either fromGLib.LogLevelFlags
or a user-defined levelformat
- the message format. See theprintf()
documentationvarargs
- the parameters to insert into the format string
-
logDefaultHandler
public static void logDefaultHandler(@Nullable @Nullable String logDomain, Set<LogLevelFlags> logLevel, @Nullable @Nullable String message, @Nullable @Nullable MemorySegment unusedData) The default log handler set up by GLib;logSetDefaultHandler(org.gnome.glib.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
orstdout
and if the log level is fatal it callsGLib#BREAKPOINT
. It automatically prints a new-line character after the message, so one does not need to be manually included inmessage
.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, uselogWriterDefaultSetDebugDomains(java.lang.String)
.
stderr
is used for levelsGLib.LogLevelFlags.LEVEL_ERROR
,GLib.LogLevelFlags.LEVEL_CRITICAL
,GLib.LogLevelFlags.LEVEL_WARNING
andGLib.LogLevelFlags.LEVEL_MESSAGE
.stdout
is used for the rest, unlessstderr
was requested bylogWriterDefaultSetUseStderr(boolean)
.This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain
- the log domain of the message, orNULL
for the default""
application domainlogLevel
- the level of the messagemessage
- the messageunusedData
- data passed fromlog(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.Object...)
which is unused
-
logDefaultHandler
public static void logDefaultHandler(@Nullable @Nullable String logDomain, LogLevelFlags logLevel, @Nullable @Nullable String message, @Nullable @Nullable MemorySegment unusedData) The default log handler set up by GLib;logSetDefaultHandler(org.gnome.glib.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
orstdout
and if the log level is fatal it callsGLib#BREAKPOINT
. It automatically prints a new-line character after the message, so one does not need to be manually included inmessage
.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, uselogWriterDefaultSetDebugDomains(java.lang.String)
.
stderr
is used for levelsGLib.LogLevelFlags.LEVEL_ERROR
,GLib.LogLevelFlags.LEVEL_CRITICAL
,GLib.LogLevelFlags.LEVEL_WARNING
andGLib.LogLevelFlags.LEVEL_MESSAGE
.stdout
is used for the rest, unlessstderr
was requested bylogWriterDefaultSetUseStderr(boolean)
.This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain
- the log domain of the message, orNULL
for the default""
application domainlogLevel
- the level of the messagemessage
- the messageunusedData
- data passed fromlog(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.Object...)
which is unused
-
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 fromGLib.LogWriterFunc
implementations.Note also that the value of this does not depend on
G_MESSAGES_DEBUG
, norlogWriterDefaultSetDebugDomains(java.lang.String)
; see the docs forlogSetDebugEnabled(boolean)
.- Returns:
TRUE
if debug output is enabled,FALSE
otherwise
-
logRemoveHandler
Removes the log handler.This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain
- the log domainhandlerId
- the ID of the handler, which was returned inlogSetHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogFunc)
-
logSetAlwaysFatal
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
andlogStructuredArray(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.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
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
andlogStructuredArray(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.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
andlogWriterDefaultSetDebugDomains(java.lang.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
-
logSetDefaultHandler
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.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
-
logSetFatalMask
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
orlogStructuredArray(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
). To change the fatal behaviour for specific log messages, programs must install a custom log writer function usinglogSetWriterFunc(org.gnome.glib.LogWriterFunc)
. See Using Structured Logging.This function is mostly intended to be used with
GLib.LogLevelFlags.LEVEL_CRITICAL
. You should typically not setGLib.LogLevelFlags.LEVEL_WARNING
,GLib.LogLevelFlags.LEVEL_MESSAGE
,GLib.LogLevelFlags.LEVEL_INFO
orGLib.LogLevelFlags.LEVEL_DEBUG
as fatal except inside of test programs.- Parameters:
logDomain
- the log domainfatalMask
- the new fatal mask- Returns:
- the old fatal mask for the log domain
-
logSetFatalMask
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
orlogStructuredArray(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
). To change the fatal behaviour for specific log messages, programs must install a custom log writer function usinglogSetWriterFunc(org.gnome.glib.LogWriterFunc)
. See Using Structured Logging.This function is mostly intended to be used with
GLib.LogLevelFlags.LEVEL_CRITICAL
. You should typically not setGLib.LogLevelFlags.LEVEL_WARNING
,GLib.LogLevelFlags.LEVEL_MESSAGE
,GLib.LogLevelFlags.LEVEL_INFO
orGLib.LogLevelFlags.LEVEL_DEBUG
as fatal except inside of test programs.- Parameters:
logDomain
- the log domainfatalMask
- the new fatal mask- Returns:
- the old fatal mask for the log domain
-
logSetHandler
public static int logSetHandler(@Nullable @Nullable String logDomain, Set<LogLevelFlags> logLevels, LogFunc logFunc) LikelogSetHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogFunc)
, but takes a destroy notify for theuserData
.This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain
- the log domain, orNULL
for the default""
application domainlogLevels
- the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with theGLib.LogLevelFlags.FLAG_FATAL
andGLib.LogLevelFlags.FLAG_RECURSION
bit flags.logFunc
- the log handler function- Returns:
- the ID of the new handler
-
logSetHandler
public static int logSetHandler(@Nullable @Nullable String logDomain, LogLevelFlags logLevels, LogFunc logFunc) LikelogSetHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogFunc)
, but takes a destroy notify for theuserData
.This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain
- the log domain, orNULL
for the default""
application domainlogLevels
- the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with theGLib.LogLevelFlags.FLAG_FATAL
andGLib.LogLevelFlags.FLAG_RECURSION
bit flags.logFunc
- the log handler function- Returns:
- the ID of the new handler
-
logSetWriterFunc
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(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.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 beNULL
-
logStructured
Log a message with structured data.The message will be passed through to the log writer set by the application using
logSetWriterFunc(org.gnome.glib.LogWriterFunc)
. If the message is fatal (i.e. its log level isGLib.LogLevelFlags.LEVEL_ERROR
), the program will be aborted by callingGLib#BREAKPOINT
at the end of this function. If the log writer returnsGLib.LogWriterOutput.UNHANDLED
(failure), no other fallback writers will be tried. See the documentation forGLib.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(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
. The keys for structured data should follow the [systemd journal fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html) specification. It is suggested that custom keys are namespaced according to the code which sets them. For example, custom keys from GLib all have aGLIB_
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 theGLogField
. Starting with GLib 2.74.1 this is fixed and non-nul-terminated UTF-8 strings can be passed with their correct length.The
logDomain
will be converted into aGLIB_DOMAIN
field.logLevel
will be converted into aPRIORITY
field. The format string will have its placeholders substituted for the provided values and be converted into aMESSAGE
field.Other fields you may commonly want to pass into this function:
Note that
CODE_FILE
,CODE_LINE
andCODE_FUNC
are automatically set by the logging macros,GLib#DEBUGHERE
,GLib#message
,GLib#warning
,GLib#critical
,GLib#error
, etc, if the symbolG_LOG_USE_STRUCTURED
is defined before includingglib.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](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.htmlMESSAGE_ID
=). If adding aMESSAGE_ID
, consider shipping a [message catalog](https://www.freedesktop.org/wiki/Software/systemd/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(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
and pass the pointer as a field withGLogField.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. TheMESSAGE
-format pair has to be the last of the key-value pairs, andMESSAGE
is the only field for whichprintf()
-style formatting is supported.The default writer function for
stdout
andstderr
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, usuallyG_LOG_DOMAIN
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levelvarargs
- key-value pairs of structured data to add to the log entry, followed by the keyMESSAGE
, followed by aprintf()
-style message format, followed by parameters to insert in the format string
-
logStructured
Log a message with structured data.The message will be passed through to the log writer set by the application using
logSetWriterFunc(org.gnome.glib.LogWriterFunc)
. If the message is fatal (i.e. its log level isGLib.LogLevelFlags.LEVEL_ERROR
), the program will be aborted by callingGLib#BREAKPOINT
at the end of this function. If the log writer returnsGLib.LogWriterOutput.UNHANDLED
(failure), no other fallback writers will be tried. See the documentation forGLib.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(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
. The keys for structured data should follow the [systemd journal fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html) specification. It is suggested that custom keys are namespaced according to the code which sets them. For example, custom keys from GLib all have aGLIB_
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 theGLogField
. Starting with GLib 2.74.1 this is fixed and non-nul-terminated UTF-8 strings can be passed with their correct length.The
logDomain
will be converted into aGLIB_DOMAIN
field.logLevel
will be converted into aPRIORITY
field. The format string will have its placeholders substituted for the provided values and be converted into aMESSAGE
field.Other fields you may commonly want to pass into this function:
Note that
CODE_FILE
,CODE_LINE
andCODE_FUNC
are automatically set by the logging macros,GLib#DEBUGHERE
,GLib#message
,GLib#warning
,GLib#critical
,GLib#error
, etc, if the symbolG_LOG_USE_STRUCTURED
is defined before includingglib.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](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.htmlMESSAGE_ID
=). If adding aMESSAGE_ID
, consider shipping a [message catalog](https://www.freedesktop.org/wiki/Software/systemd/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(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
and pass the pointer as a field withGLogField.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. TheMESSAGE
-format pair has to be the last of the key-value pairs, andMESSAGE
is the only field for whichprintf()
-style formatting is supported.The default writer function for
stdout
andstderr
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, usuallyG_LOG_DOMAIN
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levelvarargs
- key-value pairs of structured data to add to the log entry, followed by the keyMESSAGE
, followed by aprintf()
-style message format, followed by parameters to insert in the format string
-
logStructuredArray
Log a message with structured data.The message will be passed through to the log writer set by the application using
logSetWriterFunc(org.gnome.glib.LogWriterFunc)
. If the message is fatal (i.e. its log level isGLib.LogLevelFlags.LEVEL_ERROR
), the program will be aborted at the end of this function.See
logStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
for more documentation.This assumes that
logLevel
is already present infields
(typically as thePRIORITY
field).- Parameters:
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data to add to the log message
-
logStructuredArray
Log a message with structured data.The message will be passed through to the log writer set by the application using
logSetWriterFunc(org.gnome.glib.LogWriterFunc)
. If the message is fatal (i.e. its log level isGLib.LogLevelFlags.LEVEL_ERROR
), the program will be aborted at the end of this function.See
logStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
for more documentation.This assumes that
logLevel
is already present infields
(typically as thePRIORITY
field).- Parameters:
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data to add to the log message
-
logStructuredStandard
-
logStructuredStandard
-
logVariant
public static void logVariant(@Nullable @Nullable String logDomain, Set<LogLevelFlags> logLevel, Variant fields) Log a message with structured data, accepting the data within aGLib.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 typeG_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 thanG_MAXSSIZE
. Otherwise it will be truncated to this size. For other typesVariant.print(boolean)
will be used to convert the value into a string.For more details on its usage and about the parameters, see
logStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
.- Parameters:
logDomain
- log domain, usuallyG_LOG_DOMAIN
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levelfields
- a dictionary (GLib.Variant
of the typeG_VARIANT_TYPE_VARDICT
) containing the key-value pairs of message data.
-
logVariant
public static void logVariant(@Nullable @Nullable String logDomain, LogLevelFlags logLevel, Variant fields) Log a message with structured data, accepting the data within aGLib.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 typeG_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 thanG_MAXSSIZE
. Otherwise it will be truncated to this size. For other typesVariant.print(boolean)
will be used to convert the value into a string.For more details on its usage and about the parameters, see
logStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
.- Parameters:
logDomain
- log domain, usuallyG_LOG_DOMAIN
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levelfields
- a dictionary (GLib.Variant
of the typeG_VARIANT_TYPE_VARDICT
) containing the key-value pairs of message data.
-
logWriterDefault
public static LogWriterOutput logWriterDefault(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable @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
orstderr
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 usinglogSetWriterFunc(org.gnome.glib.LogWriterFunc)
.As with
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
, this function drops debug and informational messages unless their log domain (orall
) is listed in the space-separatedG_MESSAGES_DEBUG
environment variable, or set at runtime bylogWriterDefaultSetDebugDomains(java.lang.String)
.logWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
uses the mask set bylogSetAlwaysFatal(java.util.Set<org.gnome.glib.LogLevelFlags>)
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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterDefault
public static LogWriterOutput logWriterDefault(LogLevelFlags logLevel, LogField[] fields, @Nullable @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
orstderr
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 usinglogSetWriterFunc(org.gnome.glib.LogWriterFunc)
.As with
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
, this function drops debug and informational messages unless their log domain (orall
) is listed in the space-separatedG_MESSAGES_DEBUG
environment variable, or set at runtime bylogWriterDefaultSetDebugDomains(java.lang.String)
.logWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
uses the mask set bylogSetAlwaysFatal(java.util.Set<org.gnome.glib.LogLevelFlags>)
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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterDefaultSetDebugDomains
Reset the list of domains to be logged, that might be initially set by theG_MESSAGES_DEBUG
environment variable.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.
-
logWriterDefaultSetUseStderr
public static void logWriterDefaultSetUseStderr(boolean useStderr) Configure whether the built-in log functions will output all log messages tostderr
.The built-in log functions are
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
for the old-style API, and bothlogWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
andlogWriterStandardStreams(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
for the structured API.By default, log messages of levels
GLib.LogLevelFlags.LEVEL_INFO
andGLib.LogLevelFlags.LEVEL_DEBUG
are sent tostdout
, and other log messages are sent tostderr
. This is problematic for applications that intend to reservestdout
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
- IfTRUE
, usestderr
for log messages that would normally have appeared onstdout
-
logWriterDefaultWouldDrop
public static boolean logWriterDefaultWouldDrop(Set<LogLevelFlags> logLevel, @Nullable @Nullable String logDomain) Check whetherlogWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
andlogDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
would ignore a message with the given domain and level.As with
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
, this function drops debug and informational messages unless their log domain (orall
) is listed in the space-separatedG_MESSAGES_DEBUG
environment variable, or bylogWriterDefaultSetDebugDomains(java.lang.String)
.This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:
c if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN)) { g_autofree gchar *result = expensive_computation (my_object);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 {@code G_MESSAGES_DEBUG} is not set:
g_debug ("my_object result:
s
", result); } ```- Parameters:
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levellogDomain
- log domain- Returns:
TRUE
if the log message would be dropped by GLib’s default log handlers
-
logWriterDefaultWouldDrop
public static boolean logWriterDefaultWouldDrop(LogLevelFlags logLevel, @Nullable @Nullable String logDomain) Check whetherlogWriterDefault(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[], java.lang.foreign.MemorySegment)
andlogDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
would ignore a message with the given domain and level.As with
logDefaultHandler(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.foreign.MemorySegment)
, this function drops debug and informational messages unless their log domain (orall
) is listed in the space-separatedG_MESSAGES_DEBUG
environment variable, or bylogWriterDefaultSetDebugDomains(java.lang.String)
.This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:
c if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN)) { g_autofree gchar *result = expensive_computation (my_object);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 {@code G_MESSAGES_DEBUG} is not set:
g_debug ("my_object result:
s
", result); } ```- Parameters:
logLevel
- log level, either fromGLib.LogLevelFlags
, or a user-defined levellogDomain
- log domain- Returns:
TRUE
if the log message would be dropped by GLib’s default log handlers
-
logWriterFormatFields
public static String logWriterFormatFields(Set<LogLevelFlags> logLevel, LogField[] 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
andGLIB_DOMAIN
(see the documentation forlogStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuseColor
-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
-
logWriterFormatFields
public static String logWriterFormatFields(LogLevelFlags logLevel, LogField[] 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
andGLIB_DOMAIN
(see the documentation forlogStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuseColor
-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
-
logWriterIsJournald
public static boolean logWriterIsJournald(int outputFd) Check whether the givenoutputFd
file descriptor is a connection to the systemd journal, or something else (like a log file orstdout
orstderr
).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
ifoutputFd
points to the journal,FALSE
otherwise
-
logWriterJournald
public static LogWriterOutput logWriterJournald(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable @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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterJournald
public static LogWriterOutput logWriterJournald(LogLevelFlags logLevel, LogField[] fields, @Nullable @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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterStandardStreams
public static LogWriterOutput logWriterStandardStreams(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdout
orstderr
, depending on its log level.GLib.LogLevelFlags.LEVEL_INFO
andGLib.LogLevelFlags.LEVEL_DEBUG
messages are sent tostdout
, or tostderr
if requested bylogWriterDefaultSetUseStderr(boolean)
; all other log levels are sent tostderr
. 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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterStandardStreams
public static LogWriterOutput logWriterStandardStreams(LogLevelFlags logLevel, LogField[] fields, @Nullable @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdout
orstderr
, depending on its log level.GLib.LogLevelFlags.LEVEL_INFO
andGLib.LogLevelFlags.LEVEL_DEBUG
messages are sent tostdout
, or tostderr
if requested bylogWriterDefaultSetUseStderr(boolean)
; all other log levels are sent tostderr
. 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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterSupportsColor
public static boolean logWriterSupportsColor(int outputFd) Check whether the givenoutputFd
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
-
logWriterSyslog
public static LogWriterOutput logWriterSyslog(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable @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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
logWriterSyslog
public static LogWriterOutput logWriterSyslog(LogLevelFlags logLevel, LogField[] fields, @Nullable @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 fromGLib.LogLevelFlags
, or a user-defined levelfields
- key–value pairs of structured data forming the log messageuserData
- user data passed tologSetWriterFunc(org.gnome.glib.LogWriterFunc)
- Returns:
GLib.LogWriterOutput.HANDLED
on success,GLib.LogWriterOutput.UNHANDLED
otherwise
-
lstat
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
-
mainCurrentSource
Returns the currently firing source for this thread.- Returns:
- The currently firing source or
null
.
-
mainDepth
public static int mainDepth()Returns the depth of the stack of calls toMainContext.dispatch()
on anyGMainContext
in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback fromMainContext.iteration(boolean)
(orMainLoop.run()
, etc.) it returns 1. When called from within a callback to a recursive call toMainContext.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 ifmainDepth()
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
AllocatesnBytes
bytes of memory. IfnBytes
is 0 it returnsnull
.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
AllocatesnBytes
bytes of memory, initialized to 0's. IfnBytes
is 0 it returnsnull
.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
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 allocatenBlockBytes
- the size of each block in bytes- Returns:
- a pointer to the allocated memory
-
mallocN
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 allocatenBlockBytes
- the size of each block in bytes- Returns:
- a pointer to the allocated memory
-
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 theGMarkupParser
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
anderror
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 benull
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 typeMarkupError.UNKNOWN_ATTRIBUTE
) and duplicate attributes (of typeMarkupError.INVALID_CONTENT
) as well as parse errors for boolean-valued attributes (again of typeMarkupError.INVALID_CONTENT
). In all of these casesfalse
will be returned anderror
will be set as appropriate.- Parameters:
elementName
- the current tag nameattributeNames
- the attribute namesattributeValues
- the attribute valueserror
- a pointer to aGError
ornull
firstType
- theGMarkupCollectType
of the first attributefirstAttr
- the name of the first attributevarargs
- a pointer to the storage location of the first attribute (ornull
), followed by more types names and pointers, ending withMarkupCollectType.INVALID
- Returns:
true
if successful
-
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 theGMarkupParser
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
anderror
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 benull
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 typeMarkupError.UNKNOWN_ATTRIBUTE
) and duplicate attributes (of typeMarkupError.INVALID_CONTENT
) as well as parse errors for boolean-valued attributes (again of typeMarkupError.INVALID_CONTENT
). In all of these casesfalse
will be returned anderror
will be set as appropriate.- Parameters:
elementName
- the current tag nameattributeNames
- the attribute namesattributeValues
- the attribute valueserror
- a pointer to aGError
ornull
firstType
- theGMarkupCollectType
of the first attributefirstAttr
- the name of the first attributevarargs
- a pointer to the storage location of the first attribute (ornull
), followed by more types names and pointers, ending withMarkupCollectType.INVALID
- Returns:
true
if successful
-
markupErrorQuark
-
markupEscapeText
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 textlength
- length oftext
in bytes, or -1 if the text is nul-terminated- Returns:
- a newly allocated string with the escaped text
-
markupPrintfEscaped
Formats arguments according toformat
, 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 stringvarargs
- the arguments to insert in the format string- Returns:
- newly allocated result from formatting operation. Free with g_free().
-
memIsSystemMalloc
Deprecated.GLib always uses the system malloc, so this function always returnstrue
.Checks whether the allocator used by g_malloc() is the system's malloc implementation. If it returnstrue
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.Use other memory profiling tools insteadGLib 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.This function now does nothing. Use other memory profiling tools insteadThis 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.Usememdup2(java.lang.foreign.MemorySegment, long)
instead, as it accepts a gsize argument forbyteSize
, avoiding the possibility of overflow in agsize
→guint
conversionAllocatesbyteSize
bytes of memory, and copiesbyteSize
bytes into it frommem
. Ifmem
isNULL
it returnsNULL
.- Parameters:
mem
- the memory to copybyteSize
- the number of bytes to copy- Returns:
- a pointer to the newly-allocated copy of the memory
-
memdup2
AllocatesbyteSize
bytes of memory, and copiesbyteSize
bytes into it frommem
. Ifmem
isNULL
it returnsNULL
.This replaces
memdup(java.lang.foreign.MemorySegment, int)
, which was prone to integer overflows when converting the argument from agsize
to aguint
.- Parameters:
mem
- the memory to copybyteSize
- the number of bytes to copy- Returns:
- a pointer to the newly-allocated copy of the memory
-
mkdir
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
-
mkdirWithParents
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 encodingmode
- 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.
-
mkdtemp
Creates a temporary 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 anderrno
will be set.
-
mkdtempFull
Creates a temporary 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 namemode
- 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, anderrno
will be set.
-
mkstemp
Opens a temporary file. 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
Opens a temporary file. 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 additionalflags
. 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 filenameflags
- flags to pass to an open() call in addition to O_EXCL and O_CREAT, which are passed automaticallymode
- 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.
-
nullifyPointer
Set the pointer at the specified location tonull
.- Parameters:
nullifyLocation
- the memory address of the pointer.
-
numberParserErrorQuark
-
onErrorQuery
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 "[E]xit" is selected, the application terminates with a call to _exit(0).
If "[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 "[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 "[S]tack trace" option. IfprgName
isnull
, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called)
-
onErrorStackTrace
Invokes gdb, which attaches to the current process and shows a stack trace. Called by g_on_error_query() when the "[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 "[S]tack trace" option
-
open
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().
-
optionErrorQuark
-
parseDebugString
Parses a string containing debugging options into aguint
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" instring
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 inkeys
are printed out to standard error.- Parameters:
string
- a list of debug options separated by colons, spaces, or commas, ornull
.keys
- pointer to an array ofGDebugKey
which associate strings with bit flags.- Returns:
- the combined set of bit flags.
-
pathGetBasename
Gets the last component of the filename.If
fileName
ends with a directory separator it gets the component before the last slash. IffileName
consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. IffileName
is empty, it gets ".".- Parameters:
fileName
- the name of the file- Returns:
- a newly allocated string containing the last component of the filename
-
pathGetDirname
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
Returnstrue
if the givenfileName
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
iffileName
is absolute
-
pathSkipRoot
Returns a pointer intofileName
after the root component, i.e. after the "/" in UNIX or "C:\\" under Windows. IffileName
is not an absolute path it returnsnull
.- 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 @Nullable String stringReversed) Deprecated.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, asg_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(java.lang.String)
. This works only if the string does not contain any multibyte characters. GLib offers theutf8Strreverse(java.lang.String, long)
function to reverse UTF-8 encoded strings.- Parameters:
pspec
- aGPatternSpec
stringLength
- the length ofstring
(in bytes, i.e.strlen()
, notutf8Strlen(java.lang.String, long)
)string
- the UTF-8 encoded string to matchstringReversed
- the reverse ofstring
- Returns:
true
ifstring
matchespspec
-
patternMatchSimple
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(java.lang.String)
and callPatternSpec.matchString(java.lang.String)
repeatedly.- Parameters:
pattern
- the UTF-8 encoded patternstring
- the UTF-8 encoded string to match- Returns:
true
ifstring
matchespspec
-
patternMatchString
Deprecated.UsePatternSpec.matchString(java.lang.String)
insteadMatches a string against a compiled pattern.If the string is to be matched against more than one pattern, consider using
PatternSpec.match(long, java.lang.String, java.lang.String)
instead while supplying the reversed string.- Parameters:
pspec
- aGPatternSpec
string
- the UTF-8 encoded string to match- Returns:
true
ifstring
matchespspec
-
pointerBitLock
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 avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.- Parameters:
address
- a pointer to agpointer
-sized valuelockBit
- a bit value between 0 and 31
-
pointerBitLockAndGet
public static void pointerBitLockAndGet(MemorySegment address, int lockBit, @Nullable @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 agpointer
-sized valuelockBit
- a bit value between 0 and 31outPtr
- returns the set pointer atomically. This is the value after setting the lock, it thus always has the lock bit set, while previouslyaddress
had the lockbit unset. You may also use g_pointer_bit_lock_mask_ptr() to clear the lock bit.
-
pointerBitLockMaskPtr
public static MemorySegment pointerBitLockMaskPtr(@Nullable @Nullable MemorySegment ptr, int lockBit, boolean set, long preserveMask, @Nullable @Nullable MemorySegment preservePtr) This manglesptr
as g_pointer_bit_lock() and g_pointer_bit_unlock() do.- Parameters:
ptr
- the pointer to masklockBit
- the bit to set/clear. If set toG_MAXUINT
, the lockbit is taken frompreservePtr
orptr
(depending onpreserveMask
).set
- whether to set (lock) the bit or unset (unlock). This has no effect, iflockBit
is set toG_MAXUINT
.preserveMask
- if non-zero, a bit-mask forpreservePtr
. ThepreserveMask
bits frompreservePtr
are set in the result. Note that thelockBit
bit will be always set according toset
, regardless ofpreserveMask
andpreservePtr
(unlesslockBit
isG_MAXUINT
).preservePtr
- ifpreserveMask
is non-zero, the bits from this pointer are set in the result.- Returns:
- the mangled pointer.
-
pointerBitTrylock
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 avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.- Parameters:
address
- a pointer to agpointer
-sized valuelockBit
- a bit value between 0 and 31- Returns:
true
if the lock was acquired
-
pointerBitUnlock
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 avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.- Parameters:
address
- a pointer to agpointer
-sized valuelockBit
- a bit value between 0 and 31
-
pointerBitUnlockAndSet
public static void pointerBitUnlockAndSet(MemorySegment address, int lockBit, @Nullable @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 havelockBit
unset. This also means, you usually can only use this on the lowest bits.- Parameters:
address
- a pointer to agpointer
-sized valuelockBit
- a bit value between 0 and 31ptr
- the new pointer value to setpreserveMask
- if non-zero, those bits of the current pointer inaddress
are preserved. Note that thelockBit
bit will be always set according toset
, regardless ofpreserveMask
and the currently set value inaddress
.
-
poll
Pollsfds
, as with the poll() system call, but portably. (On systems that don't have poll(), it is emulated using select().) This is used internally byGMainContext
, 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 aGPollFD
describing a single file descriptor to poll. Thefd
field indicates the file descriptor, and theevents
field indicates the events to poll for. On return, therevents
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 yourGPollFDs
with g_io_channel_win32_make_pollfd().- Parameters:
fds
- file descriptors to pollnfds
- the number of file descriptors infds
timeout
- amount of time to wait, in milliseconds, or -1 to wait forever- Returns:
- the number of entries in
fds
whoserevents
fields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.
-
prefixError
public static void prefixError(@Nullable @Nullable Out<GError> err, String format, Object... varargs) Formats a string according toformat
and prefix it to an existing error message. Iferr
isnull
(ie: no error variable) then do nothing.If *
err
isnull
(ie: an error variable is present but there is no error condition) then also do nothing.- Parameters:
err
- a return location for aGError
format
- printf()-style format stringvarargs
- arguments toformat
-
prefixErrorLiteral
-
print
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.Object...)
,logStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
, or the convenience macrosGLib#message
,GLib#warning
andGLib#error
.- Parameters:
format
- the message format. See theprintf()
documentationvarargs
- the parameters to insert into the format string
-
printerr
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.Object...)
orlogStructured(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
should be used, or the convenience macrosGLib#message
,GLib#warning
andGLib#error
.- Parameters:
format
- the message format. See theprintf()
documentationvarargs
- the parameters to insert into the format string
-
printf
An implementation of the standardprintf()
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 typicallyformat
should end with its own new-line character.glib/gprintf.h
must be explicitly included in order to use this function.- Parameters:
format
- a standardprintf()
format string, but notice string precision pitfallsvarargs
- the arguments to insert in the output- Returns:
- the number of bytes printed
-
propagateError
Ifdest
isnull
, freesrc
; otherwise, movessrc
into *dest
. The error variabledest
points to must benull
.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 tonull
after calling this function on it.- Parameters:
dest
- error return locationsrc
- error to move into the return location
-
propagatePrefixedError
public static void propagatePrefixedError(GError[] dest, GError src, String format, Object... varargs) Ifdest
isnull
, freesrc
; otherwise, movessrc
into *dest
. *dest
must benull
. After the move, add a prefix as with g_prefix_error().- Parameters:
dest
- error return locationsrc
- error to move into the return locationformat
- printf()-style format stringvarargs
- arguments toformat
-
qsortWithData
@Deprecated public static void qsortWithData(MemorySegment pbase, int totalElems, long size, CompareDataFunc compareFunc) Deprecated.total_elems
is too small to represent larger arrays; usesortArray(java.lang.foreign.MemorySegment[], long, org.gnome.glib.CompareDataFunc, java.lang.foreign.MemorySegment)
insteadThis is just like the standard Cqsort()
) function, but the comparison routine accepts a user data argument (likeqsort_r()
)).Unlike
qsort()
, this is guaranteed to be a stable sort (since GLib 2.32).- Parameters:
pbase
- start of array to sorttotalElems
- elements in the arraysize
- size of each elementcompareFunc
- function to compare elements
-
quarkFromStaticString
Gets theGQuark
identifying the given (static) string. If the string does not currently have an associatedGQuark
, a newGQuark
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 ifstring
isnull
-
quarkFromString
Gets theGQuark
identifying the given string. If the string does not currently have an associatedGQuark
, a newGQuark
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 ifstring
isnull
-
quarkToString
-
quarkTryString
Gets theGQuark
associated with the given string, or 0 if string isnull
or it has no associatedGQuark
.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 ifstring
isnull
or there is noGQuark
associated with it
-
randomDouble
public static double randomDouble()Returns a randomgdouble
equally distributed over the range [0..1).- Returns:
- a random number
-
randomDoubleRange
public static double randomDoubleRange(double begin, double end) Returns a randomgdouble
equally distributed over the range [begin
..end
).- Parameters:
begin
- lower closed bound of the intervalend
- upper open bound of the interval- Returns:
- a random number
-
randomInt
public static int randomInt()Return a randomguint32
equally distributed over the range [0..2^32-1].- Returns:
- a random number
-
randomIntRange
public static int randomIntRange(int begin, int end) Returns a randomgint32
equally distributed over the rangeend-1
.- Parameters:
begin
- lower closed bound of the intervalend
- 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, toseed
.- Parameters:
seed
- a value to reinitialize the global random number generator
-
rcBoxAcquire
Acquires a reference on the data pointed bymemBlock
.- Parameters:
memBlock
- a pointer to reference counted data- Returns:
- a pointer to the data, with its reference count increased
-
rcBoxAlloc
AllocatesblockSize
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
-
rcBoxAlloc0
AllocatesblockSize
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
-
rcBoxDup
Allocates a new block of data with reference counting semantics, and copiesblockSize
bytes ofmemBlock
into it.- Parameters:
blockSize
- the number of bytes to copy, must be greater than 0memBlock
- the memory to copy- Returns:
- a pointer to the allocated memory
-
rcBoxGetSize
Retrieves the size of the reference counted data pointed bymemBlock
.- Parameters:
memBlock
- a pointer to reference counted data- Returns:
- the size of the data, in bytes
-
rcBoxRelease
Releases a reference on the data pointed bymemBlock
.If the reference was the last one, it will free the resources allocated for
memBlock
.- Parameters:
memBlock
- a pointer to reference counted data
-
rcBoxReleaseFull
Releases a reference on the data pointed bymemBlock
.If the reference was the last one, it will call
clearFunc
to clear the contents ofmemBlock
, and then will free the resources allocated formemBlock
.- Parameters:
memBlock
- a pointer to reference counted data
-
realloc
Reallocates the memory pointed to bymem
, so that it now has space fornBytes
bytes of memory. It returns the new address of the memory, which may have been moved.mem
may benull
, in which case it's considered to have zero-length.nBytes
may be 0, in which casenull
will be returned andmem
will be freed unless it isnull
.If the allocation fails (because the system is out of memory), the program is terminated.
- Parameters:
mem
- the memory to reallocatenBytes
- new size of the memory in bytes- Returns:
- the new address of the allocated memory
-
reallocN
public static MemorySegment reallocN(@Nullable @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 reallocatenBlocks
- the number of blocks to allocatenBlockBytes
- the size of each block in bytes- Returns:
- the new address of the allocated memory
-
refCountCompare
Compares the current value ofrc
withval
.- Parameters:
rc
- the address of a reference count variableval
- the value to compare- Returns:
true
if the reference count is the same as the given value
-
refCountDec
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, andfalse
otherwise
-
refCountInc
Increases the reference count.- Parameters:
rc
- the address of a reference count variable
-
refCountInit
Initializes a reference count variable to 1.- Parameters:
rc
- the address of a reference count variable
-
refStringAcquire
-
refStringLength
Retrieves the length ofstr
.- Parameters:
str
- a reference counted string- Returns:
- the length of the given string, in bytes
-
refStringNew
-
refStringNewIntern
Creates a new reference counted string and copies the content ofstr
into it.If you call this function multiple times with the same
str
, or with the same contents ofstr
, 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
-
refStringNewLen
Creates a new reference counted string and copies the contents ofstr
into it, up tolen
bytes.Since this function does not stop at nul bytes, it is the caller's responsibility to ensure that
str
has at leastlen
addressable bytes.- Parameters:
str
- a stringlen
- length ofstr
to use, or -1 ifstr
is nul-terminated- Returns:
- the newly created reference counted string
-
refStringRelease
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
-
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.
-
remove
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
-
rename
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
-
returnIfFailWarning
public static void returnIfFailWarning(@Nullable @Nullable String logDomain, String prettyFunction, @Nullable @Nullable String expression) Internal function used to print messages from the publicGLib#returnIfFail
andGLib#returnValIfFail
macros.- Parameters:
logDomain
- log domainprettyFunction
- function containing the assertionexpression
- expression which failed
-
rmdir
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
-
setApplicationName
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
-
setError
public static void setError(@Nullable @Nullable Out<GError> err, Quark domain, int code, String format, Object... varargs) Does nothing iferr
isnull
; iferr
is non-null
, then *err
must benull
. A newGError
is created and assigned to *err
.- Parameters:
err
- a return location for aGError
domain
- error domaincode
- error codeformat
- printf()-style formatvarargs
- args forformat
-
setErrorLiteral
public static void setErrorLiteral(@Nullable @Nullable Out<GError> err, Quark domain, int code, String message) Does nothing iferr
isnull
; iferr
is non-null
, then *err
must benull
. A newGError
is created and assigned to *err
. Unlike g_set_error(),message
is not a printf()-style format string. Use this function ifmessage
contains text you don't have control over, that could include printf() escape sequences.- Parameters:
err
- a return location for aGError
domain
- error domaincode
- error codemessage
- error message
-
setPrgname
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 theGtkApplication
::startup handler. The program name is found by taking the last component ofargv
[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.
- Parameters:
prgname
- the name of the program.
-
setPrintHandler
Sets the print handler tofunc
, or resets it to the default GLib handler ifNULL
.Any messages passed to
print(java.lang.String, java.lang.Object...)
will be output via the new handler. The default handler outputs the encoded message tostdout
. 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 returnsNULL
. 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 tostderr
in all platforms. Before GLib 2.76, this wasNULL
.- Parameters:
func
- the new print handler orNULL
to reset to the default- Returns:
- the old print handler
-
setPrinterrHandler
Sets the handler for printing error messages tofunc
, or resets it to the default GLib handler ifNULL
.Any messages passed to
printerr(java.lang.String, java.lang.Object...)
will be output via the new handler. The default handler outputs the encoded message tostderr
. 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 returnsNULL
. 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 tostderr
in all platforms. Before GLib 2.76, this wasNULL
.- Parameters:
func
- he new error message handler orNULL
to reset to the default- Returns:
- the old error message handler
-
setenv
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.
-
shellErrorQuark
-
shellParseArgv
public static boolean shellParseArgv(String commandLine, @Nullable @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 thatargvp
will be a non-empty array if this function returns successfully.Free the returned vector with g_strfreev().
- Parameters:
commandLine
- command line to parseargvp
- return location for array of args- Returns:
true
on success,false
if error set- Throws:
GErrorException
- seeGError
-
shellQuote
Quotes a string so that the shell (/bin/sh) will interpret the quoted string to meanunquotedString
.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
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$
, `{@code , }"{@code , }\\
, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.- Parameters:
quotedString
- shell-quoted string- Returns:
- an unquoted string
- Throws:
GErrorException
- seeGError
-
sliceAlloc
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 ifmemSize
is 0
-
sliceAlloc0
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 ifmemSize
is 0
-
sliceCopy
Allocates a block of memory from the slice allocator and copiesblockSize
bytes into it frommemBlock
.memBlock
must be non-null
ifblockSize
is non-zero.Since GLib 2.76 this always uses the system malloc() implementation internally.
- Parameters:
blockSize
- the number of bytes to allocatememBlock
- the memory to copy- Returns:
- a pointer to the allocated memory block,
which will be
null
if and only ifmemSize
is 0
-
sliceFree1
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
][G_DEBUG] environment variable.If
memBlock
isnull
, this function does nothing.Since GLib 2.76 this always uses the system free_sized() implementation internally.
- Parameters:
blockSize
- the size of the blockmemBlock
- a pointer to the block to free
-
sliceFreeChainWithOffset
public static void sliceFreeChainWithOffset(long blockSize, @Nullable @Nullable MemorySegment memChain, long nextOffset) Frees a linked list of memory blocks of structure typetype
.The memory blocks must be equal-sized, allocated via g_slice_alloc() or g_slice_alloc0() and linked together by a
next
pointer (similar toGSList
). The offset of thenext
field in each block is passed as third argument. Note that the exact release behaviour can be changed with the [G_DEBUG=gc-friendly
][G_DEBUG] environment variable.If
memChain
isnull
, this function does nothing.Since GLib 2.76 this always uses the system free_sized() implementation internally.
- Parameters:
blockSize
- the size of the blocksmemChain
- a pointer to the first block of the chainnextOffset
- the offset of thenext
field in the blocks
-
sliceGetConfig
-
sliceGetConfigState
public static MemorySegment sliceGetConfigState(SliceConfig ckey, long address, MemorySegment nValues) -
sliceSetConfig
-
snprintf
A safer form of the standard sprintf() function. The output is guaranteed to not exceedn
characters (including the terminating nul character), so it is easy to ensure that a buffer overflow cannot occur.See also
strdupPrintf(java.lang.String, java.lang.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 outputn
- the maximum number of bytes to produce (including the terminating nul character)format
- a standardprintf()
format string, but notice string precision pitfallsvarargs
- 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(MemorySegment[] array, long elementSize, CompareDataFunc compareFunc, @Nullable @Nullable MemorySegment userData) This is just like the standard Cqsort()
) function, but the comparison routine accepts a user data argument (likeqsort_r()
)).Unlike
qsort()
, this is guaranteed to be a stable sort.- Parameters:
array
- start of array to sortelementSize
- size of each elementcompareFunc
- function to compare elementsuserData
- data to pass tocompareFunc
-
spacedPrimesClosest
public static int spacedPrimesClosest(int num) Gets the smallest prime number from a built-in array of primes which is larger thannum
. This is used within GLib to calculate the optimum size of aGHashTable
.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
- aguint
- Returns:
- the smallest prime number from a built-in array of primes
which is larger than
num
-
spawnAsync
public static boolean spawnAsync(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @Nullable Pid childPid) throws GErrorException Executes a child program asynchronously.See g_spawn_async_with_pipes() for a full description; this function simply calls the g_spawn_async_with_pipes() without any pipes.
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 theDISPLAY
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, ornull
to inherit parent'sargv
- child's argument vectorenvp
- child's environment, ornull
to inherit parent'sflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
childPid
- return location for child process reference, ornull
- Returns:
true
on success,false
if error is set- Throws:
GErrorException
- seeGError
-
spawnAsync
public static boolean spawnAsync(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, SpawnFlags flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @Nullable Pid childPid) throws GErrorException Executes a child program asynchronously.See g_spawn_async_with_pipes() for a full description; this function simply calls the g_spawn_async_with_pipes() without any pipes.
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 theDISPLAY
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, ornull
to inherit parent'sargv
- child's argument vectorenvp
- child's environment, ornull
to inherit parent'sflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
childPid
- return location for child process reference, ornull
- Returns:
true
on success,false
if error is set- Throws:
GErrorException
- seeGError
-
spawnAsyncWithFds
public static boolean spawnAsyncWithFds(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @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, ornull
to inherit parent's, in the GLib file name encodingargv
- child's argument vector, in the GLib file name encoding; it must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent's, in the GLib file name encodingflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
childPid
- return location for child process ID, ornull
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
- seeGError
-
spawnAsyncWithFds
public static boolean spawnAsyncWithFds(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, SpawnFlags flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @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, ornull
to inherit parent's, in the GLib file name encodingargv
- child's argument vector, in the GLib file name encoding; it must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent's, in the GLib file name encodingflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
childPid
- return location for child process ID, ornull
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
- seeGError
-
spawnAsyncWithPipes
public static boolean spawnAsyncWithPipes(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @Nullable Pid childPid, @Nullable @Nullable Out<Integer> standardInput, @Nullable @Nullable Out<Integer> standardOutput, @Nullable @Nullable Out<Integer> standardError) throws GErrorException Identical to g_spawn_async_with_pipes_and_fds() but withn_fds
set to zero, so no FD assignments are used.- Parameters:
workingDirectory
- child's current working directory, ornull
to inherit parent's, in the GLib file name encodingargv
- child's argument vector, in the GLib file name encoding; it must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent's, in the GLib file name encodingflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
childPid
- return location for child process ID, ornull
standardInput
- return location for file descriptor to write to child's stdin, ornull
standardOutput
- return location for file descriptor to read child's stdout, ornull
standardError
- return location for file descriptor to read child's stderr, ornull
- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
spawnAsyncWithPipes
public static boolean spawnAsyncWithPipes(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, SpawnFlags flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @Nullable Pid childPid, @Nullable @Nullable Out<Integer> standardInput, @Nullable @Nullable Out<Integer> standardOutput, @Nullable @Nullable Out<Integer> standardError) throws GErrorException Identical to g_spawn_async_with_pipes_and_fds() but withn_fds
set to zero, so no FD assignments are used.- Parameters:
workingDirectory
- child's current working directory, ornull
to inherit parent's, in the GLib file name encodingargv
- child's argument vector, in the GLib file name encoding; it must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent's, in the GLib file name encodingflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
childPid
- return location for child process ID, ornull
standardInput
- return location for file descriptor to write to child's stdin, ornull
standardOutput
- return location for file descriptor to read child's stdout, ornull
standardError
- return location for file descriptor to read child's stderr, ornull
- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
spawnAsyncWithPipesAndFds
public static boolean spawnAsyncWithPipesAndFds(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, int stdinFd, int stdoutFd, int stderrFd, @Nullable @org.jetbrains.annotations.Nullable int[] sourceFds, @Nullable @org.jetbrains.annotations.Nullable int[] targetFds, @Nullable @Nullable Pid childPidOut, @Nullable @Nullable Out<Integer> stdinPipeOut, @Nullable @Nullable Out<Integer> stdoutPipeOut, @Nullable @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 anull
-terminated array of strings, to be passed as the argument vector for the child. The first string inargv
is of course the name of the program to execute. By default, the name of the program must be a full path. Ifflags
contains theSpawnFlags.SEARCH_PATH
flag, thePATH
environment variable is used to search for the executable. Ifflags
contains theSpawnFlags.SEARCH_PATH_FROM_ENVP
flag, thePATH
variable fromenvp
is used to search for the executable. If both theSpawnFlags.SEARCH_PATH
andSpawnFlags.SEARCH_PATH_FROM_ENVP
flags are set, thePATH
variable fromenvp
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 (orworkingDirectory
, 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 awmain()
instead ofmain()
.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'sspawn*()
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 tomain()
. Complications arise when you have argument vector elements that contain spaces or double quotes. Thespawn*()
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 runtimespawn()
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 anull
-terminated array of strings, where each string has the formKEY=VALUE
. This will become the child's environment. Ifenvp
isnull
, the child inherits its parent's environment.flags
should be the bitwise OR of any flags you want to affect the function's behaviour. TheSpawnFlags.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 thechildPid
, 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 theSIGCHLD
signal manually. On Windows, calling g_spawn_close_pid() is equivalent to callingCloseHandle()
on the process handle returned inchildPid
). 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 callingexec()
in the child.SpawnFlags.SEARCH_PATH
means thatargv
[0] need not be an absolute path, it will be looked for in thePATH
environment variable.SpawnFlags.SEARCH_PATH_FROM_ENVP
means need not be an absolute path, it will be looked for in thePATH
variable fromenvp
. If bothSpawnFlags.SEARCH_PATH
andSpawnFlags.SEARCH_PATH_FROM_ENVP
are used, the value fromenvp
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, thestdinPipeOut
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, thestdoutPipeOut
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, thestderrPipeOut
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
andstderrFd
, and include it insourceFds
too).sourceFds
andtargetFds
allow zero or more FDs from this process to be remapped to different FDs in the spawned process. IfnFds
is greater than zero,sourceFds
andtargetFds
must both be non-null
and the same length. Each FD insourceFds
is remapped to the FD number at the same index intargetFds
. 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 equalstdinFd
,stdoutFd
orstderrFd
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 ofargv
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() usesargv
argv to the child. @child_setup and @user_data 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 {@code exec()}. That is, @child_setup is called just before calling {@code exec()} in the child. Obviously actions taken in this function will only affect the child, not the parent. On Windows, there is no separate {@code fork()} and {@code exec()} functionality. Child processes are created and run with a single API call, {@code CreateProcess()}. There is no sensible thing @child_setup could be used for on Windows so it is ignored and not called. If non-%NULL, @child_pid 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 {@code waitpid()}) if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be filled with a handle to the child process only if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child process using the Win32 API, for example wait for its termination with the {@code WaitFor*()} functions, or examine its exit code with {@code GetExitCodeProcess()}. You should close the handle with {@code CloseHandle()} or g_spawn_close_pid() when you no longer need it. If non-%NULL, the @stdin_pipe_out, @stdout_pipe_out, @stderr_pipe_out 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 @stdin_pipe_out is %NULL, the child's standard input is attached to {@code /dev/null} unless %G_SPAWN_CHILD_INHERITS_STDIN is set. If @stderr_pipe_out is NULL, the child's standard error goes to the same location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set. If @stdout_pipe_out is NULL, the child's standard output goes to the same location as the parent's standard output unless %G_SPAWN_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 {@code @argv[0}{@code is not found). Typically the }message{@code field of returned errors should be displayed to users. Possible errors are those from the %G_SPAWN_ERROR domain. If an error occurs, @child_pid, @stdin_pipe_out, @stdout_pipe_out, and @stderr_pipe_out will not be filled with valid values. If @child_pid 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(){@code . 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. %G_SPAWN_DO_NOT_REAP_CHILD is set 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set 4. @working_directory is %NULL 5. @child_setup 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, ornull
to inherit parent's, in the GLib file name encodingargv
- child's argument vector, in the GLib file name encoding; it must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent's, in the GLib file name encodingflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
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 processtargetFds
- array of FDs to remapsourceFds
to in the child processchildPidOut
- return location for child process ID, ornull
stdinPipeOut
- return location for file descriptor to write to child's stdin, ornull
stdoutPipeOut
- return location for file descriptor to read child's stdout, ornull
stderrPipeOut
- return location for file descriptor to read child's stderr, ornull
- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
spawnAsyncWithPipesAndFds
public static boolean spawnAsyncWithPipesAndFds(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, SpawnFlags flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, int stdinFd, int stdoutFd, int stderrFd, @Nullable @org.jetbrains.annotations.Nullable int[] sourceFds, @Nullable @org.jetbrains.annotations.Nullable int[] targetFds, @Nullable @Nullable Pid childPidOut, @Nullable @Nullable Out<Integer> stdinPipeOut, @Nullable @Nullable Out<Integer> stdoutPipeOut, @Nullable @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 anull
-terminated array of strings, to be passed as the argument vector for the child. The first string inargv
is of course the name of the program to execute. By default, the name of the program must be a full path. Ifflags
contains theSpawnFlags.SEARCH_PATH
flag, thePATH
environment variable is used to search for the executable. Ifflags
contains theSpawnFlags.SEARCH_PATH_FROM_ENVP
flag, thePATH
variable fromenvp
is used to search for the executable. If both theSpawnFlags.SEARCH_PATH
andSpawnFlags.SEARCH_PATH_FROM_ENVP
flags are set, thePATH
variable fromenvp
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 (orworkingDirectory
, 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 awmain()
instead ofmain()
.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'sspawn*()
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 tomain()
. Complications arise when you have argument vector elements that contain spaces or double quotes. Thespawn*()
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 runtimespawn()
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 anull
-terminated array of strings, where each string has the formKEY=VALUE
. This will become the child's environment. Ifenvp
isnull
, the child inherits its parent's environment.flags
should be the bitwise OR of any flags you want to affect the function's behaviour. TheSpawnFlags.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 thechildPid
, 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 theSIGCHLD
signal manually. On Windows, calling g_spawn_close_pid() is equivalent to callingCloseHandle()
on the process handle returned inchildPid
). 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 callingexec()
in the child.SpawnFlags.SEARCH_PATH
means thatargv
[0] need not be an absolute path, it will be looked for in thePATH
environment variable.SpawnFlags.SEARCH_PATH_FROM_ENVP
means need not be an absolute path, it will be looked for in thePATH
variable fromenvp
. If bothSpawnFlags.SEARCH_PATH
andSpawnFlags.SEARCH_PATH_FROM_ENVP
are used, the value fromenvp
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, thestdinPipeOut
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, thestdoutPipeOut
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, thestderrPipeOut
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
andstderrFd
, and include it insourceFds
too).sourceFds
andtargetFds
allow zero or more FDs from this process to be remapped to different FDs in the spawned process. IfnFds
is greater than zero,sourceFds
andtargetFds
must both be non-null
and the same length. Each FD insourceFds
is remapped to the FD number at the same index intargetFds
. 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 equalstdinFd
,stdoutFd
orstderrFd
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 ofargv
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() usesargv
argv to the child. @child_setup and @user_data 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 {@code exec()}. That is, @child_setup is called just before calling {@code exec()} in the child. Obviously actions taken in this function will only affect the child, not the parent. On Windows, there is no separate {@code fork()} and {@code exec()} functionality. Child processes are created and run with a single API call, {@code CreateProcess()}. There is no sensible thing @child_setup could be used for on Windows so it is ignored and not called. If non-%NULL, @child_pid 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 {@code waitpid()}) if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be filled with a handle to the child process only if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child process using the Win32 API, for example wait for its termination with the {@code WaitFor*()} functions, or examine its exit code with {@code GetExitCodeProcess()}. You should close the handle with {@code CloseHandle()} or g_spawn_close_pid() when you no longer need it. If non-%NULL, the @stdin_pipe_out, @stdout_pipe_out, @stderr_pipe_out 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 @stdin_pipe_out is %NULL, the child's standard input is attached to {@code /dev/null} unless %G_SPAWN_CHILD_INHERITS_STDIN is set. If @stderr_pipe_out is NULL, the child's standard error goes to the same location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set. If @stdout_pipe_out is NULL, the child's standard output goes to the same location as the parent's standard output unless %G_SPAWN_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 {@code @argv[0}{@code is not found). Typically the }message{@code field of returned errors should be displayed to users. Possible errors are those from the %G_SPAWN_ERROR domain. If an error occurs, @child_pid, @stdin_pipe_out, @stdout_pipe_out, and @stderr_pipe_out will not be filled with valid values. If @child_pid 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(){@code . 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. %G_SPAWN_DO_NOT_REAP_CHILD is set 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set 4. @working_directory is %NULL 5. @child_setup 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, ornull
to inherit parent's, in the GLib file name encodingargv
- child's argument vector, in the GLib file name encoding; it must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent's, in the GLib file name encodingflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
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 processtargetFds
- array of FDs to remapsourceFds
to in the child processchildPidOut
- return location for child process ID, ornull
stdinPipeOut
- return location for file descriptor to write to child's stdin, ornull
stdoutPipeOut
- return location for file descriptor to read child's stdout, ornull
stderrPipeOut
- return location for file descriptor to read child's stderr, ornull
- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
spawnCheckExitStatus
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 toexit()
or returned by g_subprocess_get_exit_status() orWEXITSTATUS()
.- Parameters:
waitStatus
- A status as returned from g_spawn_sync()- Returns:
true
if child exited successfully,false
otherwise (anderror
will be set)- Throws:
GErrorException
- seeGError
-
spawnCheckWaitStatus
Seterror
ifwaitStatus
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 inerror
will contain human-readable information about the wait status.The
domain
andcode
oferror
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 ofwaitStatus
. 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 beG_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 beSpawnError.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() onwaitStatus
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 (anderror
will be set)- Throws:
GErrorException
- seeGError
-
spawnClosePid
On some platforms, notably Windows, theGPid
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
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 thatSpawnFlags.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
- seeGError
-
spawnCommandLineSync
public static boolean spawnCommandLineSync(String commandLine, @Nullable @org.jetbrains.annotations.Nullable byte[] standardOutput, @Nullable @org.jetbrains.annotations.Nullable byte[] standardError, @Nullable @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 thatSpawnFlags.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 toexit()
or returned frommain()
.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 acommandLine
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 linestandardOutput
- return location for child outputstandardError
- return location for child errorswaitStatus
- return location for child wait status, as returned by waitpid()- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
spawnErrorQuark
-
spawnExitErrorQuark
-
spawnSync
public static boolean spawnSync(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @org.jetbrains.annotations.Nullable byte[] standardOutput, @Nullable @org.jetbrains.annotations.Nullable byte[] standardError, @Nullable @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
andstandardError
, if those parameters are non-null
. Note that you must set theSpawnFlags.STDOUT_TO_DEV_NULL
andSpawnFlags.STDERR_TO_DEV_NULL
flags when passingnull
forstandardOutput
andstandardError
.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 toexit()
or returned frommain()
.Note that it is invalid to pass
SpawnFlags.DO_NOT_REAP_CHILD
inflags
, 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
, orwaitStatus
.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, ornull
to inherit parent'sargv
- child's argument vector, which must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent'sflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
standardOutput
- return location for child output, ornull
standardError
- return location for child error messages, ornull
waitStatus
- return location for child wait status, as returned by waitpid(), ornull
- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
spawnSync
public static boolean spawnSync(@Nullable @Nullable String workingDirectory, String[] argv, @Nullable @Nullable String[] envp, SpawnFlags flags, @Nullable @Nullable SpawnChildSetupFunc childSetup, @Nullable @org.jetbrains.annotations.Nullable byte[] standardOutput, @Nullable @org.jetbrains.annotations.Nullable byte[] standardError, @Nullable @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
andstandardError
, if those parameters are non-null
. Note that you must set theSpawnFlags.STDOUT_TO_DEV_NULL
andSpawnFlags.STDERR_TO_DEV_NULL
flags when passingnull
forstandardOutput
andstandardError
.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 toexit()
or returned frommain()
.Note that it is invalid to pass
SpawnFlags.DO_NOT_REAP_CHILD
inflags
, 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
, orwaitStatus
.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, ornull
to inherit parent'sargv
- child's argument vector, which must be non-empty andnull
-terminatedenvp
- child's environment, ornull
to inherit parent'sflags
- flags fromGSpawnFlags
childSetup
- function to run in the child just beforeexec()
standardOutput
- return location for child output, ornull
standardError
- return location for child error messages, ornull
waitStatus
- return location for child wait status, as returned by waitpid(), ornull
- Returns:
true
on success,false
if an error was set- Throws:
GErrorException
- seeGError
-
sprintf
An implementation of the standardsprintf()
function which supports positional parameters, as specified in the Single Unix Specification.Note that it is usually better to use
snprintf(java.lang.String, int, java.lang.String, java.lang.Object...)
, to avoid the risk of buffer overflow.glib/gprintf.h
must be explicitly included in order to use this function.See also
strdupPrintf(java.lang.String, java.lang.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 standardprintf()
format string, but notice string precision pitfallsvarargs
- the arguments to insert in the output- Returns:
- the number of bytes printed
-
stat
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 thestMode
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
-
stpcpy
Copies a nul-terminated string into the destination buffer, including the trailing nul byte, and returns a pointer to the trailing nul byte indest
. The return value is useful for concatenating multiple strings without having to repeatedly scan for the end.- Parameters:
dest
- destination buffersrc
- source string- Returns:
- a pointer to the trailing nul byte in
dest
-
strEqual
Compares two strings for byte-by-byte equality and returnstrue
if they are equal. It can be passed to g_hash_table_new() as thekeyEqualFunc
parameter, when using non-null
strings as keys in aGHashTable
.This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-
null
strings. For anull
-safe string comparison function, see g_strcmp0().- Parameters:
v1
- a keyv2
- a key to compare withv1
- Returns:
true
if the two keys match
-
strHasPrefix
-
strHasSuffix
-
strHash
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 aGHashTable
.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
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
-
strMatchString
public static boolean strMatchString(String searchTerm, String potentialHit, boolean acceptAlternates) Checks if a search conducted forsearchTerm
should matchpotentialHit
.This function calls
strTokenizeAndFold(java.lang.String, java.lang.String, java.lang.String[])
on bothsearchTerm
andpotentialHit
. ASCII alternates are never taken forsearchTerm
but will be taken forpotentialHit
according to the value ofacceptAlternates
.A hit occurs when each folded token in
searchTerm
is a prefix of a folded token frompotentialHit
.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 callg_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 userpotentialHit
- the text that may be a hitacceptAlternates
- if true, ASCII alternates are accepted- Returns:
- true if
potentialHit
is a hit
-
strToAscii
Transliteratestr
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 asfromLocale
. It should be a valid POSIX locale string (of the formlanguage[_territory][.codeset][@modifier]
).If
fromLocale
isnull
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"
forfromLocale
.- Parameters:
str
- a string, in UTF-8fromLocale
- the source locale, if known- Returns:
- a string in plain ASCII
-
strTokenizeAndFold
public static String[] strTokenizeAndFold(String string, @Nullable @Nullable String translitLocale, @Nullable @Nullable String[] asciiAlternates) Tokenizesstring
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)
orunicharIsmark(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 tokenizetranslitLocale
- the language code (like 'de' or 'en_GB') from whichstring
originatesasciiAlternates
- a return location for ASCII alternates- Returns:
- the folded tokens
-
strcanon
For each character instring
, if the character is not invalidChars
, replaces the character withsubstitutor
.Modifies
string
in place, and returnstring
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(java.lang.String)
:reformatted = g_strcanon (g_strdup (const_str), "abc", '?'); … g_free (reformatted);
- Parameters:
string
- a nul-terminated array of bytesvalidChars
- bytes permitted instring
substitutor
- replacement character for disallowed bytes- Returns:
- the modified
string
-
strcasecmp
Deprecated.Seestrncasecmp(java.lang.String, java.lang.String, int)
for a discussion of why this function is deprecated and how to replace it.A case-insensitive string comparison, corresponding to the standardstrcasecmp()
function on platforms which support it.- Parameters:
s1
- string to compare withs2
s2
- string to compare withs1
- Returns:
- 0 if the strings match, a negative value if
s1
<s2
, or a positive value ifs1
>s2
-
strchomp
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(java.lang.String)
andGLib#strstrip
.- Parameters:
string
- a string to remove the trailing whitespace from- Returns:
- the modified
string
-
strchug
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(java.lang.String)
andGLib#strstrip
.- Parameters:
string
- a string to remove the leading whitespace from- Returns:
- the modified
string
-
strcmp0
Comparesstr1
andstr2
like strcmp(). Handlesnull
gracefully by sorting it before non-null
strings. Comparing twonull
pointers returns 0.- Parameters:
str1
- a C string ornull
str2
- another C string ornull
- Returns:
- an integer less than, equal to, or greater than zero, if
str1
is <, == or > thanstr2
.
-
strcompress
Makes a copy of a string replacing C string-style escape sequences with their one byte equivalent:\\b
→ U+0008 Backspace\\f
→ U+000C Form Feed\\n
→ U+000A Line Feed\\r
→ U+000D Carriage Return\\t
→ U+0009 Horizontal Tabulation\\v
→ U+000B Vertical Tabulation\\
followed by one to three octal digits → the numeric value (mod 255)\\
followed by any other character → the character as is. For example,\\\\
will turn into a backslash (\\
) and\\"
into a double quote ("
).
strescape(java.lang.String, java.lang.String)
does the reverse conversion.- Parameters:
source
- a string to compress- Returns:
- a newly-allocated copy of
source
with all escaped character compressed
-
strconcat
Concatenates all of the given strings into one long string.The variable argument list must end with
NULL
. If you forget theNULL
,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 beNULL
varargs
- aNULL
-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 @Nullable String delimiters, byte newDelimiter) Converts any delimiter characters instring
tonewDelimiter
.Any characters in
string
which are found indelimiters
are changed to thenewDelimiter
character. Modifiesstring
in place, and returnsstring
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(java.lang.String)
:reformatted = g_strdelimit (g_strdup (const_str), "abc", '?'); … g_free (reformatted);
- Parameters:
string
- the string to convertdelimiters
- a string containing the current delimiters, orNULL
to use the standard delimiters defined inGLib.STR_DELIMITERS
newDelimiter
- the new delimiter character- Returns:
- the modified
string
-
strdown
Deprecated.This function is totally broken for the reasons discussed in thestrncasecmp(java.lang.String, java.lang.String, int)
docs — useasciiStrdown(java.lang.String, long)
orutf8Strdown(java.lang.String, long)
instead.Converts a string to lower case.- Parameters:
string
- the string to convert- Returns:
- the string
-
strdup
-
strdupPrintf
Similar to the standard Csprintf()
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 standardprintf()
format string, but notice string precision pitfallsvarargs
- the parameters to insert into the format string- Returns:
- a newly-allocated string holding the result
-
strdupv
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 returnsNULL
.- Parameters:
strArray
- an array of strings to copy- Returns:
- a
newly-allocated array of strings. Use
strfreev(java.lang.foreign.MemorySegment)
to free it.
-
strerror
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 Cerrno
documentation- Returns:
- the string describing the error code
-
strescape
It replaces the following special characters in the stringsource
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 inexceptions
are not escaped.strcompress(java.lang.String)
does the reverse conversion.- Parameters:
source
- a string to escapeexceptions
- a string of characters not to escape insource
- Returns:
- a newly-allocated copy of
source
with special characters escaped
-
strfreev
Frees an array of strings, as well as each string it contains.If
strArray
isNULL
, this function simply returns.- Parameters:
strArray
- an array of strings to free
-
stripContext
An auxiliary function for gettext() support (see Q_()).- Parameters:
msgid
- a stringmsgval
- another string- Returns:
msgval
, unlessmsgval
is identical tomsgid
and contains a '|' character, in which case a pointer to the substring of msgid after the first '|' character is returned.
-
strjoin
Joins a number of strings together to form one long string, with the optionalseparator
inserted between each of them.- Parameters:
separator
- a string to insert between each of the stringsvarargs
- aNULL
-terminated list of strings to join- Returns:
- a newly-allocated string containing all of the strings joined
together, with
separator
between them
-
strjoinv
Joins an array of strings together to form one long string, with the optionalseparator
inserted between each of them.If
strArray
has no items, the return value will be an empty string. IfstrArray
contains a single item,separator
will not appear in the resulting string.- Parameters:
separator
- a string to insert between each of the stringsstrArray
- an array of strings to join- Returns:
- a newly-allocated string containing all of the strings joined
together, with
separator
between them
-
strlcat
Portability wrapper that callsstrlcat()
on systems which have it, and emulates it otherwise. Appends nul-terminatedsrc
string todest
, guaranteeing nul-termination fordest
. The total size ofdest
won't exceeddestSize
.At most
destSize
- 1 characters will be copied. Unlikestrncat()
,destSize
is the full size of dest, not the space left over. This function does not allocate memory. It always nul-terminates (unlessdestSize
== 0 or there were no nul characters in thedestSize
characters of dest to start with).Caveat: this is supposedly a more secure alternative to
strcat()
orstrncat()
, but for real securitystrconcat(java.lang.String, java.lang.Object...)
is harder to mess up.- Parameters:
dest
- destination buffer, already containing one nul-terminated stringsrc
- source bufferdestSize
- length ofdest
buffer in bytes (not length of existing string insidedest
)- Returns:
- size of attempted result, which is
MIN (dest_size, strlen (original dest)) + strlen (src)
, so ifretval
>=destSize
, truncation occurred
-
strlcpy
Portability wrapper that callsstrlcpy()
on systems which have it, and emulatesstrlcpy()
otherwise. Copiessrc
todest
;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 (unlessdestSize
is 0). This function does not allocate memory. Unlikestrncpy()
, this function doesn't paddest
(so it's often faster). It returns the size of the attempted result,strlen (src)
, so ifretval
>=destSize
, truncation occurred.Caveat:
strlcpy()
is supposedly more secure thanstrcpy()
orstrncpy()
, but if you really want to avoid screwups,strdup(java.lang.String)
is an even better idea.- Parameters:
dest
- destination buffersrc
- source bufferdestSize
- length ofdest
in bytes- Returns:
- length of
src
-
strncasecmp
Deprecated.The problem withg_strncasecmp()
is that it does the comparison by callingtoupper()
/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. Thusg_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(java.lang.String, java.lang.String, long)
, which only works on ASCII and is not locale-sensitive, andutf8Casefold(java.lang.String, long)
followed bystrcmp()
on the resulting strings, which is good for case-insensitive sorting of UTF-8.A case-insensitive string comparison, corresponding to the standardstrncasecmp()
function on platforms which support it. It is similar tostrcasecmp(java.lang.String, java.lang.String)
except it only compares the firstn
characters of the strings.- Parameters:
s1
- string to compare withs2
s2
- string to compare withs1
n
- the maximum number of characters to compare- Returns:
- 0 if the strings match, a negative value if
s1
<s2
, or a positive value ifs1
>s2
-
strndup
Duplicates the firstn
bytes of a string, returning a newly-allocated buffern
+ 1 bytes long which will always be nul-terminated. Ifstr
is less thann
bytes long the buffer is padded with nuls. Ifstr
isNULL
it returnsNULL
.To copy a number of characters from a UTF-8 encoded string, use
utf8Strncpy(java.lang.String, java.lang.String, long)
instead.- Parameters:
str
- the string to duplicaten
- the maximum number of bytes to copy fromstr
- Returns:
- a newly-allocated buffer containing the first
n
bytes ofstr
-
strnfill
Creates a new stringlength
bytes long filled withfillChar
.- Parameters:
length
- the length of the new stringfillChar
- the byte to fill the string with- Returns:
- a newly-allocated string filled with
fillChar
-
strreverse
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, useutf8Strreverse(java.lang.String, long)
.- Parameters:
string
- the string to reverse- Returns:
- the
string
, reversed in place
-
strrstr
Searches the stringhaystack
for the last occurrence of the stringneedle
.The fact that this function returns
gchar *
rather thanconst gchar *
is a historical artifact.- Parameters:
haystack
- a string to search inneedle
- the string to search for- Returns:
- a pointer to the found occurrence, or
NULL
if not found
-
strrstrLen
Searches the stringhaystack
for the last occurrence of the stringneedle
, limiting the length of the search tohaystackLen
.The fact that this function returns
gchar *
rather thanconst gchar *
is a historical artifact.- Parameters:
haystack
- a string to search inhaystackLen
- the maximum length ofhaystack
in bytes. A length of-1
can be used to mean "search the entire string", likestrrstr(java.lang.String, java.lang.String)
needle
- the string to search for- Returns:
- a pointer to the found occurrence, or
NULL
if not found
-
strsignal
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 thestrsignal()
function.- Parameters:
signum
- the signal number. See thesignal
documentation- Returns:
- the string describing the signal
-
strsplit
Splits a string into a maximum ofmaxTokens
pieces, using the givendelimiter
. IfmaxTokens
is reached, the remainder ofstring
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 splitdelimiter
- a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unlessmaxTokens
is reached.maxTokens
- the maximum number of pieces to splitstring
into If this is less than 1, the string is split completely- Returns:
- a newly-allocated array of strings, freed with
strfreev(java.lang.foreign.MemorySegment)
-
strsplitSet
Splitsstring
into a number of tokens not containing any of the characters indelimiters
. A token is the (possibly empty) longest string that does not contain any of the characters indelimiters
. IfmaxTokens
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:", ":/", -1) is an array containing the four strings "", "def", "ghi", 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_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 splitdelimiters
- a string containing characters that are used to split the string. Can be empty, which will result in no string splittingmaxTokens
- the maximum number of tokens to splitstring
into. If this is less than 1, the string is split completely- Returns:
- a newly-allocated array of strings. Use
strfreev(java.lang.foreign.MemorySegment)
to free it.
-
strstrLen
Searches the stringhaystack
for the first occurrence of the stringneedle
, limiting the length of the search tohaystackLen
or a nul terminator byte (whichever is reached first).A length of
-1
can be used to mean “search the entire string”, likestrstr()
.The fact that this function returns
gchar *
rather thanconst gchar *
is a historical artifact.- Parameters:
haystack
- a string to search inhaystackLen
- the maximum length ofhaystack
in bytes, or-1
to search it entirelyneedle
- the string to search for- Returns:
- a pointer to the found occurrence, or
NULL
if not found
-
strtod
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 withasciiStrtod(java.lang.String, io.github.jwharm.javagi.base.Out<java.lang.String>)
, 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(java.lang.String, io.github.jwharm.javagi.base.Out<java.lang.String>)
. 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 valueendptr
- if non-NULL
, it returns the character after the last character used in the conversion- Returns:
- the converted value
-
strup
Deprecated.This function is totally broken for the reasons discussed in thestrncasecmp(java.lang.String, java.lang.String, int)
docs — useasciiStrup(java.lang.String, long)
orutf8Strup(java.lang.String, long)
instead.Converts a string to upper case.- Parameters:
string
- the string to convert- Returns:
- the string
-
strvContains
Checks if an array of strings contains the stringstr
according tostrEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment)
.strv
must not beNULL
.- Parameters:
strv
- an array of strings to search instr
- the string to search for- Returns:
- true if
str
is an element ofstrv
-
strvEqual
Checks if two arrays of strings contain exactly the same elements in exactly the same order.Elements are compared using
strEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment)
. To match independently of order, sort the arrays first (usingqsortWithData(java.lang.foreign.MemorySegment, int, long, org.gnome.glib.CompareDataFunc)
or similar).Elements are compared using
strEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment)
. To match independently of order, sort the arrays first (usingqsortWithData(java.lang.foreign.MemorySegment, int, long, org.gnome.glib.CompareDataFunc)
or similar).Two empty arrays are considered equal. Neither
strv1
norstrv2
may beNULL
.- Parameters:
strv1
- an array of strings to compare tostrv2
strv2
- an array of strings to compare tostrv1
- Returns:
- true if
strv1
andstrv2
are equal
-
strvGetType
-
strvLength
Returns the length of an array of strings.strArray
must not beNULL
.- Parameters:
strArray
- an array of strings- Returns:
- length of
strArray
-
testAddDataFunc
public static void testAddDataFunc(String testpath, @Nullable @Nullable MemorySegment testData, TestDataFunc testFunc) Create a new test case, similar to g_test_create_case(). 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 slash-separated portions oftestpath
. ThetestData
argument will be passed as first argument totestFunc
.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 g_test_trap_subprocess().No component of
testpath
may start with a dot (.
) if theG_TEST_OPTION_ISOLATE_DIRS
option is being used; and it is recommended to do so even if it isn’t.- Parameters:
testpath
- /-separated test case path name for the test.testData
- Test data argument for the test function.testFunc
- The test function to invoke for this test.
-
testAddDataFuncFull
public static void testAddDataFuncFull(String testpath, @Nullable @Nullable MemorySegment testData, TestDataFunc testFunc) Create a new test case, as with g_test_add_data_func(), but freeingtestData
after the test run is complete.- Parameters:
testpath
- /-separated test case path name for the test.testData
- Test data argument for the test function.testFunc
- The test function to invoke for this test.
-
testAddFunc
Create a new test case, similar to g_test_create_case(). 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 slash-separated portions oftestpath
.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 g_test_trap_subprocess().No component of
testpath
may start with a dot (.
) if theG_TEST_OPTION_ISOLATE_DIRS
option is being used; and it is recommended to do so even if it isn’t.- Parameters:
testpath
- /-separated test case path name for the test.testFunc
- The test function to invoke for this test.
-
testAddVtable
public static void testAddVtable(String testpath, long dataSize, @Nullable @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) -
testAssertExpectedMessagesInternal
-
testBug
This function 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 g_test_bug_base() and
bugUriSnippet
. If g_test_bug_base() has not been called, it is assumed to be the empty string, so a full URI can be provided to g_test_bug() instead.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.
-
testBugBase
Specify the base URI for bug reports.The base URI is used to construct bug report messages for g_test_message() when g_test_bug() 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
withinuriPattern
if that is present.If g_test_bug_base() is not called, bug URIs are formed solely from the value provided by g_test_bug().
- Parameters:
uriPattern
- the base pattern for bug URIs
-
testBuildFilename
Creates the pathname to a data file that is required for a test.This function is conceptually similar to g_build_filename() except that the first argument has been replaced with a
GTestFileType
argument.The data file should either have been distributed with the module containing the test (
TestFileType.DIST
) or built as part of the build system of that module (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 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 pathnamevarargs
-null
-terminated additional path segments- Returns:
- the path of the file, to be freed using g_free()
-
testCreateCase
public static TestCase testCreateCase(String testName, long dataSize, @Nullable @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) Create a newGTestCase
, namedtestName
.This API is fairly low level, and calling g_test_add() or g_test_add_func() is preferable.
When this test is executed, a fixture structure of size
dataSize
will be automatically allocated and filled with zeros. ThendataSetup
is called to initialize the fixture. After fixture setup, the actual test functiondataTest
is called. Once the test run completes, the fixture structure is torn down by callingdataTeardown
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, g_test_create_case() will be called with the same type of fixture (the
dataSize
argument), but varyingtestName
anddataTest
arguments.- Parameters:
testName
- the name for the test casedataSize
- the size of the fixture data structuretestData
- test data argument for the test functionsdataSetup
- the function to set up the fixture datadataTest
- the actual test functiondataTeardown
- the function to teardown the fixture data- Returns:
- a newly allocated
GTestCase
.
-
testCreateSuite
-
testDisableCrashReporting
public static void testDisableCrashReporting()Attempt 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.
-
testExpectMessage
public static void testExpectMessage(@Nullable @Nullable String logDomain, Set<LogLevelFlags> logLevel, String pattern) Indicates that a message with the givenlogDomain
andlogLevel
, with text matchingpattern
, 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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.Object...)
withoutG_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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.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, sinceGLib#error
intentionally never returns even if the program doesn’t abort; usetestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)
in this case.If messages at
GLib.LogLevelFlags.LEVEL_DEBUG
are emitted, but not explicitly expected viatestExpectMessage(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String)
then they will be ignored.- Parameters:
logDomain
- the log domain of the messagelogLevel
- the log level of the messagepattern
- a glob-style pattern (seeGLib.PatternSpec
)
-
testExpectMessage
public static void testExpectMessage(@Nullable @Nullable String logDomain, LogLevelFlags logLevel, String pattern) Indicates that a message with the givenlogDomain
andlogLevel
, with text matchingpattern
, 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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String, java.lang.Object...)
withoutG_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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.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, sinceGLib#error
intentionally never returns even if the program doesn’t abort; usetestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)
in this case.If messages at
GLib.LogLevelFlags.LEVEL_DEBUG
are emitted, but not explicitly expected viatestExpectMessage(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String)
then they will be ignored.- Parameters:
logDomain
- the log domain of the messagelogLevel
- the log level of the messagepattern
- a glob-style pattern (seeGLib.PatternSpec
)
-
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 g_test_skip() and g_test_incomplete(), this function does not log a message alongside the test failure. If details of the test failure are available, either log them with g_test_message() before g_test_fail(), or use g_test_fail_printf() instead.
-
testFailPrintf
-
testFailed
public static boolean testFailed()Returns whether a test has already failed. This will be the case when g_test_fail(), g_test_incomplete() or g_test_skip() 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
-
testGetDir
Gets the pathname of the directory containing test files of the type specified byfileType
.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
-
testGetFilename
Gets the pathname to a data file that is required for a test.This is the same as g_test_build_filename() 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 pathnamevarargs
-null
-terminated additional path segments- Returns:
- the path, automatically freed at the end of the testcase
-
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. g_test_add() 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
-
testGetRoot
Get the toplevel test suite for the test path API.- Returns:
- the toplevel
GTestSuite
-
testIncomplete
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
-
testIncompletePrintf
-
testInit
Initialize the GLib testing framework, e.g. by seeding the test random number generator, the name for g_get_prgname() and parsing test related command line args.This should be called before calling any other
g_test_*()
functions.So far, 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 g_test_trap_subprocess() or g_test_expect_message() to check that appropriate assertions or warnings are given (the default).no-undefined
: Avoid tests for undefined behaviour--debug-log
: Debug test logging output.
Options which can be passed to
.
.. are:"no_g_set_prgname"
: Causes g_test_init() to not call g_set_prgname().G_TEST_OPTION_ISOLATE_DIRS
: Creates a unique temporary directory for each unit test and uses g_set_user_dirs() to set XDG directories to point into that temporary directory for the duration of the unit test. See the documentation forG_TEST_OPTION_ISOLATE_DIRS
.
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 g_assert() is commonly (erroneously) used in unit tests, and is a no-op when compiled withG_DISABLE_ASSERT
. Ensure your tests are compiled withoutG_DISABLE_ASSERT
defined.- Parameters:
argc
- Address of theargc
parameter of the main() function. Changed if any arguments were handled.argv
- Address of theargv
parameter of main(). Any parameters understood by g_test_init() stripped before return.varargs
-null
-terminated list of special options, documented below.
-
testLogSetFatalHandler
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(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.Object...)
orlogStructuredArray(java.util.Set<org.gnome.glib.LogLevelFlags>, org.gnome.glib.LogField[])
). To change the fatal behaviour for specific log messages, programs must install a custom log writer function usinglogSetWriterFunc(org.gnome.glib.LogWriterFunc)
.See Using Structured Logging.- Parameters:
logFunc
- the log handler function.
-
testLogTypeName
-
testMaximizedResult
Report 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 andmaximizedQuantity
can determine sorting order for test result reports.- Parameters:
maximizedQuantity
- the reported valueformat
- the format string of the report messagevarargs
- arguments to pass to the printf() function
-
testMessage
-
testMinimizedResult
Report 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 andminimizedQuantity
can determine sorting order for test result reports.- Parameters:
minimizedQuantity
- the reported valueformat
- the format string of the report messagevarargs
- arguments to pass to the printf() function
-
testQueueDestroy
Enqueues a callbackdestroyFunc
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 callbackB
will causeB()
to be called beforeA()
during teardown.- Parameters:
destroyData
- Destroy callback data.
-
testQueueFree
Enqueue a pointer to be released with g_free() during the next teardown phase. This is equivalent to calling g_test_queue_destroy() with a destroy callback of g_free().- Parameters:
gfreePointer
- the pointer to be stored.
-
testRandDouble
public static double testRandDouble()Get a reproducible random floating point number, see g_test_rand_int() for details on test case random numbers.- Returns:
- a random number from the seeded random number generator.
-
testRandDoubleRange
public static double testRandDoubleRange(double rangeStart, double rangeEnd) Get a reproducible random floating pointer number out of a specified range, see g_test_rand_int() for details on test case random numbers.- Parameters:
rangeStart
- the minimum value returned by this functionrangeEnd
- the minimum value not returned by this function- Returns:
- a number with
rangeStart
<= number <rangeEnd
.
-
testRandInt
public static int testRandInt()Get 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.
-
testRandIntRange
public static int testRandIntRange(int begin, int end) Get a reproducible random integer number out of a specified range, see g_test_rand_int() for details on test case random numbers.- Parameters:
begin
- the minimum value returned by this functionend
- the smallest value not to be returned by this function- Returns:
- a number with
begin
<= number <end
.
-
testRun
public static int testRun()Runs all tests under the toplevel suite which can be retrieved with g_test_get_root(). Similar to g_test_run_suite(), the test cases to be run are filtered according to test path arguments (-p testpath
and-s testpath
) as parsed by g_test_init(). g_test_run_suite() or g_test_run() 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 g_test_run() 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 g_test_add(), 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 with g_test_skip() and/or g_test_incomplete()
-
testRunSuite
Execute the tests withinsuite
and all nestedGTestSuites
. The test suites to be executed are filtered according to test path arguments (-p testpath
and-s testpath
) as parsed by g_test_init(). See the g_test_run() documentation for more information on the order that tests are run in.g_test_run_suite() or g_test_run() may only be called once in a program.
- Parameters:
suite
- aGTestSuite
- Returns:
- 0 on success
-
testSetNonfatalAssertions
public static void testSetNonfatalAssertions()Changes the behaviour of the variousg_assert_*()
macros, g_test_assert_expected_messages() and the variousg_test_trap_assert_*()
macros to not abort to program, but instead call g_test_fail() and continue. (This also changes the behavior of g_test_fail() so that it will not cause the test program to abort after completing the failed test.)Note that the g_assert_not_reached() and g_assert() macros are not affected by this.
This function can only be called after g_test_init().
-
testSkip
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
-
testSkipPrintf
-
testSubprocess
public static boolean testSubprocess()Returnstrue
(after g_test_init() has been called) if the test program is running under g_test_trap_subprocess().- Returns:
true
if the test program is running under g_test_trap_subprocess().
-
testSummary
Set the summary for a test, which describes what the test checks, and how it goes about checking it. 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.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."); … }
- Parameters:
summary
- One or two sentences summarising what the test checks, and how it checks it.
-
testTimerElapsed
public static double testTimerElapsed()Get the number of seconds since the last start of the timer with g_test_timer_start().- Returns:
- the time since the last start of the timer in seconds, as a double
-
testTimerLast
public static double testTimerLast()Report the last result of g_test_timer_elapsed().- Returns:
- the last result of g_test_timer_elapsed(), as a double
-
testTimerStart
public static void testTimerStart()Start a timing test. Call g_test_timer_elapsed() when the task is supposed to be done. Call this function again to restart the timer. -
testTrapAssertions
-
testTrapFork
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 g_test_trap_subprocess() instead.Fork 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 the
GTestTrapFlags
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\\n"); g_printerr ("some stderr text: semagic43\\n"); 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 micro seconds.testTrapFlags
- Flags to modify forking behaviour.- Returns:
true
for the forked child andfalse
for the executing parent process.
-
testTrapFork
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 g_test_trap_subprocess() instead.Fork 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 the
GTestTrapFlags
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\\n"); g_printerr ("some stderr text: semagic43\\n"); 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 micro seconds.testTrapFlags
- Flags to modify forking behaviour.- Returns:
true
for the forked child andfalse
for the executing parent process.
-
testTrapHasPassed
public static boolean testTrapHasPassed()Check the result of the last g_test_trap_subprocess() call.- Returns:
true
if the last test subprocess terminated successfully.
-
testTrapReachedTimeout
public static boolean testTrapReachedTimeout()Check the result of the last g_test_trap_subprocess() call.- Returns:
true
if the last test subprocess got killed due to a timeout.
-
testTrapSubprocess
public static void testTrapSubprocess(@Nullable @Nullable String testPath, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPath
in a subprocess.This is equivalent to calling g_test_trap_subprocess_with_envp() with
envp
set tonull
. See the documentation for that function for full details.- Parameters:
testPath
- Test to run in a subprocessusecTimeout
- Timeout for the subprocess test in micro seconds.testFlags
- Flags to modify subprocess behaviour.
-
testTrapSubprocess
public static void testTrapSubprocess(@Nullable @Nullable String testPath, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPath
in a subprocess.This is equivalent to calling g_test_trap_subprocess_with_envp() with
envp
set tonull
. See the documentation for that function for full details.- Parameters:
testPath
- Test to run in a subprocessusecTimeout
- Timeout for the subprocess test in micro seconds.testFlags
- Flags to modify subprocess behaviour.
-
testTrapSubprocessWithEnvp
public static void testTrapSubprocessWithEnvp(@Nullable @Nullable String testPath, @Nullable @Nullable String[] envp, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPath
in a subprocess with the givenenvp
environment.This can be used for a test case that might not return, or that might abort.
If
testPath
isnull
then the same test is re-run in a subprocess. You can use g_test_subprocess() 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
isnull
, 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 the
GTestSubprocessFlags
flags.You can use methods such as g_test_trap_assert_passed(), g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to check the results of the subprocess. (But note that g_test_trap_assert_stdout() and g_test_trap_assert_stderr() 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 g_test_subprocess() (after calling g_test_init()) to see whether you are in a subprocess.Internally, this function tracks the child process using g_child_watch_source_new(), 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_autoptr(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 subprocessenvp
- Environment to run the test in, ornull
to inherit the parent’s environment. This must be in the GLib filename encoding.usecTimeout
- Timeout for the subprocess test in micro seconds.testFlags
- Flags to modify subprocess behaviour.
-
testTrapSubprocessWithEnvp
public static void testTrapSubprocessWithEnvp(@Nullable @Nullable String testPath, @Nullable @Nullable String[] envp, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPath
in a subprocess with the givenenvp
environment.This can be used for a test case that might not return, or that might abort.
If
testPath
isnull
then the same test is re-run in a subprocess. You can use g_test_subprocess() 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
isnull
, 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 the
GTestSubprocessFlags
flags.You can use methods such as g_test_trap_assert_passed(), g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to check the results of the subprocess. (But note that g_test_trap_assert_stdout() and g_test_trap_assert_stderr() 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 g_test_subprocess() (after calling g_test_init()) to see whether you are in a subprocess.Internally, this function tracks the child process using g_child_watch_source_new(), 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_autoptr(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 subprocessenvp
- Environment to run the test in, ornull
to inherit the parent’s environment. This must be in the GLib filename encoding.usecTimeout
- Timeout for the subprocess test in micro seconds.testFlags
- Flags to modify subprocess behaviour.
-
timeoutAdd
Sets a function to be called at regular intervals, with the given priority. The function is called repeatedly until it returnsfalse
, at which point the timeout is automatically destroyed and the function will not be called again. Thenotify
function is called when the timeout is destroyed. The first call to the function will be at the end of the firstinterval
.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 mainloop 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 globalGLib.MainContext
usingSource.attach(org.gnome.glib.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 betweenGLib.PRIORITY_DEFAULT
andGLib.PRIORITY_HIGH
.interval
- the time between calls to the function, in milliseconds (1/1000ths of a second)function
- function to call- Returns:
- the ID (greater than 0) of the event source.
-
timeoutAddOnce
Sets a function to be called afterinterval
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, org.gnome.glib.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
-
timeoutAddSeconds
Sets a function to be called at regular intervals, withpriority
.The function is called repeatedly until it returns
GLib.SOURCE_REMOVE
orfalse
, at which point the timeout is automatically destroyed and the function will not be called again.Unlike
timeoutAdd(int, int, org.gnome.glib.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, theinterval
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 mainloop 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, org.gnome.glib.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, org.gnome.glib.SourceFunc)
is preferred overtimeoutAdd(int, int, org.gnome.glib.SourceFunc)
.This internally creates a main loop source using
timeoutSourceNewSeconds(int)
and attaches it to the main loop context usingSource.attach(org.gnome.glib.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 betweenGLib.PRIORITY_DEFAULT
andGLib.PRIORITY_HIGH
.interval
- the time between calls to the function, in secondsfunction
- function to call- Returns:
- the ID (greater than 0) of the event source.
-
timeoutAddSecondsOnce
This function behaves liketimeoutAddOnce(int, org.gnome.glib.SourceOnceFunc)
but with a range in seconds.- Parameters:
interval
- the time after which the function will be called, in secondsfunction
- function to call- Returns:
- the ID (greater than 0) of the event source
-
timeoutSourceNew
Creates a new timeout source.The source will not initially be associated with any
GLib.MainContext
and must be added to one withSource.attach(org.gnome.glib.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
Creates a new timeout source.The source will not initially be associated with any
GLib.MainContext
and must be added to one withSource.attach(org.gnome.glib.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
-
tryMalloc
Attempts to allocatenBytes
, and returnsnull
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
Attempts to allocatenBytes
, initialized to 0's, and returnsnull
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
-
tryMalloc0N
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 allocatenBlockBytes
- the size of each block in bytes- Returns:
- the allocated memory, or
null
-
tryMallocN
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 allocatenBlockBytes
- the size of each block in bytes- Returns:
- the allocated memory, or
null
.
-
tryRealloc
Attempts to reallocmem
to a new size,nBytes
, and returnsnull
on failure. Contrast with g_realloc(), which aborts the program on failure.If
mem
isnull
, behaves the same as g_try_malloc().- Parameters:
mem
- previously-allocated memory, ornull
.nBytes
- number of bytes to allocate.- Returns:
- the allocated memory, or
null
.
-
tryReallocN
public static MemorySegment tryReallocN(@Nullable @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, ornull
.nBlocks
- the number of blocks to allocatenBlockBytes
- the size of each block in bytes- Returns:
- the allocated memory, or
null
.
-
ucs4ToUtf16
public static MemorySegment ucs4ToUtf16(int[] str, @Nullable @Nullable Out<Integer> itemsRead, @Nullable @Nullable Out<Integer> itemsWritten) throws GErrorException Convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.- Parameters:
str
- a UCS-4 encoded stringitemsRead
- location to store number of bytes read, ornull
. If an error occurs then the index of the invalid input is stored here.itemsWritten
- location to store number ofgunichar2
written, ornull
. The value stored here does not include the trailing 0.- Returns:
- a pointer to a newly allocated UTF-16 string.
This value must be freed with g_free(). If an error occurs,
null
will be returned anderror
set. - Throws:
GErrorException
- seeGError
-
ucs4ToUtf8
public static String ucs4ToUtf8(int[] str, @Nullable @Nullable Out<Integer> itemsRead, @Nullable @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 0 byte.- Parameters:
str
- a UCS-4 encoded stringitemsRead
- location to store number of characters read, ornull
.itemsWritten
- location to store number of bytes written ornull
. The value here stored does not include the trailing 0 byte.- Returns:
- a pointer to a newly allocated UTF-8 string.
This value must be freed with g_free(). If an error occurs,
null
will be returned anderror
set. In that case,itemsRead
will be set to the position of the first invalid input character. - Throws:
GErrorException
- seeGError
-
unicharBreakType
Determines the break type ofc
.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
-
unicharCompose
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
orb
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 <a
,b
>. See the Unicode Standard for the definition of Primary Composite.If
a
andb
do not compose a new character,ch
is set to zero.See UAX#15 for details.
- Parameters:
a
- a Unicode characterb
- a Unicode characterch
- return location for the composed character- Returns:
true
if the characters could be composed
-
unicharDecompose
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 toch
and *b
is set to zero.Note that the way Unicode decomposition pairs are defined, it is guaranteed that
b
would not decompose further, buta
may itself decompose. To get the full canonical decomposition forch
, one would need to recursively call this function ona
. Or use g_unichar_fully_decompose().See UAX#15 for details.
- Parameters:
ch
- a Unicode charactera
- return location for the first component ofch
b
- return location for the second component ofch
- Returns:
true
if the character could be decomposed
-
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 @Nullable Out<Integer> result, long resultLen) Computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, passtrue
forcompat
; for canonical decomposition passfalse
forcompat
.The decomposed sequence is placed in
result
. Only up toresultLen
characters are written intoresult
. The length of the full decomposition (irrespective ofresultLen
) 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 asG_UNICHAR_MAX_DECOMPOSITION_LENGTH
.See UAX#15 for details.
- Parameters:
ch
- a Unicode character.compat
- whether perform canonical or compatibility decompositionresult
- location to store decomposed result, ornull
resultLen
- length ofresult
- Returns:
- the length of the full decomposition.
-
unicharGetMirrorChar
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 ofch
's glyph andmirroredCh
is set, it puts that character in the address pointed to bymirroredCh
. Otherwise the original character is put.- Parameters:
ch
- a Unicode charactermirroredCh
- location to store the mirrored character- Returns:
true
ifch
has a mirrored character,false
otherwise
-
unicharGetScript
Looks up theGUnicodeScript
for a particular character (as defined by Unicode Standard Annex \\24
). No check is made forch
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.
-
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
ifc
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
ifc
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
ifc
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
ifc
is a digit
-
unicharIsgraph
public static boolean unicharIsgraph(int c) Determines whether a character is printable and not a space (returnsfalse
for control characters, format characters, and spaces). g_unichar_isprint() is similar, but returnstrue
for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().- Parameters:
c
- a Unicode character- Returns:
true
ifc
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
ifc
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
ifc
is a mark character
-
unicharIsprint
public static boolean unicharIsprint(int c) Determines whether a character is printable. Unlike g_unichar_isgraph(), returnstrue
for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().- Parameters:
c
- a Unicode character- Returns:
true
ifc
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
ifc
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
ifc
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
ifc
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
-
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 istrue
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
-
unicharToUtf8
Converts a single character to UTF-8.- Parameters:
c
- a Unicode character codeoutbuf
- output buffer, must have at least 6 bytes of space. Ifnull
, the length will be computed and returned and nothing will be written tooutbuf
.- Returns:
- number of bytes written
-
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. Ifc
is not an upperlower or titlecase character, or has no lowercase equivalentc
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. Ifc
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. Ifc
is not a lowercase or titlecase character, or has no upper case equivalentc
is returned unchanged.
-
unicharType
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 whetherch
is a valid Unicode character. Some possible integer values ofch
will not be valid. 0 is considered a valid character, though it's normally a string terminator.- Parameters:
ch
- a Unicode character- Returns:
true
ifch
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(int[] 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.
-
unixErrorQuark
-
unixFdAdd
Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.function
will be called when the specified IO condition becomestrue
. The function is expected to clear whatever event caused the IO condition to become true and returntrue
in order to be notified when it happens again. Iffunction
returnsfalse
then the watch will be cancelled.The return value of this function can be passed to g_source_remove() to cancel the watch at any time that it exists.
The source will never close the fd -- you must do it yourself.
- Parameters:
fd
- a file descriptorcondition
- IO conditions to watch for onfd
function
- aGUnixFDSourceFunc
- Returns:
- the ID (greater than 0) of the event source
-
unixFdAdd
Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.function
will be called when the specified IO condition becomestrue
. The function is expected to clear whatever event caused the IO condition to become true and returntrue
in order to be notified when it happens again. Iffunction
returnsfalse
then the watch will be cancelled.The return value of this function can be passed to g_source_remove() to cancel the watch at any time that it exists.
The source will never close the fd -- you must do it yourself.
- Parameters:
fd
- a file descriptorcondition
- IO conditions to watch for onfd
function
- aGUnixFDSourceFunc
- Returns:
- the ID (greater than 0) of the event source
-
unixFdAddFull
public static int unixFdAddFull(int priority, int fd, Set<IOCondition> condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.This is the same as g_unix_fd_add(), except that it allows you to specify a non-default priority and a provide a
GDestroyNotify
foruserData
.- Parameters:
priority
- the priority of the sourcefd
- a file descriptorcondition
- IO conditions to watch for onfd
function
- aGUnixFDSourceFunc
- Returns:
- the ID (greater than 0) of the event source
-
unixFdAddFull
public static int unixFdAddFull(int priority, int fd, IOCondition condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified bycondition
becomes true forfd
.This is the same as g_unix_fd_add(), except that it allows you to specify a non-default priority and a provide a
GDestroyNotify
foruserData
.- Parameters:
priority
- the priority of the sourcefd
- a file descriptorcondition
- IO conditions to watch for onfd
function
- aGUnixFDSourceFunc
- Returns:
- the ID (greater than 0) of the event source
-
unixFdSourceNew
Creates aGSource
to watch for a particular I/O condition on a file descriptor.The source will never close the
fd
— you must do it yourself.Any callback attached to the returned
GSource
must have typeGUnixFDSourceFunc
.- Parameters:
fd
- a file descriptorcondition
- I/O conditions to watch for onfd
- Returns:
- the newly created
GSource
-
unixFdSourceNew
Creates aGSource
to watch for a particular I/O condition on a file descriptor.The source will never close the
fd
— you must do it yourself.Any callback attached to the returned
GSource
must have typeGUnixFDSourceFunc
.- Parameters:
fd
- a file descriptorcondition
- I/O conditions to watch for onfd
- Returns:
- the newly created
GSource
-
unixGetPasswdEntry
Get thepasswd
file entry for the givenuserName
usinggetpwnam_r()
. This can fail if the givenuserName
doesn’t exist.The returned
struct passwd
has been allocated using g_malloc() and should be freed using g_free(). The strings referenced by the returned struct are included in the same allocation, so are valid until thestruct passwd
is freed.This function is safe to call from multiple threads concurrently.
You will need to include
pwd.h
to get the definition ofstruct passwd
.- Parameters:
userName
- the username to get the passwd file entry for- Returns:
- passwd entry, or
null
on error; free the returned value with g_free() - Throws:
GErrorException
- seeGError
-
unixOpenPipe
Similar to the UNIX pipe() call, but on modern systems like Linux uses the pipe2() system call, which atomically creates a pipe with the configured flags.As of GLib 2.78, the supported flags are
O_CLOEXEC
/FD_CLOEXEC
(see below) andO_NONBLOCK
. Prior to GLib 2.78, onlyFD_CLOEXEC
was supported — if you wanted to configureO_NONBLOCK
then that had to be done separately withfcntl()
.Since GLib 2.80, the constants
UnixPipeEnd.READ
andUnixPipeEnd.WRITE
can be used as mnemonic indexes infds
.It is a programmer error to call this function with unsupported flags, and a critical warning will be raised.
As of GLib 2.78, it is preferred to pass
O_CLOEXEC
in, rather thanFD_CLOEXEC
, as that matches the underlyingpipe()
API more closely. Prior to 2.78, onlyFD_CLOEXEC
was supported. Support forFD_CLOEXEC
may be deprecated and removed in future.- Parameters:
fds
- Array of two integersflags
- Bitfield of file descriptor flags, as for fcntl()- Returns:
true
on success,false
if not (and errno will be set).- Throws:
GErrorException
- seeGError
-
unixSetFdNonblocking
Control the non-blocking state of the given file descriptor, according tononblock
. On most systems this usesO_NONBLOCK
, but on some older ones may useO_NDELAY
.- Parameters:
fd
- A file descriptornonblock
- Iftrue
, set the descriptor to be non-blocking- Returns:
true
if successful- Throws:
GErrorException
- seeGError
-
unixSignalAdd
A convenience function for g_unix_signal_source_new(), which attaches to the defaultGMainContext
. You can remove the watch using g_source_remove().- Parameters:
priority
- the priority of the signal source. Typically this will be in the range betweenG_PRIORITY_DEFAULT
andG_PRIORITY_HIGH
.signum
- Signal numberhandler
- Callback- Returns:
- An ID (greater than 0) for the event source
-
unixSignalSourceNew
Create aGSource
that will be dispatched upon delivery of the UNIX signalsignum
. In GLib versions before 2.36, onlySIGHUP
,SIGINT
,SIGTERM
can be monitored. In GLib 2.36,SIGUSR1
andSIGUSR2
were added. In GLib 2.54,SIGWINCH
was added.Note that unlike the UNIX default, all sources which have created a watch will be dispatched, regardless of which underlying thread invoked g_unix_signal_source_new().
For example, an effective use of this function is to handle
SIGTERM
cleanly; flushing any outstanding files, and then calling g_main_loop_quit(). It is not safe to do any of this from a regular UNIX signal handler; such a handler may be invoked while malloc() or another library function is running, causing reentrancy issues if the handler attempts to use those functions. None of the GLib/GObject API is safe against this kind of reentrancy.The interaction of this source when combined with native UNIX functions like sigprocmask() is not defined.
The source will not initially be associated with any
GMainContext
and must be added to one with g_source_attach() before it will be executed.- Parameters:
signum
- A signal number- Returns:
- A newly created
GSource
-
unlink
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
-
unsetenv
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 '='
-
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(short[] str, @Nullable @Nullable Out<Integer> itemsRead, @Nullable @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 stringitemsRead
- location to store number of words read, ornull
. Ifnull
, thenConvertError.PARTIAL_INPUT
will be returned in casestr
contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.itemsWritten
- location to store number of characters written, ornull
. The value stored here does not include the trailing 0 character.- Returns:
- a pointer to a newly allocated UCS-4 string.
This value must be freed with g_free(). If an error occurs,
null
will be returned anderror
set. - Throws:
GErrorException
- seeGError
-
utf16ToUtf8
public static String utf16ToUtf8(short[] str, @Nullable @Nullable Out<Integer> itemsRead, @Nullable @Nullable Out<Integer> itemsWritten) throws GErrorException Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. g_convert() 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 e.g. 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 stringitemsRead
- location to store number of words read, ornull
. Ifnull
, thenConvertError.PARTIAL_INPUT
will be returned in casestr
contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. It’s guaranteed to be non-negative.itemsWritten
- location to store number of bytes written, ornull
. The value stored here does not include the trailing 0 byte. It’s guaranteed to be non-negative.- Returns:
- a pointer to a newly allocated UTF-8 string.
This value must be freed with g_free(). If an error occurs,
null
will be returned anderror
set. - Throws:
GErrorException
- seeGError
-
utf8Casefold
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 stringlen
- length ofstr
, in bytes, or -1 ifstr
is nul-terminated.- Returns:
- a newly allocated string, that is a
case independent form of
str
.
-
utf8Collate
Compares two strings for ordering using the linguistically correct rules for the [current locale][setlocale]. 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 stringstr2
- a UTF-8 encoded string- Returns:
- < 0 if
str1
compares beforestr2
, 0 if they compare equal, > 0 ifstr1
compares afterstr2
.
-
utf8CollateKey
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][setlocale].
- Parameters:
str
- a UTF-8 encoded string.len
- length ofstr
, in bytes, or -1 ifstr
is nul-terminated.- Returns:
- a newly allocated string. This string should be freed with g_free() when you are done with it.
-
utf8CollateKeyForFilename
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][setlocale].
- Parameters:
str
- a UTF-8 encoded string.len
- length ofstr
, in bytes, or -1 ifstr
is nul-terminated.- Returns:
- a newly allocated string. This string should be freed with g_free() when you are done with it.
-
utf8FindNextChar
Finds the start of the next UTF-8 character in the string afterp
.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
isnull
, the return value will never benull
: if the end of the string is reached, a pointer to the terminating nul byte is returned. Ifend
is non-null
, the return value will benull
if the end of the string is reached.- Parameters:
p
- a pointer to a position within a UTF-8 encoded stringend
- a pointer to the byte following the end of the string, ornull
to indicate that the string is nul-terminated- Returns:
- a pointer to the found character or
null
ifend
is set and is reached
-
utf8FindPrevChar
Given a positionp
with a UTF-8 encoded stringstr
, find the start of the previous UTF-8 character starting beforep
. Returnsnull
if no UTF-8 characters are present instr
beforep
.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 stringp
- pointer to some position withinstr
- Returns:
- a pointer to the found character or
null
.
-
utf8GetChar
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 g_utf8_get_char_validated() instead.- Parameters:
p
- a pointer to Unicode character encoded as UTF-8- Returns:
- the resulting character
-
utf8GetCharValidated
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 g_utf8_get_char_validated() 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-8maxLen
- the maximum number of bytes to read, or -1 ifp
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 ifmaxLen
is zero), returns (gunichar)-2; otherwise, ifp
does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.
-
utf8MakeValid
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-8len
- the maximum length ofstr
to use, in bytes. Iflen
< 0, then the string is nul-terminated.- Returns:
- a valid UTF-8 string whose content resembles
str
-
utf8Normalize
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, otherwisenull
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
andNormalizeMode.ALL_COMPOSE
are likeNormalizeMode.DEFAULT
andNormalizeMode.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 ofstr
, in bytes, or -1 ifstr
is nul-terminated.mode
- the type of normalization to perform.- Returns:
- a newly allocated string, that
is the normalized form of
str
, ornull
ifstr
is not valid UTF-8.
-
utf8OffsetToPointer
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 ifoffset
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 thatoffset
is within string boundaries before calling that function. Call g_utf8_strlen() 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 stringoffset
- a character offset withinstr
- Returns:
- the resulting pointer
-
utf8PointerToOffset
Converts from a pointer to position within a string to an integer character offset.Since 2.10, this function allows
pos
to be beforestr
, and returns a negative offset in this case.- Parameters:
str
- a UTF-8 encoded stringpos
- a pointer to a position withinstr
- Returns:
- the resulting character offset
-
utf8PrevChar
Finds the previous UTF-8 character in the string beforep
.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. Ifp
might be the first character of the string, you must use g_utf8_find_prev_char() instead.- Parameters:
p
- a pointer to a position within a UTF-8 encoded string- Returns:
- a pointer to the found character
-
utf8Strchr
Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search tolen
bytes. Iflen
is -1, allow unbounded search.- Parameters:
p
- a nul-terminated UTF-8 encoded stringlen
- the maximum length ofp
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
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 stringlen
- length ofstr
, in bytes, or -1 ifstr
is nul-terminated.- Returns:
- a newly allocated string, with all characters converted to lowercase.
-
utf8Strlen
Computes the length of the string in characters, not including the terminating nul character. If themax
'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 stringmax
- the maximum number of bytes to examine. Ifmax
is less than 0, then the string is assumed to be nul-terminated. Ifmax
is 0,p
will not be examined and may benull
. Ifmax
is greater than 0, up tomax
bytes are examined- Returns:
- the length of the string in characters
-
utf8Strncpy
Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes. Thesrc
string must be valid UTF-8 encoded text. (Use g_utf8_validate() 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 fromsrc
src
- UTF-8 encoded stringn
- character count- Returns:
dest
-
utf8Strrchr
Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search tolen
bytes. Iflen
is -1, allow unbounded search.- Parameters:
p
- a nul-terminated UTF-8 encoded stringlen
- the maximum length ofp
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
Reverses a UTF-8 string.str
must be valid UTF-8 encoded text. (Use g_utf8_validate() 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 g_strreverse(), this function returns newly-allocated memory, which should be freed with g_free() when no longer needed.
- Parameters:
str
- a UTF-8 encoded stringlen
- the maximum length ofstr
to use, in bytes. Iflen
< 0, then the string is nul-terminated.- Returns:
- a newly-allocated string which is the reverse of
str
-
utf8Strup
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 stringlen
- length ofstr
, in bytes, or -1 ifstr
is nul-terminated.- Returns:
- a newly allocated string, with all characters converted to uppercase.
-
utf8Substring
Copies a substring out of a UTF-8 encoded string. The substring will containendPos
-startPos
characters.Since GLib 2.72,
-1
can be passed toendPos
to indicate the end of the string.- Parameters:
str
- a UTF-8 encoded stringstartPos
- a character offset withinstr
endPos
- another character offset withinstr
, or-1
to indicate the end of the string- Returns:
- a newly allocated copy of the requested substring. Free with g_free() when no longer needed.
-
utf8ToUcs4
public static MemorySegment utf8ToUcs4(String str, int len, @Nullable @Nullable Out<Integer> itemsRead, @Nullable @Nullable Out<Integer> itemsWritten) throws GErrorException Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 character will be added to the string after the converted text.- Parameters:
str
- a UTF-8 encoded stringlen
- the maximum length ofstr
to use, in bytes. Iflen
< 0, then the string is nul-terminated.itemsRead
- location to store number of bytes read, ornull
. Ifnull
, thenConvertError.PARTIAL_INPUT
will be returned in casestr
contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.itemsWritten
- location to store number of characters written ornull
. The value here stored does not include the trailing 0 character.- Returns:
- a pointer to a newly allocated UCS-4 string.
This value must be freed with g_free(). If an error occurs,
null
will be returned anderror
set. - Throws:
GErrorException
- seeGError
-
utf8ToUcs4Fast
public static MemorySegment utf8ToUcs4Fast(String str, int len, @Nullable @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 g_utf8_to_ucs4() but does no error checking on the input. A trailing 0 character will be added to the string after the converted text.- Parameters:
str
- a UTF-8 encoded stringlen
- the maximum length ofstr
to use, in bytes. Iflen
< 0, then the string is nul-terminated.itemsWritten
- location to store the number of characters in the result, ornull
.- Returns:
- a pointer to a newly allocated UCS-4 string. This value must be freed with g_free().
-
utf8ToUtf16
public static MemorySegment utf8ToUtf16(String str, int len, @Nullable @Nullable Out<Integer> itemsRead, @Nullable @Nullable Out<Integer> itemsWritten) throws GErrorException Convert a string from UTF-8 to UTF-16. A 0 character will be added to the result after the converted text.- Parameters:
str
- a UTF-8 encoded stringlen
- the maximum length (number of bytes) ofstr
to use. Iflen
< 0, then the string is nul-terminated.itemsRead
- location to store number of bytes read, ornull
. Ifnull
, thenConvertError.PARTIAL_INPUT
will be returned in casestr
contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.itemsWritten
- location to store number ofgunichar2
written, ornull
. The value stored here does not include the trailing 0.- Returns:
- a pointer to a newly allocated UTF-16 string.
This value must be freed with g_free(). If an error occurs,
null
will be returned anderror
set. - Throws:
GErrorException
- seeGError
-
utf8TruncateMiddle
Cuts off the middle of the string, preserving half oftruncateLength
characters at the beginning and half at the end.If
string
is already short enough, this returns a copy ofstring
. IftruncateLength
is0
, an empty string is returned.- Parameters:
string
- a nul-terminated UTF-8 encoded stringtruncateLength
- the new size ofstring
, in characters, including the ellipsis character- Returns:
- a newly-allocated copy of
string
ellipsized in the middle
-
utf8Validate
Validates UTF-8 encoded text.str
is the text to validate; ifstr
is nul-terminated, thenmaxLen
can be -1, otherwisemaxLen
should be the number of bytes to validate. Ifend
is non-null
, then the end of the valid range will be stored there (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).Note that g_utf8_validate() returns
false
ifmaxLen
is positive and any of themaxLen
bytes are nul.Returns
true
if all ofstr
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 dataend
- return location for end of valid data- Returns:
true
if the text was valid UTF-8
-
utf8ValidateLen
Validates UTF-8 encoded text.As with g_utf8_validate(), but
maxLen
must be set, and hence this function will always returnfalse
if any of the bytes ofstr
are nul.- Parameters:
str
- a pointer to character dataend
- return location for end of valid data- Returns:
true
if the text was valid UTF-8
-
utime
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
-
uuidStringIsValid
Parses the stringstr
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
ifstr
is a valid UUID,false
otherwise.
- simple forms (e.g.
-
uuidStringRandom
Generates a random UUID (RFC 4122 version 4) as a string. It has the same randomness guarantees asGRand
, 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().
-
variantGetGtype
-
warnMessage
public static void warnMessage(@Nullable @Nullable String domain, String file, int line, String func, @Nullable @Nullable String warnexpr) Internal function used to print messages from the publicGLib#warnIfReached
andGLib#warnIfFail
macros.- Parameters:
domain
- log domainfile
- file containing the warningline
- line number of the warningfunc
- function containing the warningwarnexpr
- 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().
-
win32CheckWindowsVersion
Returns whether the version of the Windows operating system the code is running on is at least the specified major, minor and service pack versions. See MSDN documentation for the Operating System Version. Software that needs even more detailed version and feature information should use the Win32 API VerifyVersionInfo() directly.Successive calls of this function can be used for enabling or disabling features at run-time for a range of Windows versions, as per the VerifyVersionInfo() API documentation.
- Parameters:
major
- major version of Windowsminor
- minor version of Windowsspver
- Windows Service Pack Level, 0 if noneosType
- Type of Windows OS- Returns:
true
if the Windows Version is the same or greater than the specified major, minor and service pack versions, and whether the running Windows is a workstation or server edition of Windows, if specifically specified.
-
win32ErrorMessage
Translate a Win32 error code (as returned by GetLastError() or WSAGetLastError()) into the corresponding message. The message is either language neutral, or in the thread's language, or the user's language, the system's language, or US English (see docs for FormatMessage()). The returned string is in UTF-8. It should be deallocated with g_free().- Parameters:
error
- error code.- Returns:
- newly-allocated error message
-
win32Ftruncate
public static int win32Ftruncate(int f, int size) -
win32GetCommandLine
Gets the command line arguments, on Windows, in the GLib filename encoding (ie: UTF-8).Normally, on Windows, the command line arguments are passed to main() in the system codepage encoding. This prevents passing filenames as arguments if the filenames contain characters that fall outside of this codepage. If such filenames are passed, then substitutions will occur (such as replacing some characters with '?').
GLib's policy of using UTF-8 as a filename encoding on Windows was designed to localise the pain of dealing with filenames outside of the system codepage to one area: dealing with commandline arguments in main().
As such, most GLib programs should ignore the value of argv passed to their main() function and call g_win32_get_command_line() instead. This will get the "full Unicode" commandline arguments using GetCommandLineW() and convert it to the GLib filename encoding (which is UTF-8 on Windows).
The strings returned by this function are suitable for use with functions such as g_open() and g_file_new_for_commandline_arg() but are not suitable for use with g_option_context_parse(), which assumes that its input will be in the system codepage. The return value is suitable for use with g_option_context_parse_strv(), however, which is a better match anyway because it won't leak memory.
Unlike argv, the returned value is a normal strv and can (and should) be freed with g_strfreev() when no longer needed.
- Returns:
- the commandline arguments in the GLib filename encoding (ie: UTF-8)
-
win32GetPackageInstallationDirectory
@Deprecated public static String win32GetPackageInstallationDirectory(@Nullable @Nullable String package_, @Nullable @Nullable String dllName) Deprecated.Pass the HMODULE of a DLL or EXE to g_win32_get_package_installation_directory_of_module() instead.Try to determine the installation directory for a software package.This function is deprecated. Use g_win32_get_package_installation_directory_of_module() instead.
The use of
package_
is deprecated. You should always passnull
. A warning is printed if non-NULL is passed aspackage_
.The original intended use of
package_
was for a short identifier of the package, typically the same identifier as used forGETTEXT_PACKAGE
in software configured using GNU autotools. The function first looks in the Windows Registry for the value#InstallationDirectory
in the key#HKLM\\Software\\@package
, and if that value exists and is a string, returns that.It is strongly recommended that packagers of GLib-using libraries for Windows do not store installation paths in the Registry to be used by this function as that interferes with having several parallel installations of the library. Enabling multiple installations of different versions of some GLib-using library, or GLib itself, is desirable for various reasons.
For this reason it is recommended to always pass
null
aspackage_
to this function, to avoid the temptation to use the Registry. In version 2.20 of GLib thepackage_
parameter will be ignored and this function won't look in the Registry at all.If
package_
isnull
, or the above value isn't found in the Registry, butdllName
is non-null
, it should name a DLL loaded into the current process. Typically that would be the name of the DLL calling this function, looking for its installation directory. The function then asks Windows what directory that DLL was loaded from. If that directory's last component is "bin" or "lib", the parent directory is returned, otherwise the directory itself. If that DLL isn't loaded, the function proceeds as ifdllName
wasnull
.If both
package_
anddllName
arenull
, the directory from where the main executable of the process was loaded is used instead in the same way as above.- Parameters:
package_
- You should passnull
for this.dllName
- The name of a DLL that a package provides in UTF-8, ornull
.- Returns:
- a string containing the installation directory for
package_
. The string is in the GLib file name encoding, i.e. UTF-8. The return value should be freed with g_free() when not needed any longer. If the function failsnull
is returned.
-
win32GetPackageInstallationDirectoryOfModule
public static String win32GetPackageInstallationDirectoryOfModule(@Nullable @Nullable MemorySegment hmodule) This function tries to determine the installation directory of a software package based on the location of a DLL of the software package.hmodule
should be the handle of a loaded DLL ornull
. The function looks up the directory that DLL was loaded from. Ifhmodule
is NULL, the directory the main executable of the current process is looked up. If that directory's last component is "bin" or "lib", its parent directory is returned, otherwise the directory itself.It thus makes sense to pass only the handle to a "public" DLL of a software package to this function, as such DLLs typically are known to be installed in a "bin" or occasionally "lib" subfolder of the installation folder. DLLs that are of the dynamically loaded module or plugin variety are often located in more private locations deeper down in the tree, from which it is impossible for GLib to deduce the root of the package installation.
The typical use case for this function is to have a DllMain() that saves the handle for the DLL. Then when code in the DLL needs to construct names of files in the installation tree it calls this function passing the DLL handle.
- Parameters:
hmodule
- The Win32 handle for a DLL loaded into the current process, ornull
- Returns:
- a string containing the guessed installation directory for
the software package
hmodule
is from. The string is in the GLib file name encoding, i.e. UTF-8. The return value should be freed with g_free() when not needed any longer. If the function failsnull
is returned.
-
win32GetPackageInstallationSubdirectory
@Deprecated public static String win32GetPackageInstallationSubdirectory(@Nullable @Nullable String package_, @Nullable @Nullable String dllName, String subdir) Deprecated.Pass the HMODULE of a DLL or EXE to g_win32_get_package_installation_directory_of_module() instead, and then construct a subdirectory pathname with g_build_filename().This function is deprecated. Use g_win32_get_package_installation_directory_of_module() and g_build_filename() instead.Returns a newly-allocated string containing the path of the subdirectory
subdir
in the return value from calling g_win32_get_package_installation_directory() with thepackage_
anddllName
parameters. See the documentation for g_win32_get_package_installation_directory() for more details. In particular, note that it is deprecated to pass anything except NULL aspackage_
.- Parameters:
package_
- You should passnull
for this.dllName
- The name of a DLL that a package provides, in UTF-8, ornull
.subdir
- A subdirectory of the package installation directory, also in UTF-8- Returns:
- a string containing the complete path to
subdir
inside the installation directory ofpackage_
. The returned string is in the GLib file name encoding, i.e. UTF-8. The return value should be freed with g_free() when no longer needed. If something goes wrong,null
is returned.
-
win32GetSystemDataDirsForModule
public static String[] win32GetSystemDataDirsForModule(@Nullable @Nullable MemorySegment addressOfFunction) -
win32GetWindowsVersion
Deprecated.Be aware that for Windows 8.1 and Windows Server 2012 R2 and later, this will return 62 unless the application is manifested for Windows 8.1/Windows Server 2012 R2, for example. MSDN stated that GetVersion(), which is used here, is subject to further change or removal after Windows 8.1.This function is deprecated. Use g_win32_check_windows_version() instead.Returns version information for the Windows operating system the code is running on. See MSDN documentation for the GetVersion() function. To summarize, the most significant bit is one on Win9x, and zero on NT-based systems. Since version 2.14, GLib works only on NT-based systems, so checking whether your are running on Win9x in your own software is moot. The least significant byte is 4 on Windows NT 4, and 5 on Windows XP. Software that needs really detailed version and feature information should use Win32 API like GetVersionEx() and VerifyVersionInfo().
- Returns:
- The version information.
-
win32Getlocale
The setlocale() function in the Microsoft C library uses locale names of the form "English_United States.1252" etc. We want the UNIXish standard form "en_US", "zh_TW" etc. This function gets the current thread locale from Windows - without any encoding info - and returns it as a string of the above form for use in forming file names etc. The returned string should be deallocated with g_free().- Returns:
- newly-allocated locale name.
-
win32LocaleFilenameFromUtf8
Converts a filename from UTF-8 to the system codepage.On NT-based Windows, on NTFS file systems, file names are in Unicode. It is quite possible that Unicode file names contain characters not representable in the system codepage. (For instance, Greek or Cyrillic characters on Western European or US Windows installations, or various less common CJK characters on CJK Windows installations.)
In such a case, and if the filename refers to an existing file, and the file system stores alternate short (8.3) names for directory entries, the short form of the filename is returned. Note that the "short" name might in fact be longer than the Unicode name if the Unicode name has very short pathname components containing non-ASCII characters. If no system codepage name for the file is possible,
null
is returned.The return value is dynamically allocated and should be freed with g_free() when no longer needed.
- Parameters:
utf8filename
- a UTF-8 encoded filename.- Returns:
- The converted filename, or
null
on conversion failure and lack of short names.
-