Class GLib
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intA good size for a buffer to be passed intoasciiDtostr(java.lang.String, int, double).static final intEvaluates to the initial reference count forgatomicrefcount.static final intSpecifies one of the possible types of byte order.static final intThe 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 StringThe set of lowercase ASCII alphabet characters.static final StringThe set of uppercase ASCII alphabet characters.static final StringThe set of ASCII digits.static final intA bitmask that restricts the possible flags passed to g_datalist_set_flags().static final intRepresents an invalidGDateDay.static final intRepresents an invalid Julian day number.static final intRepresents an invalid year.static final intThe directory separator character.static final StringThe directory separator as a string.static final doubleThe base of natural logarithms.static final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final StringDeprecated.Use G_STRFUNC() insteadstatic final StringDeprecated.Use G_STRFUNC() insteadstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final intstatic final intstatic final intDefined to 1 if gcc-style visibility handling is supported.static final intstatic final intstatic final intThe position of the first bit which is not reserved for internal use be theGHookimplementation, i.e.static final intThe bias by which exponents in double-precision floats are offset.static final intThe bias by which exponents in single-precision floats are offset.static final StringThe name of the main group of a desktop entry file, as defined in the Desktop Entry Specification.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string list giving the available application actions.static final StringA key underGLib.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 StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the tooltip for the desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean set to true if the application is D-Bus activatable.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the command line to execute.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the generic name of the desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry has been deleted by the user.static final StringA key underGLib.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 StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the MIME types supported by this desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the specific name of the desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry should be shown in menus.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should not display the desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should display the desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string containing the working directory to run the program in.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification.static final StringA key underGLib.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 StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the program should be run in a terminal window.static final StringA key underGLib.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 StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the type of the desktop entry.static final StringA key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the URL to access.static final StringA key underGLib.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 StringThe value of theGLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing applications.static final StringThe value of theGLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing directories.static final StringThe value of theGLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing links to documents.static final intSpecifies one of the possible types of byte order.static final doubleThe natural logarithm of 10.static final doubleThe natural logarithm of 2.static final doubleMultiplying the base 2 exponent by this number yields the base 10 exponent.static final byteDefines the log domain.static final intGLib log levels that are considered fatal by default.static final intLog levels below1<<G_LOG_LEVEL_USER_SHIFTare used by GLib.static final intstatic final intstatic final intstatic final intThe major version number of the GLib library.static final shortstatic final intstatic final longstatic final bytestatic final shortstatic final intstatic final longstatic final bytestatic final intThe micro version number of the GLib library.static final shortThe minimum value which can be held in agint16.static final intThe minimum value which can be held in agint32.static final longThe minimum value which can be held in agint64.static final byteThe minimum value which can be held in agint8.static final intThe minor version number of the GLib library.static final Stringstatic final StringIf a long option in the main group has this name, it is not treated as a regular option.static final intSpecifies one of the possible types of byte order (currently unused).static final doubleThe value of pi (ratio of circle's circumference to its diameter).static final doublePi divided by 2.static final doublePi divided by 4.static final StringA format specifier that can be used in printf()-style format strings when printing aGPid.static final StringA format specifier that can be used in printf()-style format strings when printing thefdmember of aGPollFD.static final intUse this for default priority event sources.static final intUse this for default priority idle functions.static final intUse this for high priority event sources.static final intUse this for high priority idle functions.static final intUse this for very low priority background tasks.static final intEvaluates to the initial reference count forgrefcount.static final intThe search path separator character.static final StringThe search path separator as a string.static final intstatic final intstatic final intstatic final intstatic final booleanUse this macro as the return value of aGLib.SourceFuncto leave theGLib.Sourcein the main loop.static final booleanUse this macro as the return value of aGLib.SourceFuncto remove theGLib.Sourcefrom the main loop.static final doubleThe square root of two.static final StringThe standard delimiters, used instrdelimit(java.lang.String, java.lang.String, byte).static final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final StringA value that can be passed as an option totestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).static final StringA value that can be passed as an option totestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).static final StringA value that can be passed as an option totestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).static final longEvaluates to a time span of one day.static final longEvaluates to a time span of one hour.static final longEvaluates to a time span of one millisecond.static final longEvaluates to a time span of one minute.static final longEvaluates to a time span of one second.static final intThe maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.static final StringGeneric delimiters characters as defined in RFC 3986.static final StringSubcomponent delimiter characters as defined in RFC 3986.static final intNumber of microseconds in one second (1 million).static final intstatic final intA macro that should be defined by the user prior to including the glib.h header.static final int -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic voidabort()A wrapper for the POSIX abort() function.static intA wrapper for the POSIX access() function.static MemorySegmentalignedAlloc(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 MemorySegmentalignedAlloc0(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 voidalignedFree(@Nullable MemorySegment mem) Frees the memory allocated by g_aligned_alloc().static voidalignedFreeSized(@Nullable MemorySegment mem, long alignment, long size) Frees the memory pointed to bymem, assuming it is has the givensizeandalignment.static intasciiDigitValue(byte c) Determines the numeric value of a character as a decimal digit.static StringasciiDtostr(String buffer, int bufLen, double d) Converts agdoubleto a string, using the '.' as decimal point.static StringasciiFormatd(String buffer, int bufLen, String format, double d) Converts agdoubleto a string, using the '.' as decimal point.static intasciiStrcasecmp(String s1, String s2) Compare two strings, ignoring the case of ASCII characters.static StringasciiStrdown(String str, long len) Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly matchasciiTolower(byte).static booleanasciiStringToSigned(String str, int base, long min, long max, @Nullable Out<Long> outNum) A convenience function for converting a string to a signed number.static booleanasciiStringToUnsigned(String str, int base, long min, long max, @Nullable Out<Long> outNum) A convenience function for converting a string to an unsigned number.static intasciiStrncasecmp(String s1, String s2, long n) Compares1ands2, ignoring the case of ASCII characters and any characters after the firstnin each string.static doubleasciiStrtod(String nptr, @Nullable Out<String> endptr) Converts a string to a floating point value.static longasciiStrtoll(String nptr, @Nullable Out<String> endptr, int base) Converts a string to agint64value.static longasciiStrtoull(String nptr, @Nullable Out<String> endptr, int base) Converts a string to aguint64value.static StringasciiStrup(String str, long len) Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly matchasciiToupper(byte).static byteasciiTolower(byte c) Convert a character to ASCII lower case.static byteasciiToupper(byte c) Convert a character to ASCII upper case.static intasciiXdigitValue(byte c) Determines the numeric value of a character as a hexadecimal digit.static voidassertionMessage(String domain, String file, int line, String func, String message) static voidassertionMessageCmpint(String domain, String file, int line, String func, String expr, long arg1, String cmp, long arg2, byte numtype) static voidassertionMessageCmpnum(String domain, String file, int line, String func, String expr, double arg1, String cmp, double arg2, byte numtype) static voidassertionMessageCmpstr(String domain, String file, int line, String func, String expr, String arg1, String cmp, String arg2) static voidassertionMessageCmpstrv(String domain, String file, int line, String func, String expr, String arg1, String arg2, long firstWrongIdx) static voidassertionMessageError(String domain, String file, int line, String func, String expr, GError error, Quark errorDomain, int errorCode) static voidassertionMessageExpr(@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 voidassertWarning(String logDomain, String file, int line, String prettyFunction, String expression) static voidDeprecated.It is best to avoid g_atexit().static intatomicIntAdd(MemorySegment atomic, int val) Atomically addsvalto the value ofatomic.static intatomicIntAnd(MemorySegment atomic, int val) Performs an atomic bitwise 'and' of the value ofatomicandval, storing the result back inatomic.static booleanatomicIntCompareAndExchange(MemorySegment atomic, int oldval, int newval) Comparesatomictooldvaland, if equal, sets it tonewval.static booleanatomicIntCompareAndExchangeFull(MemorySegment atomic, int oldval, int newval, Out<Integer> preval) Comparesatomictooldvaland, if equal, sets it tonewval.static booleanatomicIntDecAndTest(MemorySegment atomic) Decrements the value ofatomicby 1.static intatomicIntExchange(MemorySegment atomic, int newval) Sets theatomictonewvaland returns the old value fromatomic.static intatomicIntExchangeAndAdd(MemorySegment atomic, int val) Deprecated.Use g_atomic_int_add() instead.static intatomicIntGet(MemorySegment atomic) Gets the current value ofatomic.static voidatomicIntInc(MemorySegment atomic) Increments the value ofatomicby 1.static intatomicIntOr(MemorySegment atomic, int val) Performs an atomic bitwise 'or' of the value ofatomicandval, storing the result back inatomic.static voidatomicIntSet(MemorySegment atomic, int newval) Sets the value ofatomictonewval.static intatomicIntXor(MemorySegment atomic, int val) Performs an atomic bitwise 'xor' of the value ofatomicandval, storing the result back inatomic.static longatomicPointerAdd(MemorySegment atomic, long val) Atomically addsvalto the value ofatomic.static longatomicPointerAnd(MemorySegment atomic, long val) Performs an atomic bitwise 'and' of the value ofatomicandval, storing the result back inatomic.static booleanatomicPointerCompareAndExchange(MemorySegment atomic, @Nullable MemorySegment oldval, @Nullable MemorySegment newval) Comparesatomictooldvaland, if equal, sets it tonewval.static booleanatomicPointerCompareAndExchangeFull(MemorySegment atomic, @Nullable MemorySegment oldval, @Nullable MemorySegment newval, Out<MemorySegment> preval) Comparesatomictooldvaland, if equal, sets it tonewval.static MemorySegmentatomicPointerExchange(@Nullable MemorySegment atomic, @Nullable MemorySegment newval) Sets theatomictonewvaland returns the old value fromatomic.static MemorySegmentatomicPointerGet(MemorySegment atomic) Gets the current value ofatomic.static longatomicPointerOr(MemorySegment atomic, long val) Performs an atomic bitwise 'or' of the value ofatomicandval, storing the result back inatomic.static voidatomicPointerSet(MemorySegment atomic, @Nullable MemorySegment newval) Sets the value ofatomictonewval.static longatomicPointerXor(MemorySegment atomic, long val) Performs an atomic bitwise 'xor' of the value ofatomicandval, storing the result back inatomic.static MemorySegmentatomicRcBoxAcquire(MemorySegment memBlock) Atomically acquires a reference on the data pointed bymemBlock.static MemorySegmentatomicRcBoxAlloc(long blockSize) AllocatesblockSizebytes of memory, and adds atomic reference counting semantics to it.static MemorySegmentatomicRcBoxAlloc0(long blockSize) AllocatesblockSizebytes of memory, and adds atomic reference counting semantics to it.static MemorySegmentatomicRcBoxDup(long blockSize, MemorySegment memBlock) Allocates a new block of data with atomic reference counting semantics, and copiesblockSizebytes ofmemBlockinto it.static longatomicRcBoxGetSize(MemorySegment memBlock) Retrieves the size of the reference counted data pointed bymemBlock.static voidatomicRcBoxRelease(MemorySegment memBlock) Atomically releases a reference on the data pointed bymemBlock.static voidatomicRcBoxReleaseFull(MemorySegment memBlock) Atomically releases a reference on the data pointed bymemBlock.static booleanatomicRefCountCompare(MemorySegment arc, int val) Atomically compares the current value ofarcwithval.static booleanAtomically decreases the reference count.static voidAtomically increases the reference count.static voidInitializes a reference count variable to 1.static byte[]base64Decode(String text) Decode a sequence of Base-64 encoded text into binary data.static MemorySegmentbase64DecodeInplace(Out<byte[]> text) Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.static longbase64DecodeStep(byte[] in, byte[] out, Out<Integer> state, Out<Integer> save) Incrementally decode a sequence of binary data from its Base-64 stringified representation.static Stringbase64Encode(@org.jetbrains.annotations.Nullable byte[] data) Encode a sequence of binary data into its Base-64 stringified representation.static longbase64EncodeClose(boolean breakLines, byte[] out, Out<Integer> state, Out<Integer> save) Flush the status from a sequence of calls to g_base64_encode_step().static longbase64EncodeStep(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 StringDeprecated.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 voidbitLock(MemorySegment address, int lockBit) Sets the indicatedlockBitinaddress.static intbitNthLsf(int mask, int nthBit) Find the position of the first bit set inmask, searching from (but not including)nthBitupwards.static intbitNthMsf(int mask, int nthBit) Find the position of the first bit set inmask, searching from (but not including)nthBitdownwards.static intbitStorage(int number) Gets the number of bits used to holdnumber, e.g.static booleanbitTrylock(MemorySegment address, int lockBit) Sets the indicatedlockBitinaddress, returningtrueif successful.static voidbitUnlock(MemorySegment address, int lockBit) Clears the indicatedlockBitinaddress.static voidstatic StringbuildFilename(String firstElement, Object... varargs) Creates a filename from a series of elements using the correct separator for the current platform.static StringbuildFilenamev(String[] args) Creates a filename from a vector of elements using the correct separator for the current platform.static StringCreates a path from a series of elements usingseparatoras the separator between elements.static StringbuildPathv(String separator, String[] args) Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of variadic arguments.static StringcanonicalizeFilename(String filename, @Nullable String relativeTo) Gets the canonical file name fromfilename.static intA wrapper for the POSIX chdir() function.static StringcheckVersion(int requiredMajor, int requiredMinor, int requiredMicro) Checks that the GLib library in use is compatible with the given version.static intchildWatchAdd(int priority, Pid pid, ChildWatchFunc function) Sets a function to be called when the child indicated bypidexits, at the prioritypriority.static SourcechildWatchSourceNew(Pid pid) Creates a new child_watch source.static intA wrapper for the POSIX chmod() function.static voidclearHandleId(MemorySegment tagPtr, ClearHandleFunc clearFunc) Clears a numeric handler, such as aGSourceID.static voidclearList(Out<List<MemorySegment>> listPtr) Clears a pointer to aGList, freeing it and, optionally, freeing its elements usingdestroy.static voidclearPointer(Out<MemorySegment> pp) Clears a reference to a variable.static voidclearSlist(SList<MemorySegment>[] slistPtr) Clears a pointer to aGSList, freeing it and, optionally, freeing its elements usingdestroy.static booleanclose(int fd) This wraps the close() call.static intclosefrom(int lowfd) Close every file descriptor equal to or greater thanlowfd.static StringcomputeChecksumForBytes(ChecksumType checksumType, byte[] data) Computes the checksum for a binarydata.static StringcomputeChecksumForData(ChecksumType checksumType, byte[] data) Computes the checksum for a binarydataoflength.static StringcomputeChecksumForString(ChecksumType checksumType, String str, long length) Computes the checksum of a string.static StringcomputeHmacForBytes(ChecksumType digestType, byte[] key, byte[] data) Computes the HMAC for a binarydata.static StringcomputeHmacForData(ChecksumType digestType, byte[] key, byte[] data) Computes the HMAC for a binarydataoflength.static StringcomputeHmacForString(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 Quarkstatic 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 intA wrapper for the POSIX creat() function.static voiddatalistClear(Data[] datalist) Frees all the data elements of the datalist.static voiddatalistForeach(Data[] datalist, DataForeachFunc func) Calls the given function for each data element of the datalist.static MemorySegmentdatalistGetData(Data[] datalist, String key) Gets a data element, using its string identifier.static intdatalistGetFlags(Data[] datalist) Gets flags values packed in together with the datalist.static MemorySegmentdatalistIdDupData(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 MemorySegmentdatalistIdGetData(Data[] datalist, Quark keyId) Retrieves the data element corresponding tokeyId.static voiddatalistIdRemoveMultiple(Data[] datalist, Quark[] keys) Removes multiple keys from a datalist.static MemorySegmentdatalistIdRemoveNoNotify(Data[] datalist, Quark keyId) Removes an element, without calling its destroy notification function.static booleandatalistIdReplaceData(Data[] datalist, Quark keyId, @Nullable MemorySegment oldval, @Nullable MemorySegment newval) Compares the member that is associated withkeyIdindatalisttooldval, and if they are the same, replaceoldvalwithnewval.static voiddatalistIdSetDataFull(Data[] datalist, Quark keyId, @Nullable MemorySegment data) Sets the data corresponding to the givenGQuarkid, and the function to be called when the element is removed from the datalist.static voiddatalistInit(Data[] datalist) Resets the datalist tonull.static voiddatalistSetFlags(Data[] datalist, int flags) Turns on flag values for a data list.static voiddatalistUnsetFlags(Data[] datalist, int flags) Turns off flag values for a data list.static voiddatasetDestroy(MemorySegment datasetLocation) Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.static voiddatasetForeach(MemorySegment datasetLocation, DataForeachFunc func) Calls the given function for each data element which is associated with the given location.static MemorySegmentdatasetIdGetData(MemorySegment datasetLocation, Quark keyId) Gets the data element corresponding to aGQuark.static MemorySegmentdatasetIdRemoveNoNotify(MemorySegment datasetLocation, Quark keyId) Removes an element, without calling its destroy notification function.static voiddatasetIdSetDataFull(MemorySegment datasetLocation, Quark keyId, @Nullable MemorySegment data) Sets the data element associated with the givenGQuarkid, and also the function to call when the data element is destroyed.static StringThis is a variant of g_dgettext() that allows specifying a locale category instead of always usingLC_MESSAGES.static StringThis 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 booleandirectEqual(@Nullable MemorySegment v1, @Nullable MemorySegment v2) Compares twogpointerarguments and returnstrueif they are equal.static intdirectHash(@Nullable MemorySegment v) Converts a gpointer to a hash value.static StringThis 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 booleandoubleEqual(MemorySegment v1, MemorySegment v2) Compares the twogdoublevalues being pointed to and returnstrueif they are equal.static intConverts a pointer to agdoubleto a hash value.static StringThis function is a variant of g_dgettext() which supports a disambiguating message context.static Stringdpgettext2(@Nullable String domain, String context, String msgid) This function is a variant of g_dgettext() which supports a disambiguating message context.static StringenvironGetenv(@Nullable String[] envp, String variable) Returns the value of the environment variablevariablein the provided listenvp.static String[]environSetenv(@Nullable String[] envp, String variable, String value, boolean overwrite) Sets the environment variablevariablein the provided listenvptovalue.static String[]environUnsetenv(@Nullable String[] envp, String variable) Removes the environment variablevariablefrom the provided environmentenvp.static intfdwalkSetCloexec(int lowfd) Mark every file descriptor equal to or greater thanlowfdto be closed at the nextexecve()or similar, as if via theFD_CLOEXECflag.static FileErrorfileErrorFromErrno(int errNo) Gets aGFileErrorconstant based on the passed-inerrNo.static Quarkstatic booleanfileGetContents(String filename, Out<byte[]> contents) Reads an entire file into allocated memory, with good error checking.static StringfilenameDisplayBasename(String filename) Returns the display basename for the particular filename, guaranteed to be valid UTF-8.static StringfilenameDisplayName(String filename) Converts a filename into a valid UTF-8 string.static StringfilenameFromUri(String uri, @Nullable Out<String> hostname) Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.static StringfilenameFromUtf8(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 StringfilenameToUri(String filename, @Nullable String hostname) Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3.static StringfilenameToUtf8(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 intfileOpenTmp(@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 StringfileReadLink(String filename) Reads the contents of the symbolic linkfilenamelike the POSIXreadlink()function.static booleanfileSetContents(String filename, byte[] contents) Writes all ofcontentsto a file namedfilename.static booleanfileSetContentsFull(String filename, byte[] contents, Set<FileSetContentsFlags> flags, int mode) Writes all ofcontentsto a file namedfilename, with good error checking.static booleanfileSetContentsFull(String filename, byte[] contents, FileSetContentsFlags flags, int mode) Writes all ofcontentsto a file namedfilename, with good error checking.static booleanReturnstrueif any of the tests in the bitfieldtestaretrue.static booleanReturnstrueif any of the tests in the bitfieldtestaretrue.static StringfindProgramInPath(String program) Locates the first executable namedprogramin the user's path, in the same way that execvp() would locate it.static MemorySegmentA wrapper for the stdiofopen()function.static StringformatSize(long size) Formats a size (for example the size of a file) into a human readable string.static StringformatSizeForDisplay(long size) Deprecated.This function is broken due to its use of SI suffixes to denote IEC units.static StringformatSizeFull(long size, Set<FormatSizeFlags> flags) Formats a size.static StringformatSizeFull(long size, FormatSizeFlags... flags) Formats a size.static intfprintf(MemorySegment file, String format, Object... varargs) An implementation of the standardfprintf()function which supports positional parameters, as specified in the Single Unix Specification.static voidfree(@Nullable MemorySegment mem) Frees the memory pointed to bymem.static voidfreeSized(@Nullable MemorySegment mem, long size) Frees the memory pointed to bymem, assuming it is has the givensize.static MemorySegmentfreopen(String filename, String mode, @Nullable MemorySegment stream) A wrapper for the POSIX freopen() function.static intfsync(int fd) A wrapper for the POSIXfsync()function.static StringGets a human-readable name for the application, as set by g_set_application_name().static booleangetCharset(@Nullable Out<String> charset) Obtains the character set for the current locale; you might use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding.static StringGets the character set for the current locale.static booleangetConsoleCharset(@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 StringGets the current directory.static voidgetCurrentTime(TimeVal result) Deprecated.GTimeValis not year-2038-safe.static StringReturns the value of an environment variable.static String[]Gets the list of environment variables for the current process.static booleangetFilenameCharsets(Out<String[]> filenameCharsets) Determines the preferred character sets used for filenames.static StringGets the current user's home directory.static StringReturn 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 longQueries the system monotonic time.static intDetermine the approximate number of threads that the system will schedule simultaneously for this process.static StringGet information about the operating system.static StringGets the name of the program.static StringGets the real name of the user.static longQueries 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 StringGets the directory to use for temporary files.static StringReturns a base directory in which to store non-essential, cached data specific to particular user.static StringReturns a base directory in which to store user-specific application configuration information such as user preferences and settings.static StringReturns a base directory in which to access application data such as icons that is customized for a particular user.static StringGets the user name of the current user.static StringReturns a directory that is unique to the current user on the local system.static StringgetUserSpecialDir(UserDirectory directory) Returns the full path of a special directory using its logical id.static StringReturns a base directory in which to store state files specific to particular user.static booleanhostnameIsAsciiEncoded(String hostname) Tests ifhostnamecontains segments with an ASCII-compatible encoding of an Internationalized Domain Name.static booleanhostnameIsIpAddress(String hostname) Tests ifhostnameis the string form of an IPv4 or IPv6 address.static booleanhostnameIsNonAscii(String hostname) Tests ifhostnamecontains Unicode characters.static StringhostnameToAscii(String hostname) Convertshostnameto its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.static StringhostnameToUnicode(String hostname) Convertshostnameto 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 longiconv(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 intidleAdd(int priority, SourceFunc function) Adds a function to be called whenever there are no higher priority events pending.static intidleAddOnce(SourceOnceFunc function) Adds a function to be called whenever there are no higher priority events pending to the default main loop.static booleanidleRemoveByData(@Nullable MemorySegment data) Removes the idle function with the given data.static SourceCreates a new idle source.static booleanint64Equal(MemorySegment v1, MemorySegment v2) Compares the twogint64values being pointed to and returnstrueif they are equal.static intConverts a pointer to agint64to a hash value.static booleanintEqual(MemorySegment v1, MemorySegment v2) Compares the twogintvalues being pointed to and returnstrueif they are equal.static StringinternStaticString(@Nullable String string) Returns a canonical representation forstring.static StringinternString(@Nullable String string) Returns a canonical representation forstring.static intConverts a pointer to agintto a hash value.static intioAddWatch(IOChannel channel, int priority, Set<IOCondition> condition, IOFunc func) Adds theGIOChannelinto the default main loop context with the given priority.static intioAddWatch(IOChannel channel, int priority, IOCondition condition, IOFunc func) Adds theGIOChannelinto the default main loop context with the given priority.static SourceioCreateWatch(IOChannel channel, Set<IOCondition> condition) Creates aGSourcethat's dispatched whenconditionis met for the givenchannel.static SourceioCreateWatch(IOChannel channel, IOCondition... condition) Creates aGSourcethat's dispatched whenconditionis met for the givenchannel.static voidstatic 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.static StringlocaleToUtf8(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 into a UTF-8 string.static voidLogs an error or debugging message.static voidlog(@Nullable String logDomain, LogLevelFlags logLevel, String format, Object... varargs) Logs an error or debugging message.static voidlogDefaultHandler(@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 voidlogDefaultHandler(@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 booleanReturn whether debug output from the GLib logging system is enabled.static voidlogRemoveHandler(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 voidlogSetDebugEnabled(boolean enabled) Enable or disable debug output from the GLib logging system for all domains.static LogFunclogSetDefaultHandler(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 intlogSetHandler(@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 intlogSetHandler(@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 voidSet a writer function which will be called to format and write out each log message.static voidlogStructured(String logDomain, Set<LogLevelFlags> logLevel, Object... varargs) Log a message with structured data.static voidlogStructured(String logDomain, LogLevelFlags logLevel, Object... varargs) Log a message with structured data.static voidlogStructuredArray(Set<LogLevelFlags> logLevel, LogField[] fields) Log a message with structured data.static voidlogStructuredArray(LogLevelFlags logLevel, LogField[] fields) Log a message with structured data.static voidlogStructuredStandard(String logDomain, Set<LogLevelFlags> logLevel, String file, String line, String func, String messageFormat, Object... varargs) static voidlogStructuredStandard(String logDomain, LogLevelFlags logLevel, String file, String line, String func, String messageFormat, Object... varargs) static voidlogVariant(@Nullable String logDomain, Set<LogLevelFlags> logLevel, Variant fields) Log a message with structured data, accepting the data within aGLib.Variant.static voidlogVariant(@Nullable String logDomain, LogLevelFlags logLevel, Variant fields) Log a message with structured data, accepting the data within aGLib.Variant.static LogWriterOutputlogWriterDefault(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 LogWriterOutputlogWriterDefault(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and output it to the default log destination for the platform.static voidlogWriterDefaultSetDebugDomains(@Nullable String domains) Reset the list of domains to be logged, that might be initially set by theG_MESSAGES_DEBUGorDEBUG_INVOCATIONenvironment variables.static voidlogWriterDefaultSetUseStderr(boolean useStderr) Configure whether the built-in log functions will output all log messages tostderr.static booleanlogWriterDefaultWouldDrop(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 booleanlogWriterDefaultWouldDrop(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 StringlogWriterFormatFields(Set<LogLevelFlags> logLevel, LogField[] fields, boolean useColor) Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).static StringlogWriterFormatFields(LogLevelFlags logLevel, LogField[] fields, boolean useColor) Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).static booleanlogWriterIsJournald(int outputFd) Check whether the givenoutputFdfile descriptor is a connection to the systemd journal, or something else (like a log file orstdoutorstderr).static LogWriterOutputlogWriterJournald(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 LogWriterOutputlogWriterJournald(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 LogWriterOutputlogWriterStandardStreams(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdoutorstderr, depending on its log level.static LogWriterOutputlogWriterStandardStreams(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdoutorstderr, depending on its log level.static booleanlogWriterSupportsColor(int outputFd) Check whether the givenoutputFdfile descriptor supports ANSI color escape sequences.static LogWriterOutputlogWriterSyslog(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and send it to the syslog daemon.static LogWriterOutputlogWriterSyslog(LogLevelFlags logLevel, LogField[] fields, @Nullable MemorySegment userData) Format a structured log message and send it to the syslog daemon.static intA wrapper for the POSIX lstat() function.static SourceReturns the currently firing source for this thread.static intReturns the depth of the stack of calls toMainContext.dispatch()on anyGMainContextin the current thread.static MemorySegmentmalloc(long nBytes) AllocatesnBytesbytes of memory.static MemorySegmentmalloc0(long nBytes) AllocatesnBytesbytes of memory, initialized to 0's.static MemorySegmentmalloc0N(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 MemorySegmentmallocN(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 booleanmarkupCollectAttributes(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 theGMarkupParserstart_element function, dealing with common error conditions and supporting boolean values.static booleanmarkupCollectAttributes(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 theGMarkupParserstart_element function, dealing with common error conditions and supporting boolean values.static Quarkstatic StringmarkupEscapeText(String text, long length) Escapes text so that the markup parser will parse it verbatim.static StringmarkupPrintfEscaped(String format, Object... varargs) Formats arguments according toformat, escaping all string and character arguments in the fashion of g_markup_escape_text().static MemorySegmentmemdup(@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→guintconversionstatic MemorySegmentmemdup2(@Nullable MemorySegment mem, long byteSize) AllocatesbyteSizebytes of memory, and copiesbyteSizebytes into it frommem.static booleanDeprecated.GLib always uses the system malloc, so this function always returnstrue.static voidDeprecated.Use other memory profiling tools insteadstatic voidmemSetVtable(MemVTable vtable) Deprecated.This function now does nothing.static intA wrapper for the POSIX mkdir() function.static intmkdirWithParents(String pathname, int mode) Create a directory if it doesn't already exist.static StringCreates a temporary directory in the current directory.static StringmkdtempFull(String tmpl, int mode) Creates a temporary directory in the current directory.static intOpens a temporary file in the current directory.static intmkstempFull(String tmpl, int flags, int mode) Opens a temporary file in the current directory.static voidnullifyPointer(MemorySegment nullifyLocation) Set the pointer at the specified location tonull.static Quarkstatic voidonErrorQuery(String prgName) Prompts the user with[E]xit, [H]alt, show [S]tack trace or [P]roceed.static voidonErrorStackTrace(@Nullable String prgName) Invokes gdb, which attaches to the current process and shows a stack trace.static intA wrapper for the POSIX open() function.static Quarkstatic intparseDebugString(@Nullable String string, DebugKey[] keys) Parses a string containing debugging options into aguintcontaining bit flags.static StringpathGetBasename(String fileName) Gets the last component of the filename.static StringpathGetDirname(String fileName) Gets the directory components of a file name.static booleanpathIsAbsolute(String fileName) Returnstrueif the givenfileNameis an absolute file name.static StringpathSkipRoot(String fileName) Returns a pointer intofileNameafter the root component, i.e.static booleanpatternMatch(PatternSpec pspec, int stringLength, String string, @Nullable String stringReversed) Deprecated.static booleanpatternMatchSimple(String pattern, String string) Matches a string against a pattern given as a string.static booleanpatternMatchString(PatternSpec pspec, String string) Deprecated.UsePatternSpec.matchString(java.lang.String)insteadstatic voidpointerBitLock(MemorySegment address, int lockBit) This is equivalent to g_bit_lock, but working on pointers (or other pointer-sized values).static voidpointerBitLockAndGet(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 MemorySegmentpointerBitLockMaskPtr(@Nullable MemorySegment ptr, int lockBit, boolean set, long preserveMask, @Nullable MemorySegment preservePtr) This manglesptras g_pointer_bit_lock() and g_pointer_bit_unlock() do.static booleanpointerBitTrylock(MemorySegment address, int lockBit) This is equivalent to g_bit_trylock(), but working on pointers (or other pointer-sized values).static voidpointerBitUnlock(MemorySegment address, int lockBit) This is equivalent to g_bit_unlock, but working on pointers (or other pointer-sized values).static voidpointerBitUnlockAndSet(MemorySegment address, int lockBit, @Nullable MemorySegment ptr, long preserveMask) This is equivalent to g_pointer_bit_unlock() and atomically setting the pointer value.static intPollsfds, as with the poll() system call, but portably.static voidprefixError(@Nullable Out<GError> err, String format, Object... varargs) Formats a string according toformatand prefix it to an existing error message.static voidprefixErrorLiteral(@Nullable Out<GError> err, String prefix) Prefixesprefixto an existing error message.static voidOutputs a formatted message via the print handler.static voidOutputs a formatted message via the error message handler.static intAn implementation of the standardprintf()function which supports positional parameters, as specified in the Single Unix Specification.static voidpropagateError(@Nullable Out<GError> dest, GError src) Ifdestisnull, freesrc; otherwise, movessrcinto*dest.static voidpropagatePrefixedError(GError[] dest, GError src, String format, Object... varargs) Ifdestisnull, freesrc; otherwise, movessrcinto*dest.static voidqsortWithData(MemorySegment pbase, int totalElems, long size, CompareDataFunc compareFunc) Deprecated.total_elemsis too small to represent larger arrays; usesortArray(java.lang.foreign.MemorySegment[], long, org.gnome.glib.CompareDataFunc)insteadstatic QuarkquarkFromStaticString(@Nullable String string) Gets theGQuarkidentifying the given (static) string.static QuarkquarkFromString(@Nullable String string) Gets theGQuarkidentifying the given string.static StringquarkToString(Quark quark) Gets the string associated with the givenGQuark.static QuarkquarkTryString(@Nullable String string) Gets theGQuarkassociated with the given string, or 0 if string isnullor it has no associatedGQuark.static doubleReturns a randomgdoubleequally distributed over the range [0..1).static doublerandomDoubleRange(double begin, double end) Returns a randomgdoubleequally distributed over the range [begin..end).static intReturn a randomguint32equally distributed over the range [0..2^32-1].static intrandomIntRange(int begin, int end) Returns a randomgint32equally distributed over the rangeend-1.static voidrandomSetSeed(int seed) Sets the seed for the global random number generator, which is used by the g_random_* functions, toseed.static MemorySegmentrcBoxAcquire(MemorySegment memBlock) Acquires a reference on the data pointed bymemBlock.static MemorySegmentrcBoxAlloc(long blockSize) AllocatesblockSizebytes of memory, and adds reference counting semantics to it.static MemorySegmentrcBoxAlloc0(long blockSize) AllocatesblockSizebytes of memory, and adds reference counting semantics to it.static MemorySegmentrcBoxDup(long blockSize, MemorySegment memBlock) Allocates a new block of data with reference counting semantics, and copiesblockSizebytes ofmemBlockinto it.static longrcBoxGetSize(MemorySegment memBlock) Retrieves the size of the reference counted data pointed bymemBlock.static voidrcBoxRelease(MemorySegment memBlock) Releases a reference on the data pointed bymemBlock.static voidrcBoxReleaseFull(MemorySegment memBlock) Releases a reference on the data pointed bymemBlock.static MemorySegmentrealloc(@Nullable MemorySegment mem, long nBytes) Reallocates the memory pointed to bymem, so that it now has space fornBytesbytes of memory.static MemorySegmentreallocN(@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 booleanrefCountCompare(MemorySegment rc, int val) Compares the current value ofrcwithval.static booleanDecreases the reference count.static voidIncreases the reference count.static voidInitializes a reference count variable to 1.static StringrefStringAcquire(String str) Acquires a reference on a string.static booleanrefStringEqual(String str1, String str2) Compares two ref-counted strings for byte-by-byte equality.static longrefStringLength(String str) Retrieves the length ofstr.static StringrefStringNew(String str) Creates a new reference counted string and copies the contents ofstrinto it.static StringrefStringNewIntern(String str) Creates a new reference counted string and copies the content ofstrinto it.static StringrefStringNewLen(String str, long len) Creates a new reference counted string and copies the contents ofstrinto it, up tolenbytes.static voidrefStringRelease(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 voidResets the cache used for g_get_user_special_dir(), so that the latest on-disk version is used.static intA wrapper for the POSIX remove() function.static intA wrapper for the POSIX rename() function.static voidreturnIfFailWarning(@Nullable String logDomain, String prettyFunction, @Nullable String expression) Internal function used to print messages from the publicGLib#returnIfFailandGLib#returnValIfFailmacros.static intA wrapper for the POSIX rmdir() function.static voidsetApplicationName(String applicationName) Sets a human-readable name for the application.static booleanSets an environment variable.static voidDoes nothing iferrisnull; iferris non-null, then*errmust benull.static voidsetErrorLiteral(@Nullable Out<GError> err, Quark domain, int code, String message) Does nothing iferrisnull; iferris non-null, then*errmust benull.static voidsetPrgname(String prgname) Sets the name of the program.static PrintFuncsetPrinterrHandler(@Nullable PrintFunc func) Sets the handler for printing error messages tofunc, or resets it to the default GLib handler ifNULL.static PrintFuncsetPrintHandler(@Nullable PrintFunc func) Sets the print handler tofunc, or resets it to the default GLib handler ifNULL.static Quarkstatic booleanshellParseArgv(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 StringshellQuote(String unquotedString) Quotes a string so that the shell (/bin/sh) will interpret the quoted string to meanunquotedString.static StringshellUnquote(String quotedString) Unquotes a string as the shell (/bin/sh) would.static MemorySegmentsliceAlloc(long blockSize) Allocates a block of memory from the libc allocator.static MemorySegmentsliceAlloc0(long blockSize) Allocates a block of memory via g_slice_alloc() and initializes the returned memory to 0.static MemorySegmentsliceCopy(long blockSize, @Nullable MemorySegment memBlock) Allocates a block of memory from the slice allocator and copiesblockSizebytes into it frommemBlock.static voidsliceFree1(long blockSize, @Nullable MemorySegment memBlock) Frees a block of memory.static voidsliceFreeChainWithOffset(long blockSize, @Nullable MemorySegment memChain, long nextOffset) Frees a linked list of memory blocks of structure typetype.static longsliceGetConfig(SliceConfig ckey) static MemorySegmentsliceGetConfigState(SliceConfig ckey, long address, MemorySegment nValues) static voidsliceSetConfig(SliceConfig ckey, long value) static intA safer form of the standard sprintf() function.static voidsortArray(MemorySegment[] array, long elementSize, CompareDataFunc compareFunc) static intspacedPrimesClosest(int num) Gets the smallest prime number from a built-in array of primes which is larger thannum.static booleanspawnAsync(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid) Executes a child program asynchronously.static booleanspawnAsync(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Pid childPid) Executes a child program asynchronously.static booleanspawnAsyncWithFds(@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 booleanspawnAsyncWithFds(@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 booleanspawnAsyncWithPipes(@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_fdsset to zero, so no FD assignments are used.static booleanspawnAsyncWithPipes(@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_fdsset to zero, so no FD assignments are used.static booleanspawnAsyncWithPipesAndFds(@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 booleanspawnAsyncWithPipesAndFds(@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 booleanspawnCheckExitStatus(int waitStatus) Deprecated.Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.static booleanspawnCheckWaitStatus(int waitStatus) SeterrorifwaitStatusindicates the child exited abnormally (e.g.static voidspawnClosePid(Pid pid) On some platforms, notably Windows, theGPidtype represents a resource which must be closed to prevent resource leaking.static booleanspawnCommandLineAsync(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 booleanspawnCommandLineSync(String commandLine, @Nullable Out<byte[]> standardOutput, @Nullable Out<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 Quarkstatic Quarkstatic booleanspawnSync(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, Set<SpawnFlags> flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Out<byte[]> standardOutput, @Nullable Out<byte[]> standardError, @Nullable Out<Integer> waitStatus) Executes a child synchronously (waits for the child to exit before returning).static booleanspawnSync(@Nullable String workingDirectory, String[] argv, @Nullable String[] envp, SpawnFlags flags, @Nullable SpawnChildSetupFunc childSetup, @Nullable Out<byte[]> standardOutput, @Nullable Out<byte[]> standardError, @Nullable Out<Integer> waitStatus) Executes a child synchronously (waits for the child to exit before returning).static intAn implementation of the standardsprintf()function which supports positional parameters, as specified in the Single Unix Specification.static intA wrapper for the POSIX stat() function.static StringCopies a nul-terminated string into the destination buffer, including the trailing nul byte, and returns a pointer to the trailing nul byte indest.static StringFor each character instring, if the character is not invalidChars, replaces the character withsubstitutor.static intstrcasecmp(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 StringRemoves trailing whitespace from a string.static StringRemoves leading whitespace from a string, by moving the rest of the characters forward.static intComparesstr1andstr2likestrcmp().static Stringstrcompress(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 StringConcatenates all of the given strings into one long string.static Stringstrdelimit(String string, @Nullable String delimiters, byte newDelimiter) Converts any delimiter characters instringtonewDelimiter.static StringDeprecated.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 StringDuplicates a string.static StringstrdupPrintf(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 booleanstrEqual(MemorySegment v1, MemorySegment v2) Compares two strings for byte-by-byte equality and returnstrueif they are equal.static Stringstrerror(int errnum) Returns a string corresponding to the given error code, e.g.static StringIt replaces the following special characters in the stringsourcewith their corresponding C escape sequence:static voidstrfreev(@Nullable MemorySegment strArray) Frees an array of strings, as well as each string it contains.static intConverts a string to a hash value.static booleanstrHasPrefix(String str, String prefix) Looks whether the stringstrbegins withprefix.static booleanstrHasSuffix(String str, String suffix) Looks whether a string ends withsuffix.static StringstripContext(String msgid, String msgval) An auxiliary function for gettext() support (see Q_()).static booleanstrIsAscii(String str) Determines if a string is pure ASCII.static StringJoins a number of strings together to form one long string, with the optionalseparatorinserted between each of them.static StringJoins an array of strings together to form one long string, with the optionalseparatorinserted between each of them.static longPortability wrapper that callsstrlcat()on systems which have it, and emulates it otherwise.static longPortability wrapper that callsstrlcpy()on systems which have it, and emulatesstrlcpy()otherwise.static booleanstrMatchString(String searchTerm, String potentialHit, boolean acceptAlternates) Checks if a search conducted forsearchTermshould matchpotentialHit.static intstrncasecmp(String s1, String s2, int n) Deprecated.The problem withg_strncasecmp()is that it does the comparison by callingtoupper()/tolower().static StringDuplicates the firstnbytes of a string, returning a newly-allocated buffern+ 1 bytes long which will always be nul-terminated.static Stringstrnfill(long length, byte fillChar) Creates a new stringlengthbytes long filled withfillChar.static Stringstrreverse(String string) Reverses all of the bytes in a string.static StringSearches the stringhaystackfor the last occurrence of the stringneedle.static StringstrrstrLen(String haystack, long haystackLen, String needle) Searches the stringhaystackfor the last occurrence of the stringneedle, limiting the length of the search tohaystackLen.static Stringstrsignal(int signum) Returns a string describing the given signal, e.g.static String[]Splits a string into a maximum ofmaxTokenspieces, using the givendelimiter.static String[]strsplitSet(String string, String delimiters, int maxTokens) Splitsstringinto a number of tokens not containing any of the characters indelimiters.static StringSearches the stringhaystackfor the first occurrence of the stringneedle, limiting the length of the search tohaystackLenor a nul terminator byte (whichever is reached first).static StringstrToAscii(String str, @Nullable String fromLocale) Transliteratestrto plain ASCII.static doubleConverts a string to a floating point value.static String[]strTokenizeAndFold(String string, @Nullable String translitLocale, @Nullable Out<String[]> asciiAlternates) Tokenizesstringand performs folding on each token.static StringDeprecated.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 booleanstrvContains(String[] strv, String str) Checks if an array of strings contains the stringstraccording tostrEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment).static booleanChecks if two arrays of strings contain exactly the same elements in exactly the same order.static Typestatic intstrvLength(String[] strArray) Returns the length of an array of strings.static voidtestAddDataFunc(String testpath, @Nullable MemorySegment testData, TestDataFunc testFunc) Creates a new test case.static voidtestAddDataFuncFull(String testpath, @Nullable MemorySegment testData, TestDataFunc testFunc) Creates a new test case.static voidtestAddFunc(String testpath, TestFunc testFunc) Creates a new test case.static voidtestAddVtable(String testpath, long dataSize, @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) static voidtestAssertExpectedMessagesInternal(String domain, String file, int line, String func) static voidAdds a message to test reports that associates a bug URI with a test case.static voidtestBugBase(String uriPattern) Specifies the base URI for bug reports.static StringtestBuildFilename(TestFileType fileType, String firstPath, Object... varargs) Creates the pathname to a data file that is required for a test.static TestCasetestCreateCase(String testName, long dataSize, @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) Creates a newGLib.TestCase.static TestSuitetestCreateSuite(String suiteName) Creates a new test suite with the namesuiteName.static voidAttempts to disable system crash reporting infrastructure.static voidtestExpectMessage(@Nullable String logDomain, Set<LogLevelFlags> logLevel, String pattern) Indicates that a message with the givenlogDomainandlogLevel, with text matchingpattern, is expected to be logged.static voidtestExpectMessage(@Nullable String logDomain, LogLevelFlags logLevel, String pattern) Indicates that a message with the givenlogDomainandlogLevel, with text matchingpattern, is expected to be logged.static voidtestFail()Indicates that a test failed.static booleanReturns whether a test has already failed.static voidtestFailPrintf(String format, Object... varargs) Indicates that a test failed and records a message.static StringtestGetDir(TestFileType fileType) Gets the pathname of the directory containing test files of the type specified byfileType.static StringtestGetFilename(TestFileType fileType, String firstPath, Object... varargs) Gets the pathname to a data file that is required for a test.static StringGets the test path for the test currently being run.static TestSuiteGets the toplevel test suite for the test path API.static voidtestIncomplete(@Nullable String msg) Indicates that a test failed because of some incomplete functionality.static voidtestIncompletePrintf(String format, Object... varargs) Indicates that a test failed because of some incomplete functionality.static voidtestInit(MemorySegment argc, String[] argv, Object... varargs) Initializes the GLib testing framework.static voidtestLogSetFatalHandler(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 StringtestLogTypeName(TestLogType logType) static voidtestMaximizedResult(double maximizedQuantity, String format, Object... varargs) Reports the result of a performance or measurement test.static voidtestMessage(String format, Object... varargs) Adds a message to the test report.static voidtestMinimizedResult(double minimizedQuantity, String format, Object... varargs) Reports the result of a performance or measurement test.static voidtestQueueDestroy(@Nullable MemorySegment destroyData) Enqueues a callbackdestroyFuncto be executed during the next test case teardown phase.static voidtestQueueFree(@Nullable MemorySegment gfreePointer) Enqueues a pointer to be released withfree(java.lang.foreign.MemorySegment)during the next teardown phase.static doubleGets a reproducible random floating point number.static doubletestRandDoubleRange(double rangeStart, double rangeEnd) Gets a reproducible random floating point number out of a specified range.static intGets a reproducible random integer number.static inttestRandIntRange(int begin, int end) Gets a reproducible random integer number out of a specified range.static inttestRun()Runs all tests under the toplevel suite.static inttestRunSuite(TestSuite suite) Executes the tests withinsuiteand all nested test suites.static voidChanges the behaviour of the various assertion macros.static voidIndicates that a test was skipped.static voidtestSkipPrintf(String format, Object... varargs) Indicates that a test was skipped.static booleanReturns true if the test program is running undertestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>).static voidtestSummary(String summary) Sets the summary for a test.static doubleGets the number of seconds since the last start of the timer withtestTimerStart().static doubleReports the last result oftestTimerElapsed().static voidStarts a timing test.static voidtestTrapAssertions(String domain, String file, int line, String func, long assertionFlags, String pattern) static booleantestTrapFork(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 booleantestTrapFork(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 booleanChecks the result of the lasttestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)call.static booleanChecks the result of the lasttestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)call.static voidtestTrapSubprocess(@Nullable String testPath, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPathin a subprocess.static voidtestTrapSubprocess(@Nullable String testPath, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPathin a subprocess.static voidtestTrapSubprocessWithEnvp(@Nullable String testPath, @Nullable String[] envp, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPathin a subprocess with a given environment.static voidtestTrapSubprocessWithEnvp(@Nullable String testPath, @Nullable String[] envp, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPathin a subprocess with a given environment.static inttimeoutAdd(int priority, int interval, SourceFunc function) Sets a function to be called at regular intervals, with the given priority.static inttimeoutAddOnce(int interval, SourceOnceFunc function) Sets a function to be called afterintervalmilliseconds have elapsed, with the default priority,GLib.PRIORITY_DEFAULT.static inttimeoutAddSeconds(int priority, int interval, SourceFunc function) Sets a function to be called at regular intervals, withpriority.static inttimeoutAddSecondsOnce(int interval, SourceOnceFunc function) This function behaves liketimeoutAddOnce(int, org.gnome.glib.SourceOnceFunc)but with a range in seconds.static SourcetimeoutSourceNew(int interval) Creates a new timeout source.static SourcetimeoutSourceNewSeconds(int interval) Creates a new timeout source.static MemorySegmenttryMalloc(long nBytes) Attempts to allocatenBytes, and returnsnullon failure.static MemorySegmenttryMalloc0(long nBytes) Attempts to allocatenBytes, initialized to 0's, and returnsnullon failure.static MemorySegmenttryMalloc0N(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 MemorySegmenttryMallocN(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 MemorySegmenttryRealloc(@Nullable MemorySegment mem, long nBytes) Attempts to reallocmemto a new size,nBytes, and returnsnullon failure.static MemorySegmenttryReallocN(@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 MemorySegmentucs4ToUtf16(int[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UCS-4 to UTF-16.static Stringucs4ToUtf8(int[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from a 32-bit fixed width representation as UCS-4.static UnicodeBreakTypeunicharBreakType(int c) Determines the break type ofc.static intunicharCombiningClass(int uc) Determines the canonical combining class of a Unicode character.static booleanunicharCompose(int a, int b, Out<Integer> ch) Performs a single composition step of the Unicode canonical composition algorithm.static booleanunicharDecompose(int ch, Out<Integer> a, Out<Integer> b) Performs a single decomposition step of the Unicode canonical decomposition algorithm.static intunicharDigitValue(int c) Determines the numeric value of a character as a decimal digit.static longunicharFullyDecompose(int ch, boolean compat, @Nullable Out<Integer> result, long resultLen) Computes the canonical or compatibility decomposition of a Unicode character.static booleanunicharGetMirrorChar(int ch, Out<Integer> mirroredCh) In Unicode, some characters are "mirrored".static UnicodeScriptunicharGetScript(int ch) Looks up theGUnicodeScriptfor a particular character (as defined by Unicode Standard Annex \\24).static booleanunicharIsalnum(int c) Determines whether a character is alphanumeric.static booleanunicharIsalpha(int c) Determines whether a character is alphabetic (i.e.static booleanunicharIscntrl(int c) Determines whether a character is a control character.static booleanunicharIsdefined(int c) Determines if a given character is assigned in the Unicode standard.static booleanunicharIsdigit(int c) Determines whether a character is numeric (i.e.static booleanunicharIsgraph(int c) Determines whether a character is printable and not a space (returnsfalsefor control characters, format characters, and spaces).static booleanunicharIslower(int c) Determines whether a character is a lowercase letter.static booleanunicharIsmark(int c) Determines whether a character is a mark (non-spacing mark, combining mark, or enclosing mark in Unicode speak).static booleanunicharIsprint(int c) Determines whether a character is printable.static booleanunicharIspunct(int c) Determines whether a character is punctuation or a symbol.static booleanunicharIsspace(int c) Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.).static booleanunicharIstitle(int c) Determines if a character is titlecase.static booleanunicharIsupper(int c) Determines if a character is uppercase.static booleanunicharIswide(int c) Determines if a character is typically rendered in a double-width cell.static booleanunicharIswideCjk(int c) Determines if a character is typically rendered in a double-width cell under legacy East Asian locales.static booleanunicharIsxdigit(int c) Determines if a character is a hexadecimal digit.static booleanunicharIszerowidth(int c) Determines if a given character typically takes zero width when rendered.static intunicharTolower(int c) Converts a character to lower case.static intunicharTotitle(int c) Converts a character to the titlecase.static intunicharToupper(int c) Converts a character to uppercase.static intunicharToUtf8(int c, @Nullable Out<String> outbuf) Converts a single character to UTF-8.static UnicodeTypeunicharType(int c) Classifies a Unicode character by type.static booleanunicharValidate(int ch) Checks whetherchis a valid Unicode character.static intunicharXdigitValue(int c) Determines the numeric value of a character as a hexadecimal digit.static MemorySegmentunicodeCanonicalDecomposition(int ch, MemorySegment resultLen) Deprecated.Use the more flexible g_unichar_fully_decompose() instead.static voidunicodeCanonicalOrdering(int[] string) Computes the canonical ordering of a string in-place.static Quarkstatic intunixFdAdd(int fd, Set<IOCondition> condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified byconditionbecomes true forfd.static intunixFdAdd(int fd, IOCondition condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified byconditionbecomes true forfd.static intunixFdAddFull(int priority, int fd, Set<IOCondition> condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified byconditionbecomes true forfd.static intunixFdAddFull(int priority, int fd, IOCondition condition, UnixFDSourceFunc function) Sets a function to be called when the IO condition, as specified byconditionbecomes true forfd.static SourceunixFdSourceNew(int fd, Set<IOCondition> condition) Creates aGSourceto watch for a particular I/O condition on a file descriptor.static SourceunixFdSourceNew(int fd, IOCondition... condition) Creates aGSourceto watch for a particular I/O condition on a file descriptor.static MemorySegmentunixGetPasswdEntry(String userName) Get thepasswdfile entry for the givenuserNameusinggetpwnam_r().static booleanunixOpenPipe(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 booleanunixSetFdNonblocking(int fd, boolean nonblock) Control the non-blocking state of the given file descriptor, according tononblock.static intunixSignalAdd(int priority, int signum, SourceFunc handler) A convenience function for g_unix_signal_source_new(), which attaches to the defaultGMainContext.static SourceunixSignalSourceNew(int signum) Create aGSourcethat will be dispatched upon delivery of the UNIX signalsignum.static intA wrapper for the POSIX unlink() function.static voidRemoves an environment variable from the environment.static voidusleep(int microseconds) Pauses the current thread for the given number of microseconds.static MemorySegmentutf16ToUcs4(short[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-16 to UCS-4.static Stringutf16ToUtf8(short[] str, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-16 to UTF-8.static Stringutf8Casefold(String str, long len) Converts a string into a form that is independent of case.static intutf8Collate(String str1, String str2) Compares two strings for ordering using the linguistically correct rules for the current locale.static Stringutf8CollateKey(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 Stringutf8CollateKeyForFilename(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 Stringutf8FindNextChar(String p, @Nullable String end) Finds the start of the next UTF-8 character in the string afterp.static Stringutf8FindPrevChar(String str, String p) Given a positionpwith a UTF-8 encoded stringstr, find the start of the previous UTF-8 character starting beforep.static intConverts a sequence of bytes encoded as UTF-8 to a Unicode character.static intutf8GetCharValidated(String p, long maxLen) Convert a sequence of bytes encoded as UTF-8 to a Unicode character.static Stringutf8MakeValid(String str, long len) If the provided string is valid UTF-8, return a copy of it.static Stringutf8Normalize(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 Stringutf8OffsetToPointer(String str, int offset) Converts from an integer character offset to a pointer to a position within the string.static intutf8PointerToOffset(String str, String pos) Converts from a pointer to position within a string to an integer character offset.static StringFinds the previous UTF-8 character in the string beforep.static Stringutf8Strchr(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 tolenbytes.static Stringutf8Strdown(String str, long len) Converts all Unicode characters in the string that have a case to lowercase.static intutf8Strlen(String p, long max) Computes the length of the string in characters, not including the terminating nul character.static Stringutf8Strncpy(String dest, String src, long n) Like the standard Cstrncpy()function, but copies a given number of characters instead of a given number of bytes.static Stringutf8Strrchr(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 tolenbytes.static Stringutf8Strreverse(String str, long len) Reverses a UTF-8 string.static StringConverts all Unicode characters in the string that have a case to uppercase.static Stringutf8Substring(String str, int startPos, int endPos) Copies a substring out of a UTF-8 encoded string.static MemorySegmentutf8ToUcs4(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 MemorySegmentutf8ToUcs4Fast(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 MemorySegmentutf8ToUtf16(String str, int len, @Nullable Out<Integer> itemsRead, @Nullable Out<Integer> itemsWritten) Convert a string from UTF-8 to UTF-16.static Stringutf8TruncateMiddle(String string, long truncateLength) Cuts off the middle of the string, preserving half oftruncateLengthcharacters at the beginning and half at the end.static booleanutf8Validate(byte[] str, @Nullable Out<String> end) Validates UTF-8 encoded text.static booleanutf8ValidateLen(byte[] str, @Nullable Out<String> end) Validates UTF-8 encoded text.static intutime(String filename, @Nullable MemorySegment utb) A wrapper for the POSIX utime() function.static booleanuuidStringIsValid(String str) Parses the stringstrand verify if it is a UUID.static StringGenerates a random UUID (RFC 4122 version 4) as a string.static Typestatic voidwarnMessage(@Nullable String domain, String file, int line, String func, @Nullable String warnexpr) Internal function used to print messages from the publicGLib#warnIfReachedandGLib#warnIfFailmacros.static booleanwin32CheckWindowsVersion(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 Stringwin32ErrorMessage(int error) Translate a Win32 error code (as returned by GetLastError() or WSAGetLastError()) into the corresponding message.static intwin32Ftruncate(int f, int size) static String[]Gets the command line arguments, on Windows, in the GLib filename encoding (ie: UTF-8).static StringThe setlocale() function in the Microsoft C library uses locale names of the form "English_United States.1252" etc.static Stringwin32GetPackageInstallationDirectory(@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 Stringwin32GetPackageInstallationDirectoryOfModule(@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 Stringwin32GetPackageInstallationSubdirectory(@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 intDeprecated.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 Stringwin32LocaleFilenameFromUtf8(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
gatomicrefcountfields inside structures, for instance:typedef struct { gatomicrefcount ref_count; char *name; char *address; } Person; static const Person default_person = { .ref_count = G_ATOMIC_REF_COUNT_INIT, .name = "Default name", .address = "Default address", };- Since:
- 2.78
- See Also:
-
BIG_ENDIAN
public static final int BIG_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_VERSIONandG_CXX_STD_VERSION- Since:
- 2.76
- 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
Deprecated.Use G_STRFUNC() insteadExpands to "" on all modern compilers, and to __FUNCTION__ on gcc version 2.x. Don't use it.- See Also:
-
GNUC_PRETTY_FUNCTION
Deprecated.Use G_STRFUNC() insteadExpands 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 theGHookimplementation, i.e.1 << G_HOOK_FLAG_USER_SHIFTis 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.
- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_ACTIONS
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string list giving the available application actions.- Since:
- 2.38
- See Also:
-
KEY_FILE_DESKTOP_KEY_CATEGORIES
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the categories in which the desktop entry should be shown in a menu.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_COMMENT
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the tooltip for the desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean set to true if the application is D-Bus activatable.- Since:
- 2.38
- See Also:
-
KEY_FILE_DESKTOP_KEY_EXEC
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the command line to execute.It is only valid for desktop entries with the
Applicationtype.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_GENERIC_NAME
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the generic name of the desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_HIDDEN
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry has been deleted by the user.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_ICON
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the name of the icon to be displayed for the desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_MIME_TYPE
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the MIME types supported by this desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_NAME
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the specific name of the desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should not display the desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_NO_DISPLAY
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry should be shown in menus.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should display the desktop entry.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_PATH
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string containing the working directory to run the program in.It is only valid for desktop entries with the
Applicationtype.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is string identifying the WM class or name hint of a window that the application will create, which can be used to emulate Startup Notification with older applications.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_TERMINAL
A key underGLib.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
Applicationtype.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_TRY_EXEC
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the file name of a binary on disk used to determine if the program is actually installed.It is only valid for desktop entries with the
Applicationtype.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_TYPE
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the type of the desktop entry.Usually
GLib.KEY_FILE_DESKTOP_TYPE_APPLICATION,GLib.KEY_FILE_DESKTOP_TYPE_LINK, orGLib.KEY_FILE_DESKTOP_TYPE_DIRECTORY.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_URL
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the URL to access.It is only valid for desktop entries with the
Linktype.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_KEY_VERSION
A key underGLib.KEY_FILE_DESKTOP_GROUP, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_TYPE_APPLICATION
The value of theGLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing applications.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_TYPE_DIRECTORY
The value of theGLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing directories.- Since:
- 2.14
- See Also:
-
KEY_FILE_DESKTOP_TYPE_LINK
The value of theGLib.KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing links to documents.- Since:
- 2.14
- 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,
bloatpadorbloatpad-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_DEBUGenvironment 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_SHIFTare 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.- Since:
- 2.4
- See Also:
-
MININT32
public static final int MININT32The minimum value which can be held in agint32.- Since:
- 2.4
- 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.- Since:
- 2.4
- 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_ARRAYorOptionArg.FILENAME_ARRAY.Using
G_OPTION_REMAININGinstead of simply scanningargvfor leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.- Since:
- 2.6
- See Also:
-
PDP_ENDIAN
public static final int PDP_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.- Since:
- 2.50
- 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 thefdmember 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
grefcountfields inside structures, for instance:typedef struct { grefcount ref_count; char *name; char *address; } Person; static const Person default_person = { .ref_count = G_REF_COUNT_INIT, .name = "Default name", .address = "Default address", };- Since:
- 2.78
- See Also:
-
SEARCHPATH_SEPARATOR
public static final int SEARCHPATH_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.SourceFuncto leave theGLib.Sourcein the main loop.- Since:
- 2.32
- See Also:
-
SOURCE_REMOVE
public static final boolean SOURCE_REMOVEUse this macro as the return value of aGLib.SourceFuncto remove theGLib.Sourcefrom the main loop.- Since:
- 2.32
- 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
A value that can be passed as an option totestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).Creates a unique temporary directory for each unit test and uses sets XDG directories to point into subdirectories of it for the duration of the unit test. The directory tree is cleaned up after the test finishes successfully.
Note that this doesn’t take effect until
testRun()is called, so calls to (for example)getHomeDir()will return the system-wide value when made in a test program’s main() function.The following functions will return subdirectories of the temporary directory when this option is used. The specific subdirectory paths in use are not guaranteed to be stable API — always use a getter function to retrieve them.
getHomeDir()getUserCacheDir()getSystemConfigDirs()getUserConfigDir()getSystemDataDirs()getUserDataDir()getUserStateDir()getUserRuntimeDir()
The subdirectories may not be created by the test harness; as with normal calls to functions like
getUserCacheDir(), the caller must be prepared to create the directory if it doesn’t exist.- Since:
- 2.60
- See Also:
-
TEST_OPTION_NONFATAL_ASSERTIONS
A value that can be passed as an option totestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).If this option is given, assertions will not abort the process, but call
testFail(). Equivalent totestSetNonfatalAssertions().- Since:
- 2.84
- See Also:
-
TEST_OPTION_NO_PRGNAME
A value that can be passed as an option totestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).If this option is given,
testInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...)will not callsetPrgname(java.lang.String).- Since:
- 2.84
- See Also:
-
TIME_SPAN_DAY
public static final long TIME_SPAN_DAYEvaluates to a time span of one day.- Since:
- 2.26
- See Also:
-
TIME_SPAN_HOUR
public static final long TIME_SPAN_HOUREvaluates to a time span of one hour.- Since:
- 2.26
- See Also:
-
TIME_SPAN_MILLISECOND
public static final long TIME_SPAN_MILLISECONDEvaluates to a time span of one millisecond.- Since:
- 2.26
- See Also:
-
TIME_SPAN_MINUTE
public static final long TIME_SPAN_MINUTEEvaluates to a time span of one minute.- Since:
- 2.26
- See Also:
-
TIME_SPAN_SECOND
public static final long TIME_SPAN_SECONDEvaluates to a time span of one second.- Since:
- 2.26
- 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.
- Since:
- 2.32
- 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_REQUIREDor earlier will cause warnings (but using functions deprecated in later releases will not).- Since:
- 2.32
- See Also:
-
WIN32_MSG_HANDLE
public static final int WIN32_MSG_HANDLE- See Also:
-
macro__has_attribute___noreturn__
public static final int macro__has_attribute___noreturn__- See Also:
-
macro__has_attribute_ifunc
public static final int macro__has_attribute_ifunc- See Also:
-
macro__has_attribute_no_sanitize_address
public static final int macro__has_attribute_no_sanitize_address- See Also:
-
-
Constructor Details
-
GLib
public GLib()
-
-
Method Details
-
javagi$ensureInitialized
public static void javagi$ensureInitialized() -
access
A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.On Windows, the file protection mechanism is not at all POSIX-like, and the underlying function in the C library only checks the FAT-style READONLY attribute, and does not look at the ACL of a file at all. This function is this in practise almost useless on Windows. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.
See your C library manual for more details about access().
- Parameters:
filename- a pathname in the GLib file name encoding (UTF-8 on Windows)mode- as in access()- Returns:
- zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.
- Since:
- 2.8
-
alignedAlloc
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
- Since:
- 2.72
-
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
- Since:
- 2.72
-
alignedFree
Frees the memory allocated by g_aligned_alloc().- Parameters:
mem- the memory to deallocate- Since:
- 2.72
-
alignedFreeSized
public static void alignedFreeSized(@Nullable @Nullable MemorySegment mem, long alignment, long size) Frees the memory pointed to bymem, assuming it is has the givensizeandalignment.If
memisnullthis is a no-op (andsizeis ignored).It is an error if
sizedoesn’t match the size, oralignmentdoesn’t match the alignment, passed whenmemwas allocated.sizeandalignmentare 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 ofmemsize- size ofmem, in bytes- Since:
- 2.76
-
asciiDigitValue
public static int asciiDigitValue(byte c) Determines the numeric value of a character as a decimal digit. If the character is not a decimal digit according toGLib#asciiIsdigit,-1is 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
cif it is a decimal digit,-1otherwise
-
asciiDtostr
Converts agdoubleto a string, using the '.' as decimal point.This function generates enough precision that converting the string back using
asciiStrtod(java.lang.String, org.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_SIZEbytes, 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 agdoubleto 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
formatmust just be a single format specifier starting with%, expecting agdoubleargument.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
s1ands2must be non-NULL.- Parameters:
s1- string to compare withs2s2- 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 ofstrin bytes, or-1ifstris nul-terminated- Returns:
- a newly-allocated string, with all the upper case characters in
strconverted 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
strcontains only a number of the givenbasethat is within inclusive bounds limited byminandmax. 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.basecan 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_ERRORdomain. 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, org.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
strwas a number, false otherwise - Throws:
GErrorException- seeGError- Since:
- 2.54
-
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
strcontains only a number of the givenbasethat is within inclusive bounds limited byminandmax. 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.basecan 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_ERRORdomain. 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, org.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
strwas a number, false otherwise - Throws:
GErrorException- seeGError- Since:
- 2.54
-
asciiStrncasecmp
Compares1ands2, ignoring the case of ASCII characters and any characters after the firstnin each string. If either string is less thannbytes 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 withs2s2- string to compare withs1n- 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_VALis returned (according to the sign of the value), andERANGEis stored inerrno. If the correct value would cause underflow, zero is returned andERANGEis stored inerrno.This function resets
errnobefore 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 agint64value.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.MAXINT64orGLib.MININT64is returned, andERANGEis stored inerrno. If the base is outside the valid range, zero is returned, andEINVALis stored inerrno. If the string conversion fails, zero is returned, andendptrreturnsnptr(ifendptris 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
- Since:
- 2.12
-
asciiStrtoull
Converts a string to aguint64value.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.MAXUINT64is returned, andERANGEis stored inerrno. If the base is outside the valid range, zero is returned, andEINVALis stored inerrno. If the string conversion fails, zero is returned, andendptrreturnsnptr(ifendptris 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
- Since:
- 2.2
-
asciiStrup
Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly matchasciiToupper(byte).- Parameters:
str- a stringlen- length ofstrin bytes, or-1ifstris nul-terminated- Returns:
- a newly-allocated string, with all the lower case characters
in
strconverted 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 onEOFbut no need to worry about casting togucharbefore 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 onEOFbut no need to worry about casting togucharbefore 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,-1is 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
cif it is a hex digit,-1otherwise
-
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 addsvalto 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguintval- the value to add- Returns:
- the value of
atomicbefore the add, signed - Since:
- 2.4
-
atomicIntAnd
Performs an atomic bitwise 'and' of the value ofatomicandval, 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 invalid input: '&'= val; return tmp; }.While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguintval- the value to 'and'- Returns:
- the value of
atomicbefore the operation, unsigned - Since:
- 2.30
-
atomicIntCompareAndExchange
Comparesatomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguintoldval- the value to compare withnewval- the value to conditionally replace with- Returns:
trueif the exchange took place- Since:
- 2.4
-
atomicIntCompareAndExchangeFull
public static boolean atomicIntCompareAndExchangeFull(MemorySegment atomic, int oldval, int newval, Out<Integer> preval) Comparesatomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen no change occurs. In any case the value ofatomicbefore 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 agintorguintoldval- the value to compare withnewval- the value to conditionally replace withpreval- the contents ofatomicbefore this operation- Returns:
trueif the exchange took place- Since:
- 2.74
-
atomicIntDecAndTest
Decrements the value ofatomicby 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguint- Returns:
trueif the resultant value is zero- Since:
- 2.4
-
atomicIntExchange
Sets theatomictonewvaland 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 agintorguintnewval- the value to replace with- Returns:
- the value of
atomicbefore the exchange, signed - Since:
- 2.74
-
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 agintval- the value to add- Returns:
- the value of
atomicbefore the add, signed - Since:
- 2.4
-
atomicIntGet
Gets the current value ofatomic.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguint- Returns:
- the value of the integer
- Since:
- 2.4
-
atomicIntInc
Increments the value ofatomicby 1.Think of this operation as an atomic version of
{ *atomic += 1; }.This call acts as a full compiler and hardware memory barrier.
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguint- Since:
- 2.4
-
atomicIntOr
Performs an atomic bitwise 'or' of the value ofatomicandval, 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguintval- the value to 'or'- Returns:
- the value of
atomicbefore the operation, unsigned - Since:
- 2.30
-
atomicIntSet
Sets the value ofatomictonewval.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguintnewval- a new value to store- Since:
- 2.4
-
atomicIntXor
Performs an atomic bitwise 'xor' of the value ofatomicandval, 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.- Parameters:
atomic- a pointer to agintorguintval- the value to 'xor'- Returns:
- the value of
atomicbefore the operation, unsigned - Since:
- 2.30
-
atomicPointerAdd
Atomically addsvalto 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gssizetogintptrto 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
atomicbefore the add, signed - Since:
- 2.30
-
atomicPointerAnd
Performs an atomic bitwise 'and' of the value ofatomicandval, storing the result back inatomic.Think of this operation as an atomic version of
{ tmp = *atomic; *atomic invalid input: '&'= val; return tmp; }.This call acts as a full compiler and hardware memory barrier.
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gsizetoguintptrto 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
atomicbefore the operation, unsigned - Since:
- 2.30
-
atomicPointerCompareAndExchange
public static boolean atomicPointerCompareAndExchange(MemorySegment atomic, @Nullable @Nullable MemorySegment oldval, @Nullable @Nullable MemorySegment newval) Comparesatomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen 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
atomichas avolatilequalifier, 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:
trueif the exchange took place- Since:
- 2.4
-
atomicPointerCompareAndExchangeFull
public static boolean atomicPointerCompareAndExchangeFull(MemorySegment atomic, @Nullable @Nullable MemorySegment oldval, @Nullable @Nullable MemorySegment newval, Out<MemorySegment> preval) Comparesatomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen no change occurs. In any case the value ofatomicbefore 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 ofatomicbefore this operation- Returns:
trueif the exchange took place- Since:
- 2.74
-
atomicPointerExchange
public static MemorySegment atomicPointerExchange(@Nullable @Nullable MemorySegment atomic, @Nullable @Nullable MemorySegment newval) Sets theatomictonewvaland 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
atomicbefore the exchange - Since:
- 2.74
-
atomicPointerGet
Gets the current value ofatomic.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomichas avolatilequalifier, 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
- Since:
- 2.4
-
atomicPointerOr
Performs an atomic bitwise 'or' of the value ofatomicandval, 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gsizetoguintptrto 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
atomicbefore the operation, unsigned - Since:
- 2.30
-
atomicPointerSet
Sets the value ofatomictonewval.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomichas avolatilequalifier, 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- Since:
- 2.4
-
atomicPointerXor
Performs an atomic bitwise 'xor' of the value ofatomicandval, 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gsizetoguintptrto 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
atomicbefore the operation, unsigned - Since:
- 2.30
-
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
- Since:
- 2.58
-
atomicRcBoxAlloc
AllocatesblockSizebytes of memory, and adds atomic reference counting semantics to it.The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
- Parameters:
blockSize- the size of the allocation, must be greater than 0- Returns:
- a pointer to the allocated memory
- Since:
- 2.58
-
atomicRcBoxAlloc0
AllocatesblockSizebytes of memory, and adds atomic reference counting semantics to it.The contents of the returned data is set to zero.
The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
- Parameters:
blockSize- the size of the allocation, must be greater than 0- Returns:
- a pointer to the allocated memory
- Since:
- 2.58
-
atomicRcBoxDup
Allocates a new block of data with atomic reference counting semantics, and copiesblockSizebytes ofmemBlockinto 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
- Since:
- 2.58
-
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
- Since:
- 2.58
-
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- Since:
- 2.58
-
atomicRcBoxReleaseFull
Atomically releases a reference on the data pointed bymemBlock.If the reference was the last one, it will call
clearFuncto clear the contents ofmemBlock, and then will free the resources allocated formemBlock.Note that implementing weak references via
clearFuncis not thread-safe: clearing a pointer to the memory from the callback can race with another thread trying to access it asmemBlockalready has a reference count of 0 when the callback is called and will be freed.- Parameters:
memBlock- a pointer to reference counted data- Since:
- 2.58
-
atomicRefCountCompare
Atomically compares the current value ofarcwithval.- Parameters:
arc- the address of an atomic reference count variableval- the value to compare- Returns:
trueif the reference count is the same as the given value- Since:
- 2.58
-
atomicRefCountDec
Atomically decreases the reference count.If
trueis returned, the reference count reached 0. After this point,arcis 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:
trueif the reference count reached 0, andfalseotherwise- Since:
- 2.58
-
atomicRefCountInc
Atomically increases the reference count.- Parameters:
arc- the address of an atomic reference count variable- Since:
- 2.58
-
atomicRefCountInit
Initializes a reference count variable to 1.- Parameters:
arc- the address of an atomic reference count variable- Since:
- 2.58
-
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
textrepresents. The returned buffer must be freed with g_free(). - Since:
- 2.12
-
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
textresponds. This pointer is the same as the inputtext. - Since:
- 2.20
-
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
- Since:
- 2.12
-
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(). - Since:
- 2.12
-
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
outarray 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
- Since:
- 2.12
-
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.breakLinesis 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 withLFcharacters, notCR LFsequences, 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
- Since:
- 2.12
-
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 indicatedlockBitinaddress. 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). Ifbitis not between 0 and 31 then the result is undefined.This function accesses
addressatomically. All other accesses toaddressmust be atomic in order for this function to work reliably. Whileaddresshas avolatilequalifier, 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- Since:
- 2.24
-
bitNthLsf
public static int bitNthLsf(int mask, int nthBit) Find the position of the first bit set inmask, searching from (but not including)nthBitupwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, setnthBitto -1.- Parameters:
mask- agulongcontaining 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)nthBitdownwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, setnthBitto -1 or GLIB_SIZEOF_LONG * 8.- Parameters:
mask- agulongcontaining 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. ifnumberis 4, 3 bits are needed.- Parameters:
number- aguint- Returns:
- the number of bits used to hold
number
-
bitTrylock
Sets the indicatedlockBitinaddress, returningtrueif successful. If the bit is already set, returnsfalseimmediately.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). Ifbitis not between 0 and 31 then the result is undefined.This function accesses
addressatomically. All other accesses toaddressmust be atomic in order for this function to work reliably. Whileaddresshas avolatilequalifier, 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:
trueif the lock was acquired- Since:
- 2.24
-
bitUnlock
Clears the indicatedlockBitinaddress. If another thread is currently blocked in g_bit_lock() on this same bit then it will be woken up.This function accesses
addressatomically. All other accesses toaddressmust be atomic in order for this function to work reliably. Whileaddresshas avolatilequalifier, 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- Since:
- 2.24
-
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
GPathBufinstead.- 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
GPathBufinstead.- Parameters:
args-null-terminated array of strings containing the path elements.- Returns:
- the newly allocated path
- Since:
- 2.8
-
buildPath
Creates a path from a series of elements usingseparatoras 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, thenABABAhas 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().
- Since:
- 2.8
-
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
filenameis an absolute path,relativeTois ignored. Otherwise,relativeTowill be prepended tofilenameto make it absolute.relativeTomust be an absolute path, ornull. IfrelativeToisnull, 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, ornullto use the current working directory- Returns:
- a newly allocated string with the canonical file path
- Since:
- 2.58
-
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.
- Since:
- 2.8
-
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_VERSIONas 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:
nullif the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.- Since:
- 2.6
-
childWatchAdd
Sets a function to be called when the child indicated bypidexits, at the prioritypriority.If you obtain
pidfromspawnAsync(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, org.javagi.base.Out<java.lang.Integer>, org.javagi.base.Out<java.lang.Integer>, org.javagi.base.Out<java.lang.Integer>)you will need to passSpawnFlags.DO_NOT_REAP_CHILDas 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
GPidmust be explicitly closed (seespawnClosePid(org.gnome.glib.Pid))pidmust 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_IDLEandGLib.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.
- Since:
- 2.4
-
childWatchSourceNew
Creates a new child_watch source.The source will not initially be associated with any
GLib.MainContextand 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_CHILDflag is used.Note that on platforms where
GPidmust be explicitly closed (seespawnClosePid(org.gnome.glib.Pid))pidmust 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:
pidmust be a child of this processpidmust be positive- the application must not call
waitpidwith a non-positive first argument, for instance in another thread - the application must not wait for
pidto 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 watchedpidin a race free manner. Since 2.78, you can do that while the associatedGLib.MainContextis acquired. - Before 2.78, even after destroying the
GLib.Source, you could not be sure thatpidwasn'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
ECHILDwas received bywaitpid.Calling
waitpidfor specific processes other thanpidremains 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
- Since:
- 2.4
-
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
- Since:
- 2.8
-
clearHandleId
Clears a numeric handler, such as aGSourceID.tagPtrmust be a valid pointer to the variable holding the handler.If the ID is zero then this function does nothing. Otherwise,
clearFuncis 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- Since:
- 2.56
-
clearList
Clears a pointer to aGList, freeing it and, optionally, freeing its elements usingdestroy.listPtrmust be a valid pointer. IflistPtrpoints to a nullGList, this does nothing.- Parameters:
listPtr- aGListreturn location- Since:
- 2.64
-
clearPointer
Clears a reference to a variable.ppmust not benull.If the reference is
nullthen this function does nothing. Otherwise, the variable is destroyed usingdestroyand 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
destroyfunction is compatible with being called asGLib.DestroyNotifyusing 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
__stdcallcalling convention rather than the__cdeclcalling convention.The affected functions can be used by wrapping them in a
GLib.DestroyNotifythat is declared with the standard calling convention:// Wrapper needed to avoid mismatched calling conventions on Windows static void destroy_sync (void *sync) { glDeleteSync (sync); } // … g_clear_pointer (&sync, destroy_sync);- Parameters:
pp- a pointer to a variable, struct member etc. holding a pointer- Since:
- 2.34
-
clearSlist
Clears a pointer to aGSList, freeing it and, optionally, freeing its elements usingdestroy.slistPtrmust be a valid pointer. IfslistPtrpoints to a nullGSList, this does nothing.- Parameters:
slistPtr- aGSListreturn location- Since:
- 2.64
-
close
This wraps the close() call. In case of error,errnowill be preserved, but the error will also be stored as aGErrorinerror. In case of success,errnois 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)
errorisnullandfdis a valid open file descriptor. This makes it safe to call from a signal handler or aGSpawnChildSetupFuncunder those conditions. Seesignal(7)) andsignal-safety(7)) for more details.- Parameters:
fd- A file descriptor- Returns:
trueon success,falseif there was an error.- Throws:
GErrorException- seeGError- Since:
- 2.36
-
closefrom
public static int closefrom(int lowfd) Close every file descriptor equal to or greater thanlowfd.Typically
lowfdwill 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 aslowfdis 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
- Since:
- 2.80
-
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- aGChecksumTypedata- binary blob to compute the digest of- Returns:
- the digest of the binary data as a
string in hexadecimal, or
nullif g_checksum_new() fails forchecksumType. The returned string should be freed with g_free() when done using it. - Since:
- 2.34
-
computeChecksumForData
Computes the checksum for a binarydataoflength. 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- aGChecksumTypedata- binary blob to compute the digest of- Returns:
- the digest of the binary data as a
string in hexadecimal, or
nullif g_checksum_new() fails forchecksumType. The returned string should be freed with g_free() when done using it. - Since:
- 2.16
-
computeChecksumForString
Computes the checksum of a string.The hexadecimal string returned will be in lower case.
- Parameters:
checksumType- aGChecksumTypestr- 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
nullif g_checksum_new() fails forchecksumType. The returned string should be freed with g_free() when done using it. - Since:
- 2.16
-
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- aGChecksumTypeto 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.
- Since:
- 2.50
-
computeHmacForData
Computes the HMAC for a binarydataoflength. 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- aGChecksumTypeto 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.
- Since:
- 2.30
-
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- aGChecksumTypeto 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.
- Since:
- 2.30
-
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
bytesReadcan 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 convertstrfromCodeset- 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 thanlenif there were partial characters at the end of the input. If the errorConvertError.ILLEGAL_SEQUENCEoccurs, 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
nullanderrorwill 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 infallbackwill be honored. Some systems may do an approximate conversion fromfromCodesettotoCodesetin 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
bytesReadcan 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 convertstrfromCodeset- 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 thanlenif 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
nullanderrorwill 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
bytesReadcan 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_SEQUENCEerror. 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 thanlenif there were partial characters at the end of the input. If the errorConvertError.ILLEGAL_SEQUENCEoccurs, 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
nullanderrorwill 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().
- Since:
- 2.8
-
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'sGQuarkid and data, together with the givenuserDataparameter. Note that this function is NOT thread-safe. So unlessdatalistcan be protected from any modifications during invocation of this function, it should not be called.funccan 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
nullif 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
- Since:
- 2.8
-
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.dupFuncdefines the meaning of 'duplicate' in this context, it could e.g. take a reference on a ref-counted object.If the
keyIdis not set in the datalist thendupFuncwill be called with anullargument.Note that
dupFuncis 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- theGQuarkidentifying a data elementdupFunc- function to duplicate the old value- Returns:
- the result of calling
dupFuncon the value associated withkeyIdindatalist, ornullif not set. IfdupFuncisnull, the value is returned unmodified. - Since:
- 2.34
-
datalistIdGetData
Retrieves the data element corresponding tokeyId.- Parameters:
datalist- a datalist.keyId- theGQuarkidentifying a data element.- Returns:
- the data element, or
nullif 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,
nKeyshad to be not larger than 16. Since 2.84, performance is improved for larger number of keys.- Parameters:
datalist- a datalistkeys- keys to remove- Since:
- 2.74
-
datalistIdRemoveNoNotify
Removes an element, without calling its destroy notification function.- Parameters:
datalist- a datalist.keyId- theGQuarkidentifying a data element.- Returns:
- the data previously stored at
keyId, ornullif none.
-
datalistIdReplaceData
public static boolean datalistIdReplaceData(Data[] datalist, Quark keyId, @Nullable @Nullable MemorySegment oldval, @Nullable @Nullable MemorySegment newval) Compares the member that is associated withkeyIdindatalisttooldval, and if they are the same, replaceoldvalwithnewval.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 usingoldDestroyas sometimes replacement should not destroy the object in the normal way.- Parameters:
datalist- location of a datalistkeyId- theGQuarkidentifying a data elementoldval- the old value to compare againstnewval- the new value to replace it with- Returns:
trueif the existing value forkeyIdwas replaced bynewval,falseotherwise.- Since:
- 2.34
-
datalistIdSetDataFull
public static void datalistIdSetDataFull(Data[] datalist, Quark keyId, @Nullable @Nullable MemorySegment data) Sets the data corresponding to the givenGQuarkid, 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- theGQuarkto identify the data element.data- the data element ornullto 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 baseGObjecttype, 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 forflagsthat doesn't fit within the mask is an error.- Since:
- 2.8
-
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 forflagsthat doesn't fit within the mask is an error.- Since:
- 2.8
-
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 unlessdatasetLocationcan be protected from any modifications during invocation of this function, it should not be called.funccan 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- theGQuarkid to identify the data element.- Returns:
- the data element corresponding to
the
GQuark, ornullif it is not found.
-
datasetIdRemoveNoNotify
Removes an element, without calling its destroy notification function.- Parameters:
datasetLocation- the location identifying the dataset.keyId- theGQuarkID identifying the data element.- Returns:
- the data previously stored at
keyId, ornullif none.
-
datasetIdSetDataFull
public static void datasetIdSetDataFull(MemorySegment datasetLocation, Quark keyId, @Nullable @Nullable MemorySegment data) Sets the data element associated with the givenGQuarkid, 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- theGQuarkid 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, ornullto use the domain set with textdomain()msgid- message to translatecategory- a locale category- Returns:
- the translated string for the given locale category
- Since:
- 2.26
-
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:
domainis 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, ornullto use the domain set with textdomain()msgid- message to translate- Returns:
- The translated string
- Since:
- 2.18
-
directEqual
public static boolean directEqual(@Nullable @Nullable MemorySegment v1, @Nullable @Nullable MemorySegment v2) Compares twogpointerarguments and returnstrueif they are equal. It can be passed to g_hash_table_new() as thekeyEqualFuncparameter, 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:
trueif the two keys match.
-
directHash
Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as thehashFuncparameter, 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- agpointerkey- 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, ornullto 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
- Since:
- 2.18
-
doubleEqual
Compares the twogdoublevalues being pointed to and returnstrueif they are equal. It can be passed to g_hash_table_new() as thekeyEqualFuncparameter, when using non-nullpointers to doubles as keys in aGHashTable.- Parameters:
v1- a pointer to agdoublekeyv2- a pointer to agdoublekey to compare withv1- Returns:
trueif the two keys match.- Since:
- 2.22
-
doubleHash
Converts a pointer to agdoubleto a hash value. It can be passed to g_hash_table_new() as thehashFuncparameter, It can be passed to g_hash_table_new() as thehashFuncparameter, when using non-nullpointers to doubles as keys in aGHashTable.- Parameters:
v- a pointer to agdoublekey- Returns:
- a hash value corresponding to the key.
- Since:
- 2.22
-
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, ornullto 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
- Since:
- 2.16
-
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, ornullto use the domain set with textdomain()context- the message contextmsgid- the message- Returns:
- The translated string
- Since:
- 2.18
-
environGetenv
Returns the value of the environment variablevariablein the provided listenvp.- Parameters:
envp- an environment list (eg, as returned from g_get_environ()), ornullfor an empty environment listvariable- the environment variable to get- Returns:
- the value of the environment variable, or
nullif the environment variable is not set inenvp. The returned string is owned byenvp, and will be freed ifvariableis set or unset again. - Since:
- 2.32
-
environSetenv
public static String[] environSetenv(@Nullable @Nullable String[] envp, String variable, String value, boolean overwrite) Sets the environment variablevariablein the provided listenvptovalue.- Parameters:
envp- an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), ornullfor 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().
- Since:
- 2.32
-
environUnsetenv
Removes the environment variablevariablefrom the provided environmentenvp.- Parameters:
envp- an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), ornullfor an empty environment listvariable- the environment variable to remove, must not contain '='- Returns:
- the updated environment list. Free it using g_strfreev().
- Since:
- 2.32
-
fdwalkSetCloexec
public static int fdwalkSetCloexec(int lowfd) Mark every file descriptor equal to or greater thanlowfdto be closed at the nextexecve()or similar, as if via theFD_CLOEXECflag.Typically
lowfdwill 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 aslowfdis 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
- Since:
- 2.80
-
fileErrorFromErrno
Gets aGFileErrorconstant based on the passed-inerrNo.For example, if you pass in
EEXISTthis function returnsFileError.EXIST. Unlikeerrnovalues, you can portably assume that allGFileErrorvalues will exist.Normally a
GFileErrorvalue goes into aGErrorreturned from a function that manipulates files. So you would use g_file_error_from_errno() when constructing aGError.- Parameters:
errNo- an "errno" value- Returns:
GFileErrorcorresponding to the givenerrNo
-
fileErrorQuark
-
fileGetContents
Reads an entire file into allocated memory, with good error checking.If the call was successful, it returns
trueand setscontentsto the file contents andlengthto the length of the file contents in bytes. The string stored incontentswill be nul-terminated, so for text files you can passnullfor thelengthargument. If the call was not successful, it returnsfalseand setserror. The error domain isG_FILE_ERROR. Possible error codes are those in theGFileErrorenumeration. In the error case,contentsis set tonullandlengthis 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:
trueon success,falseif 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()).tmplshould 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())
tmplis not modified, and might thus be a read-only literal string.Upon success, and if
nameUsedis 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, ornullfor 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
errorwill be set. - Throws:
GErrorException- seeGError
-
fileReadLink
Reads the contents of the symbolic linkfilenamelike 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
nullif an error occurred. - Throws:
GErrorException- seeGError- Since:
- 2.4
-
fileSetContents
Writes all ofcontentsto a file namedfilename. This is a convenience wrapper around calling g_file_set_contents_full() withflagsset toG_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTINGandmodeset to0666.- Parameters:
filename- name of a file to writecontentsto, in the GLib file name encodingcontents- string to write to the file- Returns:
trueon success,falseif an error occurred- Throws:
GErrorException- seeGError- Since:
- 2.8
-
fileSetContentsFull
public static boolean fileSetContentsFull(String filename, byte[] contents, Set<FileSetContentsFlags> flags, int mode) throws GErrorException Writes all ofcontentsto a file namedfilename, with good error checking. If a file calledfilenamealready exists it will be overwritten.flagscontrol 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
flagshas any value other thanFileSetContentsFlags.NONEthen this function may callfsync().If
FileSetContentsFlags.CONSISTENTis 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
filenamealready exists hard links tofilenamewill break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. Iffilenameis a symbolic link, the link itself will be replaced, not the linked file.
- On UNIX, if
filenamealready exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and ifFileSetContentsFlags.CONSISTENTis set inflags, thefsync()call (or equivalent) will be used to ensure atomic replacement:filenamewill contain either its old contents orcontents, even in the face of system power loss, the disk being unsafely removed, etc.
- On UNIX, if
filenamedoes not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leavefilenameempty or full of NUL bytes, depending on the underlying filesystem, unlessFileSetContentsFlags.DURABLEandFileSetContentsFlags.CONSISTENTare 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
filenamealready exists and is open.
If the call was successful, it returns
true. If the call was not successful, it returnsfalseand setserror. The error domain isG_FILE_ERROR. Possible error codes are those in theGFileErrorenumeration.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 tomodedepending onflags, or they may remain unchanged.- Parameters:
filename- name of a file to writecontentsto, 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:
trueon success,falseif an error occurred- Throws:
GErrorException- seeGError- Since:
- 2.66
- On UNIX, if
-
fileSetContentsFull
public static boolean fileSetContentsFull(String filename, byte[] contents, FileSetContentsFlags flags, int mode) throws GErrorException Writes all ofcontentsto a file namedfilename, with good error checking. If a file calledfilenamealready exists it will be overwritten.flagscontrol 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
flagshas any value other thanFileSetContentsFlags.NONEthen this function may callfsync().If
FileSetContentsFlags.CONSISTENTis 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
filenamealready exists hard links tofilenamewill break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. Iffilenameis a symbolic link, the link itself will be replaced, not the linked file.
- On UNIX, if
filenamealready exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and ifFileSetContentsFlags.CONSISTENTis set inflags, thefsync()call (or equivalent) will be used to ensure atomic replacement:filenamewill contain either its old contents orcontents, even in the face of system power loss, the disk being unsafely removed, etc.
- On UNIX, if
filenamedoes not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leavefilenameempty or full of NUL bytes, depending on the underlying filesystem, unlessFileSetContentsFlags.DURABLEandFileSetContentsFlags.CONSISTENTare 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
filenamealready exists and is open.
If the call was successful, it returns
true. If the call was not successful, it returnsfalseand setserror. The error domain isG_FILE_ERROR. Possible error codes are those in theGFileErrorenumeration.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 tomodedepending onflags, or they may remain unchanged.- Parameters:
filename- name of a file to writecontentsto, 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:
trueon success,falseif an error occurred- Throws:
GErrorException- seeGError- Since:
- 2.66
- On UNIX, if
-
fileTest
Returnstrueif any of the tests in the bitfieldtestaretrue. For example,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)will returntrueif 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_SYMLINKall tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will returntruefor bothFileTest.IS_SYMLINKandFileTest.IS_REGULAR.Note, that for a dangling symbolic link g_file_test() will return
trueforFileTest.IS_SYMLINKandfalsefor 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_SYMLINKto 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.EXISTSandFileTest.IS_EXECUTABLEare 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_SYMLINKwill always returnfalse. Testing forFileTest.IS_EXECUTABLEwill just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in thePATHEXTenvironment variable.- Parameters:
filename- a filename to test in the GLib file name encodingtest- bitfield ofGFileTestflags- Returns:
- whether a test was
true
-
fileTest
Returnstrueif any of the tests in the bitfieldtestaretrue. For example,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)will returntrueif 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_SYMLINKall tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will returntruefor bothFileTest.IS_SYMLINKandFileTest.IS_REGULAR.Note, that for a dangling symbolic link g_file_test() will return
trueforFileTest.IS_SYMLINKandfalsefor 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_SYMLINKto 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.EXISTSandFileTest.IS_EXECUTABLEare 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_SYMLINKwill always returnfalse. Testing forFileTest.IS_EXECUTABLEwill just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in thePATHEXTenvironment variable.- Parameters:
filename- a filename to test in the GLib file name encodingtest- bitfield ofGFileTestflags- 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 iffilenamewas in an invalid encoding.You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.
This function is preferred over g_filename_display_name() if you know the whole path, as it allows translation.
- Parameters:
filename- an absolute pathname in the GLib file name encoding- Returns:
- a newly allocated string containing a rendition of the basename of the filename in valid UTF-8
- Since:
- 2.6
-
filenameDisplayName
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-nulleven 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 iffilenamewas in an invalid encoding.If you know the whole pathname of the file you should use g_filename_display_basename(), since that allows location-based translation of filenames.
- Parameters:
filename- a pathname hopefully in the GLib file name encoding- Returns:
- a newly allocated string containing a rendition of the filename in valid UTF-8
- Since:
- 2.6
-
filenameFromUri
public static String filenameFromUri(String uri, @Nullable @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,nullwill be stored in this location.- Returns:
- a newly-allocated string holding
the resulting filename, or
nullon 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.The input string shall not contain nul characters even if the
lenargument 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_NULis 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 thanlenif there were partial characters at the end of the input. If the errorConvertError.ILLEGAL_SEQUENCEoccurs, 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
nullon 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, ornullfor none.- Returns:
- a newly-allocated string holding the resulting
URI, or
nullon 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.The input string shall not contain nul characters even if the
lenargument 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_NULis 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 thelenparameter 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 thanlenif there were partial characters at the end of the input. If the errorConvertError.ILLEGAL_SEQUENCEoccurs, 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
nullon an error. - Throws:
GErrorException- seeGError
-
findProgramInPath
Locates the first executable namedprogramin the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, ornullif the program is not found in the path. Ifprogramis already an absolute path, returns a copy ofprogramifprogramexists and is executable, andnullotherwise. On Windows, ifprogramdoes not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in thePATHEXTenvironment 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
PATHenvironment 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
FILEstruct, 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, ornullif an error occurred - Since:
- 2.6
-
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
- Since:
- 2.30
-
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
- Since:
- 2.16
-
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-GFormatSizeFlagsto modify the output- Returns:
- a newly-allocated formatted string containing a human readable file size
- Since:
- 2.30
-
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-GFormatSizeFlagsto modify the output- Returns:
- a newly-allocated formatted string containing a human readable file size
- Since:
- 2.30
-
fprintf
An implementation of the standardfprintf()function which supports positional parameters, as specified in the Single Unix Specification.glib/gprintf.hmust 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
- Since:
- 2.2
-
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
memisnullit simply returns, so there is no need to checkmemagainstnullbefore calling this function.- Parameters:
mem- the memory to free
-
freeSized
Frees the memory pointed to bymem, assuming it is has the givensize.If
memisnullthis is a no-op (andsizeis ignored).It is an error if
sizedoesn’t match the size passed whenmemwas allocated.sizeis 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- Since:
- 2.76
-
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
nullif an error occurred. - Since:
- 2.6
-
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().
- Since:
- 2.64
-
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 benullif g_set_prgname() has also not been called).- Returns:
- human-readable application
name. May return
null - Since:
- 2.2
-
getCharset
Obtains the character set for the current locale; you might use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8() are nice shortcuts, though.)On Windows the character set returned by this function is the so-called system default ANSI code-page. That is the character set used by the "narrow" versions of C library and Win32 functions that handle file names. It might be different from the character set used by the C library's current locale.
On Linux, the character set is found by consulting nl_langinfo() if available. If not, the environment variables
LC_ALL,LC_CTYPE,LANGandCHARSETare queried in order. nl_langinfo() returns the C locale if no locale has been loaded by setlocale().The return value is
trueif the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().The string returned in
charsetis not allocated, and should not be freed.- Parameters:
charset- return location for character set name, ornull.- Returns:
trueif 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
trueif the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().The string returned in
charsetis not allocated, and should not be freed.- Parameters:
charset- return location for character set name, ornull.- Returns:
trueif the returned charset is UTF-8- Since:
- 2.62
-
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.GTimeValis not year-2038-safe. UsegetRealTime()instead.Equivalent to the UNIX gettimeofday() function, but portable.You may find
getRealTime()to be more convenient.- Parameters:
result-GTimeValstructure in which to store current time.
-
getEnviron
Gets the list of environment variables for the current process.The list is
nullterminated and each item in the list is of the form 'NAME=VALUE'.This is equivalent to direct access to the 'environ' global variable, except portable.
The return value is freshly allocated and it should be freed with g_strfreev() when it is no longer needed.
- Returns:
- the list of environment variables
- Since:
- 2.28
-
getFilenameCharsets
Determines the preferred character sets used for filenames. The first character set from thecharsetsis 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_ENCODINGandG_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_ENCODINGmay be set to a comma-separated list of character set names. The special token@localeis taken to mean the character set for the current locale. IfG_FILENAME_ENCODINGis not set, butG_BROKEN_FILENAMESis, 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
charsetsbelong to GLib and must not be freed.Note that on Unix, regardless of the locale character set or
G_FILENAME_ENCODINGvalue, 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:
trueif the filename encoding is UTF-8.- Since:
- 2.6
-
getHomeDir
Gets the current user's home directory.As with most UNIX tools, this function will return the value of the
HOMEenvironment variable if it is set to an existing absolute path name, falling back to thepasswdfile in the case that it is unset.If the path given in
HOMEis non-absolute, does not exist, or is not a directory, the result is undefined.Before version 2.36 this function would ignore the
HOMEenvironment variable, taking the value from thepasswddatabase 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
HOMEenvironment 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.
- Since:
- 2.8
-
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_MESSAGESandLANGto find the list of locales specified by the user.- Returns:
- a
null-terminated array of strings owned by GLib that must not be modified or freed. - Since:
- 2.6
-
getLanguageNamesWithCategory
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, andLANGto find the list of locales specified by the user.g_get_language_names() returns g_get_language_names_with_category("LC_MESSAGES").
- Parameters:
categoryName- a locale category name- Returns:
- a
null-terminated array of strings owned by the thread g_get_language_names_with_category was called from. It must not be modified or freed. It must be copied if planned to be used in another thread. - Since:
- 2.58
-
getLocaleVariants
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.localeitself is guaranteed to be returned in the output.For example, if
localeisfr_BE, then the returned list isfr_BE,fr. Iflocaleisen_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().
- Since:
- 2.28
-
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
- Since:
- 2.28
-
getNumProcessors
public static int getNumProcessors()Determine the approximate number of threads that the system will schedule simultaneously for this process. This is intended to be used as a parameter to g_thread_pool_new() for CPU bound tasks and similar cases.- Returns:
- Number of schedulable threads, always greater than 0
- Since:
- 2.36
-
getOsInfo
Get information about the operating system.On Linux this comes from the
/etc/os-releasefile. On other systems, it may come from a variety of sources. You can either use the standard key names likeG_OS_INFO_KEY_NAMEor pass any UTF-8 string key name. For example,/etc/os-releaseprovides 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
nullif this information is not provided. - Since:
- 2.64
-
getPrgname
Gets the name of the program. This name should not be localized, in contrast to g_get_application_name().If you are using
GApplicationthe 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
nullif 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 thepasswdfile. 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.
- Since:
- 2.28
-
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_DIRSis defined. IfXDG_CONFIG_DIRSis 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. - Since:
- 2.6
-
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_DIRSis defined. IfXDG_DATA_DIRSis undefined, the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for FOLDERID_ProgramData and FOLDERID_PublicDocuments.Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.
Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.
The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.
Note that on Windows the returned list can vary depending on where this function is called.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
- Returns:
- a
null-terminated array of strings owned by GLib that must not be modified or freed. - Since:
- 2.6
-
getTmpDir
Gets the directory to use for temporary files.On UNIX, this is taken from the
TMPDIRenvironment variable. If the variable is not set,P_tmpdiris used, as defined by the system C library. Failing that, a hard-coded default of "/tmp" is returned.On Windows, the
TEMPenvironment 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
nullor 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_HOMEis defined. IfXDG_CACHE_HOMEis 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.
- Since:
- 2.6
-
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_HOMEis defined. IfXDG_CONFIG_HOMEis 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.
- Since:
- 2.6
-
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_HOMEis defined. IfXDG_DATA_HOMEis 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.
- Since:
- 2.6
-
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_DIRenvironment variable. In the case that this variable is not set, we return the value of g_get_user_cache_dir(), after verifying that it exists.The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
- Returns:
- a string owned by GLib that must not be modified or freed.
- Since:
- 2.28
-
getUserSpecialDir
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_DESKTOPfalls back to$HOME/Desktopwhen 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
nullif the logical id was not found. The returned string is owned by GLib and should not be modified or freed. - Since:
- 2.14
-
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_HOMEis defined. IfXDG_STATE_HOMEis 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.
- Since:
- 2.72
-
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
nullif 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 ifhostnamecontains 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
truefor a name.- Parameters:
hostname- a hostname- Returns:
trueifhostnamecontains any ASCII-encoded segments.- Since:
- 2.22
-
hostnameIsIpAddress
Tests ifhostnameis 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:
trueifhostnameis an IP address- Since:
- 2.22
-
hostnameIsNonAscii
Tests ifhostnamecontains 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
truefor a name.- Parameters:
hostname- a hostname- Returns:
trueifhostnamecontains any non-ASCII characters- Since:
- 2.22
-
hostnameToAscii
Convertshostnameto 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
nullifhostnameis in some way invalid. - Since:
- 2.22
-
hostnameToUnicode
Convertshostnameto 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
hostnameis 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
nullifhostnameis in some way invalid. - Since:
- 2.22
-
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.See
iconv(3posix)) andiconv(3)) for more details about behavior when an error occurs.- Parameters:
converter- conversion descriptor from g_iconv_open()inbuf- bytes to convertinbytesLeft- inout parameter, bytes remaining to convert ininbufoutbuf- 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_REMOVEorfalseit 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.MainContextusingSource.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_IDLEandGLib.PRIORITY_HIGH_IDLE.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:
trueif an idle source was found and removed.
-
idleSourceNew
Creates a new idle source.The source will not initially be associated with any
GLib.MainContextand 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 twogint64values being pointed to and returnstrueif they are equal. It can be passed to g_hash_table_new() as thekeyEqualFuncparameter, when using non-nullpointers to 64-bit integers as keys in aGHashTable.- Parameters:
v1- a pointer to agint64keyv2- a pointer to agint64key to compare withv1- Returns:
trueif the two keys match.- Since:
- 2.22
-
int64Hash
Converts a pointer to agint64to a hash value.It can be passed to g_hash_table_new() as the
hashFuncparameter, when using non-nullpointers to 64-bit integer values as keys in aGHashTable.- Parameters:
v- a pointer to agint64key- Returns:
- a hash value corresponding to the key.
- Since:
- 2.22
-
intEqual
Compares the twogintvalues being pointed to and returnstrueif they are equal. It can be passed to g_hash_table_new() as thekeyEqualFuncparameter, when using non-nullpointers to integers as keys in aGHashTable.Note that this function acts on pointers to
gint, not ongintdirectly: if your hash table's keys are of the formGINT_TO_POINTER (n), use g_direct_equal() instead.- Parameters:
v1- a pointer to agintkeyv2- a pointer to agintkey to compare withv1- Returns:
trueif the two keys match.
-
intHash
Converts a pointer to agintto a hash value. It can be passed to g_hash_table_new() as thehashFuncparameter, when using non-nullpointers to integer values as keys in aGHashTable.Note that this function acts on pointers to
gint, not ongintdirectly: if your hash table's keys are of the formGINT_TO_POINTER (n), use g_direct_hash() instead.- Parameters:
v- a pointer to agintkey- 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, thereforestringmust not be freed or modified.This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.
- Parameters:
string- a static string- Returns:
- a canonical representation for the string
- Since:
- 2.10
-
internString
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
- Since:
- 2.10
-
ioAddWatch
public static int ioAddWatch(IOChannel channel, int priority, Set<IOCondition> condition, IOFunc func) Adds theGIOChannelinto 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- aGIOChannelpriority- the priority of theGIOChannelsourcecondition- the condition to watch forfunc- the function to call when the condition is satisfied- Returns:
- the event source id
-
ioAddWatch
Adds theGIOChannelinto 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- aGIOChannelpriority- the priority of theGIOChannelsourcecondition- the condition to watch forfunc- the function to call when the condition is satisfied- Returns:
- the event source id
-
ioCreateWatch
Creates aGSourcethat's dispatched whenconditionis 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
GSourceshould 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
GSourcecreated 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- aGIOChannelto watchcondition- conditions to watch for- Returns:
- a new
GSource
-
ioCreateWatch
Creates aGSourcethat's dispatched whenconditionis 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
GSourceshould 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
GSourcecreated 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- aGIOChannelto 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(). - Since:
- 2.8
-
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. On Windows this means the system codepage.The input string shall not contain nul characters even if the
lenargument 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 thanlenif there were partial characters at the end of the input. If the errorConvertError.ILLEGAL_SEQUENCEoccurs, the value stored will be the byte offset after the last valid input sequence.- Returns:
- A newly-allocated buffer containing the converted string,
or
nullon 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 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_NULis set and the function returnsnull. If the source encoding is UTF-8, an embedded nul character is treated with theConvertError.ILLEGAL_SEQUENCEerror 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 thanlenif there were partial characters at the end of the input. If the errorConvertError.ILLEGAL_SEQUENCEoccurs, 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
nullon 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#BREAKPOINTis called to terminate the program. See the documentation forGLib#BREAKPOINTfor 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, orNULLfor the defaultlogLevel- the log level, either fromGLib.LogLevelFlagsor 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#BREAKPOINTis called to terminate the program. See the documentation forGLib#BREAKPOINTfor 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, orNULLfor the defaultlogLevel- the log level, either fromGLib.LogLevelFlagsor 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
stderrorstdoutand 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).DEBUG_INVOCATION: If set to1, this is equivalent toG_MESSAGES_DEBUG=all.DEBUG_INVOCATIONis a standard environment variable set by systemd to prompt debug output. (Since: 2.84)
stderris used for levelsGLib.LogLevelFlags.LEVEL_ERROR,GLib.LogLevelFlags.LEVEL_CRITICAL,GLib.LogLevelFlags.LEVEL_WARNINGandGLib.LogLevelFlags.LEVEL_MESSAGE.stdoutis used for the rest, unlessstderrwas requested bylogWriterDefaultSetUseStderr(boolean).This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain- the log domain of the message, orNULLfor 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
stderrorstdoutand 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).DEBUG_INVOCATION: If set to1, this is equivalent toG_MESSAGES_DEBUG=all.DEBUG_INVOCATIONis a standard environment variable set by systemd to prompt debug output. (Since: 2.84)
stderris used for levelsGLib.LogLevelFlags.LEVEL_ERROR,GLib.LogLevelFlags.LEVEL_CRITICAL,GLib.LogLevelFlags.LEVEL_WARNINGandGLib.LogLevelFlags.LEVEL_MESSAGE.stdoutis used for the rest, unlessstderrwas requested bylogWriterDefaultSetUseStderr(boolean).This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
logDomain- the log domain of the message, orNULLfor 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#debugor other logging functions; it should only be used fromGLib.LogWriterFuncimplementations.Note also that the value of this does not depend on
G_MESSAGES_DEBUG, norDEBUG_INVOCATION, norlogWriterDefaultSetDebugDomains(java.lang.String); see the docs forlogSetDebugEnabled(boolean).- Returns:
TRUEif debug output is enabled,FALSEotherwise- Since:
- 2.72
-
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_ERRORis always fatal.You can also make some message levels fatal at runtime by setting the
G_DEBUGenvironment 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_ERRORis always fatal.You can also make some message levels fatal at runtime by setting the
G_DEBUGenvironment 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,DEBUG_INVOCATIONandlogWriterDefaultSetDebugDomains(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-TRUEto enable debug output,FALSEotherwise- Since:
- 2.72
-
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
- Since:
- 2.6
-
logSetFatalMask
Sets the log levels which are fatal in the given domain.GLib.LogLevelFlags.LEVEL_ERRORis 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_INFOorGLib.LogLevelFlags.LEVEL_DEBUGas 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_ERRORis 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_INFOorGLib.LogLevelFlags.LEVEL_DEBUGas 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.
The
log_domainparameter can be set toNULLor an empty string to use the default application domain.- Parameters:
logDomain- the log domain 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_FATALandGLib.LogLevelFlags.FLAG_RECURSIONbit flags.logFunc- the log handler function- Returns:
- the ID of the new handler
- Since:
- 2.46
-
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.
The
log_domainparameter can be set toNULLor an empty string to use the default application domain.- Parameters:
logDomain- the log domain 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_FATALandGLib.LogLevelFlags.FLAG_RECURSIONbit flags.logFunc- the log handler function- Returns:
- the ID of the new handler
- Since:
- 2.46
-
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- Since:
- 2.50
-
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#BREAKPOINTat the end of this function. If the log writer returnsGLib.LogWriterOutput.UNHANDLED(failure), no other fallback writers will be tried. See the documentation forGLib.LogWriterFuncfor 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, with the exception of"GLIB_DOMAIN"which was only fixed with GLib 2.82.3.The
logDomainwill be converted into aGLIB_DOMAINfield.logLevelwill be converted into aPRIORITYfield. The format string will have its placeholders substituted for the provided values and be converted into aMESSAGEfield.Other fields you may commonly want to pass into this function:
Note that
CODE_FILE,CODE_LINEandCODE_FUNCare automatically set by the logging macros,GLib#DEBUGHERE,GLib#message,GLib#warning,GLib#critical,GLib#error, etc, if the symbolG_LOG_USE_STRUCTUREDis 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_IDmust 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.lengthset 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
MESSAGEkey before the format string. TheMESSAGE-format pair has to be the last of the key-value pairs, andMESSAGEis the only field for whichprintf()-style formatting is supported.The default writer function for
stdoutandstderrwill 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_DOMAINlogLevel- 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- Since:
- 2.50
-
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#BREAKPOINTat the end of this function. If the log writer returnsGLib.LogWriterOutput.UNHANDLED(failure), no other fallback writers will be tried. See the documentation forGLib.LogWriterFuncfor 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, with the exception of"GLIB_DOMAIN"which was only fixed with GLib 2.82.3.The
logDomainwill be converted into aGLIB_DOMAINfield.logLevelwill be converted into aPRIORITYfield. The format string will have its placeholders substituted for the provided values and be converted into aMESSAGEfield.Other fields you may commonly want to pass into this function:
Note that
CODE_FILE,CODE_LINEandCODE_FUNCare automatically set by the logging macros,GLib#DEBUGHERE,GLib#message,GLib#warning,GLib#critical,GLib#error, etc, if the symbolG_LOG_USE_STRUCTUREDis 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_IDmust 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.lengthset 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
MESSAGEkey before the format string. TheMESSAGE-format pair has to be the last of the key-value pairs, andMESSAGEis the only field for whichprintf()-style formatting is supported.The default writer function for
stdoutandstderrwill 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_DOMAINlogLevel- 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- Since:
- 2.50
-
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
logLevelis already present infields(typically as thePRIORITYfield).- Parameters:
logLevel- log level, either fromGLib.LogLevelFlags, or a user-defined levelfields- key–value pairs of structured data to add to the log message- Since:
- 2.50
-
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
logLevelis already present infields(typically as thePRIORITYfield).- Parameters:
logLevel- log level, either fromGLib.LogLevelFlags, or a user-defined levelfields- key–value pairs of structured data to add to the log message- Since:
- 2.50
-
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
fieldsdictionary is the"MESSAGE"which must contain the text shown to the user.The values in the
fieldsdictionary 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_DOMAINlogLevel- log level, either fromGLib.LogLevelFlags, or a user-defined levelfields- a dictionary (GLib.Variantof the typeG_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.- Since:
- 2.50
-
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
fieldsdictionary is the"MESSAGE"which must contain the text shown to the user.The values in the
fieldsdictionary 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_DOMAINlogLevel- log level, either fromGLib.LogLevelFlags, or a user-defined levelfields- a dictionary (GLib.Variantof the typeG_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.- Since:
- 2.50
-
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
stdoutorstderrif 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_DEBUGenvironment variable, orDEBUG_INVOCATION=1is set in the environment, 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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.50
-
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
stdoutorstderrif 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_DEBUGenvironment variable, orDEBUG_INVOCATION=1is set in the environment, 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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.50
-
logWriterDefaultSetDebugDomains
Reset the list of domains to be logged, that might be initially set by theG_MESSAGES_DEBUGorDEBUG_INVOCATIONenvironment variables.This function is thread-safe.
- Parameters:
domains-NULL-terminated array with domains to be printed.NULLor an array with no values means none. Array with a single value"all"means all.- Since:
- 2.80
-
logWriterDefaultSetUseStderr
public static void logWriterDefaultSetUseStderr(boolean useStderr) Configure whether the built-in log functions will output all log messages 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_INFOandGLib.LogLevelFlags.LEVEL_DEBUGare sent tostdout, and other log messages are sent tostderr. This is problematic for applications that intend to reservestdoutfor 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, usestderrfor log messages that would normally have appeared onstdout- Since:
- 2.68
-
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_DEBUGenvironment variable, orDEBUG_INVOCATION=1is set in the environment, 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} and {@code DEBUG_INVOCATION} are not set:g_debug ("my_object result:
s", result); } ```- Parameters:
logLevel- log level, either fromGLib.LogLevelFlags, or a user-defined levellogDomain- log domain- Returns:
TRUEif the log message would be dropped by GLib’s default log handlers- Since:
- 2.68
-
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_DEBUGenvironment variable, orDEBUG_INVOCATION=1is set in the environment, 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} and {@code DEBUG_INVOCATION} are not set:g_debug ("my_object result:
s", result); } ```- Parameters:
logLevel- log level, either fromGLib.LogLevelFlags, or a user-defined levellogDomain- log domain- Returns:
TRUEif the log message would be dropped by GLib’s default log handlers- Since:
- 2.68
-
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
MESSAGEandGLIB_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-TRUEto use ANSI color escape sequences when formatting the message,FALSEto not- Returns:
- string containing the formatted log message, in the character set of the current locale
- Since:
- 2.50
-
logWriterFormatFields
public static String logWriterFormatFields(LogLevelFlags logLevel, 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
MESSAGEandGLIB_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-TRUEto use ANSI color escape sequences when formatting the message,FALSEto not- Returns:
- string containing the formatted log message, in the character set of the current locale
- Since:
- 2.50
-
logWriterIsJournald
public static boolean logWriterIsJournald(int outputFd) Check whether the givenoutputFdfile descriptor is a connection to the systemd journal, or something else (like a log file orstdoutorstderr).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:
TRUEifoutputFdpoints to the journal,FALSEotherwise- Since:
- 2.50
-
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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.50
-
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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.50
-
logWriterStandardStreams
public static LogWriterOutput logWriterStandardStreams(Set<LogLevelFlags> logLevel, LogField[] fields, @Nullable @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdoutorstderr, depending on its log level.GLib.LogLevelFlags.LEVEL_INFOandGLib.LogLevelFlags.LEVEL_DEBUGmessages are sent tostdout, or tostderrif 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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.50
-
logWriterStandardStreams
public static LogWriterOutput logWriterStandardStreams(LogLevelFlags logLevel, LogField[] fields, @Nullable @Nullable MemorySegment userData) Format a structured log message and print it to eitherstdoutorstderr, depending on its log level.GLib.LogLevelFlags.LEVEL_INFOandGLib.LogLevelFlags.LEVEL_DEBUGmessages are sent tostdout, or tostderrif 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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.50
-
logWriterSupportsColor
public static boolean logWriterSupportsColor(int outputFd) Check whether the givenoutputFdfile 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:
TRUEif ANSI color escapes are supported,FALSEotherwise- Since:
- 2.50
-
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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.80
-
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.HANDLEDon success,GLib.LogWriterOutput.UNHANDLEDotherwise- Since:
- 2.80
-
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
- Since:
- 2.6
-
mainCurrentSource
Returns the currently firing source for this thread.- Returns:
- The currently firing source or
null. - Since:
- 2.12
-
mainDepth
public static int mainDepth()Returns the depth of the stack of calls toMainContext.dispatch()on anyGMainContextin 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
AllocatesnBytesbytes of memory. IfnBytesis 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
AllocatesnBytesbytes of memory, initialized to 0's. IfnBytesis 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
- Since:
- 2.24
-
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
- Since:
- 2.24
-
markupCollectAttributes
public static boolean markupCollectAttributes(String elementName, String[] attributeNames, String[] attributeValues, GError[] error, Set<MarkupCollectType> firstType, String firstAttr, Object... varargs) Collects the attributes of the element from the data passed to theGMarkupParserstart_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,attributeValuesanderrorparameters 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
attributeNamesarray then an unknown attribute error will result.The
GMarkupCollectTypefield 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 benullin 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 casesfalsewill be returned anderrorwill be set as appropriate.- Parameters:
elementName- the current tag nameattributeNames- the attribute namesattributeValues- the attribute valueserror- a pointer to aGErrorornullfirstType- theGMarkupCollectTypeof 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:
trueif successful- Since:
- 2.16
-
markupCollectAttributes
public static boolean markupCollectAttributes(String elementName, String[] attributeNames, String[] attributeValues, GError[] error, MarkupCollectType firstType, String firstAttr, Object... varargs) Collects the attributes of the element from the data passed to theGMarkupParserstart_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,attributeValuesanderrorparameters 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
attributeNamesarray then an unknown attribute error will result.The
GMarkupCollectTypefield 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 benullin 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 casesfalsewill be returned anderrorwill be set as appropriate.- Parameters:
elementName- the current tag nameattributeNames- the attribute namesattributeValues- the attribute valueserror- a pointer to aGErrorornullfirstType- theGMarkupCollectTypeof 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:
trueif successful- Since:
- 2.16
-
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 oftextin 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().
- Since:
- 2.4
-
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 returnstruememory 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→guintconversionAllocatesbyteSizebytes of memory, and copiesbyteSizebytes into it frommem. IfmemisNULLit 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
AllocatesbyteSizebytes of memory, and copiesbyteSizebytes into it frommem. IfmemisNULLit returnsNULL.This replaces
memdup(java.lang.foreign.MemorySegment, int), which was prone to integer overflows when converting the argument from agsizeto aguint.- Parameters:
mem- the memory to copybyteSize- the number of bytes to copy- Returns:
- a pointer to the newly-allocated copy of the memory
- Since:
- 2.68
-
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
- Since:
- 2.6
-
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.
- Since:
- 2.8
-
mkdtemp
Creates a temporary directory in the current directory.See the
mkdtemp()) documentation on most UNIX-like systems.The parameter is a string that should follow the rules for mkdtemp() templates, i.e. contain the string "XXXXXX". g_mkdtemp() is slightly more flexible than mkdtemp() in that the sequence does not have to occur at the very end of the template. The X string will be modified to form the name of a directory that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.
If you are going to be creating a temporary directory inside the directory returned by g_get_tmp_dir(), you might want to use g_dir_make_tmp() instead.
- Parameters:
tmpl- template directory name- Returns:
- A pointer to
tmpl, which has been modified to hold the directory name. In case of errors,nullis returned anderrnowill be set. - Since:
- 2.30
-
mkdtempFull
Creates a temporary directory in the current directory.See the
mkdtemp()) documentation on most UNIX-like systems.The parameter is a string that should follow the rules for mkdtemp() templates, i.e. contain the string "XXXXXX". g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the sequence does not have to occur at the very end of the template and you can pass a
mode. The X string will be modified to form the name of a directory that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.If you are going to be creating a temporary directory inside the directory returned by g_get_tmp_dir(), you might want to use g_dir_make_tmp() instead.
- Parameters:
tmpl- template directory 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,nullis returned, anderrnowill be set. - Since:
- 2.30
-
mkstemp
Opens a temporary file in the current directory.See the
mkstemp()) documentation on most UNIX-like systems.The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template. The X string will be modified to form the name of a file that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.
- Parameters:
tmpl- template filename- Returns:
- A file handle (as from open()) to the file
opened for reading and writing. The file is opened in binary
mode on platforms where there is a difference. The file handle
should be closed with close(). In case of errors, -1 is
returned and
errnowill be set.
-
mkstempFull
Opens a temporary file in the current directory.See the
mkstemp()) documentation on most UNIX-like systems.The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp_full() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template and you can pass a
modeand 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
errnowill be set. - Since:
- 2.22
-
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_DEBUGGERenvironment 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. IfprgNameisnull, 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_DEBUGGERenvironment 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, orNULLto use a default string
-
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().
- Since:
- 2.6
-
optionErrorQuark
-
parseDebugString
Parses a string containing debugging options into aguintcontaining bit flags. This is used within GDK and GTK to parse the debug options passed on the command line or through environment variables.If
stringis equal to "all", all flags are set. Any flags specified along with "all" instringare inverted; thus, "all,foo,bar" or "foo,bar,all" sets all flags except those corresponding to "foo" and "bar".If
stringis equal to "help", all the available keys inkeysare printed out to standard error.- Parameters:
string- a list of debug options separated by colons, spaces, or commas, ornull.keys- pointer to an array ofGDebugKeywhich associate strings with bit flags.- Returns:
- the combined set of bit flags.
-
pathGetBasename
Gets the last component of the filename.If
fileNameends with a directory separator it gets the component before the last slash. IffileNameconsists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. IffileNameis 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/testis/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
Returnstrueif the givenfileNameis 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:
trueiffileNameis absolute
-
pathSkipRoot
Returns a pointer intofileNameafter the root component, i.e. after the "/" in UNIX or "C:\\" under Windows. IffileNameis not an absolute path it returnsnull.- Parameters:
fileName- a file name- Returns:
- a pointer into
fileNameafter 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- aGPatternSpecstringLength- 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:
trueifstringmatchespspec
-
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:
trueifstringmatchespspec
-
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- aGPatternSpecstring- the UTF-8 encoded string to match- Returns:
trueifstringmatchespspec
-
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
addresshas avolatilequalifier, 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- Since:
- 2.30
-
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 previouslyaddresshad the lockbit unset. You may also use g_pointer_bit_lock_mask_ptr() to clear the lock bit.- Since:
- 2.80
-
pointerBitLockMaskPtr
public static MemorySegment pointerBitLockMaskPtr(@Nullable @Nullable MemorySegment ptr, int lockBit, boolean set, long preserveMask, @Nullable @Nullable MemorySegment preservePtr) This manglesptras 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 frompreservePtrorptr(depending onpreserveMask).set- whether to set (lock) the bit or unset (unlock). This has no effect, iflockBitis set toG_MAXUINT.preserveMask- if non-zero, a bit-mask forpreservePtr. ThepreserveMaskbits frompreservePtrare set in the result. Note that thelockBitbit will be always set according toset, regardless ofpreserveMaskandpreservePtr(unlesslockBitisG_MAXUINT).preservePtr- ifpreserveMaskis non-zero, the bits from this pointer are set in the result.- Returns:
- the mangled pointer.
- Since:
- 2.80
-
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
addresshas avolatilequalifier, 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:
trueif the lock was acquired- Since:
- 2.30
-
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
addresshas avolatilequalifier, 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- Since:
- 2.30
-
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,ptrmust havelockBitunset. 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 inaddressare preserved. Note that thelockBitbit will be always set according toset, regardless ofpreserveMaskand the currently set value inaddress.- Since:
- 2.80
-
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
fdsis aGPollFDdescribing a single file descriptor to poll. Thefdfield indicates the file descriptor, and theeventsfield indicates the events to poll for. On return, thereventsfields will be filled with the events that actually occurred.On POSIX systems, the file descriptors in
fdscan 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 yourGPollFDswith g_io_channel_win32_make_pollfd().- Parameters:
fds- file descriptors to pollnfds- the number of file descriptors infdstimeout- amount of time to wait, in milliseconds, or -1 to wait forever- Returns:
- the number of entries in
fdswhosereventsfields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted. - Since:
- 2.20
-
prefixError
public static void prefixError(@Nullable @Nullable Out<GError> err, String format, Object... varargs) Formats a string according toformatand prefix it to an existing error message. Iferrisnull(ie: no error variable) then do nothing.If
*errisnull(ie: an error variable is present but there is no error condition) then also do nothing.- Parameters:
err- a return location for aGErrorformat- printf()-style format stringvarargs- arguments toformat- Since:
- 2.16
-
prefixErrorLiteral
Prefixesprefixto an existing error message. Iferror*errisnull(i.e.: no error variable) then do nothing.- Parameters:
err- a return location for aGError, ornullprefix- string to prefixerrwith- Since:
- 2.70
-
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,formatshould 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#warningandGLib#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,formatshould 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#warningandGLib#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 typicallyformatshould end with its own new-line character.glib/gprintf.hmust 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
- Since:
- 2.2
-
propagateError
Ifdestisnull, freesrc; otherwise, movessrcinto*dest. The error variabledestpoints to must benull.srcmust be non-null.Note that
srcis no longer valid after this call. If you want to keep using the same GError*, you need to set it tonullafter 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) Ifdestisnull, freesrc; otherwise, movessrcinto*dest.*destmust 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- Since:
- 2.16
-
qsortWithData
@Deprecated public static void qsortWithData(MemorySegment pbase, int totalElems, long size, CompareDataFunc compareFunc) Deprecated.total_elemsis too small to represent larger arrays; usesortArray(java.lang.foreign.MemorySegment[], long, org.gnome.glib.CompareDataFunc)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 theGQuarkidentifying the given (static) string. If the string does not currently have an associatedGQuark, a newGQuarkis created, linked to the given string.Note that this function is identical to g_quark_from_string() except that if a new
GQuarkis 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
GQuarkidentifying the string, or 0 ifstringisnull
-
quarkFromString
Gets theGQuarkidentifying the given string. If the string does not currently have an associatedGQuark, a newGQuarkis 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
GQuarkidentifying the string, or 0 ifstringisnull
-
quarkToString
-
quarkTryString
Gets theGQuarkassociated with the given string, or 0 if string isnullor 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
GQuarkassociated with the string, or 0 ifstringisnullor there is noGQuarkassociated with it
-
randomDouble
public static double randomDouble()Returns a randomgdoubleequally distributed over the range [0..1).- Returns:
- a random number
-
randomDoubleRange
public static double randomDoubleRange(double begin, double end) Returns a randomgdoubleequally 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 randomguint32equally distributed over the range [0..2^32-1].- Returns:
- a random number
-
randomIntRange
public static int randomIntRange(int begin, int end) Returns a randomgint32equally 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
- Since:
- 2.58
-
rcBoxAlloc
AllocatesblockSizebytes of memory, and adds reference counting semantics to it.The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
- Parameters:
blockSize- the size of the allocation, must be greater than 0- Returns:
- a pointer to the allocated memory
- Since:
- 2.58
-
rcBoxAlloc0
AllocatesblockSizebytes of memory, and adds reference counting semantics to it.The contents of the returned data is set to zero.
The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
- Parameters:
blockSize- the size of the allocation, must be greater than 0- Returns:
- a pointer to the allocated memory
- Since:
- 2.58
-
rcBoxDup
Allocates a new block of data with reference counting semantics, and copiesblockSizebytes ofmemBlockinto 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
- Since:
- 2.58
-
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
- Since:
- 2.58
-
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- Since:
- 2.58
-
rcBoxReleaseFull
Releases a reference on the data pointed bymemBlock.If the reference was the last one, it will call
clearFuncto clear the contents ofmemBlock, and then will free the resources allocated formemBlock.- Parameters:
memBlock- a pointer to reference counted data- Since:
- 2.58
-
realloc
Reallocates the memory pointed to bymem, so that it now has space fornBytesbytes of memory. It returns the new address of the memory, which may have been moved.memmay benull, in which case it's considered to have zero-length.nBytesmay be 0, in which casenullwill be returned andmemwill 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
- Since:
- 2.24
-
refCountCompare
Compares the current value ofrcwithval.- Parameters:
rc- the address of a reference count variableval- the value to compare- Returns:
trueif the reference count is the same as the given value- Since:
- 2.58
-
refCountDec
Decreases the reference count.If
trueis returned, the reference count reached 0. After this point,rcis 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:
trueif the reference count reached 0, andfalseotherwise- Since:
- 2.58
-
refCountInc
Increases the reference count.- Parameters:
rc- the address of a reference count variable- Since:
- 2.58
-
refCountInit
Initializes a reference count variable to 1.- Parameters:
rc- the address of a reference count variable- Since:
- 2.58
-
refStringAcquire
-
refStringEqual
Compares two ref-counted strings for byte-by-byte equality.It can be passed to
HashTable.new_(org.gnome.glib.HashFunc, org.gnome.glib.EqualFunc)as the key equality function, and behaves exactly the same asstrEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment)(orstrcmp()), but can return slightly faster as it can check the string lengths before checking all the bytes.- Parameters:
str1- a reference counted stringstr2- a reference counted string- Returns:
TRUEif the strings are equal, otherwiseFALSE- Since:
- 2.84
-
refStringLength
Retrieves the length ofstr.- Parameters:
str- a reference counted string- Returns:
- the length of the given string, in bytes
- Since:
- 2.58
-
refStringNew
-
refStringNewIntern
Creates a new reference counted string and copies the content ofstrinto 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
- Since:
- 2.58
-
refStringNewLen
Creates a new reference counted string and copies the contents ofstrinto it, up tolenbytes.Since this function does not stop at nul bytes, it is the caller's responsibility to ensure that
strhas at leastlenaddressable bytes.- Parameters:
str- a stringlen- length ofstrto use, or -1 ifstris nul-terminated- Returns:
- the newly created reference counted string
- Since:
- 2.58
-
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- Since:
- 2.58
-
reloadUserSpecialDirsCache
public static void reloadUserSpecialDirsCache()Resets the cache used for g_get_user_special_dir(), so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.Due to thread safety issues this may cause leaking of strings that were previously returned from g_get_user_special_dir() that can't be freed. We ensure to only leak the data for the directories that actually changed value though.
- Since:
- 2.22
-
remove
A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.
If this function fails on Windows you can't infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().
- Parameters:
filename- a pathname in the GLib file name encoding (UTF-8 on Windows)- Returns:
- 0 if the file was successfully removed, -1 if an error occurred
- Since:
- 2.6
-
rename
A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.See your C library manual for more details about how rename() works on your system. It is not possible in general on Windows to rename a file that is open to some process.
- Parameters:
oldfilename- a pathname in the GLib file name encoding (UTF-8 on Windows)newfilename- a pathname in the GLib file name encoding- Returns:
- 0 if the renaming succeeded, -1 if an error occurred
- Since:
- 2.6
-
returnIfFailWarning
public static void returnIfFailWarning(@Nullable @Nullable String logDomain, String prettyFunction, @Nullable @Nullable String expression) Internal function used to print messages from the publicGLib#returnIfFailandGLib#returnValIfFailmacros.- 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
- Since:
- 2.6
-
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- Since:
- 2.2
-
setError
public static void setError(@Nullable @Nullable Out<GError> err, Quark domain, int code, String format, Object... varargs) Does nothing iferrisnull; iferris non-null, then*errmust benull. A newGErroris created and assigned to*err.- Parameters:
err- a return location for aGErrordomain- 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 iferrisnull; iferris non-null, then*errmust benull. A newGErroris created and assigned to*err. Unlike g_set_error(),messageis not a printf()-style format string. Use this function ifmessagecontains text you don't have control over, that could include printf() escape sequences.- Parameters:
err- a return location for aGErrordomain- error domaincode- error codemessage- error message- Since:
- 2.18
-
setPrgname
Sets the name of the program. This name should not be localized, in contrast to g_set_application_name().If you are using
GApplicationthe 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. By default, 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.
See the GTK documentation for requirements on integrating g_set_prgname() with GTK applications.
- 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 tostderrin all platforms. Before GLib 2.76, this wasNULL.- Parameters:
func- the new print handler orNULLto 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 tostderrin all platforms. Before GLib 2.76, this wasNULL.- Parameters:
func- he new error message handler orNULLto 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:
falseif the environment variable couldn't be set.- Since:
- 2.4
-
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_ERRORdomain.In particular, if
commandLineis an empty string (or a string containing only whitespace),ShellError.EMPTY_STRINGwill be returned. It’s guaranteed thatargvpwill 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:
trueon success,falseif 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
nulland sets the error.The
quotedStringneed 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_ERRORdomain.Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even
\\'- if you want a'in the quoted text, you have to do something like'foo'\\''bar'. Double quotes allow$, `, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.,",\\- Parameters:
quotedString- shell-quoted string- Returns:
- an unquoted string
- Throws:
GErrorException- 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
nullif and only ifmemSizeis 0 - Since:
- 2.10
-
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
nullif and only ifmemSizeis 0 - Since:
- 2.10
-
sliceCopy
Allocates a block of memory from the slice allocator and copiesblockSizebytes into it frommemBlock.memBlockmust be non-nullifblockSizeis 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
nullif and only ifmemSizeis 0 - Since:
- 2.14
-
sliceFree1
Frees a block of memory.The memory must have been allocated via g_slice_alloc() or g_slice_alloc0() and the
blockSizehas to match the size specified upon allocation. Note that the exact release behaviour can be changed with theG_DEBUG=gc-friendlyenvironment variable.If
memBlockisnull, 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- Since:
- 2.10
-
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
nextpointer (similar toGSList). The offset of thenextfield in each block is passed as third argument. Note that the exact release behaviour can be changed with theG_DEBUG=gc-friendlyenvironment variable.If
memChainisnull, 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 thenextfield in the blocks- Since:
- 2.10
-
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 exceedncharacters (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
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 elements- Since:
- 2.82
-
spacedPrimesClosest
public static int spacedPrimesClosest(int num) Gets the smallest prime number from a built-in array of primes which is larger 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 theDISPLAYenvironment variable.Note that the returned
childPidon 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, ornullto inherit parent'sargv- child's argument vectorenvp- child's environment, ornullto inherit parent'sflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()childPid- return location for child process reference, ornull- Returns:
trueon success,falseif 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 theDISPLAYenvironment variable.Note that the returned
childPidon 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, ornullto inherit parent'sargv- child's argument vectorenvp- child's environment, ornullto inherit parent'sflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()childPid- return location for child process reference, ornull- Returns:
trueon success,falseif 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_fdsset to zero, so no FD assignments are used.- Parameters:
workingDirectory- child's current working directory, ornullto 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, ornullto inherit parent's, in the GLib file name encodingflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()childPid- return location for child process ID, ornullstdinFd- file descriptor to use for child's stdin, or-1stdoutFd- file descriptor to use for child's stdout, or-1stderrFd- file descriptor to use for child's stderr, or-1- Returns:
trueon success,falseif an error was set- Throws:
GErrorException- seeGError- Since:
- 2.58
-
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_fdsset to zero, so no FD assignments are used.- Parameters:
workingDirectory- child's current working directory, ornullto 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, ornullto inherit parent's, in the GLib file name encodingflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()childPid- return location for child process ID, ornullstdinFd- file descriptor to use for child's stdin, or-1stdoutFd- file descriptor to use for child's stdout, or-1stderrFd- file descriptor to use for child's stderr, or-1- Returns:
trueon success,falseif an error was set- Throws:
GErrorException- seeGError- Since:
- 2.58
-
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_fdsset to zero, so no FD assignments are used.- Parameters:
workingDirectory- child's current working directory, ornullto 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, ornullto inherit parent's, in the GLib file name encodingflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()childPid- return location for child process ID, ornullstandardInput- return location for file descriptor to write to child's stdin, ornullstandardOutput- return location for file descriptor to read child's stdout, ornullstandardError- return location for file descriptor to read child's stderr, ornull- Returns:
trueon success,falseif 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_fdsset to zero, so no FD assignments are used.- Parameters:
workingDirectory- child's current working directory, ornullto 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, ornullto inherit parent's, in the GLib file name encodingflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()childPid- return location for child process ID, ornullstandardInput- return location for file descriptor to write to child's stdin, ornullstandardOutput- return location for file descriptor to read child's stdout, ornullstandardError- return location for file descriptor to read child's stderr, ornull- Returns:
trueon success,falseif 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.argvshould be anull-terminated array of strings, to be passed as the argument vector for the child. The first string inargvis of course the name of the program to execute. By default, the name of the program must be a full path. Ifflagscontains theSpawnFlags.SEARCH_PATHflag, thePATHenvironment variable is used to search for the executable. Ifflagscontains theSpawnFlags.SEARCH_PATH_FROM_ENVPflag, thePATHvariable fromenvpis used to search for the executable. If both theSpawnFlags.SEARCH_PATHandSpawnFlags.SEARCH_PATH_FROM_ENVPflags are set, thePATHvariable fromenvptakes precedence over the environment variable.If the program name is not a full path and
SpawnFlags.SEARCH_PATHflag 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
childPidon Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.envpis anull-terminated array of strings, where each string has the formKEY=VALUE. This will become the child's environment. Ifenvpisnull, the child inherits its parent's environment.flagsshould be the bitwise OR of any flags you want to affect the function's behaviour. TheSpawnFlags.DO_NOT_REAP_CHILDmeans 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 theSIGCHLDsignal 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_CLOEXECwill be automatically closed in the child process.SpawnFlags.LEAVE_DESCRIPTORS_OPENmeans 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_PATHmeans thatargv[0] need not be an absolute path, it will be looked for in thePATHenvironment variable.SpawnFlags.SEARCH_PATH_FROM_ENVPmeans need not be an absolute path, it will be looked for in thePATHvariable fromenvp. If bothSpawnFlags.SEARCH_PATHandSpawnFlags.SEARCH_PATH_FROM_ENVPare used, the value fromenvptakes precedence over the environment.SpawnFlags.CHILD_INHERITS_STDINmeans 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_NULLexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestdinPipeOutargument is ignored.SpawnFlags.STDOUT_TO_DEV_NULLmeans 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_STDOUTexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestdoutPipeOutargument is ignored.SpawnFlags.STDERR_TO_DEV_NULLmeans 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_STDERRexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestderrPipeOutargument is ignored.It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both
stdoutFdandstderrFd, and include it insourceFdstoo).sourceFdsandtargetFdsallow zero or more FDs from this process to be remapped to different FDs in the spawned process. IfnFdsis greater than zero,sourceFdsandtargetFdsmust both be non-nulland the same length. Each FD insourceFdsis 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,stdoutFdorstderrFdwill overwrite them in the spawned process.sourceFdsis supported on Windows since 2.72.SpawnFlags.FILE_AND_ARGV_ZEROmeans that the first element ofargvis the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() usesargvargv 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[0is not found). Typically themessagefield 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 byposix_spawn(). This has the advantage of avoiding the fork-time performance costs of cloning the parent process address space, and avoiding associated memory overcommit checks that are not relevant in the context of immediately executing a distinct process. This optimized codepath will be used provided that the following conditions are met: 1. %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 theDISPLAY environment variable.- Parameters:
workingDirectory- child's current working directory, ornullto 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, ornullto inherit parent's, in the GLib file name encodingflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()stdinFd- file descriptor to use for child's stdin, or-1stdoutFd- file descriptor to use for child's stdout, or-1stderrFd- file descriptor to use for child's stderr, or-1sourceFds- array of FDs from the parent process to make available in the child processtargetFds- array of FDs to remapsourceFdsto in the child processchildPidOut- return location for child process ID, ornullstdinPipeOut- return location for file descriptor to write to child's stdin, ornullstdoutPipeOut- return location for file descriptor to read child's stdout, ornullstderrPipeOut- return location for file descriptor to read child's stderr, ornull- Returns:
trueon success,falseif an error was set- Throws:
GErrorException- seeGError- Since:
- 2.68
-
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.argvshould be anull-terminated array of strings, to be passed as the argument vector for the child. The first string inargvis of course the name of the program to execute. By default, the name of the program must be a full path. Ifflagscontains theSpawnFlags.SEARCH_PATHflag, thePATHenvironment variable is used to search for the executable. Ifflagscontains theSpawnFlags.SEARCH_PATH_FROM_ENVPflag, thePATHvariable fromenvpis used to search for the executable. If both theSpawnFlags.SEARCH_PATHandSpawnFlags.SEARCH_PATH_FROM_ENVPflags are set, thePATHvariable fromenvptakes precedence over the environment variable.If the program name is not a full path and
SpawnFlags.SEARCH_PATHflag 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
childPidon Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.envpis anull-terminated array of strings, where each string has the formKEY=VALUE. This will become the child's environment. Ifenvpisnull, the child inherits its parent's environment.flagsshould be the bitwise OR of any flags you want to affect the function's behaviour. TheSpawnFlags.DO_NOT_REAP_CHILDmeans 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 theSIGCHLDsignal 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_CLOEXECwill be automatically closed in the child process.SpawnFlags.LEAVE_DESCRIPTORS_OPENmeans 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_PATHmeans thatargv[0] need not be an absolute path, it will be looked for in thePATHenvironment variable.SpawnFlags.SEARCH_PATH_FROM_ENVPmeans need not be an absolute path, it will be looked for in thePATHvariable fromenvp. If bothSpawnFlags.SEARCH_PATHandSpawnFlags.SEARCH_PATH_FROM_ENVPare used, the value fromenvptakes precedence over the environment.SpawnFlags.CHILD_INHERITS_STDINmeans 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_NULLexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestdinPipeOutargument is ignored.SpawnFlags.STDOUT_TO_DEV_NULLmeans 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_STDOUTexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestdoutPipeOutargument is ignored.SpawnFlags.STDERR_TO_DEV_NULLmeans 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_STDERRexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestderrPipeOutargument is ignored.It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both
stdoutFdandstderrFd, and include it insourceFdstoo).sourceFdsandtargetFdsallow zero or more FDs from this process to be remapped to different FDs in the spawned process. IfnFdsis greater than zero,sourceFdsandtargetFdsmust both be non-nulland the same length. Each FD insourceFdsis 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,stdoutFdorstderrFdwill overwrite them in the spawned process.sourceFdsis supported on Windows since 2.72.SpawnFlags.FILE_AND_ARGV_ZEROmeans that the first element ofargvis the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() usesargvargv 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[0is not found). Typically themessagefield 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 byposix_spawn(). This has the advantage of avoiding the fork-time performance costs of cloning the parent process address space, and avoiding associated memory overcommit checks that are not relevant in the context of immediately executing a distinct process. This optimized codepath will be used provided that the following conditions are met: 1. %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 theDISPLAY environment variable.- Parameters:
workingDirectory- child's current working directory, ornullto 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, ornullto inherit parent's, in the GLib file name encodingflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()stdinFd- file descriptor to use for child's stdin, or-1stdoutFd- file descriptor to use for child's stdout, or-1stderrFd- file descriptor to use for child's stderr, or-1sourceFds- array of FDs from the parent process to make available in the child processtargetFds- array of FDs to remapsourceFdsto in the child processchildPidOut- return location for child process ID, ornullstdinPipeOut- return location for file descriptor to write to child's stdin, ornullstdoutPipeOut- return location for file descriptor to read child's stdout, ornullstderrPipeOut- return location for file descriptor to read child's stderr, ornull- Returns:
trueon success,falseif an error was set- Throws:
GErrorException- seeGError- Since:
- 2.68
-
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,
waitStatusmust 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:
trueif child exited successfully,falseotherwise (anderrorwill be set)- Throws:
GErrorException- seeGError- Since:
- 2.34
-
spawnCheckWaitStatus
SeterrorifwaitStatusindicates 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
waitStatusrequired 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
GErroror print a message to standard error. In that common case, this function can be used. Note that the error message inerrorwill contain human-readable information about the wait status.The
domainandcodeoferrorhave 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_ERRORand 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() onwaitStatusdirectly. 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:
trueif child exited successfully,falseotherwise (anderrorwill be set)- Throws:
GErrorException- seeGError- Since:
- 2.70
-
spawnClosePid
On some platforms, notably Windows, theGPidtype 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_PATHflag is enabled, other flags are not. Note thatSpawnFlags.SEARCH_PATHcan 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:
trueon success,falseif error is set- Throws:
GErrorException- seeGError
-
spawnCommandLineSync
public static boolean spawnCommandLineSync(String commandLine, @Nullable @Nullable Out<byte[]> standardOutput, @Nullable @Nullable Out<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
commandLineargument will be parsed by g_shell_parse_argv().Unlike g_spawn_sync(), the
SpawnFlags.SEARCH_PATHflag is enabled. Note thatSpawnFlags.SEARCH_PATHcan 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
waitStatusis 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 acommandLinecontaining 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:
trueon success,falseif 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 @Nullable Out<byte[]> standardOutput, @Nullable @Nullable Out<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
standardOutputandstandardError, if those parameters are non-null. Note that you must set theSpawnFlags.STDOUT_TO_DEV_NULLandSpawnFlags.STDERR_TO_DEV_NULLflags when passingnullforstandardOutputandstandardError.If
waitStatusis 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_CHILDinflags, 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, ornullto inherit parent'sargv- child's argument vector, which must be non-empty andnull-terminatedenvp- child's environment, ornullto inherit parent'sflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()standardOutput- return location for child output, ornullstandardError- return location for child error messages, ornullwaitStatus- return location for child wait status, as returned by waitpid(), ornull- Returns:
trueon success,falseif 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 @Nullable Out<byte[]> standardOutput, @Nullable @Nullable Out<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
standardOutputandstandardError, if those parameters are non-null. Note that you must set theSpawnFlags.STDOUT_TO_DEV_NULLandSpawnFlags.STDERR_TO_DEV_NULLflags when passingnullforstandardOutputandstandardError.If
waitStatusis 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_CHILDinflags, 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, ornullto inherit parent'sargv- child's argument vector, which must be non-empty andnull-terminatedenvp- child's environment, ornullto inherit parent'sflags- flags fromGSpawnFlagschildSetup- function to run in the child just beforeexec()standardOutput- return location for child output, ornullstandardError- return location for child error messages, ornullwaitStatus- return location for child wait status, as returned by waitpid(), ornull- Returns:
trueon success,falseif 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.hmust 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
- Since:
- 2.2
-
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 thestModefield 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
GStatBufwhich is the appropriate struct type depending on the platform and/or compiler being used. On POSIX it is just struct stat, but note that even on POSIX platforms, stat() might be a macro.See your C library manual for more details about stat().
- Parameters:
filename- a pathname in the GLib file name encoding (UTF-8 on Windows)buf- a pointer to a stat struct, which will be filled with the file information- Returns:
- 0 if the information was successfully retrieved, -1 if an error occurred
- Since:
- 2.6
-
stpcpy
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 returnstrueif they are equal. It can be passed to g_hash_table_new() as thekeyEqualFuncparameter, when using non-nullstrings as keys in aGHashTable.This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-
nullstrings. For anull-safe string comparison function, see g_strcmp0().- Parameters:
v1- a keyv2- a key to compare withv1- Returns:
trueif 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
hashFuncparameter, when using non-nullstrings 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
stris ASCII - Since:
- 2.40
-
strMatchString
public static boolean strMatchString(String searchTerm, String potentialHit, boolean acceptAlternates) Checks if a search conducted forsearchTermshould matchpotentialHit.This function calls
strTokenizeAndFold(java.lang.String, java.lang.String, org.javagi.base.Out<java.lang.String[]>)on bothsearchTermandpotentialHit. ASCII alternates are never taken forsearchTermbut will be taken forpotentialHitaccording to the value ofacceptAlternates.A hit occurs when each folded token in
searchTermis 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
potentialHitis a hit - Since:
- 2.40
-
strToAscii
Transliteratestrto plain ASCII.For best results,
strshould 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
stris 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
fromLocaleisnullthen 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
- Since:
- 2.40
-
strTokenizeAndFold
public static String[] strTokenizeAndFold(String string, @Nullable @Nullable String translitLocale, @Nullable @Nullable Out<String[]> asciiAlternates) Tokenizesstringand 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
asciiAlternatesis non-NULLand 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 whichstringoriginatesasciiAlternates- a return location for ASCII alternates- Returns:
- the folded tokens
- Since:
- 2.40
-
strcanon
For each character instring, if the character is not invalidChars, replaces the character withsubstitutor.Modifies
stringin place, and returnstringitself, 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 instringsubstitutor- 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 withs2s2- 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
stringin place. Therefore, it cannot be used on statically allocated strings.The pointer to
stringis 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
stringin place. Therefore, it cannot be used on statically allocated strings.The pointer to
stringis 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
Comparesstr1andstr2likestrcmp().Handles
NULLgracefully by sorting it before non-NULLstrings. Comparing twoNULLpointers returns 0.- Parameters:
str1- a stringstr2- another string- Returns:
- an integer less than, equal to, or greater than zero,
if
str1is <, == or > thanstr2 - Since:
- 2.16
-
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
sourcewith 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 beNULLvarargs- 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 instringtonewDelimiter.Any characters in
stringwhich are found indelimitersare changed to thenewDelimitercharacter. Modifiesstringin place, and returnsstringitself, 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, orNULLto use the standard delimiters defined inGLib.STR_DELIMITERSnewDelimiter- 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
formatcontains%lcor%lsconversions, 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
NULLvalue,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
errnowill 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 Cerrnodocumentation- Returns:
- the string describing the error code
-
strescape
It replaces the following special characters in the stringsourcewith 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 inexceptionsare 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
sourcewith special characters escaped
-
strfreev
Frees an array of strings, as well as each string it contains.If
strArrayisNULL, 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, unlessmsgvalis identical tomsgidand contains a '|' character, in which case a pointer to the substring of msgid after the first '|' character is returned.- Since:
- 2.4
-
strjoin
Joins a number of strings together to form one long string, with the optionalseparatorinserted 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
separatorbetween them
-
strjoinv
Joins an array of strings together to form one long string, with the optionalseparatorinserted between each of them.If
strArrayhas no items, the return value will be an empty string. IfstrArraycontains a single item,separatorwill 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
separatorbetween them
-
strlcat
Portability wrapper that callsstrlcat()on systems which have it, and emulates it otherwise. Appends nul-terminatedsrcstring todest, guaranteeing nul-termination fordest. The total size ofdestwon't exceeddestSize.At most
destSize- 1 characters will be copied. Unlikestrncat(),destSizeis 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 thedestSizecharacters 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 ofdestbuffer 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. Copiessrctodest;destis guaranteed to be nul-terminated;srcmust be nul-terminated;destSizeis the buffer size, not the number of bytes to copy.At most
destSize- 1 characters will be copied. Always nul-terminates (unlessdestSizeis 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 ofdestin 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 firstncharacters of the strings.- Parameters:
s1- string to compare withs2s2- string to compare withs1n- 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 firstnbytes of a string, returning a newly-allocated buffern+ 1 bytes long which will always be nul-terminated. Ifstris less thannbytes long the buffer is padded with nuls. IfstrisNULLit 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
nbytes ofstr
-
strnfill
Creates a new stringlengthbytes 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 stringhaystackfor 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
NULLif not found
-
strrstrLen
Searches the stringhaystackfor 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 ofhaystackin bytes. A length of-1can 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
NULLif 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 thesignaldocumentation- Returns:
- the string describing the signal
-
strsplit
Splits a string into a maximum ofmaxTokenspieces, using the givendelimiter. IfmaxTokensis reached, the remainder ofstringis 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, unlessmaxTokensis reached.maxTokens- the maximum number of pieces to splitstringinto 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
Splitsstringinto 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. IfmaxTokensis 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 splitstringinto. 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. - Since:
- 2.4
-
strstrLen
Searches the stringhaystackfor the first occurrence of the stringneedle, limiting the length of the search tohaystackLenor a nul terminator byte (whichever is reached first).A length of
-1can 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 ofhaystackin bytes, or-1to search it entirelyneedle- the string to search for- Returns:
- a pointer to the found occurrence, or
NULLif 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, org.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, org.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 stringstraccording tostrEqual(java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment).strvmust not beNULL.- Parameters:
strv- an array of strings to search instr- the string to search for- Returns:
- true if
stris an element ofstrv - Since:
- 2.44
-
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).Two empty arrays are considered equal. Neither
strv1norstrv2may beNULL.- Parameters:
strv1- an array of strings to compare tostrv2strv2- an array of strings to compare tostrv1- Returns:
- true if
strv1andstrv2are equal - Since:
- 2.60
-
strvGetType
-
strvLength
Returns the length of an array of strings.strArraymust not beNULL.- Parameters:
strArray- an array of strings- Returns:
- length of
strArray - Since:
- 2.6
-
testAddDataFunc
public static void testAddDataFunc(String testpath, @Nullable @Nullable MemorySegment testData, TestDataFunc testFunc) Creates a new test case.This function is similar to
testCreateCase(java.lang.String, long, java.lang.foreign.MemorySegment, org.gnome.glib.TestFixtureFunc, org.gnome.glib.TestFixtureFunc, org.gnome.glib.TestFixtureFunc). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions oftestpath. ThetestDataargument will be passed as first argument totestFunc.If
testpathincludes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the-pcommand-line option ortestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>).No component of
testpathmay start with a dot (.) if theGLib.TEST_OPTION_ISOLATE_DIRSoption is being used; and it is recommended to do so even if it isn’t.- Parameters:
testpath- a /-separated name for the testtestData- data for thetestFunctestFunc- the test function to invoke for this test- Since:
- 2.16
-
testAddDataFuncFull
public static void testAddDataFuncFull(String testpath, @Nullable @Nullable MemorySegment testData, TestDataFunc testFunc) Creates a new test case.In constract to
testAddDataFunc(java.lang.String, java.lang.foreign.MemorySegment, org.gnome.glib.TestDataFunc), this function is freeingtestDataafter the test run is complete.- Parameters:
testpath- a /-separated name for the testtestData- data fortestFunctestFunc- the test function to invoke for this test- Since:
- 2.34
-
testAddFunc
Creates a new test case.This function is similar to
testCreateCase(java.lang.String, long, java.lang.foreign.MemorySegment, org.gnome.glib.TestFixtureFunc, org.gnome.glib.TestFixtureFunc, org.gnome.glib.TestFixtureFunc). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions oftestpath.If
testpathincludes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the-pcommand-line option ortestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>).No component of
testpathmay start with a dot (.) if theGLib.TEST_OPTION_ISOLATE_DIRSoption is being used; and it is recommended to do so even if it isn’t.- Parameters:
testpath- a /-separated name for the testtestFunc- the test function to invoke for this test- Since:
- 2.16
-
testAddVtable
public static void testAddVtable(String testpath, long dataSize, @Nullable @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) -
testAssertExpectedMessagesInternal
-
testBug
Adds a message to test reports that associates a bug URI with a test case.Bug URIs are constructed from a base URI set with
testBugBase(java.lang.String)andbugUriSnippet. IftestBugBase(java.lang.String)has not been called, it is assumed to be the empty string, so a full URI can be provided totestBug(java.lang.String)instead.See also
testSummary(java.lang.String).Since GLib 2.70, the base URI is not prepended to
bugUriSnippetif it is already a valid URI.- Parameters:
bugUriSnippet- Bug specific bug tracker URI or URI portion.- Since:
- 2.16
-
testBugBase
Specifies the base URI for bug reports.The base URI is used to construct bug report messages for
testMessage(java.lang.String, java.lang.Object...)whentestBug(java.lang.String)is called. Calling this function outside of a test case sets the default base URI for all test cases. Calling it from within a test case changes the base URI for the scope of the test case only. Bug URIs are constructed by appending a bug specific URI portion touriPattern, or by replacing the special string%swithinuriPatternif that is present.If
testBugBase(java.lang.String)is not called, bug URIs are formed solely from the value provided bytestBug(java.lang.String).- Parameters:
uriPattern- the base pattern for bug URIs- Since:
- 2.16
-
testBuildFilename
Creates the pathname to a data file that is required for a test.This function is conceptually similar to
buildFilename(java.lang.String, java.lang.Object...)except that the first argument has been replaced with aGLib.TestFileTypeargument.The data file should either have been distributed with the module containing the test (
GLib.TestFileType.distor built as part of the buildcsystem of that module (GLib.TestFileType.built).In order for this function to work in srcdir != builddir situations, the
G_TEST_SRCDIRandG_TEST_BUILDDIRenvironment variables need to have been defined. As of 2.38, this is done by the glib.mk that is included in GLib. Please ensure that your copy is up to date before using this function.In case neither variable is set, this function will fall back to using the dirname portion of
argv[0], possibly removing ".libs". This allows for casual running of tests directly from the commandline in the srcdir == builddir case and should also support running of installed tests, assuming the data files have been installed in the same relative path as the test binary.- Parameters:
fileType- the type of file (built vs. distributed)firstPath- the first segment of the pathnamevarargs-NULL-terminated additional path segments- Returns:
- the path of the file, to be freed using
free(java.lang.foreign.MemorySegment) - Since:
- 2.38
-
testCreateCase
public static TestCase testCreateCase(String testName, long dataSize, @Nullable @Nullable MemorySegment testData, TestFixtureFunc dataSetup, TestFixtureFunc dataTest, TestFixtureFunc dataTeardown) Creates a newGLib.TestCase.This API is fairly low level, and calling
GLib#testAddortestAddFunc(java.lang.String, org.gnome.glib.TestFunc)is preferable.When this test is executed, a fixture structure of size
dataSizewill be automatically allocated and filled with zeros. ThendataSetupis called to initialize the fixture. After fixture setup, the actual test functiondataTestis called. Once the test run completes, the fixture structure is torn down by callingdataTeardownand after that the memory is automatically released by the test framework.Splitting up a test run into fixture setup, test function and fixture teardown is most useful if the same fixture type is used for multiple tests. In this cases,
testCreateCase(java.lang.String, long, java.lang.foreign.MemorySegment, org.gnome.glib.TestFixtureFunc, org.gnome.glib.TestFixtureFunc, org.gnome.glib.TestFixtureFunc)will be called with the same type of fixture (thedataSizeargument), but varyingtestNameanddataTestarguments.- 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 test case
- Since:
- 2.16
-
testCreateSuite
-
testDisableCrashReporting
public static void testDisableCrashReporting()Attempts to disable system crash reporting infrastructure.This function should be called before exercising code paths that are expected or intended to crash, to avoid wasting resources in system-wide crash collection infrastructure such as systemd-coredump or abrt.
- Since:
- 2.78
-
testExpectMessage
public static void testExpectMessage(@Nullable @Nullable String logDomain, Set<LogLevelFlags> logLevel, String pattern) Indicates that a message with the givenlogDomainandlogLevel, 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_STRUCTUREDdefined). It will not work with the structured logging API. See Testing for Messages.Use
GLib#testAssertExpectedMessagesto 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#errormessages, sinceGLib#errorintentionally 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_DEBUGare 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)- Since:
- 2.34
-
testExpectMessage
public static void testExpectMessage(@Nullable @Nullable String logDomain, LogLevelFlags logLevel, String pattern) Indicates that a message with the givenlogDomainandlogLevel, 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_STRUCTUREDdefined). It will not work with the structured logging API. See Testing for Messages.Use
GLib#testAssertExpectedMessagesto 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#errormessages, sinceGLib#errorintentionally 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_DEBUGare 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)- Since:
- 2.34
-
testFail
public static void testFail()Indicates that a test failed.This function can be called multiple times from the same test. You can use this function if your test failed in a recoverable way.
Do not use this function if the failure of a test could cause other tests to malfunction.
Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.
If not called from inside a test, this function does nothing.
Note that unlike
testSkip(java.lang.String)andtestIncomplete(java.lang.String), this function does not log a message alongside the test failure. If details of the test failure are available, either log them withtestMessage(java.lang.String, java.lang.Object...)beforetestFail(), or usetestFailPrintf(java.lang.String, java.lang.Object...)instead.- Since:
- 2.30
-
testFailPrintf
Indicates that a test failed and records a message.Also see
testFail().The message is formatted as if by
strdupPrintf(java.lang.String, java.lang.Object...).- Parameters:
format- the format stringvarargs- printf-like arguments toformat- Since:
- 2.70
-
testFailed
public static boolean testFailed()Returns whether a test has already failed.This will be the case when
testFail(),testIncomplete(java.lang.String)ortestSkip(java.lang.String)have been called, but also if an assertion has failed.This can be useful to return early from a test if continuing after a failed assertion might be harmful.
The return value of this function is only meaningful if it is called from inside a test function.
- Returns:
- true if the test has failed
- Since:
- 2.38
-
testGetDir
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
- Since:
- 2.38
-
testGetFilename
Gets the pathname to a data file that is required for a test.This is the same as
testBuildFilename(org.gnome.glib.TestFileType, java.lang.String, java.lang.Object...)with two differences. The first difference is that you must only use this function from within a testcase function. The second difference is that you need not free the return value — it will be automatically freed when the testcase finishes running.It is safe to use this function from a thread inside of a testcase but you must ensure that all such uses occur before the main testcase function returns (ie: it is best to ensure that all threads have been joined).
- Parameters:
fileType- the type of file (built vs. distributed)firstPath- the first segment of the pathnamevarargs-NULL-terminated additional path segments- Returns:
- the path, automatically freed at the end of the testcase
- Since:
- 2.38
-
testGetPath
Gets the test path for the test currently being run.In essence, it will be the same string passed as the first argument to e.g.
GLib#testAddwhen the test was added.This function returns a valid string only within a test function.
Note that this is a test path, not a file system path.
- Returns:
- the test path for the test currently being run
- Since:
- 2.68
-
testGetRoot
Gets the toplevel test suite for the test path API.- Returns:
- the toplevel test suite
- Since:
- 2.16
-
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- Since:
- 2.38
-
testIncompletePrintf
Indicates that a test failed because of some incomplete functionality.Equivalent to
testIncomplete(java.lang.String), but the explanation is formatted as if bystrdupPrintf(java.lang.String, java.lang.Object...).- Parameters:
format- the format stringvarargs- printf-like arguments toformat- Since:
- 2.70
-
testInit
Initializes the GLib testing framework.This includes seeding the test random number generator, setting the program name, and parsing test-related commandline args.
This should be called before calling any other
g_test_*()functions.The following arguments are understood:
-l: List test cases available in a test executable.--seed=SEED: Provide a random seed to reproduce test runs using random numbers.--verbose: Run tests verbosely.-q,--quiet: Run tests quietly.-p PATH: Execute all tests matching the given path.-s PATH: Skip all tests matching the given path. This can also be used to force a test to run that would otherwise be skipped (ie, a test whose name contains "/subprocess").-m {perf|slow|thorough|quick|undefined|no-undefined}: Execute tests according to these test modes:
perf: Performance tests, may take long and report results (off by default).slow,thorough: Slow and thorough tests, may take quite long and maximize coverage (off by default).quick: Quick tests, should run really quickly and give good coverage (the default).undefined: Tests for undefined behaviour, may provoke programming errors undertestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)ortestExpectMessage(java.lang.String, java.util.Set<org.gnome.glib.LogLevelFlags>, java.lang.String)to check that appropriate assertions or warnings are given (the default).no-undefined: Avoid tests for undefined behaviour.--debug-log: Debug test logging output.
Any parsed arguments are removed from
argv, andargcis adjust accordingly.The following options are supported:
G_TEST_OPTION_NO_PRGNAME: Causes g_test_init() to not callsetPrgname(java.lang.String). Since. 2.84G_TEST_OPTION_ISOLATE_DIRS: Creates a unique temporary directory for each unit test and sets XDG directories to point there for the duration of the unit test. SeeGLib.TEST_OPTION_ISOLATE_DIRS.G_TEST_OPTION_NONFATAL_ASSERTIONS: This has the same effect astestSetNonfatalAssertions(). Since 2.84
Since 2.58, if tests are compiled with
G_DISABLE_ASSERTdefined,g_test_init()will print an error and exit. This is to prevent no-op tests from being executed, asGLib#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_ASSERTdefined.- Parameters:
argc- address of theargcparameter ofmain()argv- address of theargvparameter ofmain()varargs-NULL-terminated list of special options- Since:
- 2.16
-
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.- Since:
- 2.22
-
testLogTypeName
-
testMaximizedResult
Reports the result of a performance or measurement test.The test should generally strive to maximize the reported quantities (larger values are better than smaller ones), this and
maximizedQuantitycan determine sorting order for test result reports.- Parameters:
maximizedQuantity- the reported valueformat- the format string of the report messagevarargs- printf-like arguments toformat- Since:
- 2.16
-
testMessage
-
testMinimizedResult
Reports the result of a performance or measurement test.The test should generally strive to minimize the reported quantities (smaller values are better than larger ones), this and
minimizedQuantitycan determine sorting order for test result reports.- Parameters:
minimizedQuantity- the reported valueformat- the format string of the report messagevarargs- printf-like arguments toformat- Since:
- 2.16
-
testQueueDestroy
Enqueues a callbackdestroyFuncto 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
Abefore callbackBwill causeB()to be called beforeA()during teardown.- Parameters:
destroyData- destroy callback data- Since:
- 2.16
-
testQueueFree
Enqueues a pointer to be released withfree(java.lang.foreign.MemorySegment)during the next teardown phase.This is equivalent to calling
testQueueDestroy(java.lang.foreign.MemorySegment)with a destroy callback offree(java.lang.foreign.MemorySegment).- Parameters:
gfreePointer- the pointer to be stored- Since:
- 2.16
-
testRandDouble
public static double testRandDouble()Gets a reproducible random floating point number.See
testRandInt()for details on test case random numbers.- Returns:
- a random number from the seeded random number generator
- Since:
- 2.16
-
testRandDoubleRange
public static double testRandDoubleRange(double rangeStart, double rangeEnd) Gets a reproducible random floating point number out of a specified range.See
testRandInt()for details on test case random numbers.- Parameters:
rangeStart- the minimum value returned by this functionrangeEnd- the minimum value not returned by this function- Returns:
- a number with
rangeStart<= number <rangeEnd - Since:
- 2.16
-
testRandInt
public static int testRandInt()Gets a reproducible random integer number.The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the --seed option is given when starting test programs.
For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make --seed effective for all test cases.
- Returns:
- a random number from the seeded random number generator
- Since:
- 2.16
-
testRandIntRange
public static int testRandIntRange(int begin, int end) Gets a reproducible random integer number out of a specified range.See
testRandInt()for details on test case random numbers.- Parameters:
begin- the minimum value returned by this functionend- the smallest value not to be returned by this function- Returns:
- a number with
begin<= number <end - Since:
- 2.16
-
testRun
public static int testRun()Runs all tests under the toplevel suite.The toplevel suite can be retrieved with
testGetRoot().Similar to
testRunSuite(org.gnome.glib.TestSuite), the test cases to be run are filtered according to test path arguments (-p testpathand-s testpath) as parsed bytestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).testRunSuite(org.gnome.glib.TestSuite)ortestRun()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 (sincetestRun()would run the first "/foo" suite, then the "/bar" suite, then the second "/foo" suite). As of 2.36, this bug is fixed, and adding the tests in that order would result in a running order of "/foo/simple", "/foo/using-bar", "/bar/simple". If this new ordering is sub-optimal (because it puts more-complicated tests before simpler ones, making it harder to figure out exactly what has failed), you can fix it by changing the test paths to group tests by suite in a way that will result in the desired running order. Eg, "/simple/foo", "/simple/bar", "/complex/foo-using-bar".However, you should never make the actual result of a test depend on the order that tests are run in. If you need to ensure that some particular code runs before or after a given test case, use
GLib#testAdd, which lets you specify setup and teardown functions.If all tests are skipped or marked as incomplete (expected failures), this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.
- Returns:
- 0 on success, 1 on failure (assuming it returns at all), 0 or 77 if all tests were skipped or marked as incomplete
- Since:
- 2.16
-
testRunSuite
Executes the tests withinsuiteand all nested test suites.The test suites to be executed are filtered according to test path arguments (
-p testpathand-s testpath) as parsed bytestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...). See thetestRun()documentation for more information on the order that tests are run in.testRunSuite(org.gnome.glib.TestSuite)ortestRun()may only be called once in a program.- Parameters:
suite- a test suite- Returns:
- 0 on success
- Since:
- 2.16
-
testSetNonfatalAssertions
public static void testSetNonfatalAssertions()Changes the behaviour of the various assertion macros.The
g_assert_*()macros,g_test_assert_expected_messages()and the variousg_test_trap_assert_*()macros are changed to not abort to program.Instead, they will call
testFail()and continue. (This also changes the behavior oftestFail()so that it will not cause the test program to abort after completing the failed test.)Note that the
GLib#assertNotReachedandGLib#assert_macros are not affected by this.This function can only be called after
testInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...).- Since:
- 2.38
-
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- Since:
- 2.38
-
testSkipPrintf
Indicates that a test was skipped.Equivalent to
testSkip(java.lang.String), but the explanation is formatted as if bystrdupPrintf(java.lang.String, java.lang.Object...).- Parameters:
format- the format stringvarargs- printf-like arguments toformat- Since:
- 2.70
-
testSubprocess
public static boolean testSubprocess()Returns true if the test program is running undertestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>).- Returns:
- true if the test program is running under
testTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>) - Since:
- 2.38
-
testSummary
Sets the summary for a test.This may be included in test report output, and is useful documentation for anyone reading the source code or modifying a test in future. It must be a single line, and it should summarise what the test checks, and how.
This should be called at the top of a test function.
For example:
static void test_array_sort (void) { g_test_summary ("Test my_array_sort() sorts the array correctly and stably, " "including testing zero length and one-element arrays."); // ... }See also
testBug(java.lang.String).- Parameters:
summary- summary of the test purpose- Since:
- 2.62
-
testTimerElapsed
public static double testTimerElapsed()Gets the number of seconds since the last start of the timer withtestTimerStart().- Returns:
- the time since the last start of the timer in seconds
- Since:
- 2.16
-
testTimerLast
public static double testTimerLast()Reports the last result oftestTimerElapsed().- Returns:
- the last result of
testTimerElapsed() - Since:
- 2.16
-
testTimerStart
public static void testTimerStart()Starts a timing test.Call
testTimerElapsed()when the task is supposed to be done. Call this function again to restart the timer.- Since:
- 2.16
-
testTrapAssertions
-
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 funcGLib.test_trap_subprocess] instead.Forks the current test program to execute a test case that might not return or that might abort.If
usecTimeoutis non-0, the forked test case is aborted and considered failing if its run time exceeds it.The forking behavior can be configured with
GLib.TestTrapFlagsflags.In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.
static void test_fork_patterns (void) { if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) { g_print ("some stdout text: somagic17 "); g_printerr ("some stderr text: semagic43 "); exit (0); // successful test run } g_test_trap_assert_passed (); g_test_trap_assert_stdout ("*somagic17*"); g_test_trap_assert_stderr ("*semagic43*"); }- Parameters:
usecTimeout- timeout for the forked test in microsecondstestTrapFlags- flags to modify forking behaviour- Returns:
- true for the forked child and false for the executing parent process.
- Since:
- 2.16
-
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 funcGLib.test_trap_subprocess] instead.Forks the current test program to execute a test case that might not return or that might abort.If
usecTimeoutis non-0, the forked test case is aborted and considered failing if its run time exceeds it.The forking behavior can be configured with
GLib.TestTrapFlagsflags.In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.
static void test_fork_patterns (void) { if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) { g_print ("some stdout text: somagic17 "); g_printerr ("some stderr text: semagic43 "); exit (0); // successful test run } g_test_trap_assert_passed (); g_test_trap_assert_stdout ("*somagic17*"); g_test_trap_assert_stderr ("*semagic43*"); }- Parameters:
usecTimeout- timeout for the forked test in microsecondstestTrapFlags- flags to modify forking behaviour- Returns:
- true for the forked child and false for the executing parent process.
- Since:
- 2.16
-
testTrapHasPassed
public static boolean testTrapHasPassed()Checks the result of the lasttestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)call.- Returns:
- true if the last test subprocess terminated successfully
- Since:
- 2.16
-
testTrapReachedTimeout
public static boolean testTrapReachedTimeout()Checks the result of the lasttestTrapSubprocess(java.lang.String, long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)call.- Returns:
- true if the last test subprocess got killed due to a timeout
- Since:
- 2.16
-
testTrapSubprocess
public static void testTrapSubprocess(@Nullable @Nullable String testPath, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPathin a subprocess.This is equivalent to calling
testTrapSubprocessWithEnvp(java.lang.String, java.lang.String[], long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)withenvpset toNULL. See the documentation for that function for full details.- Parameters:
testPath- test to run in a subprocessusecTimeout- timeout for the subprocess test in microseconds.testFlags- flags to modify subprocess behaviour- Since:
- 2.38
-
testTrapSubprocess
public static void testTrapSubprocess(@Nullable @Nullable String testPath, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPathin a subprocess.This is equivalent to calling
testTrapSubprocessWithEnvp(java.lang.String, java.lang.String[], long, java.util.Set<org.gnome.glib.TestSubprocessFlags>)withenvpset toNULL. See the documentation for that function for full details.- Parameters:
testPath- test to run in a subprocessusecTimeout- timeout for the subprocess test in microseconds.testFlags- flags to modify subprocess behaviour- Since:
- 2.38
-
testTrapSubprocessWithEnvp
public static void testTrapSubprocessWithEnvp(@Nullable @Nullable String testPath, @Nullable @Nullable String[] envp, long usecTimeout, Set<TestSubprocessFlags> testFlags) Respawns the test program to run onlytestPathin a subprocess with a given environment.This can be used for a test case that might not return, or that might abort.
If
testPathisNULLthen the same test is re-run in a subprocess. You can usetestSubprocess()to determine whether the test is in a subprocess or not.testPathcan 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
envpisNULL, the parent process’ environment will be inherited.If
usecTimeoutis non-0, the test subprocess is aborted and considered failing if its run time exceeds it.The subprocess behavior can be configured with
GLib.TestSubprocessFlagsflags.You can use methods such as
GLib#testTrapAssertPassed,GLib#testTrapAssertFailed, andGLib#testTrapAssertStderrto check the results of the subprocess. (But note thatGLib#testTrapAssertStdoutandGLib#testTrapAssertStderrcannot be used iftestFlagsspecifies that the child should inherit the parent stdout/stderr.)If your
main ()needs to behave differently in the subprocess, you can calltestSubprocess()(after callingtestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...)) to see whether you are in a subprocess.Internally, this function tracks the child process using
childWatchSourceNew(org.gnome.glib.Pid), so your process must not ignoreSIGCHLD, 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 inusecTimeout- timeout for the subprocess test in microsecondstestFlags- flags to modify subprocess behaviour- Since:
- 2.80
-
testTrapSubprocessWithEnvp
public static void testTrapSubprocessWithEnvp(@Nullable @Nullable String testPath, @Nullable @Nullable String[] envp, long usecTimeout, TestSubprocessFlags... testFlags) Respawns the test program to run onlytestPathin a subprocess with a given environment.This can be used for a test case that might not return, or that might abort.
If
testPathisNULLthen the same test is re-run in a subprocess. You can usetestSubprocess()to determine whether the test is in a subprocess or not.testPathcan 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
envpisNULL, the parent process’ environment will be inherited.If
usecTimeoutis non-0, the test subprocess is aborted and considered failing if its run time exceeds it.The subprocess behavior can be configured with
GLib.TestSubprocessFlagsflags.You can use methods such as
GLib#testTrapAssertPassed,GLib#testTrapAssertFailed, andGLib#testTrapAssertStderrto check the results of the subprocess. (But note thatGLib#testTrapAssertStdoutandGLib#testTrapAssertStderrcannot be used iftestFlagsspecifies that the child should inherit the parent stdout/stderr.)If your
main ()needs to behave differently in the subprocess, you can calltestSubprocess()(after callingtestInit(java.lang.foreign.MemorySegment, java.lang.String[], java.lang.Object...)) to see whether you are in a subprocess.Internally, this function tracks the child process using
childWatchSourceNew(org.gnome.glib.Pid), so your process must not ignoreSIGCHLD, 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 inusecTimeout- timeout for the subprocess test in microsecondstestFlags- flags to modify subprocess behaviour- Since:
- 2.80
-
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. Thenotifyfunction 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.MainContextusingSource.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_DEFAULTandGLib.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.
-
timeoutAddSeconds
Sets a function to be called at regular intervals, withpriority.The function is called repeatedly until it returns
GLib.SOURCE_REMOVEorfalse, 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, theintervalto 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
intervalSee 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_DEFAULTandGLib.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.
- Since:
- 2.14
-
timeoutSourceNew
Creates a new timeout source.The source will not initially be associated with any
GLib.MainContextand 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.MainContextand 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
- Since:
- 2.14
-
tryMalloc
Attempts to allocatenBytes, and returnsnullon 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 returnsnullon failure. Contrast with g_malloc0(), which aborts the program on failure.- Parameters:
nBytes- number of bytes to allocate- Returns:
- the allocated memory, or
null - Since:
- 2.8
-
tryMalloc0N
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 - Since:
- 2.24
-
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. - Since:
- 2.24
-
tryRealloc
Attempts to reallocmemto a new size,nBytes, and returnsnullon failure. Contrast with g_realloc(), which aborts the program on failure.If
memisnull, 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. - Since:
- 2.24
-
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 nul character (U+0000) 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 ofgunichar2written, orNULL. The value stored here does not include the trailing nul.- Returns:
- a pointer to a newly allocated UTF-16 string.
This value must be freed with
free(java.lang.foreign.MemorySegment). - 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 nul 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 nul byte.- Returns:
- a pointer to a newly allocated UTF-8 string.
This value must be freed with
free(java.lang.foreign.MemorySegment). If an error occurs,itemsReadwill be set to the position of the first invalid input character. - Throws:
GErrorException- seeGError
-
unicharBreakType
Determines the break type ofc.cshould be a Unicode character (to derive a character from UTF-8 encoded text, use g_utf8_get_char()). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally you would use a function such as pango_break() instead of caring about break types yourself.- Parameters:
c- a Unicode character- Returns:
- the break type of
c
-
unicharCombiningClass
public static int unicharCombiningClass(int uc) Determines the canonical combining class of a Unicode character.- Parameters:
uc- a Unicode character- Returns:
- the combining class of the character
- Since:
- 2.14
-
unicharCompose
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
aorbequal 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
aandbdo not compose a new character,chis set to zero.See UAX#15 for details.
- Parameters:
a- a Unicode characterb- a Unicode characterch- return location for the composed character- Returns:
trueif the characters could be composed- Since:
- 2.30
-
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
*bwill be set to zero.If
chis not decomposable,*ais set tochand*bis set to zero.Note that the way Unicode decomposition pairs are defined, it is guaranteed that
bwould not decompose further, butamay 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 ofchb- return location for the second component ofch- Returns:
trueif the character could be decomposed- Since:
- 2.30
-
unicharDigitValue
public static int unicharDigitValue(int c) Determines the numeric value of a character as a decimal digit.- Parameters:
c- a Unicode character- Returns:
- If
cis 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, passtrueforcompat; for canonical decomposition passfalseforcompat.The decomposed sequence is placed in
result. Only up toresultLencharacters 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, ornullresultLen- length ofresult- Returns:
- the length of the full decomposition.
- Since:
- 2.30
-
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
chhas the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image ofch's glyph andmirroredChis 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:
trueifchhas a mirrored character,falseotherwise- Since:
- 2.4
-
unicharGetScript
Looks up theGUnicodeScriptfor a particular character (as defined by Unicode Standard Annex \\24). No check is made forchbeing 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
GUnicodeScriptfor the character. - Since:
- 2.14
-
unicharIsalnum
public static boolean unicharIsalnum(int c) Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with g_utf8_get_char().- Parameters:
c- a Unicode character- Returns:
trueifcis 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:
trueifcis 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:
trueifcis 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:
trueif 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:
trueifcis a digit
-
unicharIsgraph
public static boolean unicharIsgraph(int c) Determines whether a character is printable and not a space (returnsfalsefor control characters, format characters, and spaces). g_unichar_isprint() is similar, but returnstruefor spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().- Parameters:
c- a Unicode character- Returns:
trueifcis 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:
trueifcis 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:
trueifcis a mark character- Since:
- 2.14
-
unicharIsprint
public static boolean unicharIsprint(int c) Determines whether a character is printable. Unlike g_unichar_isgraph(), returnstruefor spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().- Parameters:
c- a Unicode character- Returns:
trueifcis 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:
trueifcis 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:
trueifcis 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:
trueif the character is titlecase
-
unicharIsupper
public static boolean unicharIsupper(int c) Determines if a character is uppercase.- Parameters:
c- a Unicode character- Returns:
trueifcis 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:
trueif 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:
trueif the character is wide in legacy East Asian locales- Since:
- 2.12
-
unicharIsxdigit
public static boolean unicharIsxdigit(int c) Determines if a character is a hexadecimal digit.- Parameters:
c- a Unicode character.- Returns:
trueif 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 istruefor 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:
trueif the character has zero width- Since:
- 2.14
-
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
cto lower case. Ifcis not an upperlower or titlecase character, or has no lowercase equivalentcis 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
cto titlecase. Ifcis not an uppercase or lowercase character,cis returned unchanged.
-
unicharToupper
public static int unicharToupper(int c) Converts a character to uppercase.- Parameters:
c- a Unicode character- Returns:
- the result of converting
cto uppercase. Ifcis not a lowercase or titlecase character, or has no upper case equivalentcis 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 whetherchis a valid Unicode character.Some possible integer values of
chwill not be valid. U+0000 is considered a valid character, though it’s normally a string terminator.- Parameters:
ch- a Unicode character- Returns:
TRUEifchis 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
cis 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.
resultLenis 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 byconditionbecomes true forfd.functionwill be called when the specified IO condition becomestrue. The function is expected to clear whatever event caused the IO condition to become true and returntruein order to be notified when it happens again. Iffunctionreturnsfalsethen 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 onfdfunction- aGUnixFDSourceFunc- Returns:
- the ID (greater than 0) of the event source
- Since:
- 2.36
-
unixFdAdd
Sets a function to be called when the IO condition, as specified byconditionbecomes true forfd.functionwill be called when the specified IO condition becomestrue. The function is expected to clear whatever event caused the IO condition to become true and returntruein order to be notified when it happens again. Iffunctionreturnsfalsethen 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 onfdfunction- aGUnixFDSourceFunc- Returns:
- the ID (greater than 0) of the event source
- Since:
- 2.36
-
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 byconditionbecomes 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
GDestroyNotifyforuserData.- Parameters:
priority- the priority of the sourcefd- a file descriptorcondition- IO conditions to watch for onfdfunction- aGUnixFDSourceFunc- Returns:
- the ID (greater than 0) of the event source
- Since:
- 2.36
-
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 byconditionbecomes 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
GDestroyNotifyforuserData.- Parameters:
priority- the priority of the sourcefd- a file descriptorcondition- IO conditions to watch for onfdfunction- aGUnixFDSourceFunc- Returns:
- the ID (greater than 0) of the event source
- Since:
- 2.36
-
unixFdSourceNew
Creates aGSourceto 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
GSourcemust have typeGUnixFDSourceFunc.- Parameters:
fd- a file descriptorcondition- I/O conditions to watch for onfd- Returns:
- the newly created
GSource - Since:
- 2.36
-
unixFdSourceNew
Creates aGSourceto 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
GSourcemust have typeGUnixFDSourceFunc.- Parameters:
fd- a file descriptorcondition- I/O conditions to watch for onfd- Returns:
- the newly created
GSource - Since:
- 2.36
-
unixGetPasswdEntry
Get thepasswdfile entry for the givenuserNameusinggetpwnam_r(). This can fail if the givenuserNamedoesn’t exist.The returned
struct passwdhas 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 passwdis freed.This function is safe to call from multiple threads concurrently.
You will need to include
pwd.hto get the definition ofstruct passwd.- Parameters:
userName- the username to get the passwd file entry for- Returns:
- passwd entry, or
nullon error; free the returned value with g_free() - Throws:
GErrorException- seeGError- Since:
- 2.64
-
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_CLOEXECwas supported — if you wanted to configureO_NONBLOCKthen that had to be done separately withfcntl().Since GLib 2.80, the constants
UnixPipeEnd.READandUnixPipeEnd.WRITEcan 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_CLOEXECin, rather thanFD_CLOEXEC, as that matches the underlyingpipe()API more closely. Prior to 2.78, onlyFD_CLOEXECwas supported. Support forFD_CLOEXECmay be deprecated and removed in future.- Parameters:
fds- Array of two integersflags- Bitfield of file descriptor flags, as for fcntl()- Returns:
trueon success,falseif not (and errno will be set).- Throws:
GErrorException- seeGError- Since:
- 2.30
-
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:
trueif successful- Throws:
GErrorException- seeGError- Since:
- 2.30
-
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_DEFAULTandG_PRIORITY_HIGH.signum- Signal numberhandler- Callback- Returns:
- An ID (greater than 0) for the event source
- Since:
- 2.30
-
unixSignalSourceNew
Create aGSourcethat will be dispatched upon delivery of the UNIX signalsignum. In GLib versions before 2.36, onlySIGHUP,SIGINT,SIGTERMcan be monitored. In GLib 2.36,SIGUSR1andSIGUSR2were added. In GLib 2.54,SIGWINCHwas 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
SIGTERMcleanly; 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
GMainContextand must be added to one with g_source_attach() before it will be executed.- Parameters:
signum- A signal number- Returns:
- A newly created
GSource - Since:
- 2.30
-
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
- Since:
- 2.6
-
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 '='- Since:
- 2.4
-
usleep
public static void usleep(int microseconds) Pauses the current thread for the given number of microseconds.There are 1 million microseconds per second (represented by the
G_USEC_PER_SECmacro). 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, thenGLib.ConvertError.PARTIAL_INPUTwill be returned in casestrcontains 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 nul character.- Returns:
- a pointer to a newly allocated UCS-4 string.
This value must be freed with
free(java.lang.foreign.MemorySegment). - 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 nul byte.
Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially.
convert(byte[], java.lang.String, java.lang.String, org.javagi.base.Out<java.lang.Long>)can be used to convert a byte buffer of UTF-16 data of ambiguous endianness.Further note that this function does not validate the result string; it may (for example) include embedded nul characters. The only validation done by this function is to ensure that the input can be correctly interpreted as UTF-16, i.e. it doesn’t contain unpaired surrogates or partial character sequences.
- Parameters:
str- a UTF-16 encoded stringitemsRead- location to store number of words read, orNULL. IfNULL, thenGLib.ConvertError.PARTIAL_INPUTwill be returned in casestrcontains 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 nul byte. It’s guaranteed to be non-negative.- Returns:
- a pointer to a newly allocated UTF-8 string.
This value must be freed with
free(java.lang.foreign.MemorySegment). - 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 ifstris 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. 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
str1compares beforestr2, 0 if they compare equal, > 0 ifstr1compares 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.
Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.
- Parameters:
str- a UTF-8 encoded string.len- length ofstr, in bytes, or -1 ifstris nul-terminated.- Returns:
- a newly allocated string. The contents of the string are only meant to be used when sorting. This string should be freed with g_free() when you are done with it.
-
utf8CollateKeyForFilename
Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".
Note that this function depends on the current locale.
Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.
- Parameters:
str- a UTF-8 encoded string.len- length ofstr, in bytes, or -1 ifstris nul-terminated.- Returns:
- a newly allocated string. The contents of the string are only meant to be used when sorting. This string should be freed with g_free() when you are done with it.
- Since:
- 2.8
-
utf8FindNextChar
Finds the start of the next UTF-8 character in the string afterp.pdoes 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
endisNULL, the return value will never beNULL: if the end of the string is reached, a pointer to the terminating nul byte is returned. Ifendis non-NULL, the return value will beNULLif 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, orNULLto indicate that the string is nul-terminated- Returns:
- a pointer to the found character or
NULLifendis set and is reached
-
utf8FindPrevChar
Given a positionpwith a UTF-8 encoded stringstr, find the start of the previous UTF-8 character starting beforep. ReturnsNULLif no UTF-8 characters are present instrbeforep.pdoes 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
-
utf8GetChar
Converts a sequence of bytes encoded as UTF-8 to a Unicode character.If
pdoes 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 useutf8GetCharValidated(java.lang.String, long)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
utf8GetCharValidated(java.lang.String, long)returns(gunichar)-2ifmaxLenis 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-1ifpis nul-terminated- Returns:
- the resulting character. If
ppoints to a partial sequence at the end of a string that could begin a valid character (or ifmaxLenis zero), returns(gunichar)-2; otherwise, ifpdoes 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 ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.- Returns:
- a valid UTF-8 string whose content resembles
str - Since:
- 2.52
-
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, otherwisenullis returned. You should generally call g_utf8_normalize() before comparing two Unicode strings.The normalization mode
NormalizeMode.DEFAULTonly standardizes differences that do not affect the text content, such as the above-mentioned accent representation.NormalizeMode.ALLalso 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_COMPOSEandNormalizeMode.ALL_COMPOSEare likeNormalizeMode.DEFAULTandNormalizeMode.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 ifstris nul-terminated.mode- the type of normalization to perform.- Returns:
- a newly allocated string, that
is the normalized form of
str, ornullifstris 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
offsetto step backwards. It is usually worth stepping backwards from the end instead of forwards ifoffsetis 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 thatoffsetis within string boundaries before calling that function. Callutf8Strlen(java.lang.String, long)when unsure. This limitation exists as this function is called frequently during text rendering and therefore has to be as fast as possible.- Parameters:
str- a UTF-8 encoded 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
posto 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.pdoes 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. Ifpmight be the first character of the string, you must useutf8FindPrevChar(java.lang.String, java.lang.String)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 tolenbytes.If
lenis-1, allow unbounded search.- Parameters:
p- a nul-terminated UTF-8 encoded stringlen- the maximum length ofpc- a Unicode character- Returns:
NULLif 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 ifstris 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. Ifmaxis less than 0, then the string is assumed to be nul-terminated. Ifmaxis 0,pwill not be examined and may beNULL. Ifmaxis greater than 0, up tomaxbytes are examined- Returns:
- the length of the string in characters
-
utf8Strncpy
Like the standard Cstrncpy()function, but copies a given number of characters instead of a given number of bytes.The
srcstring must be valid UTF-8 encoded text. (Useutf8Validate(byte[], org.javagi.base.Out<java.lang.String>)on all text before trying to use UTF-8 utility functions with it.)Note you must ensure
destis at least 4 *n+ 1 to fit the largest possible UTF-8 characters- Parameters:
dest- buffer to fill with characters fromsrcsrc- 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 tolenbytes.If
lenis-1, allow unbounded search.- Parameters:
p- a nul-terminated UTF-8 encoded stringlen- the maximum length ofpc- a Unicode character- Returns:
NULLif 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.strmust be valid UTF-8 encoded text. (Useutf8Validate(byte[], org.javagi.base.Out<java.lang.String>)on all text before trying to use UTF-8 utility functions with it.)This function is intended for programmatic uses of reversed strings. It pays no attention to decomposed characters, combining marks, byte order marks, directional indicators (LRM, LRO, etc) and similar characters which might need special handling when reversing a string for display purposes.
Note that unlike
strreverse(java.lang.String), this function returns newly-allocated memory, which should be freed withfree(java.lang.foreign.MemorySegment)when no longer needed.- Parameters:
str- a UTF-8 encoded stringlen- the maximum length ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.- Returns:
- a newly-allocated string which is the reverse of
str - Since:
- 2.2
-
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 ifstris 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-startPoscharacters.Since GLib 2.72,
-1can be passed toendPosto indicate the end of the string.- Parameters:
str- a UTF-8 encoded stringstartPos- a character offset withinstrendPos- another character offset withinstr, or-1to indicate the end of the string- Returns:
- a newly allocated copy of the requested
substring. Free with
free(java.lang.foreign.MemorySegment)when no longer needed. - Since:
- 2.30
-
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 nul character (U+0000) will be added to the string after the converted text.
- Parameters:
str- a UTF-8 encoded stringlen- the maximum length ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.itemsRead- location to store number of bytes read, orNULL. IfNULL, thenConvertError.PARTIAL_INPUTwill be returned in casestrcontains 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 nul character.- Returns:
- a pointer to a newly allocated UCS-4 string.
This value must be freed with
free(java.lang.foreign.MemorySegment). - 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
utf8ToUcs4(java.lang.String, int, org.javagi.base.Out<java.lang.Integer>, org.javagi.base.Out<java.lang.Integer>)but does no error checking on the input. A trailing nul character (U+0000) will be added to the string after the converted text.- Parameters:
str- a UTF-8 encoded stringlen- the maximum length ofstrto use, in bytes. Iflenis negative, 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
free(java.lang.foreign.MemorySegment).
-
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 nul character (U+0000) will be added to the result after the converted text.
- Parameters:
str- a UTF-8 encoded stringlen- the maximum length (number of bytes) ofstrto use. Iflenis negative, then the string is nul-terminated.itemsRead- location to store number of bytes read, orNULL. IfNULL, thenGLib.ConvertError.PARTIAL_INPUTwill be returned in casestrcontains a trailing partial character. If an error occurs then the index of the invalid input is stored here.itemsWritten- location to store number ofgunichar2written, orNULL. The value stored here does not include the trailing nul.- Returns:
- a pointer to a newly allocated UTF-16 string.
This value must be freed with
free(java.lang.foreign.MemorySegment). - Throws:
GErrorException- seeGError
-
utf8TruncateMiddle
Cuts off the middle of the string, preserving half oftruncateLengthcharacters at the beginning and half at the end.If
stringis already short enough, this returns a copy ofstring. IftruncateLengthis0, 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
stringellipsized in the middle - Since:
- 2.78
-
utf8Validate
Validates UTF-8 encoded text.stris the text to validate; ifstris nul-terminated, thenmaxLencan be-1, otherwisemaxLenshould be the number of bytes to validate.If
endis non-NULL, then the end of the valid range will be stored there. This is the first byte of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise — either the trailing nul byte, or the first byte beyondmaxLen(if it’s positive).Note that
g_utf8_validate()returnsFALSEifmaxLenis positive and any of themaxLenbytes are nul.Returns
TRUEif all ofstrwas valid. Many GLib and GTK routines require valid UTF-8 as input; so data read from a file or the network should be checked withg_utf8_validate()before doing anything else with it.- Parameters:
str- a pointer to character dataend- return location for end of valid data- Returns:
TRUEif the text was valid UTF-8
-
utf8ValidateLen
Validates UTF-8 encoded text.As with
utf8Validate(byte[], org.javagi.base.Out<java.lang.String>), butmaxLenmust be set, and hence this function will always returnFALSEif any of the bytes ofstrare nul.- Parameters:
str- a pointer to character dataend- return location for end of valid data- Returns:
TRUEif the text was valid UTF-8- Since:
- 2.60
-
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
- Since:
- 2.18
-
uuidStringIsValid
Parses the stringstrand 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:
trueifstris a valid UUID,falseotherwise.- Since:
- 2.52
- 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().
- Since:
- 2.52
-
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#warnIfReachedandGLib#warnIfFailmacros.- 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().
- Since:
- 2.50
-
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:
trueif 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.- Since:
- 2.44
-
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)
- Since:
- 2.40
-
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_PACKAGEin software configured using GNU autotools. The function first looks in the Windows Registry for the value#InstallationDirectoryin 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
nullaspackage_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, butdllNameis 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 ifdllNamewasnull.If both
package_anddllNamearenull, 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 passnullfor 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 failsnullis 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.hmoduleshould be the handle of a loaded DLL ornull. The function looks up the directory that DLL was loaded from. Ifhmoduleis 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
hmoduleis 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 failsnullis returned. - Since:
- 2.16
-
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
subdirin the return value from calling g_win32_get_package_installation_directory() with thepackage_anddllNameparameters. 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 passnullfor 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
subdirinside 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,nullis 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,
nullis 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
nullon conversion failure and lack of short names. - Since:
- 2.8
-
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
-
timeoutAddOnce
Sets a function to be called afterintervalmilliseconds have elapsed, with the default priority,GLib.PRIORITY_DEFAULT.The given
functionis 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
-
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
-