gi-glib-2.0.17: GLib bindings

CopyrightWill Thompson Iñaki García Etxebarria and Jonas Platte
LicenseLGPL-2.1
MaintainerIñaki García Etxebarria (garetxe@gmail.com)
Safe HaskellNone
LanguageHaskell2010

GI.GLib.Functions

Contents

Description

 
Synopsis

Methods

access

access Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: a pathname in the GLib file name encoding (UTF-8 on Windows)

-> Int32

mode: as in access()

-> m Int32

Returns: zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.

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().

Since: 2.8

asciiDigitValue

asciiDigitValue Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int8

c: an ASCII character

-> m Int32

Returns: If c is a decimal digit (according to g_ascii_isdigit()), its numeric value. Otherwise, -1.

Determines the numeric value of a character as a decimal digit. Differs from unicharDigitValue because it takes a char, so there's no worry about sign extension if characters are signed.

asciiDtostr

asciiDtostr Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

buffer: A buffer to place the resulting string in

-> Int32

bufLen: The length of the buffer.

-> Double

d: The gdouble to convert

-> m Text

Returns: The pointer to the buffer with the converted string.

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

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

asciiFormatd

asciiFormatd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

buffer: A buffer to place the resulting string in

-> Int32

bufLen: The length of the buffer.

-> Text

format: The printf()-style format to use for the code to use for converting.

-> Double

d: The gdouble to convert

-> m Text

Returns: The pointer to the buffer with the converted string.

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

The returned buffer is guaranteed to be nul-terminated.

If you just want to want to serialize the value into a string, use asciiDtostr.

asciiStrcasecmp

asciiStrcasecmp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

s1: string to compare with s2

-> Text

s2: string to compare with s1

-> m Int32

Returns: 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

Compare two strings, ignoring the case of ASCII characters.

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

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

Both s1 and s2 must be non-Nothing.

asciiStrdown

asciiStrdown Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string

-> Int64

len: length of str in bytes, or -1 if str is nul-terminated

-> m Text

Returns: a newly-allocated string, with all the upper case characters in str converted to lower case, with semantics that exactly match asciiTolower. (Note that this is unlike the old strdown, which modified the string in place.)

Converts all upper case ASCII letters to lower case ASCII letters.

asciiStringToSigned

asciiStringToSigned Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string

-> Word32

base: base of a parsed number

-> Int64

min: a lower bound (inclusive)

-> Int64

max: an upper bound (inclusive)

-> m Int64

(Can throw GError)

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

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

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

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

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

Since: 2.54

asciiStringToUnsigned

asciiStringToUnsigned Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string

-> Word32

base: base of a parsed number

-> Word64

min: a lower bound (inclusive)

-> Word64

max: an upper bound (inclusive)

-> m Word64

(Can throw GError)

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

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

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

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

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

Since: 2.54

asciiStrncasecmp

asciiStrncasecmp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

s1: string to compare with s2

-> Text

s2: string to compare with s1

-> Word64

n: number of characters to compare

-> m Int32

Returns: 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string.

Unlike the BSD strcasecmp() 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 applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

asciiStrtod

asciiStrtod Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

nptr: the string to convert to a numeric value.

-> m (Double, Text)

Returns: the gdouble value.

Converts a string to a gdouble 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.

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

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

asciiStrtoll

asciiStrtoll Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

nptr: the string to convert to a numeric value.

-> Word32

base: to be used for the conversion, 2..36 or 0

-> m (Int64, Text)

Returns: the gint64 value or zero on error.

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

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

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

Since: 2.12

asciiStrtoull

asciiStrtoull Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

nptr: the string to convert to a numeric value.

-> Word32

base: to be used for the conversion, 2..36 or 0

-> m (Word64, Text)

Returns: the guint64 value or zero on error.

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

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, MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-Nothing).

Since: 2.2

asciiStrup

asciiStrup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string

-> Int64

len: length of str in bytes, or -1 if str is nul-terminated

-> m Text

Returns: a newly allocated string, with all the lower case characters in str converted to upper case, with semantics that exactly match asciiToupper. (Note that this is unlike the old strup, which modified the string in place.)

Converts all lower case ASCII letters to upper case ASCII letters.

asciiTolower

asciiTolower Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int8

c: any character

-> m Int8

Returns: the result of converting c to lower case. If c is not an ASCII upper case letter, c is returned unchanged.

Convert a character to ASCII lower case.

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

asciiToupper

asciiToupper Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int8

c: any character

-> m Int8

Returns: the result of converting c to upper case. If c is not an ASCII lower case letter, c is returned unchanged.

Convert a character to ASCII upper case.

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

asciiXdigitValue

asciiXdigitValue Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int8

c: an ASCII character.

-> m Int32

Returns: If c is a hex digit (according to g_ascii_isxdigit()), its numeric value. Otherwise, -1.

Determines the numeric value of a character as a hexidecimal digit. Differs from unicharXdigitValue because it takes a char, so there's no worry about sign extension if characters are signed.

assertWarning

assertWarning :: (HasCallStack, MonadIO m) => Text -> Text -> Int32 -> Text -> Text -> m () Source #

No description available in the introspection data.

assertionMessage

assertionMessage :: (HasCallStack, MonadIO m) => Text -> Text -> Int32 -> Text -> Text -> m () Source #

No description available in the introspection data.

assertionMessageCmpstr

assertionMessageCmpstr :: (HasCallStack, MonadIO m) => Text -> Text -> Int32 -> Text -> Text -> Text -> Text -> Text -> m () Source #

No description available in the introspection data.

assertionMessageError

assertionMessageError :: (HasCallStack, MonadIO m) => Text -> Text -> Int32 -> Text -> Text -> GError -> Word32 -> Int32 -> m () Source #

No description available in the introspection data.

atexit

atexit Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> VoidFunc

func: the function to call on normal program termination.

-> m () 

Deprecated: (Since version 2.32)It is best to avoid atexit.

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows 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 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 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 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 atexit (or atexit()) except in the main executable of a program.

atomicIntAdd

atomicIntAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint or guint

-> Int32

val: the value to add

-> m Int32

Returns: the value of atomic before the add, signed

Atomically adds val to the value of atomic.

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

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

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

Since: 2.4

atomicIntAnd

atomicIntAnd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

atomic: a pointer to a gint or guint

-> Word32

val: the value to 'and'

-> m Word32

Returns: the value of atomic before the operation, unsigned

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

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

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

Since: 2.30

atomicIntCompareAndExchange

atomicIntCompareAndExchange Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint or guint

-> Int32

oldval: the value to compare with

-> Int32

newval: the value to conditionally replace with

-> m Bool

Returns: True if the exchange took place

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

This compare and exchange is done atomically.

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

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

Since: 2.4

atomicIntDecAndTest

atomicIntDecAndTest Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint or guint

-> m Bool

Returns: True if the resultant value is zero

Decrements the value of atomic by 1.

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

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

Since: 2.4

atomicIntExchangeAndAdd

atomicIntExchangeAndAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint

-> Int32

val: the value to add

-> m Int32

Returns: the value of atomic before the add, signed

Deprecated: (Since version 2.30)Use atomicIntAdd instead.

This function existed before atomicIntAdd 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.

Since: 2.4

atomicIntGet

atomicIntGet Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint or guint

-> m Int32

Returns: the value of the integer

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier (before the get).

Since: 2.4

atomicIntInc

atomicIntInc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint or guint

-> m () 

Increments the value of atomic by 1.

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

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

Since: 2.4

atomicIntOr

atomicIntOr Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

atomic: a pointer to a gint or guint

-> Word32

val: the value to 'or'

-> m Word32

Returns: the value of atomic before the operation, unsigned

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

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

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

Since: 2.30

atomicIntSet

atomicIntSet Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

atomic: a pointer to a gint or guint

-> Int32

newval: a new value to store

-> m () 

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier (after the set).

Since: 2.4

atomicIntXor

atomicIntXor Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

atomic: a pointer to a gint or guint

-> Word32

val: the value to 'xor'

-> m Word32

Returns: the value of atomic before the operation, unsigned

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

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

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

Since: 2.30

atomicPointerAdd

atomicPointerAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> Int64

val: the value to add

-> m Int64

Returns: the value of atomic before the add, signed

Atomically adds val to the value of atomic.

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

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

Since: 2.30

atomicPointerAnd

atomicPointerAnd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> Word64

val: the value to 'and'

-> m Word64

Returns: the value of atomic before the operation, unsigned

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

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

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

Since: 2.30

atomicPointerCompareAndExchange

atomicPointerCompareAndExchange Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> Ptr ()

oldval: the value to compare with

-> Ptr ()

newval: the value to conditionally replace with

-> m Bool

Returns: True if the exchange took place

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

This compare and exchange is done atomically.

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

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

Since: 2.4

atomicPointerGet

atomicPointerGet Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> m (Ptr ())

Returns: the value of the pointer

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier (before the get).

Since: 2.4

atomicPointerOr

atomicPointerOr Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> Word64

val: the value to 'or'

-> m Word64

Returns: the value of atomic before the operation, unsigned

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

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

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

Since: 2.30

atomicPointerSet

atomicPointerSet Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> Ptr ()

newval: a new value to store

-> m () 

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier (after the set).

Since: 2.4

atomicPointerXor

atomicPointerXor Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

atomic: a pointer to a gpointer-sized value

-> Word64

val: the value to 'xor'

-> m Word64

Returns: the value of atomic before the operation, unsigned

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

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

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

Since: 2.30

base64Decode

base64Decode Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

text: zero-terminated string with base64 text to decode

-> m ByteString

Returns: newly allocated buffer containing the binary data that text represents. The returned buffer must be freed with free.

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.

Since: 2.12

base64DecodeInplace

base64DecodeInplace Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ByteString

text: zero-terminated string with base64 text to decode

-> m (Word8, ByteString)

Returns: The binary data that text responds. This pointer is the same as the input text.

Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.

Since: 2.20

base64Encode

base64Encode Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ByteString

data: the binary data to encode

-> m Text

Returns: a newly allocated, zero-terminated Base-64 encoded string representing data. The returned string must be freed with free.

Encode a sequence of binary data into its Base-64 stringified representation.

Since: 2.12

basename

basename Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

fileName: the name of the file

-> m [Char]

Returns: the name of the file without any leading directory components

Deprecated: (Since version 2.2)Use pathGetBasename instead, but notice that pathGetBasename 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.

bitLock

bitLock Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

address: a pointer to an integer

-> Int32

lockBit: a bit value between 0 and 31

-> m () 

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

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

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

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

Since: 2.24

bitNthLsf

bitNthLsf Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> CULong

mask: a gulong containing flags

-> Int32

nthBit: the index of the bit to start the search from

-> m Int32

Returns: the index of the first bit set which is higher than nthBit, or -1 if no higher bits are set

Find the position of the first bit set in mask, searching from (but not including) nthBit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nthBit to -1.

bitNthMsf

bitNthMsf Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> CULong

mask: a gulong containing flags

-> Int32

nthBit: the index of the bit to start the search from

-> m Int32

Returns: the index of the first bit set which is lower than nthBit, or -1 if no lower bits are set

Find the position of the first bit set in mask, searching from (but not including) nthBit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nthBit to -1 or GLIB_SIZEOF_LONG * 8.

bitStorage

bitStorage Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> CULong

number: a guint

-> m Word32

Returns: the number of bits used to hold number

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

bitTrylock

bitTrylock Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

address: a pointer to an integer

-> Int32

lockBit: a bit value between 0 and 31

-> m Bool

Returns: True if the lock was acquired

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

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

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

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

Since: 2.24

bitUnlock

bitUnlock Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

address: a pointer to an integer

-> Int32

lockBit: a bit value between 0 and 31

-> m () 

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

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

Since: 2.24

buildFilenamev

buildFilenamev Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [[Char]]

args: Nothing-terminated array of strings containing the path elements.

-> m [Char]

Returns: a newly-allocated string that must be freed with free.

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.

Since: 2.8

buildPathv

buildPathv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

separator: a string used to separator the elements of the path.

-> [[Char]]

args: Nothing-terminated array of strings containing the path elements.

-> m [Char]

Returns: a newly-allocated string that must be freed with free.

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

Since: 2.8

chdir

chdir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

path: a pathname in the GLib file name encoding (UTF-8 on Windows)

-> m Int32

Returns: 0 on success, -1 if an error occurred.

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

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

Since: 2.8

checkVersion

checkVersion Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

requiredMajor: the required major version

-> Word32

requiredMinor: the required minor version

-> Word32

requiredMicro: the required micro version

-> m Text

Returns: Nothing if the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.

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

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

Since: 2.6

childWatchAdd

childWatchAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

priority: the priority of the idle source. Typically this will be in the range between PRIORITY_DEFAULT_IDLE and PRIORITY_HIGH_IDLE.

-> Int32

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).

-> ChildWatchFunc

function: function to call

-> m Word32

Returns: the ID (greater than 0) of the event source.

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

If you obtain pid from spawnAsync or spawnAsyncWithPipes you will need to pass G_SPAWN_DO_NOT_REAP_CHILD as flag to the spawn function for the child watching to work.

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

Also, note that on platforms where GPid must be explicitly closed (see spawnClosePid) pid must not be closed while the source is still active. Typically, you should invoke spawnClosePid 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 apply to this function.

This internally creates a main loop source using childWatchSourceNew and attaches it to the main loop context using sourceAttach. You can do these steps manually if you need greater control.

Since: 2.4

childWatchSourceNew

childWatchSourceNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

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).

-> m Source

Returns: the newly-created child watch source

Creates a new child_watch source.

The source will not initially be associated with any MainContext and must be added to one with sourceAttach before it will be executed.

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

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

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

  • pid must be a child of this process
  • pid must be positive
  • the application must not call waitpid with a non-positive first argument, for instance in another thread
  • the application must not wait for pid to exit by any other mechanism, including waitpid(pid, ...) or a second child-watch source for the same pid
  • the application must not ignore SIGCHILD

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

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

Since: 2.4

clearError

clearError Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m ()

(Can throw GError)

If err or *err is Nothing, does nothing. Otherwise, calls errorFree on *err and sets *err to Nothing.

close

close Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

fd: A file descriptor

-> m ()

(Can throw GError)

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

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

Since: 2.36

computeChecksumForBytes

computeChecksumForBytes Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ChecksumType

checksumType: a ChecksumType

-> Bytes

data: binary blob to compute the digest of

-> m Text

Returns: the digest of the binary data as a string in hexadecimal. The returned string should be freed with free when done using it.

Computes the checksum for a binary data. This is a convenience wrapper for checksumNew, checksumGetString and checksumFree.

The hexadecimal string returned will be in lower case.

Since: 2.34

computeChecksumForData

computeChecksumForData Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ChecksumType

checksumType: a ChecksumType

-> ByteString

data: binary blob to compute the digest of

-> m Text

Returns: the digest of the binary data as a string in hexadecimal. The returned string should be freed with free when done using it.

Computes the checksum for a binary data of length. This is a convenience wrapper for checksumNew, checksumGetString and checksumFree.

The hexadecimal string returned will be in lower case.

Since: 2.16

computeChecksumForString

computeChecksumForString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ChecksumType

checksumType: a ChecksumType

-> Text

str: the string to compute the checksum of

-> Int64

length: the length of the string, or -1 if the string is null-terminated.

-> m Text

Returns: the checksum as a hexadecimal string. The returned string should be freed with free when done using it.

Computes the checksum of a string.

The hexadecimal string returned will be in lower case.

Since: 2.16

computeHmacForBytes

computeHmacForBytes Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ChecksumType

digestType: a ChecksumType to use for the HMAC

-> Bytes

key: the key to use in the HMAC

-> Bytes

data: binary blob to compute the HMAC of

-> m Text

Returns: the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with free when done using it.

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

The hexadecimal string returned will be in lower case.

Since: 2.50

computeHmacForData

computeHmacForData Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ChecksumType

digestType: a ChecksumType to use for the HMAC

-> ByteString

key: the key to use in the HMAC

-> ByteString

data: binary blob to compute the HMAC of

-> m Text

Returns: the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with free when done using it.

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

The hexadecimal string returned will be in lower case.

Since: 2.30

computeHmacForString

computeHmacForString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ChecksumType

digestType: a ChecksumType to use for the HMAC

-> ByteString

key: the key to use in the HMAC

-> Text

str: the string to compute the HMAC for

-> Int64

length: the length of the string, or -1 if the string is nul-terminated

-> m Text

Returns: the HMAC as a hexadecimal string. The returned string should be freed with free when done using it.

Computes the HMAC for a string.

The hexadecimal string returned will be in lower case.

Since: 2.30

convert

convert Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ByteString

str: the string to convert.

-> Text

toCodeset: name of character set into which to convert str

-> Text

fromCodeset: character set of str.

-> m (ByteString, Word64)

Returns: If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with free. Otherwise Nothing and error will be set. (Can throw GError)

Converts a string from one character set to another.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytesRead can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to convert, g_convert_with_iconv() or convertWithFallback. (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 strToAscii instead.

convertErrorQuark

convertErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

convertWithFallback

convertWithFallback Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ByteString

str: the string to convert.

-> Text

toCodeset: name of character set into which to convert str

-> Text

fromCodeset: character set of str.

-> Text

fallback: UTF-8 string to use in place of characters not present in the target encoding. (The string must be representable in the target encoding). If Nothing, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.

-> m (ByteString, Word64)

Returns: If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with free. Otherwise Nothing and error will be set. (Can throw GError)

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

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytesRead can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to convert, g_convert_with_iconv() or convertWithFallback. (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.)

datalistForeach

datalistForeach Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Data

datalist: a datalist.

-> DataForeachFunc

func: the function to call for each data element.

-> m () 

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

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

datalistGetData

datalistGetData Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Data

datalist: a datalist.

-> Text

key: the string identifying a data element.

-> m (Ptr ())

Returns: the data element, or Nothing if it is not found.

Gets a data element, using its string identifier. This is slower than datalistIdGetData because it compares strings.

datalistGetFlags

datalistGetFlags Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Data

datalist: pointer to the location that holds a list

-> m Word32

Returns: the flags of the datalist

Gets flags values packed in together with the datalist. See datalistSetFlags.

Since: 2.8

datalistIdGetData

datalistIdGetData Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Data

datalist: a datalist.

-> Word32

keyId: the GQuark identifying a data element.

-> m (Ptr ())

Returns: the data element, or Nothing if it is not found.

Retrieves the data element corresponding to keyId.

datalistSetFlags

datalistSetFlags Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Data

datalist: pointer to the location that holds a list

-> Word32

flags: the flags to turn on. The values of the flags are restricted by DATALIST_FLAGS_MASK (currently 3; giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

-> m () 

Turns on flag values for a data list. This function is used to keep a small number of boolean flags in an object with a data list without using any additional space. It is not generally useful except in circumstances where space is very tight. (It is used in the base GObject type, for example.)

Since: 2.8

datalistUnsetFlags

datalistUnsetFlags Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Data

datalist: pointer to the location that holds a list

-> Word32

flags: the flags to turn off. The values of the flags are restricted by DATALIST_FLAGS_MASK (currently 3: giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

-> m () 

Turns off flag values for a data list. See datalistUnsetFlags

Since: 2.8

datasetDestroy

datasetDestroy Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

datasetLocation: the location identifying the dataset.

-> m () 

Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

datasetForeach

datasetForeach Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

datasetLocation: the location identifying the dataset.

-> DataForeachFunc

func: the function to call for each data element.

-> m () 

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

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

datasetIdGetData

datasetIdGetData Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

datasetLocation: the location identifying the dataset.

-> Word32

keyId: the GQuark id to identify the data element.

-> m (Ptr ())

Returns: the data element corresponding to the GQuark, or Nothing if it is not found.

Gets the data element corresponding to a GQuark.

dcgettext

dcgettext Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

domain: the translation domain to use, or Nothing to use the domain set with textdomain()

-> Text

msgid: message to translate

-> Int32

category: a locale category

-> m Text

Returns: the translated string for the given locale category

This is a variant of dgettext that allows specifying a locale category instead of always using LC_MESSAGES. See dgettext for more information about how this functions differs from calling dcgettext() directly.

Since: 2.26

dgettext

dgettext Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

domain: the translation domain to use, or Nothing to use the domain set with textdomain()

-> Text

msgid: message to translate

-> m Text

Returns: The translated string

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

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 dgettext invocations. For GTK+, it means calling textdomain() before gtk_init or its variants.

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

  • domain is not Nothing
  • 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.

Since: 2.18

directEqual

directEqual Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v1: a key

-> Ptr ()

v2: a key to compare with v1

-> m Bool

Returns: True if the two keys match.

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

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

directHash

directHash Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v: a gpointer key

-> m Word32

Returns: a hash value corresponding to the key.

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

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

dngettext

dngettext Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

domain: the translation domain to use, or Nothing to use the domain set with textdomain()

-> Text

msgid: message to translate

-> Text

msgidPlural: plural form of the message

-> CULong

n: the quantity for which translation is needed

-> m Text

Returns: The translated string

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

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

Since: 2.18

doubleEqual

doubleEqual Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v1: a pointer to a gdouble key

-> Ptr ()

v2: a pointer to a gdouble key to compare with v1

-> m Bool

Returns: True if the two keys match.

Compares the two gdouble values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-Nothing pointers to doubles as keys in a HashTable.

Since: 2.22

doubleHash

doubleHash Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v: a pointer to a gdouble key

-> m Word32

Returns: a hash value corresponding to the key.

Converts a pointer to a gdouble to a hash value. It can be passed to g_hash_table_new() as the hashFunc parameter, It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-Nothing pointers to doubles as keys in a HashTable.

Since: 2.22

dpgettext

dpgettext Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

domain: the translation domain to use, or Nothing to use the domain set with textdomain()

-> Text

msgctxtid: a combined message context and message id, separated by a \004 character

-> Word64

msgidoffset: the offset of the message id in msgctxid

-> m Text

Returns: The translated string

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

This uses 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.

Since: 2.16

dpgettext2

dpgettext2 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

domain: the translation domain to use, or Nothing to use the domain set with textdomain()

-> Text

context: the message context

-> Text

msgid: the message

-> m Text

Returns: The translated string

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

This uses 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.

Since: 2.18

environGetenv

environGetenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [[Char]]

envp: an environment list (eg, as returned from getEnviron), or Nothing for an empty environment list

-> [Char]

variable: the environment variable to get

-> m [Char]

Returns: the value of the environment variable, or Nothing if the environment variable is not set in envp. The returned string is owned by envp, and will be freed if variable is set or unset again.

Returns the value of the environment variable variable in the provided list envp.

Since: 2.32

environSetenv

environSetenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [[Char]]

envp: an environment list that can be freed using strfreev (e.g., as returned from getEnviron), or Nothing for an empty environment list

-> [Char]

variable: the environment variable to set, must not contain '='

-> [Char]

value: the value for to set the variable to

-> Bool

overwrite: whether to change the variable if it already exists

-> m [[Char]]

Returns: the updated environment list. Free it using strfreev.

Sets the environment variable variable in the provided list envp to value.

Since: 2.32

environUnsetenv

environUnsetenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [[Char]]

envp: an environment list that can be freed using strfreev (e.g., as returned from getEnviron), or Nothing for an empty environment list

-> [Char]

variable: the environment variable to remove, must not contain '='

-> m [[Char]]

Returns: the updated environment list. Free it using strfreev.

Removes the environment variable variable from the provided environment envp.

Since: 2.32

fileErrorFromErrno

fileErrorFromErrno Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

errNo: an "errno" value

-> m FileError

Returns: FileError corresponding to the given errno

Gets a FileError constant based on the passed-in errNo. For example, if you pass in EEXIST this function returns G_FILE_ERROR_EXIST. Unlike errno values, you can portably assume that all FileError values will exist.

Normally a FileError value goes into a GError returned from a function that manipulates files. So you would use fileErrorFromErrno when constructing a GError.

fileErrorQuark

fileErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

fileGetContents

fileGetContents Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: name of a file to read contents from, in the GLib file name encoding

-> m ByteString

(Can throw GError)

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

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

fileOpenTmp

fileOpenTmp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [Char]

tmpl: Template for file name, as in g_mkstemp(), basename only, or Nothing for a default template

-> m (Int32, [Char])

Returns: A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and error will be set. (Can throw GError)

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

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

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

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

fileReadLink

fileReadLink Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: the symbolic link

-> m [Char]

Returns: A newly-allocated string with the contents of the symbolic link, or Nothing if an error occurred. (Can throw GError)

Reads the contents of the symbolic link filename like the POSIX readlink() function. The returned string is in the encoding used for filenames. Use filenameToUtf8 to convert it to UTF-8.

Since: 2.4

fileSetContents

fileSetContents Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: name of a file to write contents to, in the GLib file name encoding

-> ByteString

contents: string to write to the file

-> m ()

(Can throw GError)

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

This write is atomic in the sense that it is first written to a temporary file which is then renamed to the final name. Notes:

  • On UNIX, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.
  • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.
  • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

If the call was successful, it returns True. If the call was not successful, it returns False and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the FileError enumeration.

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

Since: 2.8

fileTest

fileTest Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: a filename to test in the GLib file name encoding

-> [FileTest]

test: bitfield of FileTest flags

-> m Bool

Returns: whether a test was True

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

Apart from FileTestIsSymlink all tests follow symbolic links, so for a symbolic link to a regular file fileTest will return True for both FileTestIsSymlink and FileTestIsRegular.

Note, that for a dangling symbolic link fileTest will return True for FileTestIsSymlink and False for all other flags.

You should never use fileTest 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. For example, you might think you could use FileTestIsSymlink to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn't work!

C code

// DON'T DO THIS
if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
  {
    fd = g_open (filename, O_WRONLY);
    // write to fd
  }

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

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

filenameDisplayBasename

filenameDisplayBasename Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: an absolute pathname in the GLib file name encoding

-> m Text

Returns: a newly allocated string containing a rendition of the basename of the filename in valid UTF-8

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

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

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

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

Since: 2.6

filenameDisplayName

filenameDisplayName Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: a pathname hopefully in the GLib file name encoding

-> m Text

Returns: a newly allocated string containing a rendition of the filename in valid UTF-8

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 filenameToUtf8, the result is guaranteed to be non-Nothing even if the filename actually isn't in the GLib file name encoding.

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

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

Since: 2.6

filenameFromUri

filenameFromUri Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

uri: a uri describing a filename (escaped, encoded in ASCII).

-> m ([Char], Maybe Text)

Returns: a newly-allocated string holding the resulting filename, or Nothing on an error. (Can throw GError)

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

filenameFromUtf8

filenameFromUtf8 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

utf8string: a UTF-8 encoded string.

-> Int64

len: the length of the string, or -1 if the string is nul-terminated.

-> m ([Char], Word64, Word64)

Returns: The converted string, or Nothing on an error. (Can throw GError)

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

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

filenameToUri

filenameToUri Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windows

-> Maybe Text

hostname: A UTF-8 encoded hostname, or Nothing for none.

-> m Text

Returns: a newly-allocated string holding the resulting URI, or Nothing on an error. (Can throw GError)

Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.

filenameToUtf8

filenameToUtf8 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

opsysstring: a string in the encoding for filenames

-> Int64

len: the length of the string, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)

-> m (Text, Word64, Word64)

Returns: The converted string, or Nothing on an error. (Can throw GError)

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

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

findProgramInPath

findProgramInPath Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

program: a program name in the GLib file name encoding

-> m [Char]

Returns: a newly-allocated string with the absolute path, or Nothing

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

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

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

formatSize

formatSize Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

size: a size in bytes

-> m Text

Returns: a newly-allocated formatted string containing a human readable file size

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

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

This string should be freed with free when not needed any longer.

See formatSizeFull for more options about how the size might be formatted.

Since: 2.30

formatSizeForDisplay

formatSizeForDisplay Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int64

size: a size in bytes

-> m Text

Returns: a newly-allocated formatted string containing a human readable file size

Deprecated: (Since version 2.30)This function is broken due to its use of SI suffixes to denote IEC units. Use formatSize 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 free when not needed any longer.

Since: 2.16

formatSizeFull

formatSizeFull Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

size: a size in bytes

-> [FormatSizeFlags]

flags: FormatSizeFlags to modify the output

-> m Text

Returns: a newly-allocated formatted string containing a human readable file size

Formats a size.

This function is similar to formatSize but allows for flags that modify the output. See FormatSizeFlags.

Since: 2.30

free

free Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

mem: the memory to free

-> m () 

Frees the memory pointed to by mem.

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

getApplicationName

getApplicationName Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Text

Returns: human-readable application name. may return Nothing

Gets a human-readable name for the application, as set by setApplicationName. This name should be localized if possible, and is intended for display to the user. Contrast with getPrgname, which gets a non-localized name. If setApplicationName has not been called, returns the result of getPrgname (which may be Nothing if setPrgname has also not been called).

Since: 2.2

getCharset

getCharset Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m (Bool, Text)

Returns: True if the returned charset is UTF-8

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

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

On Linux, the character set is found by consulting nl_langinfo() if available. If not, the environment variables LC_ALL, LC_CTYPE, LANG and CHARSET are queried in order.

The return value is True if the locale's encoding is UTF-8, in that case you can perhaps avoid calling convert.

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

getCodeset

getCodeset Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Text

Returns: a newly allocated string containing the name of the character set. This string must be freed with free.

Gets the character set for the current locale.

getCurrentDir

getCurrentDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: the current directory

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.

getCurrentTime

getCurrentTime Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> TimeVal

result: TimeVal structure in which to store current time.

-> m () 

Equivalent to the UNIX gettimeofday() function, but portable.

You may find getRealTime to be more convenient.

getEnviron

getEnviron Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [[Char]]

Returns: the list of environment variables

Gets the list of environment variables for the current process.

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

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

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

Since: 2.28

getFilenameCharsets

getFilenameCharsets Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text 
-> m Bool

Returns: True if the filename encoding is UTF-8.

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

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

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

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

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

Since: 2.6

getHomeDir

getHomeDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: the current user's home directory

Gets the current user's home directory.

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

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

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

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

getHostName

getHostName Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Text

Returns: the host name of the machine.

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.

Since: 2.8

getLanguageNames

getLanguageNames Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Text]

Returns: a Nothing-terminated array of strings owned by GLib that must not be modified or freed.

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

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

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

Since: 2.6

getLocaleVariants

getLocaleVariants Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

locale: a locale identifier

-> m [Text]

Returns: a newly allocated array of newly allocated strings with the locale variants. Free with strfreev.

Returns a list of derived variants of locale, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable. This function handles territory, charset and extra locale modifiers.

For example, if locale is "fr_BE", then the returned list is "fr_BE", "fr".

If you need the list of variants for the current locale, use getLanguageNames.

Since: 2.28

getMonotonicTime

getMonotonicTime Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Int64

Returns: the monotonic time, in microseconds

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.

Since: 2.28

getNumProcessors

getNumProcessors Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Word32

Returns: Number of schedulable threads, always greater than 0

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.

Since: 2.36

getPrgname

getPrgname Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Text

Returns: the name of the program. The returned string belongs to GLib and must not be modified or freed.

Gets the name of the program. This name should not be localized, in contrast to getApplicationName.

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

getRealName

getRealName Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: the user's real name.

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

getRealTime

getRealTime Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Int64

Returns: the number of microseconds since January 1, 1970 UTC.

Queries the system wall-clock time.

This call is functionally equivalent to getCurrentTime except that the return value is often more convenient than dealing with a TimeVal.

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.

Since: 2.28

getSystemConfigDirs

getSystemConfigDirs Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [[Char]]

Returns: a Nothing-terminated array of strings owned by GLib that must not be modified or freed.

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

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

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

Since: 2.6

getSystemDataDirs

getSystemDataDirs Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [[Char]]

Returns: a Nothing-terminated array of strings owned by GLib that must not be modified or freed.

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

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

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

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.

Since: 2.6

getTmpDir

getTmpDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: the directory to use for temporary files.

Gets the directory to use for temporary files.

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

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

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

getUserCacheDir

getUserCacheDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: a string owned by GLib that must not be modified or freed.

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

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

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

Since: 2.6

getUserConfigDir

getUserConfigDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: a string owned by GLib that must not be modified or freed.

Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.

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

On Windows it follows XDG Base Directory Specification if XDG_CONFIG_HOME is defined. If XDG_CONFIG_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for `CSIDL_LOCAL_APPDATA`. Note that in this case on Windows it will be the same as what getUserDataDir returns.

Since: 2.6

getUserDataDir

getUserDataDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: a string owned by GLib that must not be modified or freed.

Returns a base directory in which to access application data such as icons that is customized for a particular user.

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

On Windows it follows XDG Base Directory Specification if XDG_DATA_HOME is defined. If XDG_DATA_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for `CSIDL_LOCAL_APPDATA`. Note that in this case on Windows it will be the same as what getUserConfigDir returns.

Since: 2.6

getUserName

getUserName Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: the user name of the current user.

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.

getUserRuntimeDir

getUserRuntimeDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [Char]

Returns: a string owned by GLib that must not be modified or freed.

Returns a directory that is unique to the current user on the local system.

This is determined using the mechanisms described in the XDG Base Directory Specification. This is the directory specified in the XDG_RUNTIME_DIR environment variable. In the case that this variable is not set, we return the value of getUserCacheDir, after verifying that it exists.

Since: 2.28

getUserSpecialDir

getUserSpecialDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> UserDirectory

directory: the logical id of special directory

-> m [Char]

Returns: the path to the specified special directory, or Nothing if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.

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, UserDirectoryDirectoryDesktop falls back to $HOME/Desktop when XDG special user directories have not been set up.

Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

Since: 2.14

getenv

getenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

variable: the environment variable to get

-> m [Char]

Returns: the value of the environment variable, or Nothing if the environment variable is not found. The returned string may be overwritten by the next call to getenv, setenv or unsetenv.

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.

hostnameIsAsciiEncoded

hostnameIsAsciiEncoded Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

hostname: a hostname

-> m Bool

Returns: True if hostname contains any ASCII-encoded segments.

Tests if hostname contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returns True, you should decode the hostname with hostnameToUnicode 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 hostnameIsNonAscii and hostnameIsAsciiEncoded to both return True for a name.

Since: 2.22

hostnameIsIpAddress

hostnameIsIpAddress Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

hostname: a hostname (or IP address in string form)

-> m Bool

Returns: True if hostname is an IP address

Tests if hostname is the string form of an IPv4 or IPv6 address. (Eg, "192.168.0.1".)

Since: 2.22

hostnameIsNonAscii

hostnameIsNonAscii Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

hostname: a hostname

-> m Bool

Returns: True if hostname contains any non-ASCII characters

Tests if hostname contains Unicode characters. If this returns True, you need to encode the hostname with hostnameToAscii 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 hostnameIsNonAscii and hostnameIsAsciiEncoded to both return True for a name.

Since: 2.22

hostnameToAscii

hostnameToAscii Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

hostname: a valid UTF-8 or ASCII hostname

-> m Text

Returns: an ASCII hostname, which must be freed, or Nothing if hostname is in some way invalid.

Converts hostname to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.

Since: 2.22

hostnameToUnicode

hostnameToUnicode Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

hostname: a valid UTF-8 or ASCII hostname

-> m Text

Returns: a UTF-8 hostname, which must be freed, or Nothing if hostname is in some way invalid.

Converts hostname to its canonical presentation form; a UTF-8 string in Unicode normalization form C, containing no uppercase letters, no forbidden characters, and no ASCII-encoded segments, and not ending with a trailing dot.

Of course if hostname is not an internationalized hostname, then the canonical presentation form will be entirely ASCII.

Since: 2.22

idleAdd

idleAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

priority: the priority of the idle source. Typically this will be in the range between PRIORITY_DEFAULT_IDLE and PRIORITY_HIGH_IDLE.

-> SourceFunc

function: function to call

-> m Word32

Returns: the ID (greater than 0) of the event source.

Adds a function to be called whenever there are no higher priority events pending. If the function returns False it is automatically removed from the list of event sources and will not be called again.

See [memory management of sources][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 global MainContext using sourceAttach, 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.

idleRemoveByData

idleRemoveByData Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

data: the data for the idle source's callback.

-> m Bool

Returns: True if an idle source was found and removed.

Removes the idle function with the given data.

idleSourceNew

idleSourceNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Source

Returns: the newly-created idle source

Creates a new idle source.

The source will not initially be associated with any MainContext and must be added to one with sourceAttach before it will be executed. Note that the default priority for idle sources is PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of PRIORITY_DEFAULT.

int64Equal

int64Equal Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v1: a pointer to a gint64 key

-> Ptr ()

v2: a pointer to a gint64 key to compare with v1

-> m Bool

Returns: True if the two keys match.

Compares the two gint64 values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-Nothing pointers to 64-bit integers as keys in a HashTable.

Since: 2.22

int64Hash

int64Hash Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v: a pointer to a gint64 key

-> m Word32

Returns: a hash value corresponding to the key.

Converts a pointer to a gint64 to a hash value.

It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-Nothing pointers to 64-bit integer values as keys in a HashTable.

Since: 2.22

intEqual

intEqual Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v1: a pointer to a gint key

-> Ptr ()

v2: a pointer to a gint key to compare with v1

-> m Bool

Returns: True if the two keys match.

Compares the two gint values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-Nothing pointers to integers as keys in a HashTable.

Note that this function acts on pointers to gint, not on gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use directEqual instead.

intHash

intHash Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v: a pointer to a gint key

-> m Word32

Returns: a hash value corresponding to the key.

Converts a pointer to a gint to a hash value. It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-Nothing pointers to integer values as keys in a HashTable.

Note that this function acts on pointers to gint, not on gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use directHash instead.

internStaticString

internStaticString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

string: a static string

-> m Text

Returns: a canonical representation for the string

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). internStaticString does not copy the string, therefore string must not be freed or modified.

Since: 2.10

internString

internString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

string: a string

-> m Text

Returns: a canonical representation for the string

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

Since: 2.10

ioAddWatch

ioAddWatch Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> IOChannel

channel: a IOChannel

-> Int32

priority: the priority of the IOChannel source

-> [IOCondition]

condition: the condition to watch for

-> IOFunc

func: the function to call when the condition is satisfied

-> m Word32

Returns: the event source id

Adds the IOChannel into the default main loop context with the given priority.

This internally creates a main loop source using ioCreateWatch and attaches it to the main loop context with sourceAttach. You can do these steps manually if you need greater control.

ioCreateWatch

ioCreateWatch Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> IOChannel

channel: a IOChannel to watch

-> [IOCondition]

condition: conditions to watch for

-> m Source

Returns: a new Source

Creates a Source that's dispatched when condition is met for the given channel. For example, if condition is G_IO_IN, the source will be dispatched when there's data available for reading.

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 Source created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

listenv

listenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m [[Char]]

Returns: a Nothing-terminated list of strings which must be freed with strfreev.

Gets the names of all variables set in the environment.

Programs that want to be portable to Windows should typically use this function and 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 getenv provide.

Since: 2.8

localeFromUtf8

localeFromUtf8 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

utf8string: a UTF-8 encoded string

-> Int64

len: the length of the string, or -1 if the string is nul-terminated.

-> m (ByteString, Word64)

Returns: A newly-allocated buffer containing the converted string, or Nothing on an error, and error will be set. (Can throw GError)

Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the [current locale][setlocale]. On Windows this means the system codepage.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertErrorIllegalSequence. Use convert to convert input that may contain embedded nul characters.

localeToUtf8

localeToUtf8 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ByteString

opsysstring: a string in the encoding of the current locale. On Windows this means the system codepage.

-> m (Text, Word64, Word64)

Returns: The converted string, or Nothing on an error. (Can throw GError)

Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the [current locale][setlocale] into a UTF-8 string.

If the source encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertErrorEmbeddedNul is set and the function returns Nothing. If the source encoding is UTF-8, an embedded nul character is treated with the ConvertErrorIllegalSequence error for backward compatibility with earlier versions of this library. Use convert to produce output that may contain embedded nul characters.

logDefaultHandler

logDefaultHandler Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

logDomain: the log domain of the message, or Nothing for the default "" application domain

-> [LogLevelFlags]

logLevel: the level of the message

-> Maybe Text

message: the message

-> Ptr ()

unusedData: data passed from g_log() which is unused

-> m () 

The default log handler set up by GLib; g_log_set_default_handler() allows to install an alternate default log handler. This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls abort(). It automatically prints a new-line character after the message, so one does not need to be manually included in message.

The behavior of this log handler can be influenced by a number of environment variables:

  • G_MESSAGES_PREFIXED: A :-separated list of log levels for which messages should be prefixed by the program name and PID of the aplication.
  • 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.

stderr is used for levels LogLevelFlagsLevelError, LogLevelFlagsLevelCritical, LogLevelFlagsLevelWarning and LogLevelFlagsLevelMessage. stdout is used for the rest.

This has no effect if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

logRemoveHandler

logRemoveHandler Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

logDomain: the log domain

-> Word32

handlerId: the id of the handler, which was returned in g_log_set_handler()

-> m () 

Removes the log handler.

This has no effect if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

logSetAlwaysFatal

logSetAlwaysFatal Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [LogLevelFlags]

fatalMask: the mask containing bits set for each level of error which is to be fatal

-> m [LogLevelFlags]

Returns: the old fatal mask

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. LogLevelFlagsLevelError is always fatal.

You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

Structured log messages (using g_log_structured() and logStructuredArray) 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][using-structured-logging].

logSetFatalMask

logSetFatalMask Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

logDomain: the log domain

-> [LogLevelFlags]

fatalMask: the new fatal mask

-> m [LogLevelFlags]

Returns: the old fatal mask for the log domain

Sets the log levels which are fatal in the given domain. LogLevelFlagsLevelError is always fatal.

This has no effect on structured log messages (using g_log_structured() or logStructuredArray). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using logSetWriterFunc. See [Using Structured Logging][using-structured-logging].

logSetHandler

logSetHandler Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

logDomain: the log domain, or Nothing for the default "" application domain

-> [LogLevelFlags]

logLevels: the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the G_LOG_FLAG_FATAL and G_LOG_FLAG_RECURSION bit flags.

-> LogFunc

logFunc: the log handler function

-> m Word32

Returns: the id of the new handler

Like g_log_set_handler(), but takes a destroy notify for the userData.

This has no effect if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

Since: 2.46

logStructuredArray

logStructuredArray Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [LogLevelFlags]

logLevel: log level, either from LogLevelFlags, or a user-defined level

-> [LogField]

fields: key–value pairs of structured data to add to the log message

-> m () 

Log a message with structured data. The message will be passed through to the log writer set by the application using logSetWriterFunc. If the message is fatal (i.e. its log level is LogLevelFlagsLevelError), the program will be aborted at the end of this function.

See g_log_structured() for more documentation.

This assumes that logLevel is already present in fields (typically as the PRIORITY field).

Since: 2.50

logVariant

logVariant Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

logDomain: log domain, usually LOG_DOMAIN

-> [LogLevelFlags]

logLevel: log level, either from LogLevelFlags, or a user-defined level

-> GVariant

fields: a dictionary (GVariant of the type G_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.

-> m () 

Log a message with structured data, accepting the data within a GVariant. This version is especially useful for use in other languages, via introspection.

The only mandatory item in the fields dictionary is the "MESSAGE" which must contain the text shown to the user.

The values in the fields dictionary are likely to be of type String (G_VARIANT_TYPE_STRING). Array of bytes (G_VARIANT_TYPE_BYTESTRING) is also supported. In this case the message is handled as binary and will be forwarded to the log writer as such. The size of the array should not be higher than G_MAXSSIZE. Otherwise it will be truncated to this size. For other types variantPrint will be used to convert the value into a string.

For more details on its usage and about the parameters, see g_log_structured().

Since: 2.50

logWriterDefault

logWriterDefault Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [LogLevelFlags]

logLevel: log level, either from LogLevelFlags, or a user-defined level

-> [LogField]

fields: key–value pairs of structured data forming the log message

-> Ptr ()

userData: user data passed to logSetWriterFunc

-> m LogWriterOutput

Returns: LogWriterOutputHandled on success, LogWriterOutputUnhandled otherwise

Format a structured log message and output it to the default log destination for the platform. On Linux, this is typically the systemd journal, falling back to stdout or stderr if running from the terminal or if output is being redirected to a file.

Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.

This is suitable for use as a LogWriterFunc, and is the default writer used if no other is set using logSetWriterFunc.

As with logDefaultHandler, this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable.

Since: 2.50

logWriterFormatFields

logWriterFormatFields Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [LogLevelFlags]

logLevel: log level, either from LogLevelFlags, or a user-defined level

-> [LogField]

fields: key–value pairs of structured data forming the log message

-> Bool

useColor: True to use ANSI color escape sequences when formatting the message, False to not

-> m Text

Returns: string containing the formatted log message, in the character set of the current locale

Format a structured log message as a string suitable for outputting to the terminal (or elsewhere). This will include the values of all fields it knows how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the documentation for g_log_structured()). 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.

Since: 2.50

logWriterIsJournald

logWriterIsJournald Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

outputFd: output file descriptor to check

-> m Bool

Returns: True if outputFd points to the journal, False otherwise

Check whether the given outputFd file descriptor is a connection to the systemd journal, or something else (like a log file or stdout or stderr).

Invalid file descriptors are accepted and return False, which allows for the following construct without needing any additional error handling:

C code

 is_journald = g_log_writer_is_journald (fileno (stderr));

Since: 2.50

logWriterJournald

logWriterJournald Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [LogLevelFlags]

logLevel: log level, either from LogLevelFlags, or a user-defined level

-> [LogField]

fields: key–value pairs of structured data forming the log message

-> Ptr ()

userData: user data passed to logSetWriterFunc

-> m LogWriterOutput

Returns: LogWriterOutputHandled on success, LogWriterOutputUnhandled otherwise

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 LogWriterFunc.

If GLib has been compiled without systemd support, this function is still defined, but will always return LogWriterOutputUnhandled.

Since: 2.50

logWriterStandardStreams

logWriterStandardStreams Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [LogLevelFlags]

logLevel: log level, either from LogLevelFlags, or a user-defined level

-> [LogField]

fields: key–value pairs of structured data forming the log message

-> Ptr ()

userData: user data passed to logSetWriterFunc

-> m LogWriterOutput

Returns: LogWriterOutputHandled on success, LogWriterOutputUnhandled otherwise

Format a structured log message and print it to either stdout or stderr, depending on its log level. LogLevelFlagsLevelInfo and LogLevelFlagsLevelDebug messages are sent to stdout; all other log levels are sent to stderr. Only fields which are understood by this function are included in the formatted string which is printed.

If the output stream supports ANSI color escape sequences, they will be used in the output.

A trailing new-line character is added to the log message when it is printed.

This is suitable for use as a LogWriterFunc.

Since: 2.50

logWriterSupportsColor

logWriterSupportsColor Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

outputFd: output file descriptor to check

-> m Bool

Returns: True if ANSI color escapes are supported, False otherwise

Check whether the given outputFd file descriptor supports ANSI color escape sequences. If so, they can safely be used when formatting log messages.

Since: 2.50

mainCurrentSource

mainCurrentSource Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Source

Returns: The currently firing source or Nothing.

Returns the currently firing source for this thread.

Since: 2.12

mainDepth

mainDepth Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Int32

Returns: The main loop recursion level in the current thread

Returns the depth of the stack of calls to mainContextDispatch on any MainContext in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback from mainContextIteration (or mainLoopRun, etc.) it returns 1. When called from within a callback to a recursive call to mainContextIteration, it returns 2. And so forth.

This function is useful in a situation like the following: Imagine an extremely simple "garbage collected" system.

C code

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

C code

gpointer
allocate_memory (gsize size)
{
  FreeListBlock *block = g_new (FreeListBlock, 1);
  block->mem = g_malloc (size);
  block->depth = g_main_depth ();
  free_list = g_list_prepend (free_list, block);
  return block->mem;
}

void
free_allocated_memory (void)
{
  GList *l;
  
  int depth = g_main_depth ();
  for (l = free_list; l; );
    {
      GList *next = l->next;
      FreeListBlock *block = l->data;
      if (block->depth > depth)
        {
          g_free (block->mem);
          g_free (block);
          free_list = g_list_delete_link (free_list, l);
        }
              
      l = next;
    }
  }

There is a temptation to use mainDepth to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item's callback return immediately and do nothing if mainDepth returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you'll find yourself adding these checks all over your code, since there are doubtless many, many things that the user could do. Instead, you can use the following techniques:

  1. Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.
  2. Avoid main loop recursion in situations where you can't handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.

malloc

malloc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBytes: the number of bytes to allocate

-> m (Ptr ())

Returns: a pointer to the allocated memory

Allocates nBytes bytes of memory. If nBytes is 0 it returns Nothing.

malloc0

malloc0 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBytes: the number of bytes to allocate

-> m (Ptr ())

Returns: a pointer to the allocated memory

Allocates nBytes bytes of memory, initialized to 0's. If nBytes is 0 it returns Nothing.

malloc0N

malloc0N Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBlocks: the number of blocks to allocate

-> Word64

nBlockBytes: the size of each block in bytes

-> m (Ptr ())

Returns: a pointer to the allocated memory

This function is similar to malloc0, allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

Since: 2.24

mallocN

mallocN Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBlocks: the number of blocks to allocate

-> Word64

nBlockBytes: the size of each block in bytes

-> m (Ptr ())

Returns: a pointer to the allocated memory

This function is similar to malloc, allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

Since: 2.24

markupErrorQuark

markupErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

markupEscapeText

markupEscapeText Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

text: some valid UTF-8 text

-> Int64

length: length of text in bytes, or -1 if the text is nul-terminated

-> m Text

Returns: a newly allocated string with the escaped text

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.

memIsSystemMalloc

memIsSystemMalloc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Bool

Returns: if True, malloc() and malloc can be mixed.

Deprecated: (Since version 2.46)GLib always uses the system malloc, so this function alwaysreturns True.

Checks whether the allocator used by malloc is the system's malloc implementation. If it returns True memory allocated with malloc() can be used interchangeable with memory allocated using malloc. This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.

memProfile

memProfile :: (HasCallStack, MonadIO m) => m () Source #

Deprecated: (Since version 2.46)Use other memory profiling tools instead

GLib used to support some tools for memory profiling, but this no longer works. There are many other useful tools for memory profiling these days which can be used instead.

memSetVtable

memSetVtable Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> MemVTable

vtable: table of memory allocation routines.

-> m () 

Deprecated: (Since version 2.46)This function now does nothing. Use other memoryprofiling tools instead

This function used to let you override the memory allocation function. However, its use was incompatible with the use of global constructors in GLib and GIO, because those use the GLib allocators before main is reached. Therefore this function is now deprecated and is just a stub.

memdup

memdup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

mem: the memory to copy.

-> Word32

byteSize: the number of bytes to copy.

-> m (Ptr ())

Returns: a pointer to the newly-allocated copy of the memory, or Nothing if mem is Nothing.

Allocates byteSize bytes of memory, and copies byteSize bytes into it from mem. If mem is Nothing it returns Nothing.

mkdirWithParents

mkdirWithParents Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

pathname: a pathname in the GLib file name encoding

-> Int32

mode: permissions to use for newly created directories

-> m Int32

Returns: 0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.

Create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.

Since: 2.8

nullifyPointer

nullifyPointer Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

nullifyLocation: the memory address of the pointer.

-> m () 

Set the pointer at the specified location to Nothing.

numberParserErrorQuark

numberParserErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

onErrorQuery

onErrorQuery Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

prgName: the program name, needed by gdb for the "[S]tack trace" option. If prgName is Nothing, getPrgname is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called)

-> m () 

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.

C code

#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, onErrorStackTrace 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.

onErrorStackTrace

onErrorStackTrace Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

prgName: the program name, needed by gdb for the "[S]tack trace" option

-> m () 

Invokes gdb, which attaches to the current process and shows a stack trace. Called by onErrorQuery when the "[S]tack trace" option is selected. You can get the current process's program name with getPrgname, assuming that you have called gtk_init() or gdk_init().

This function may cause different actions on non-UNIX platforms.

optionErrorQuark

optionErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

parseDebugString

parseDebugString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

string: a list of debug options separated by colons, spaces, or commas, or Nothing.

-> [DebugKey]

keys: pointer to an array of DebugKey which associate strings with bit flags.

-> m Word32

Returns: the combined set of bit flags.

Parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

If string is equal to "all", all flags are set. Any flags specified along with "all" in string are inverted; thus, "all,foo,bar" or "foo,bar,all" sets all flags except those corresponding to "foo" and "bar".

If string is equal to "help", all the available keys in keys are printed out to standard error.

pathGetBasename

pathGetBasename Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

fileName: the name of the file

-> m [Char]

Returns: a newly allocated string containing the last component of the filename

Gets the last component of the filename.

If fileName ends with a directory separator it gets the component before the last slash. If fileName consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If fileName is empty, it gets ".".

pathGetDirname

pathGetDirname Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

fileName: the name of the file

-> m [Char]

Returns: the directory components of the file

Gets the directory components of a file name.

If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

pathIsAbsolute

pathIsAbsolute Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

fileName: a file name

-> m Bool

Returns: True if fileName is absolute

Returns True if the given fileName is an absolute file name. Note that this is a somewhat vague concept on Windows.

On POSIX systems, an absolute file name is well-defined. It always starts from the single root directory. For example "/usr/local".

On Windows, the concepts of current drive and drive-specific current directory introduce vagueness. This function interprets as an absolute file name one that either begins with a directory separator such as "\Users\tml" or begins with the root on a drive, for example "C:\Windows". The first case also includes UNC paths such as "\\myserver\docs\foo". In all cases, either slashes or backslashes are accepted.

Note that a file name relative to the current drive root does not truly specify a file uniquely over time and across processes, as the current drive is a per-process value and can be changed.

File names relative the current directory on some specific drive, such as "D:foo/bar", are not interpreted as absolute by this function, but they obviously are not relative to the normal current directory as returned by getcwd() or getCurrentDir either. Such paths should be avoided, or need to be handled using Windows-specific code.

pathSkipRoot

pathSkipRoot Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

fileName: a file name

-> m (Maybe [Char])

Returns: a pointer into fileName after the root component

Returns a pointer into fileName after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If fileName is not an absolute path it returns Nothing.

patternMatch

patternMatch Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> PatternSpec

pspec: a PatternSpec

-> Word32

stringLength: the length of string (in bytes, i.e. strlen(), not utf8Strlen)

-> Text

string: the UTF-8 encoded string to match

-> Maybe Text

stringReversed: the reverse of string or Nothing

-> m Bool

Returns: True if string matches pspec

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 Nothing, this is more efficient if the reversed version of the string to be matched is not at hand, as patternMatch 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 patternMatch.

Note also that the reverse of a UTF-8 encoded string can in general not be obtained by strreverse. This works only if the string does not contain any multibyte characters. GLib offers the utf8Strreverse function to reverse UTF-8 encoded strings.

patternMatchSimple

patternMatchSimple Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

pattern: the UTF-8 encoded pattern

-> Text

string: the UTF-8 encoded string to match

-> m Bool

Returns: True if string matches pspec

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 g_pattern_spec_new() and call patternMatchString repeatedly.

patternMatchString

patternMatchString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> PatternSpec

pspec: a PatternSpec

-> Text

string: the UTF-8 encoded string to match

-> m Bool

Returns: True if string matches pspec

Matches a string against a compiled pattern. If the string is to be matched against more than one pattern, consider using patternMatch instead while supplying the reversed string.

pointerBitLock

pointerBitLock Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

address: a pointer to a gpointer-sized value

-> Int32

lockBit: a bit value between 0 and 31

-> m () 

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.

Since: 2.30

pointerBitTrylock

pointerBitTrylock Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

address: a pointer to a gpointer-sized value

-> Int32

lockBit: a bit value between 0 and 31

-> m Bool

Returns: True if the lock was acquired

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.

Since: 2.30

pointerBitUnlock

pointerBitUnlock Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

address: a pointer to a gpointer-sized value

-> Int32

lockBit: a bit value between 0 and 31

-> m () 

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.

Since: 2.30

poll

poll Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> PollFD

fds: file descriptors to poll

-> Word32

nfds: the number of file descriptors in fds

-> Int32

timeout: amount of time to wait, in milliseconds, or -1 to wait forever

-> m Int32

Returns: the number of entries in fds whose revents fields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.

Polls fds, as with the poll() system call, but portably. (On systems that don't have poll(), it is emulated using select().) This is used internally by MainContext, but it can be called directly if you need to block until a file descriptor is ready, but don't want to run the full main loop.

Each element of fds is a PollFD describing a single file descriptor to poll. The fd field indicates the file descriptor, and the events field indicates the events to poll for. On return, the revents fields will be filled with the events that actually occurred.

On POSIX systems, the file descriptors in fds can be any sort of file descriptor, but the situation is much more complicated on Windows. If you need to use poll in code that has to run on Windows, the easiest solution is to construct all of your GPollFDs with g_io_channel_win32_make_pollfd().

Since: 2.20

propagateError

propagateError Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> GError

src: error to move into the return location

-> m (Maybe GError) 

If dest is Nothing, free src; otherwise, moves src into *dest. The error variable dest points to must be Nothing.

src must be non-Nothing.

Note that src is no longer valid after this call. If you want to keep using the same GError*, you need to set it to Nothing after calling this function on it.

quarkFromStaticString

quarkFromStaticString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

string: a string

-> m Word32

Returns: the GQuark identifying the string, or 0 if string is Nothing

Gets the GQuark identifying the given (static) string. If the string does not currently have an associated GQuark, a new GQuark is created, linked to the given string.

Note that this function is identical to quarkFromString except that if a new GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will continue to exist until the program terminates. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK+ theme engines).

quarkFromString

quarkFromString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

string: a string

-> m Word32

Returns: the GQuark identifying the string, or 0 if string is Nothing

Gets the GQuark identifying the given string. If the string does not currently have an associated GQuark, a new GQuark is created, using a copy of the string.

quarkToString

quarkToString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

quark: a GQuark.

-> m Text

Returns: the string associated with the GQuark

Gets the string associated with the given GQuark.

quarkTryString

quarkTryString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

string: a string

-> m Word32

Returns: the GQuark associated with the string, or 0 if string is Nothing or there is no GQuark associated with it

Gets the GQuark associated with the given string, or 0 if string is Nothing or it has no associated GQuark.

If you want the GQuark to be created if it doesn't already exist, use quarkFromString or quarkFromStaticString.

randomDouble

randomDouble Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Double

Returns: a random number

Returns a random gdouble equally distributed over the range [0..1).

randomDoubleRange

randomDoubleRange Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Double

begin: lower closed bound of the interval

-> Double

end: upper open bound of the interval

-> m Double

Returns: a random number

Returns a random gdouble equally distributed over the range [begin..end).

randomInt

randomInt Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Word32

Returns: a random number

Return a random guint32 equally distributed over the range [0..2^32-1].

randomIntRange

randomIntRange Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

begin: lower closed bound of the interval

-> Int32

end: upper open bound of the interval

-> m Int32

Returns: a random number

Returns a random gint32 equally distributed over the range [begin..end-1].

randomSetSeed

randomSetSeed Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

seed: a value to reinitialize the global random number generator

-> m () 

Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

realloc

realloc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

mem: the memory to reallocate

-> Word64

nBytes: new size of the memory in bytes

-> m (Ptr ())

Returns: the new address of the allocated memory

Reallocates the memory pointed to by mem, so that it now has space for nBytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be Nothing, in which case it's considered to have zero-length. nBytes may be 0, in which case Nothing will be returned and mem will be freed unless it is Nothing.

reallocN

reallocN Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

mem: the memory to reallocate

-> Word64

nBlocks: the number of blocks to allocate

-> Word64

nBlockBytes: the size of each block in bytes

-> m (Ptr ())

Returns: the new address of the allocated memory

This function is similar to realloc, allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

Since: 2.24

reloadUserSpecialDirsCache

reloadUserSpecialDirsCache :: (HasCallStack, MonadIO m) => m () Source #

Resets the cache used for getUserSpecialDir, so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.

Due to threadsafety issues this may cause leaking of strings that were previously returned from getUserSpecialDir that can't be freed. We ensure to only leak the data for the directories that actually changed value though.

Since: 2.22

rmdir

rmdir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: a pathname in the GLib file name encoding (UTF-8 on Windows)

-> m Int32

Returns: 0 if the directory was successfully removed, -1 if an error occurred

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.

Since: 2.6

setApplicationName

setApplicationName Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

applicationName: localized name of the application

-> m () 

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 setPrgname, which sets a non-localized name. setPrgname will be called automatically by gtk_init(), but setApplicationName 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.

Since: 2.2

setErrorLiteral

setErrorLiteral Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

domain: error domain

-> Int32

code: error code

-> Text

message: error message

-> m GError 

Does nothing if err is Nothing; if err is non-Nothing, then *err must be Nothing. A new GError is created and assigned to *err. Unlike g_set_error(), message is not a printf()-style format string. Use this function if message contains text you don't have control over, that could include printf() escape sequences.

Since: 2.18

setPrgname

setPrgname Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

prgname: the name of the program.

-> m () 

Sets the name of the program. This name should not be localized, in contrast to setApplicationName.

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

Note that for thread-safety reasons this function can only be called once.

setenv

setenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

variable: the environment variable to set, must not contain '='.

-> [Char]

value: the value for to set the variable to.

-> Bool

overwrite: whether to change the variable if it already exists.

-> m Bool

Returns: False if the environment variable couldn't be set.

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 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 getEnviron to get an environment array, modify that with environSetenv and environUnsetenv, and then pass that array directly to execvpe(), spawnAsync, or the like.

Since: 2.4

shellErrorQuark

shellErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

shellParseArgv

shellParseArgv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

commandLine: command line to parse

-> m (Int32, [[Char]])

(Can throw GError)

Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported). The results are defined to be the same as those you would get from a UNIX98 /bin/sh, as long as the input contains none of the unsupported shell expansions. If the input does contain such expansions, they are passed through literally. Possible errors are those from the G_SHELL_ERROR domain. Free the returned vector with strfreev.

shellQuote

shellQuote Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

unquotedString: a literal string

-> m [Char]

Returns: quoted string

Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquotedString. If you pass a filename to the shell, for example, you should first quote it with this function. The return value must be freed with free. The quoting style used is undefined (single or double quotes may be used).

shellUnquote

shellUnquote Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

quotedString: shell-quoted string

-> m [Char]

Returns: an unquoted string (Can throw GError)

Unquotes a string as the shell (/bin/sh) would. 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 shellQuote. If it fails, it returns Nothing and sets the error. The quotedString need not actually contain quoted or escaped text; shellUnquote 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 free. Possible errors are in the G_SHELL_ERROR domain.

Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even \' - if you want a ' in the quoted text, you have to do something like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.

sliceAlloc

sliceAlloc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

blockSize: the number of bytes to allocate

-> m (Ptr ())

Returns: a pointer to the allocated memory block, which will be Nothing if and only if memSize is 0

Allocates a block of memory from the slice allocator. The block address handed out can be expected to be aligned to at least 1 * sizeof (void*), though in general slices are 2 * sizeof (void*) bytes aligned, if a malloc() fallback implementation is used instead, the alignment may be reduced in a libc dependent fashion. Note that the underlying slice allocation mechanism can be changed with the [G_SLICE=always-malloc][G_SLICE] environment variable.

Since: 2.10

sliceAlloc0

sliceAlloc0 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

blockSize: the number of bytes to allocate

-> m (Ptr ())

Returns: a pointer to the allocated block, which will be Nothing if and only if memSize is 0

Allocates a block of memory via sliceAlloc and initializes the returned memory to 0. Note that the underlying slice allocation mechanism can be changed with the [G_SLICE=always-malloc][G_SLICE] environment variable.

Since: 2.10

sliceCopy

sliceCopy Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

blockSize: the number of bytes to allocate

-> Ptr ()

memBlock: the memory to copy

-> m (Ptr ())

Returns: a pointer to the allocated memory block, which will be Nothing if and only if memSize is 0

Allocates a block of memory from the slice allocator and copies blockSize bytes into it from memBlock.

memBlock must be non-Nothing if blockSize is non-zero.

Since: 2.14

sliceFree1

sliceFree1 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

blockSize: the size of the block

-> Ptr ()

memBlock: a pointer to the block to free

-> m () 

Frees a block of memory.

The memory must have been allocated via sliceAlloc or sliceAlloc0 and the blockSize has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the [G_DEBUG=gc-friendly][G_DEBUG] environment variable, also see [G_SLICE][G_SLICE] for related debugging options.

If memBlock is Nothing, this function does nothing.

Since: 2.10

sliceFreeChainWithOffset

sliceFreeChainWithOffset Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

blockSize: the size of the blocks

-> Ptr ()

memChain: a pointer to the first block of the chain

-> Word64

nextOffset: the offset of the next field in the blocks

-> m () 

Frees a linked list of memory blocks of structure type type.

The memory blocks must be equal-sized, allocated via sliceAlloc or sliceAlloc0 and linked together by a next pointer (similar to SList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the [G_DEBUG=gc-friendly][G_DEBUG] environment variable, also see [G_SLICE][G_SLICE] for related debugging options.

If memChain is Nothing, this function does nothing.

Since: 2.10

sliceGetConfig

sliceGetConfig :: (HasCallStack, MonadIO m) => SliceConfig -> m Int64 Source #

No description available in the introspection data.

sliceGetConfigState

sliceGetConfigState :: (HasCallStack, MonadIO m) => SliceConfig -> Int64 -> Word32 -> m Int64 Source #

No description available in the introspection data.

sliceSetConfig

sliceSetConfig :: (HasCallStack, MonadIO m) => SliceConfig -> Int64 -> m () Source #

No description available in the introspection data.

spacedPrimesClosest

spacedPrimesClosest Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

num: a guint

-> m Word32

Returns: the smallest prime number from a built-in array of primes which is larger than num

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a HashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

spawnAsync

spawnAsync Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [Char]

workingDirectory: child's current working directory, or Nothing to inherit parent's

-> [[Char]]

argv: child's argument vector

-> Maybe [[Char]]

envp: child's environment, or Nothing to inherit parent's

-> [SpawnFlags]

flags: flags from SpawnFlags

-> Maybe SpawnChildSetupFunc

childSetup: function to run in the child just before exec()

-> m Int32

(Can throw GError)

See spawnAsyncWithPipes for a full description; this function simply calls the spawnAsyncWithPipes without any pipes.

You should call spawnClosePid on the returned child process reference when you don't need it any more.

If you are writing a GTK+ application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use GdkAppLaunchContext, GAppLaunchContext, or set the DISPLAY environment variable.

Note that the returned childPid on Windows is a handle to the child process and not its identifier. Process handles and process identifiers are different concepts on Windows.

spawnAsyncWithPipes

spawnAsyncWithPipes Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [Char]

workingDirectory: child's current working directory, or Nothing to inherit parent's, in the GLib file name encoding

-> [[Char]]

argv: child's argument vector, in the GLib file name encoding

-> Maybe [[Char]]

envp: child's environment, or Nothing to inherit parent's, in the GLib file name encoding

-> [SpawnFlags]

flags: flags from SpawnFlags

-> Maybe SpawnChildSetupFunc

childSetup: function to run in the child just before exec()

-> m (Int32, Int32, Int32, Int32)

(Can throw GError)

Executes a child program asynchronously (your program will not block waiting for the child to exit). The child program is specified by the only argument that must be provided, argv. argv should be a Nothing-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path. If flags contains the SpawnFlagsSearchPath flag, the PATH environment variable is used to search for the executable. If flags contains the SpawnFlagsSearchPathFromEnvp flag, the PATH variable from envp is used to search for the executable. If both the SpawnFlagsSearchPath and SpawnFlagsSearchPathFromEnvp flags are set, the PATH variable from envp takes precedence over the environment variable.

If the program name is not a full path and SpawnFlagsSearchPath flag is not used, then the program will be run from the current directory (or workingDirectory, if specified); this might be unexpected or even dangerous in some cases when the current directory is world-writable.

On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in these arguments will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft's tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

At least currently, mingw doesn't support wmain(), so if you use mingw to develop the spawned program, it should call g_win32_get_command_line() to get arguments in UTF-8.

On Windows the low-level child process creation API CreateProcess() doesn't use argument vectors, but a command line. The C runtime library's spawn*() family of functions (which spawnAsyncWithPipes eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when you have argument vector elements that contain spaces of double quotes. The spawn*() functions don't do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, spawnAsyncWithPipes will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

The returned childPid on Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.

envp is a Nothing-terminated array of strings, where each string has the form KEY=VALUE. This will become the child's environment. If envp is Nothing, the child inherits its parent's environment.

flags should be the bitwise OR of any flags you want to affect the function's behaviour. The SpawnFlagsDoNotReapChild means that the child will not automatically be reaped; you must use a child watch (g_child_watch_add()) to be notified about the death of the child process, otherwise it will stay around as a zombie process until this process exits. Eventually you must call spawnClosePid on the childPid, in order to free resources which may be associated with the child process. (On Unix, using a child watch is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling spawnClosePid is equivalent to calling CloseHandle() on the process handle returned in childPid). See g_child_watch_add().

SpawnFlagsLeaveDescriptorsOpen means that the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. SpawnFlagsSearchPath means that argv[0] need not be an absolute path, it will be looked for in the PATH environment variable. SpawnFlagsSearchPathFromEnvp means need not be an absolute path, it will be looked for in the PATH variable from envp. If both SpawnFlagsSearchPath and SpawnFlagsSearchPathFromEnvp are used, the value from envp takes precedence over the environment. SpawnFlagsStdoutToDevNull means that the child's standard output will be discarded, instead of going to the same location as the parent's standard output. If you use this flag, standardOutput must be Nothing. SpawnFlagsStderrToDevNull means that the child's standard error will be discarded, instead of going to the same location as the parent's standard error. If you use this flag, standardError must be Nothing. SpawnFlagsChildInheritsStdin means that the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null). If you use this flag, standardInput must be Nothing. SpawnFlagsFileAndArgvZero means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally spawnAsyncWithPipes uses argv[0] as the file to execute, and passes all of argv to the child.

childSetup and userData are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, childSetup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent.

On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). There is no sensible thing childSetup could be used for on Windows so it is ignored and not called.

If non-Nothing, childPid will on Unix be filled with the child's process ID. You can use the process ID to send signals to the child, or to use g_child_watch_add() (or waitpid()) if you specified the SpawnFlagsDoNotReapChild flag. On Windows, childPid will be filled with a handle to the child process only if you specified the SpawnFlagsDoNotReapChild flag. You can then access the child process using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). You should close the handle with CloseHandle() or spawnClosePid when you no longer need it.

If non-Nothing, the standardInput, standardOutput, standardError 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 spawnAsyncWithPipes must close these file descriptors when they are no longer in use. If these parameters are Nothing, the corresponding pipe won't be created.

If standardInput is Nothing, the child's standard input is attached to /dev/null unless SpawnFlagsChildInheritsStdin is set.

If standardError is NULL, the child's standard error goes to the same location as the parent's standard error unless SpawnFlagsStderrToDevNull is set.

If standardOutput is NULL, the child's standard output goes to the same location as the parent's standard output unless SpawnFlagsStdoutToDevNull is set.

error can be Nothing to ignore errors, or non-Nothing to report errors. If an error is set, the function returns False. Errors are reported even if they occur in the child (for example if the executable in argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

If an error occurs, childPid, standardInput, standardOutput, and standardError will not be filled with valid values.

If childPid is not Nothing and an error does not occur then the returned process reference must be closed using spawnClosePid.

If you are writing a GTK+ application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use GdkAppLaunchContext, GAppLaunchContext, or set the DISPLAY environment variable.

spawnCheckExitStatus

spawnCheckExitStatus Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

exitStatus: An exit code as returned from spawnSync

-> m ()

(Can throw GError)

Set error if exitStatus indicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal).

The spawnSync and g_child_watch_add() family of APIs return an exit status for 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 exitStatus required use of platform-specific APIs, which is problematic for software using GLib as a cross-platform layer.

Additionally, many programs simply want to determine whether or not the child exited successfully, and either propagate a GError or print a message to standard error. In that common case, this function can be used. Note that the error message in error will contain human-readable information about the exit status.

The domain and code of error have special semantics in the case where the process has an "exit code", as opposed to being killed by a signal. On Unix, this happens if WIFEXITED() would be true of exitStatus. On Windows, it is always the case.

The special semantics are that the actual exit code will be the code set in error, and the domain will be G_SPAWN_EXIT_ERROR. This allows you to differentiate between different exit codes.

If the process was terminated by some means other than an exit status, the domain will be G_SPAWN_ERROR, and the code will be SpawnErrorFailed.

This function just offers convenience; you can of course also check the available platform via a macro such as G_OS_UNIX, and use WIFEXITED() and WEXITSTATUS() on exitStatus directly. Do not attempt to scan or parse the error message string; it may be translated and/or change in future versions of GLib.

Since: 2.34

spawnClosePid

spawnClosePid Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

pid: The process reference to close

-> m () 

On some platforms, notably Windows, the GPid type represents a resource which must be closed to prevent resource leaking. spawnClosePid is provided for this purpose. It should be used on all platforms, even though it doesn't do anything under UNIX.

spawnCommandLineAsync

spawnCommandLineAsync Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

commandLine: a command line

-> m ()

(Can throw GError)

A simple version of spawnAsync that parses a command line with shellParseArgv and passes it to spawnAsync. Runs a command line in the background. Unlike spawnAsync, the SpawnFlagsSearchPath flag is enabled, other flags are not. Note that SpawnFlagsSearchPath can have security implications, so consider using spawnAsync directly if appropriate. Possible errors are those from shellParseArgv and spawnAsync.

The same concerns on Windows apply as for spawnCommandLineSync.

spawnCommandLineSync

spawnCommandLineSync Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

commandLine: a command line

-> m (ByteString, ByteString, Int32)

(Can throw GError)

A simple version of spawnSync with little-used parameters removed, taking a command line instead of an argument vector. See spawnSync for full details. commandLine will be parsed by shellParseArgv. Unlike spawnSync, the SpawnFlagsSearchPath flag is enabled. Note that SpawnFlagsSearchPath can have security implications, so consider using spawnSync directly if appropriate. Possible errors are those from spawnSync and those from shellParseArgv.

If exitStatus is non-Nothing, the platform-specific exit status of the child is stored there; see the documentation of spawnCheckExitStatus for how to use and interpret this.

On Windows, please note the implications of shellParseArgv parsing commandLine. Parsing is done according to Unix shell rules, not Windows command interpreter rules. Space is a separator, and backslashes are special. Thus you cannot simply pass a commandLine containing canonical Windows paths, like "c:\program files\app\app.exe", as the backslashes will be eaten, and the space will act as a separator. You need to enclose such paths with single quotes, like "'c:\program files\app\app.exe' 'e:\folder\argument.txt'".

spawnErrorQuark

spawnErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

spawnExitErrorQuark

spawnExitErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

spawnSync

spawnSync Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe [Char]

workingDirectory: child's current working directory, or Nothing to inherit parent's

-> [[Char]]

argv: child's argument vector

-> Maybe [[Char]]

envp: child's environment, or Nothing to inherit parent's

-> [SpawnFlags]

flags: flags from SpawnFlags

-> Maybe SpawnChildSetupFunc

childSetup: function to run in the child just before exec()

-> m (ByteString, ByteString, Int32)

(Can throw GError)

Executes a child synchronously (waits for the child to exit before returning). All output from the child is stored in standardOutput and standardError, if those parameters are non-Nothing. Note that you must set the SpawnFlagsStdoutToDevNull and SpawnFlagsStderrToDevNull flags when passing Nothing for standardOutput and standardError.

If exitStatus is non-Nothing, the platform-specific exit status of the child is stored there; see the documentation of spawnCheckExitStatus for how to use and interpret this. Note that it is invalid to pass SpawnFlagsDoNotReapChild in flags, and on POSIX platforms, the same restrictions as for childWatchSourceNew apply.

If an error occurs, no data is returned in standardOutput, standardError, or exitStatus.

This function calls spawnAsyncWithPipes internally; see that function for full details on the other parameters and details on how these functions work on Windows.

stpcpy

stpcpy Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

dest: destination buffer.

-> Text

src: source string.

-> m Text

Returns: a pointer to trailing nul byte.

Copies a nul-terminated string into the dest buffer, include the trailing nul, and return a pointer to the trailing nul byte. This is useful for concatenating multiple strings together without having to repeatedly scan for the end.

strEqual

strEqual Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v1: a key

-> Ptr ()

v2: a key to compare with v1

-> m Bool

Returns: True if the two keys match

Compares two strings for byte-by-byte equality and returns True if they are equal. It can be passed to g_hash_table_new() as the keyEqualFunc parameter, when using non-Nothing strings as keys in a HashTable.

Note that this function is primarily meant as a hash table comparison function. For a general-purpose, Nothing-safe string comparison function, see strcmp0.

strHasPrefix

strHasPrefix Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a nul-terminated string

-> Text

prefix: the nul-terminated prefix to look for

-> m Bool

Returns: True if str begins with prefix, False otherwise.

Looks whether the string str begins with prefix.

Since: 2.2

strHasSuffix

strHasSuffix Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a nul-terminated string

-> Text

suffix: the nul-terminated suffix to look for

-> m Bool

Returns: True if str end with suffix, False otherwise.

Looks whether the string str ends with suffix.

Since: 2.2

strHash

strHash Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

v: a string key

-> m Word32

Returns: a hash value corresponding to the key

Converts a string to a hash value.

This function implements the widely used "djb" hash apparently posted by Daniel Bernstein to comp.lang.c some time ago. The 32 bit unsigned hash value starts at 5381 and for each byte 'c' in the string, is updated: hash = hash * 33 + c. This function uses the signed value of each byte.

It can be passed to g_hash_table_new() as the hashFunc parameter, when using non-Nothing strings as keys in a HashTable.

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.

strIsAscii

strIsAscii Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string

-> m Bool

Returns: True if str is ASCII

Determines if a string is pure ASCII. A string is pure ASCII if it contains no bytes with the high bit set.

Since: 2.40

strMatchString

strMatchString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

searchTerm: the search term from the user

-> Text

potentialHit: the text that may be a hit

-> Bool

acceptAlternates: True to accept ASCII alternates

-> m Bool

Returns: True if potentialHit is a hit

Checks if a search conducted for searchTerm should match potentialHit.

This function calls strTokenizeAndFold on both searchTerm and potentialHit. ASCII alternates are never taken for searchTerm but will be taken for potentialHit according to the value of acceptAlternates.

A hit occurs when each folded token in searchTerm is a prefix of a folded token from potentialHit.

Depending on how you're performing the search, it will typically be faster to call strTokenizeAndFold on each string in your corpus and build an index on the returned folded tokens, then call strTokenizeAndFold 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).

Since: 2.40

strToAscii

strToAscii Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string, in UTF-8

-> Maybe Text

fromLocale: the source locale, if known

-> m Text

Returns: a string in plain ASCII

Transliterate str to plain ASCII.

For best results, str should be in composed normalised form.

This function performs a reasonably good set of character replacements. The particular set of replacements that is done may change by version or even by runtime environment.

If the source language of str is known, it can used to improve the accuracy of the translation by passing it as fromLocale. It should be a valid POSIX locale string (of the form "language[_territory][.codeset][modifier]").

If fromLocale is Nothing then the current locale is used.

If you want to do translation for no specific locale, and you want it to be done independently of the currently locale, specify "C" for fromLocale.

Since: 2.40

strTokenizeAndFold

strTokenizeAndFold Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: a string

-> Maybe Text

translitLocale: the language code (like 'de' or 'en_GB') from which string originates

-> m ([Text], [Text])

Returns: the folded tokens

Tokenises string and performs folding on each token.

A token is a non-empty sequence of alphanumeric characters in the source string, separated by non-alphanumeric characters. An "alphanumeric" character for this purpose is one that matches unicharIsalnum or unicharIsmark.

Each token is then (Unicode) normalised and case-folded. If asciiAlternates is non-Nothing and some of the returned tokens contain non-ASCII characters, ASCII alternatives will be generated.

The number of ASCII alternatives that are generated and the method for doing so is unspecified, but translitLocale (if specified) may improve the transliteration if the language of the source string is known.

Since: 2.40

strcanon

strcanon Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: a nul-terminated array of bytes

-> Text

validChars: bytes permitted in string

-> Int8

substitutor: replacement character for disallowed bytes

-> m Text

Returns: string

For each character in string, if the character is not in validChars, replaces the character with substitutor. Modifies string in place, and return string itself, not a copy. The return value is to allow nesting such as

C code

 g_ascii_strup (g_strcanon (str, "abc", '?'))

strcasecmp

strcasecmp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

s1: a string

-> Text

s2: a string to compare with s1

-> m Int32

Returns: 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

Deprecated: (Since version 2.2)See strncasecmp for a discussion of why this function is deprecated and how to replace it.

A case-insensitive string comparison, corresponding to the standard strcasecmp() function on platforms which support it.

strchomp

strchomp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: a string to remove the trailing whitespace from

-> m Text

Returns: string

Removes trailing whitespace from a string.

This function doesn't allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

The pointer to string is returned to allow the nesting of functions.

Also see strchug and g_strstrip().

strchug

strchug Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: a string to remove the leading whitespace from

-> m Text

Returns: string

Removes leading whitespace from a string, by moving the rest of the characters forward.

This function doesn't allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

The pointer to string is returned to allow the nesting of functions.

Also see strchomp and g_strstrip().

strcmp0

strcmp0 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

str1: a C string or Nothing

-> Maybe Text

str2: another C string or Nothing

-> m Int32

Returns: an integer less than, equal to, or greater than zero, if str1 is <, == or > than str2.

Compares str1 and str2 like strcmp(). Handles Nothing gracefully by sorting it before non-Nothing strings. Comparing two Nothing pointers returns 0.

Since: 2.16

strcompress

strcompress Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

source: a string to compress

-> m Text

Returns: a newly-allocated copy of source with all escaped character compressed

Replaces all escaped characters with their one byte equivalent.

This function does the reverse conversion of strescape.

strdelimit

strdelimit Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: the string to convert

-> Maybe Text

delimiters: a string containing the current delimiters, or Nothing to use the standard delimiters defined in STR_DELIMITERS

-> Int8

newDelimiter: the new delimiter character

-> m Text

Returns: string

Converts any delimiter characters in string to newDelimiter. Any characters in string which are found in delimiters are changed to the newDelimiter character. Modifies string in place, and returns string itself, not a copy. The return value is to allow nesting such as

C code

 g_ascii_strup (g_strdelimit (str, "abc", '?'))

strdown

strdown Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: the string to convert.

-> m Text

Returns: the string

Deprecated: (Since version 2.2)This function is totally broken for the reasons discussedin the strncasecmp docs - use asciiStrdown or utf8Strdowninstead.

Converts a string to lower case.

strdup

strdup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

str: the string to duplicate

-> m Text

Returns: a newly-allocated copy of str

Duplicates a string. If str is Nothing it returns Nothing. The returned string should be freed with free when no longer needed.

strerror

strerror Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

errnum: the system error number. See the standard C errno documentation

-> m Text

Returns: a UTF-8 string describing the error code. If the error code is unknown, it returns a string like "unknown error (<code>)".

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.

Note that the string may be translated according to the current locale.

The value of errno will not be changed by this function. However, it may be changed by intermediate function calls, so you should save its value as soon as the call returns: > > int saved_errno; > > ret = read (blah); > saved_errno = errno; > > g_strerror (saved_errno);

strescape

strescape Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

source: a string to escape

-> Maybe Text

exceptions: a string of characters not to escape in source

-> m Text

Returns: a newly-allocated copy of source with certain characters escaped. See above.

Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\v', '\' and '"' in the string source by inserting a '\' before them. 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 '\' followed by their octal representation. Characters supplied in exceptions are not escaped.

strcompress does the reverse conversion.

strfreev

strfreev Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

strArray: a Nothing-terminated array of strings to free

-> m () 

Frees a Nothing-terminated array of strings, as well as each string it contains.

If strArray is Nothing, this function simply returns.

stringNew

stringNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

init: the initial text to copy into the string, or Nothing to start with an empty string

-> m String

Returns: the new String

Creates a new String, initialized with the given string.

stringNewLen

stringNewLen Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

init: initial contents of the string

-> Int64

len: length of init to use

-> m String

Returns: a new String

Creates a new String with len bytes of the init buffer. Because a length is provided, init need not be nul-terminated, and can contain embedded nul bytes.

Since this function does not stop at nul bytes, it is the caller's responsibility to ensure that init has at least len addressable bytes.

stringSizedNew

stringSizedNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

dflSize: the default size of the space allocated to hold the string

-> m String

Returns: the new String

Creates a new String, with enough space for dflSize bytes. This is useful if you are going to add a lot of text to the string and don't want it to be reallocated too often.

stripContext

stripContext Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

msgid: a string

-> Text

msgval: another string

-> m Text

Returns: msgval, unless msgval is identical to msgid and contains a '|' character, in which case a pointer to the substring of msgid after the first '|' character is returned.

An auxiliary function for gettext() support (see Q_()).

Since: 2.4

strjoinv

strjoinv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

separator: a string to insert between each of the strings, or Nothing

-> Text

strArray: a Nothing-terminated array of strings to join

-> m Text

Returns: a newly-allocated string containing all of the strings joined together, with separator between them

Joins a number of strings together to form one long string, with the optional separator inserted between each of them. The returned string should be freed with free.

If strArray has no items, the return value will be an empty string. If strArray contains a single item, separator will not appear in the resulting string.

strlcat

strlcat Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

dest: destination buffer, already containing one nul-terminated string

-> Text

src: source buffer

-> Word64

destSize: length of dest buffer in bytes (not length of existing string inside dest)

-> m Word64

Returns: size of attempted result, which is MIN (dest_size, strlen (original dest)) + strlen (src), so if retval >= dest_size, truncation occurred.

Portability wrapper that calls strlcat() on systems which have it, and emulates it otherwise. Appends nul-terminated src string to dest, guaranteeing nul-termination for dest. The total size of dest won't exceed destSize.

At most destSize - 1 characters will be copied. Unlike strncat(), destSize is the full size of dest, not the space left over. This function does not allocate memory. It always nul-terminates (unless destSize == 0 or there were no nul characters in the destSize characters of dest to start with).

Caveat: this is supposedly a more secure alternative to strcat() or strncat(), but for real security g_strconcat() is harder to mess up.

strlcpy

strlcpy Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

dest: destination buffer

-> Text

src: source buffer

-> Word64

destSize: length of dest in bytes

-> m Word64

Returns: length of src

Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise. Copies src to dest; dest is guaranteed to be nul-terminated; src must be nul-terminated; destSize is the buffer size, not the number of bytes to copy.

At most destSize - 1 characters will be copied. Always nul-terminates (unless destSize is 0). This function does not allocate memory. Unlike strncpy(), this function doesn't pad dest (so it's often faster). It returns the size of the attempted result, strlen (src), so if retval >= destSize, truncation occurred.

Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(), but if you really want to avoid screwups, strdup is an even better idea.

strncasecmp

strncasecmp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

s1: a string

-> Text

s2: a string to compare with s1

-> Word32

n: the maximum number of characters to compare

-> m Int32

Returns: 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

Deprecated: (Since version 2.2)The problem with strncasecmp is that it does the comparison by calling toupper()/tolower(). These functions are locale-specific and operate on single bytes. However, it is impossible to handle things correctly from an internationalization standpoint by operating on bytes, since characters may be multibyte. Thus 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, which only works on ASCII and is not locale-sensitive, and utf8Casefold followed by strcmp() on the resulting strings, which is good for case-insensitive sorting of UTF-8.

A case-insensitive string comparison, corresponding to the standard strncasecmp() function on platforms which support it. It is similar to strcasecmp except it only compares the first n characters of the strings.

strndup

strndup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: the string to duplicate

-> Word64

n: the maximum number of bytes to copy from str

-> m Text

Returns: a newly-allocated buffer containing the first n bytes of str, nul-terminated

Duplicates the first n bytes of a string, returning a newly-allocated buffer n + 1 bytes long which will always be nul-terminated. If str is less than n bytes long the buffer is padded with nuls. If str is Nothing it returns Nothing. The returned value should be freed when no longer needed.

To copy a number of characters from a UTF-8 encoded string, use utf8Strncpy instead.

strnfill

strnfill Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

length: the length of the new string

-> Int8

fillChar: the byte to fill the string with

-> m Text

Returns: a newly-allocated string filled the fillChar

Creates a new string length bytes long filled with fillChar. The returned string should be freed when no longer needed.

strreverse

strreverse Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: the string to reverse

-> m Text

Returns: the same pointer passed in as string

Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".

Note that strreverse doesn't work on UTF-8 strings containing multibyte characters. For that purpose, use utf8Strreverse.

strrstr

strrstr Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

haystack: a nul-terminated string

-> Text

needle: the nul-terminated string to search for

-> m Text

Returns: a pointer to the found occurrence, or Nothing if not found.

Searches the string haystack for the last occurrence of the string needle.

strrstrLen

strrstrLen Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

haystack: a nul-terminated string

-> Int64

haystackLen: the maximum length of haystack

-> Text

needle: the nul-terminated string to search for

-> m Text

Returns: a pointer to the found occurrence, or Nothing if not found.

Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystackLen.

strsignal

strsignal Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

signum: the signal number. See the signal documentation

-> m Text

Returns: a UTF-8 string describing the signal. If the signal is unknown, it returns "unknown signal (<signum>)".

Returns a string describing the given signal, e.g. "Segmentation fault". You should use this function in preference to strsignal(), because it returns a string in UTF-8 encoding, and since not all platforms support the strsignal() function.

strstrLen

strstrLen Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

haystack: a string

-> Int64

haystackLen: the maximum length of haystack. Note that -1 is a valid length, if haystack is nul-terminated, meaning it will search through the whole string.

-> Text

needle: the string to search for

-> m Text

Returns: a pointer to the found occurrence, or Nothing if not found.

Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystackLen.

strtod

strtod Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

nptr: the string to convert to a numeric value.

-> m (Double, Text)

Returns: the gdouble value.

Converts a string to a gdouble value. It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with asciiStrtod, 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. 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.

strup

strup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

string: the string to convert

-> m Text

Returns: the string

Deprecated: (Since version 2.2)This function is totally broken for the reasons discussed in the strncasecmp docs - use asciiStrup or utf8Strup instead.

Converts a string to upper case.

strvContains

strvContains Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

strv: a Nothing-terminated array of strings

-> Text

str: a string

-> m Bool

Returns: True if str is an element of strv, according to strEqual.

Checks if strv contains str. strv must not be Nothing.

Since: 2.44

strvGetType

strvGetType :: (HasCallStack, MonadIO m) => m GType Source #

No description available in the introspection data.

strvLength

strvLength Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

strArray: a Nothing-terminated array of strings

-> m Word32

Returns: length of strArray.

Returns the length of the given Nothing-terminated string array strArray.

Since: 2.6

testAddDataFunc

testAddDataFunc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

testpath: /-separated test case path name for the test.

-> Ptr ()

testData: Test data argument for the test function.

-> TestDataFunc

testFunc: The test function to invoke for this test.

-> m () 

Create a new test case, similar to g_test_create_case(). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the slash-separated portions of testpath. The testData argument will be passed as first argument to testFunc.

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or testTrapSubprocess.

Since: 2.16

testAddFunc

testAddFunc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

testpath: /-separated test case path name for the test.

-> TestFunc

testFunc: The test function to invoke for this test.

-> m () 

Create a new test case, similar to g_test_create_case(). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the slash-separated portions of testpath.

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or testTrapSubprocess.

Since: 2.16

testAssertExpectedMessagesInternal

testAssertExpectedMessagesInternal :: (HasCallStack, MonadIO m) => Text -> Text -> Int32 -> Text -> m () Source #

No description available in the introspection data.

testBug

testBug Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

bugUriSnippet: Bug specific bug tracker URI portion.

-> m () 

This function adds a message to test reports that associates a bug URI with a test case. Bug URIs are constructed from a base URI set with testBugBase and bugUriSnippet.

Since: 2.16

testBugBase

testBugBase Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

uriPattern: the base pattern for bug URIs

-> m () 

Specify the base URI for bug reports.

The base URI is used to construct bug report messages for g_test_message() when testBug is called. Calling this function outside of a test case sets the default base URI for all test cases. Calling it from within a test case changes the base URI for the scope of the test case only. Bug URIs are constructed by appending a bug specific URI portion to uriPattern, or by replacing the special string '%s' within uriPattern if that is present.

Since: 2.16

testExpectMessage

testExpectMessage Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

logDomain: the log domain of the message

-> [LogLevelFlags]

logLevel: the log level of the message

-> Text

pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]

-> m () 

Indicates that a message with the given logDomain and logLevel, with text matching pattern, is expected to be logged. When this message is logged, it will not be printed, and the test case will not abort.

This API may only be used with the old logging API (g_log() without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See [Testing for Messages][testing-for-messages].

Use g_test_assert_expected_messages() to assert that all previously-expected messages have been seen and suppressed.

You can call this multiple times in a row, if multiple messages are expected as a result of a single call. (The messages must appear in the same order as the calls to testExpectMessage.)

For example:

C code

 // 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 g_error() messages, since g_error() intentionally never returns even if the program doesn't abort; use testTrapSubprocess in this case.

If messages at LogLevelFlagsLevelDebug are emitted, but not explicitly expected via testExpectMessage then they will be ignored.

Since: 2.34

testFail

testFail :: (HasCallStack, MonadIO m) => m () Source #

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.

Since: 2.30

testFailed

testFailed Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Bool

Returns: True if the test has failed

Returns whether a test has already failed. This will be the case when testFail, testIncomplete or testSkip 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.

Since: 2.38

testGetDir

testGetDir Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> TestFileType

fileType: the type of file (built vs. distributed)

-> m [Char]

Returns: the path of the directory, owned by GLib

Gets the pathname of the directory containing test files of the type specified by fileType.

This is approximately the same as calling g_test_build_filename("."), but you don't need to free the return value.

Since: 2.38

testIncomplete

testIncomplete Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

msg: explanation

-> m () 

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.

Since: 2.38

testLogTypeName

testLogTypeName :: (HasCallStack, MonadIO m) => TestLogType -> m Text Source #

No description available in the introspection data.

testQueueDestroy

testQueueDestroy Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> DestroyNotify

destroyFunc: Destroy callback for teardown phase.

-> Ptr ()

destroyData: Destroy callback data.

-> m () 

This function enqueus a callback destroyFunc to be executed during the next test case teardown phase. This is most useful to auto destruct allocated test resources at the end of a test run. Resources are released in reverse queue order, that means enqueueing callback A before callback B will cause B() to be called before A() during teardown.

Since: 2.16

testQueueFree

testQueueFree Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

gfreePointer: the pointer to be stored.

-> m () 

Enqueue a pointer to be released with free during the next teardown phase. This is equivalent to calling testQueueDestroy with a destroy callback of free.

Since: 2.16

testRandDouble

testRandDouble Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Double

Returns: a random number from the seeded random number generator.

Get a reproducible random floating point number, see testRandInt for details on test case random numbers.

Since: 2.16

testRandDoubleRange

testRandDoubleRange Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Double

rangeStart: the minimum value returned by this function

-> Double

rangeEnd: the minimum value not returned by this function

-> m Double

Returns: a number with rangeStart <= number < rangeEnd.

Get a reproducible random floating pointer number out of a specified range, see testRandInt for details on test case random numbers.

Since: 2.16

testRandInt

testRandInt Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Int32

Returns: a random number from the seeded random number generator.

Get a reproducible random integer number.

The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the --seed option is given when starting test programs.

For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make --seed effective for all test cases.

Since: 2.16

testRandIntRange

testRandIntRange Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

begin: the minimum value returned by this function

-> Int32

end: the smallest value not to be returned by this function

-> m Int32

Returns: a number with begin <= number < end.

Get a reproducible random integer number out of a specified range, see testRandInt for details on test case random numbers.

Since: 2.16

testRun

testRun Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Int32

Returns: 0 on success, 1 on failure (assuming it returns at all), 0 or 77 if all tests were skipped with testSkip

Runs all tests under the toplevel suite which can be retrieved with g_test_get_root(). Similar to testRunSuite, the test cases to be run are filtered according to test path arguments (-p testpath and -s testpath) as parsed by g_test_init(). testRunSuite or testRun may only be called once in a program.

In general, the tests and sub-suites within each suite are run in the order in which they are defined. However, note that prior to GLib 2.36, there was a bug in the g_test_add_* functions which caused them to create multiple suites with the same name, meaning that if you created tests "/foo/simple", "/bar/simple", and "/foo/using-bar" in that order, they would get run in that order (since testRun would run the first "/foo" suite, then the "/bar" suite, then the second "/foo" suite). As of 2.36, this bug is fixed, and adding the tests in that order would result in a running order of "/foo/simple", "/foo/using-bar", "/bar/simple". If this new ordering is sub-optimal (because it puts more-complicated tests before simpler ones, making it harder to figure out exactly what has failed), you can fix it by changing the test paths to group tests by suite in a way that will result in the desired running order. Eg, "/simple/foo", "/simple/bar", "/complex/foo-using-bar".

However, you should never make the actual result of a test depend on the order that tests are run in. If you need to ensure that some particular code runs before or after a given test case, use g_test_add(), which lets you specify setup and teardown functions.

If all tests are skipped, this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.

Since: 2.16

testRunSuite

testRunSuite Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> TestSuite

suite: a TestSuite

-> m Int32

Returns: 0 on success

Execute the tests within suite and all nested GTestSuites. The test suites to be executed are filtered according to test path arguments (-p testpath and -s testpath) as parsed by g_test_init(). See the testRun documentation for more information on the order that tests are run in.

testRunSuite or testRun may only be called once in a program.

Since: 2.16

testSetNonfatalAssertions

testSetNonfatalAssertions :: (HasCallStack, MonadIO m) => m () Source #

Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(), g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(), g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(), g_assert_error(), g_test_assert_expected_messages() and the various g_test_trap_assert_*() macros to not abort to program, but instead call testFail and continue. (This also changes the behavior of testFail so that it will not cause the test program to abort after completing the failed test.)

Note that the g_assert_not_reached() and g_assert() are not affected by this.

This function can only be called after g_test_init().

Since: 2.38

testSkip

testSkip Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

msg: explanation

-> m () 

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.

Since: 2.38

testSubprocess

testSubprocess Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Bool

Returns: True if the test program is running under testTrapSubprocess.

Returns True (after g_test_init() has been called) if the test program is running under testTrapSubprocess.

Since: 2.38

testTimerElapsed

testTimerElapsed Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Double

Returns: the time since the last start of the timer, as a double

Get the time since the last start of the timer with testTimerStart.

Since: 2.16

testTimerLast

testTimerLast Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Double

Returns: the last result of testTimerElapsed, as a double

Report the last result of testTimerElapsed.

Since: 2.16

testTimerStart

testTimerStart :: (HasCallStack, MonadIO m) => m () Source #

Start 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

testTrapAssertions :: (HasCallStack, MonadIO m) => Text -> Text -> Int32 -> Text -> Word64 -> Text -> m () Source #

No description available in the introspection data.

testTrapFork

testTrapFork Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

usecTimeout: Timeout for the forked test in micro seconds.

-> [TestTrapFlags]

testTrapFlags: Flags to modify forking behaviour.

-> m Bool

Returns: True for the forked child and False for the executing parent process.

Deprecated: This function is implemented only on Unix platforms,and is not always reliable due to problems inherent infork-without-exec. Use testTrapSubprocess instead.

Fork the current test program to execute a test case that might not return or that might abort.

If usecTimeout is non-0, the forked test case is aborted and considered failing if its run time exceeds it.

The forking behavior can be configured with the TestTrapFlags flags.

In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.

C code

 static void
 test_fork_patterns (void)
 {
   if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
     {
       g_print ("some stdout text: somagic17\n");
       g_printerr ("some stderr text: semagic43\n");
       exit (0); // successful test run
     }
   g_test_trap_assert_passed ();
   g_test_trap_assert_stdout ("*somagic17*");
   g_test_trap_assert_stderr ("*semagic43*");
 }

Since: 2.16

testTrapHasPassed

testTrapHasPassed Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Bool

Returns: True if the last test subprocess terminated successfully.

Check the result of the last testTrapSubprocess call.

Since: 2.16

testTrapReachedTimeout

testTrapReachedTimeout Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Bool

Returns: True if the last test subprocess got killed due to a timeout.

Check the result of the last testTrapSubprocess call.

Since: 2.16

testTrapSubprocess

testTrapSubprocess Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

testPath: Test to run in a subprocess

-> Word64

usecTimeout: Timeout for the subprocess test in micro seconds.

-> [TestSubprocessFlags]

testFlags: Flags to modify subprocess behaviour.

-> m () 

Respawns the test program to run only testPath in a subprocess. This can be used for a test case that might not return, or that might abort.

If testPath is Nothing then the same test is re-run in a subprocess. You can use testSubprocess to determine whether the test is in a subprocess or not.

testPath can also be the name of the parent test, followed by "/subprocess/" and then a name for the specific subtest (or just ending with "/subprocess" if the test only has one child test); tests with names of this form will automatically be skipped in the parent process.

If usecTimeout is non-0, the test subprocess is aborted and considered failing if its run time exceeds it.

The subprocess behavior can be configured with the TestSubprocessFlags flags.

You can use methods such as g_test_trap_assert_passed(), g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to check the results of the subprocess. (But note that g_test_trap_assert_stdout() and g_test_trap_assert_stderr() cannot be used if testFlags specifies that the child should inherit the parent stdout/stderr.)

If your main () needs to behave differently in the subprocess, you can call testSubprocess (after calling g_test_init()) to see whether you are in a subprocess.

The following example tests that calling my_object_new(1000000) will abort with an error message.

C code

 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, 0);
   g_test_trap_assert_failed ();
   g_test_trap_assert_stderr ("*ERROR*too large*");
 }

 int
 main (int argc, char **argv)
 {
   g_test_init (&argc, &argv, NULL);

   g_test_add_func ("/myobject/create_large_object",
                    test_create_large_object);
   return g_test_run ();
 }

Since: 2.38

timeoutAdd

timeoutAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

priority: the priority of the timeout source. Typically this will be in the range between PRIORITY_DEFAULT and PRIORITY_HIGH.

-> Word32

interval: the time between calls to the function, in milliseconds (1/1000ths of a second)

-> SourceFunc

function: function to call

-> m Word32

Returns: the ID (greater than 0) of the event source.

Sets a function to be called at regular intervals, with the given priority. The function is called repeatedly until it returns False, at which point the timeout is automatically destroyed and the function will not be called again. The notify function is called when the timeout is destroyed. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

See [memory management of sources][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 and attaches it to the global MainContext using sourceAttach, 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 in terms of monotonic time, not wall clock time. See getMonotonicTime.

timeoutAddSeconds

timeoutAddSeconds Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

priority: the priority of the timeout source. Typically this will be in the range between PRIORITY_DEFAULT and PRIORITY_HIGH.

-> Word32

interval: the time between calls to the function, in seconds

-> SourceFunc

function: function to call

-> m Word32

Returns: the ID (greater than 0) of the event source.

Sets a function to be called at regular intervals, with priority. The function is called repeatedly until it returns False, at which point the timeout is automatically destroyed and the function will not be called again.

Unlike g_timeout_add(), this function operates at whole second granularity. The initial starting point of the timer is determined by the implementation and the implementation is expected to group multiple timers together so that they fire all at the same time. To allow this grouping, the interval to the first timer is rounded and can deviate up to one second from the specified interval. Subsequent timer iterations will generally run at the specified interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval

See [memory management of sources][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 g_timeout_add() 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 g_timeout_add_seconds() is preferred over g_timeout_add().

This internally creates a main loop source using timeoutSourceNewSeconds and attaches it to the main loop context using sourceAttach. You can do these steps manually if you need greater control.

The interval given is in terms of monotonic time, not wall clock time. See getMonotonicTime.

Since: 2.14

timeoutSourceNew

timeoutSourceNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

interval: the timeout interval in milliseconds.

-> m Source

Returns: the newly-created timeout source

Creates a new timeout source.

The source will not initially be associated with any MainContext and must be added to one with sourceAttach before it will be executed.

The interval given is in terms of monotonic time, not wall clock time. See getMonotonicTime.

timeoutSourceNewSeconds

timeoutSourceNewSeconds Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

interval: the timeout interval in seconds

-> m Source

Returns: the newly-created timeout source

Creates a new timeout source.

The source will not initially be associated with any MainContext and must be added to one with sourceAttach before it will be executed.

The scheduling granularity/accuracy of this timeout source will be in seconds.

The interval given in terms of monotonic time, not wall clock time. See getMonotonicTime.

Since: 2.14

tryMalloc

tryMalloc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBytes: number of bytes to allocate.

-> m (Ptr ())

Returns: the allocated memory, or Nothing.

Attempts to allocate nBytes, and returns Nothing on failure. Contrast with malloc, which aborts the program on failure.

tryMalloc0

tryMalloc0 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBytes: number of bytes to allocate

-> m (Ptr ())

Returns: the allocated memory, or Nothing

Attempts to allocate nBytes, initialized to 0's, and returns Nothing on failure. Contrast with malloc0, which aborts the program on failure.

Since: 2.8

tryMalloc0N

tryMalloc0N Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBlocks: the number of blocks to allocate

-> Word64

nBlockBytes: the size of each block in bytes

-> m (Ptr ())

Returns: the allocated memory, or Nothing

This function is similar to tryMalloc0, allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

Since: 2.24

tryMallocN

tryMallocN Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word64

nBlocks: the number of blocks to allocate

-> Word64

nBlockBytes: the size of each block in bytes

-> m (Ptr ())

Returns: the allocated memory, or Nothing.

This function is similar to tryMalloc, allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

Since: 2.24

tryRealloc

tryRealloc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

mem: previously-allocated memory, or Nothing.

-> Word64

nBytes: number of bytes to allocate.

-> m (Ptr ())

Returns: the allocated memory, or Nothing.

Attempts to realloc mem to a new size, nBytes, and returns Nothing on failure. Contrast with realloc, which aborts the program on failure.

If mem is Nothing, behaves the same as tryMalloc.

tryReallocN

tryReallocN Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Ptr ()

mem: previously-allocated memory, or Nothing.

-> Word64

nBlocks: the number of blocks to allocate

-> Word64

nBlockBytes: the size of each block in bytes

-> m (Ptr ())

Returns: the allocated memory, or Nothing.

This function is similar to tryRealloc, allocating (nBlocks * nBlockBytes) bytes, but care is taken to detect possible overflow during multiplication.

Since: 2.24

unicharBreakType

unicharBreakType Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m UnicodeBreakType

Returns: the break type of c

Determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use utf8GetChar). 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.

unicharCombiningClass

unicharCombiningClass Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

uc: a Unicode character

-> m Int32

Returns: the combining class of the character

Determines the canonical combining class of a Unicode character.

Since: 2.14

unicharCompose

unicharCompose Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

a: a Unicode character

-> Char

b: a Unicode character

-> Char

ch: return location for the composed character

-> m Bool

Returns: True if the characters could be composed

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 unicharDecompose. No composition can have either of a or b equal to zero. To be precise, this function composes if and only if there exists a Primary Composite P which is canonically equivalent to the sequence <a,b>. See the Unicode Standard for the definition of Primary Composite.

If a and b do not compose a new character, ch is set to zero.

See UAX#15 for details.

Since: 2.30

unicharDecompose

unicharDecompose Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

ch: a Unicode character

-> Char

a: return location for the first component of ch

-> Char

b: return location for the second component of ch

-> m Bool

Returns: True if the character could be decomposed

Performs a single decomposition step of the Unicode canonical decomposition algorithm.

This function does not include compatibility decompositions. It does, however, include algorithmic Hangul Jamo decomposition, as well as 'singleton' decompositions which replace a character by a single other character. In the case of singletons *b will be set to zero.

If ch is not decomposable, *a is set to ch and *b is set to zero.

Note that the way Unicode decomposition pairs are defined, it is guaranteed that b would not decompose further, but a may itself decompose. To get the full canonical decomposition for ch, one would need to recursively call this function on a. Or use g_unichar_fully_decompose().

See UAX#15 for details.

Since: 2.30

unicharDigitValue

unicharDigitValue Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Int32

Returns: If c is a decimal digit (according to unicharIsdigit), its numeric value. Otherwise, -1.

Determines the numeric value of a character as a decimal digit.

unicharGetMirrorChar

unicharGetMirrorChar Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

ch: a Unicode character

-> Char

mirroredCh: location to store the mirrored character

-> m Bool

Returns: True if ch has a mirrored character, False otherwise

In Unicode, some characters are "mirrored". This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.

If ch has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of ch's glyph and mirroredCh is set, it puts that character in the address pointed to by mirroredCh. Otherwise the original character is put.

Since: 2.4

unicharGetScript

unicharGetScript Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

ch: a Unicode character

-> m UnicodeScript

Returns: the UnicodeScript for the character.

Looks up the UnicodeScript for a particular character (as defined by Unicode Standard Annex #24). No check is made for ch being a valid Unicode character; if you pass in invalid character, the result is undefined.

This function is equivalent to pango_script_for_unichar() and the two are interchangeable.

Since: 2.14

unicharIsalnum

unicharIsalnum Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is an alphanumeric character

Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIsalpha

unicharIsalpha Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is an alphabetic character

Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIscntrl

unicharIscntrl Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is a control character

Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIsdefined

unicharIsdefined Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if the character has an assigned value

Determines if a given character is assigned in the Unicode standard.

unicharIsdigit

unicharIsdigit Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is a digit

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 utf8GetChar.

unicharIsgraph

unicharIsgraph Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is printable unless it's a space

Determines whether a character is printable and not a space (returns False for control characters, format characters, and spaces). unicharIsprint is similar, but returns True for spaces. Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIslower

unicharIslower Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is a lowercase letter

Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIsmark

unicharIsmark Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is a mark character

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 utf8GetChar.

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.

Since: 2.14

unicharIsprint

unicharIsprint Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is printable

Determines whether a character is printable. Unlike unicharIsgraph, returns True for spaces. Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIspunct

unicharIspunct Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is a punctuation or symbol character

Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with utf8GetChar.

unicharIsspace

unicharIsspace Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is a space character

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 utf8GetChar.

(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.)

unicharIstitle

unicharIstitle Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if the character is titlecase

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.

unicharIsupper

unicharIsupper Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if c is an uppercase character

Determines if a character is uppercase.

unicharIswide

unicharIswide Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if the character is wide

Determines if a character is typically rendered in a double-width cell.

unicharIswideCjk

unicharIswideCjk Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if the character is wide in legacy East Asian locales

Determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to unicharIswide, 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 unicharIswide test then it will also pass this test, but not the other way around. Note that some characters may pass both this test and unicharIszerowidth.

Since: 2.12

unicharIsxdigit

unicharIsxdigit Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character.

-> m Bool

Returns: True if the character is a hexadecimal digit

Determines if a character is a hexidecimal digit.

unicharIszerowidth

unicharIszerowidth Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Bool

Returns: True if the character has zero width

Determines if a given character typically takes zero width when rendered. The return value is True for all non-spacing and enclosing marks (e.g., combining accents), format characters, zero-width space, but not U+00AD SOFT HYPHEN.

A typical use of this function is with one of unicharIswide or unicharIswideCjk 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.

Since: 2.14

unicharTolower

unicharTolower Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character.

-> m Char

Returns: the result of converting c to lower case. If c is not an upperlower or titlecase character, or has no lowercase equivalent c is returned unchanged.

Converts a character to lower case.

unicharTotitle

unicharTotitle Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Char

Returns: the result of converting c to titlecase. If c is not an uppercase or lowercase character, c is returned unchanged.

Converts a character to the titlecase.

unicharToupper

unicharToupper Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Char

Returns: the result of converting c to uppercase. If c is not an lowercase or titlecase character, or has no upper case equivalent c is returned unchanged.

Converts a character to uppercase.

unicharType

unicharType Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m UnicodeType

Returns: the type of the character.

Classifies a Unicode character by type.

unicharValidate

unicharValidate Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

ch: a Unicode character

-> m Bool

Returns: True if ch is a valid Unicode character

Checks whether ch is a valid Unicode character. Some possible integer values of ch will not be valid. 0 is considered a valid character, though it's normally a string terminator.

unicharXdigitValue

unicharXdigitValue Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

c: a Unicode character

-> m Int32

Returns: If c is a hex digit (according to unicharIsxdigit), its numeric value. Otherwise, -1.

Determines the numeric value of a character as a hexidecimal digit.

unicodeCanonicalDecomposition

unicodeCanonicalDecomposition Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

ch: a Unicode character.

-> Word64

resultLen: location to store the length of the return value.

-> m Char

Returns: a newly allocated string of Unicode characters. resultLen is set to the resulting length of the string.

Deprecated: (Since version 2.30)Use the more flexible g_unichar_fully_decompose() instead.

Computes the canonical decomposition of a Unicode character.

unicodeCanonicalOrdering

unicodeCanonicalOrdering Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Char

string: a UCS-4 encoded string.

-> Word64

len: the maximum length of string to use.

-> m () 

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.

unicodeScriptFromIso15924

unicodeScriptFromIso15924 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Word32

iso15924: a Unicode script

-> m UnicodeScript

Returns: the Unicode script for iso15924, or of UnicodeScriptInvalidCode if iso15924 is zero and UnicodeScriptUnknown if iso15924 is unknown.

Looks up the Unicode script for iso15924. ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is 'Arab'. This function accepts four letter codes encoded as a guint32 in a big-endian fashion. That is, the code expected for Arabic is 0x41726162 (0x41 is ASCII code for 'A', 0x72 is ASCII code for 'r', etc).

See Codes for the representation of names of scripts for details.

Since: 2.30

unicodeScriptToIso15924

unicodeScriptToIso15924 Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> UnicodeScript

script: a Unicode script

-> m Word32

Returns: the ISO 15924 code for script, encoded as an integer, of zero if script is UnicodeScriptInvalidCode or ISO 15924 code 'Zzzz' (script code for UNKNOWN) if script is not understood.

Looks up the ISO 15924 code for script. ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is 'Arab'. The four letter codes are encoded as a guint32 by this function in a big-endian fashion. That is, the code returned for Arabic is 0x41726162 (0x41 is ASCII code for 'A', 0x72 is ASCII code for 'r', etc).

See Codes for the representation of names of scripts for details.

Since: 2.30

unixErrorQuark

unixErrorQuark :: (HasCallStack, MonadIO m) => m Word32 Source #

No description available in the introspection data.

unixFdAddFull

unixFdAddFull Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

priority: the priority of the source

-> Int32

fd: a file descriptor

-> [IOCondition]

condition: IO conditions to watch for on fd

-> UnixFDSourceFunc

function: a UnixFDSourceFunc

-> m Word32

Returns: the ID (greater than 0) of the event source

Sets a function to be called when the IO condition, as specified by condition becomes true for fd.

This is the same as g_unix_fd_add(), except that it allows you to specify a non-default priority and a provide a DestroyNotify for userData.

Since: 2.36

unixFdSourceNew

unixFdSourceNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

fd: a file descriptor

-> [IOCondition]

condition: IO conditions to watch for on fd

-> m Source

Returns: the newly created Source

Creates a Source to watch for a particular IO condition on a file descriptor.

The source will never close the fd -- you must do it yourself.

Since: 2.36

unixOpenPipe

unixOpenPipe Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

fds: Array of two integers

-> Int32

flags: Bitfield of file descriptor flags, as for fcntl()

-> m ()

(Can throw GError)

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. The only supported flag currently is FD_CLOEXEC. If for example you want to configure O_NONBLOCK, that must still be done separately with fcntl().

This function does not take O_CLOEXEC, it takes FD_CLOEXEC as if for fcntl(); these are different on Linux/glibc.

Since: 2.30

unixSetFdNonblocking

unixSetFdNonblocking Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

fd: A file descriptor

-> Bool

nonblock: If True, set the descriptor to be non-blocking

-> m ()

(Can throw GError)

Control the non-blocking state of the given file descriptor, according to nonblock. On most systems this uses O_NONBLOCK, but on some older ones may use O_NDELAY.

Since: 2.30

unixSignalAdd

unixSignalAdd Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

priority: the priority of the signal source. Typically this will be in the range between PRIORITY_DEFAULT and PRIORITY_HIGH.

-> Int32

signum: Signal number

-> SourceFunc

handler: Callback

-> m Word32

Returns: An ID (greater than 0) for the event source

A convenience function for unixSignalSourceNew, which attaches to the default MainContext. You can remove the watch using sourceRemove.

Since: 2.30

unixSignalSourceNew

unixSignalSourceNew Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Int32

signum: A signal number

-> m Source

Returns: A newly created Source

Create a Source that will be dispatched upon delivery of the UNIX signal signum. In GLib versions before 2.36, only SIGHUP, SIGINT, SIGTERM can be monitored. In GLib 2.36, SIGUSR1 and SIGUSR2 were added. In GLib 2.54, SIGWINCH was added.

Note that unlike the UNIX default, all sources which have created a watch will be dispatched, regardless of which underlying thread invoked unixSignalSourceNew.

For example, an effective use of this function is to handle SIGTERM cleanly; flushing any outstanding files, and then calling g_main_loop_quit (). It is not safe to do any of this a regular UNIX signal handler; your handler may be invoked while malloc() or another library function is running, causing reentrancy if you attempt to use it from the handler. 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 MainContext and must be added to one with sourceAttach before it will be executed.

Since: 2.30

unlink

unlink Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

filename: a pathname in the GLib file name encoding (UTF-8 on Windows)

-> m Int32

Returns: 0 if the name was successfully deleted, -1 if an error occurred

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.

Since: 2.6

unsetenv

unsetenv Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> [Char]

variable: the environment variable to remove, must not contain '='

-> m () 

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 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 getEnviron to get an environment array, modify that with environSetenv and environUnsetenv, and then pass that array directly to execvpe(), spawnAsync, or the like.

Since: 2.4

uriEscapeString

uriEscapeString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

unescaped: the unescaped input string.

-> Maybe Text

reservedCharsAllowed: a string of reserved characters that are allowed to be used, or Nothing.

-> Bool

allowUtf8: True if the result can include UTF-8 characters.

-> m Text

Returns: an escaped version of unescaped. The returned string should be freed when no longer needed.

Escapes a string for use in a URI.

Normally all characters that are not "unreserved" (i.e. ASCII alphanumerical characters plus dash, dot, underscore and tilde) are escaped. But if you specify characters in reservedCharsAllowed they are not escaped. This is useful for the "reserved" characters in the URI specification, since those are allowed unescaped in some portions of a URI.

Since: 2.16

uriListExtractUris

uriListExtractUris Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

uriList: an URI list

-> m [Text]

Returns: a newly allocated Nothing-terminated list of strings holding the individual URIs. The array should be freed with strfreev.

Splits an URI list conforming to the text/uri-list mime type defined in RFC 2483 into individual URIs, discarding any comments. The URIs are not validated.

Since: 2.6

uriParseScheme

uriParseScheme Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

uri: a valid URI.

-> m Text

Returns: The "Scheme" component of the URI, or Nothing on error. The returned string should be freed when no longer needed.

Gets the scheme portion of a URI string. RFC 3986 decodes the scheme as: > >URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

Common schemes include "file", "http", "svn+ssh", etc.

Since: 2.16

uriUnescapeSegment

uriUnescapeSegment Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Maybe Text

escapedString: A string, may be Nothing

-> Maybe Text

escapedStringEnd: Pointer to end of escapedString, may be Nothing

-> Maybe Text

illegalCharacters: An optional string of illegal characters not to be allowed, may be Nothing

-> m Text

Returns: an unescaped version of escapedString or Nothing on error. The returned string should be freed when no longer needed. As a special case if Nothing is given for escapedString, this function will return Nothing.

Unescapes a segment of an escaped string.

If any of the characters in illegalCharacters or the character zero appears as an escaped character in escapedString then that is an error and Nothing will be returned. This is useful it you want to avoid for instance having a slash being expanded in an escaped path element, which might confuse pathname handling.

Since: 2.16

uriUnescapeString

uriUnescapeString Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

escapedString: an escaped string to be unescaped.

-> Maybe Text

illegalCharacters: a string of illegal characters not to be allowed, or Nothing.

-> m Text

Returns: an unescaped version of escapedString. The returned string should be freed when no longer needed.

Unescapes a whole escaped string.

If any of the characters in illegalCharacters or the character zero appears as an escaped character in escapedString then that is an error and Nothing will be returned. This is useful it you want to avoid for instance having a slash being expanded in an escaped path element, which might confuse pathname handling.

Since: 2.16

usleep

usleep Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> CULong

microseconds: number of microseconds to pause

-> m () 

Pauses the current thread for the given number of microseconds.

There are 1 million microseconds per second (represented by the USEC_PER_SEC macro). usleep may have limited precision, depending on hardware and operating system; don't rely on the exact length of the sleep.

utf8Casefold

utf8Casefold Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> Int64

len: length of str, in bytes, or -1 if str is nul-terminated.

-> m Text

Returns: a newly allocated string, that is a case independent form of str.

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 utf8Casefold on other strings.

Note that calling utf8Casefold followed by utf8Collate 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.

utf8Collate

utf8Collate Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str1: a UTF-8 encoded string

-> Text

str2: a UTF-8 encoded string

-> m Int32

Returns: < 0 if str1 compares before str2, 0 if they compare equal, > 0 if str1 compares after str2.

Compares two strings for ordering using the linguistically correct rules for the [current locale][setlocale]. When sorting a large number of strings, it will be significantly faster to obtain collation keys with utf8CollateKey and compare the keys with strcmp() when sorting instead of sorting the original strings.

utf8CollateKey

utf8CollateKey Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string.

-> Int64

len: length of str, in bytes, or -1 if str is nul-terminated.

-> m Text

Returns: a newly allocated string. This string should be freed with free when you are done with it.

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 utf8Collate.

Note that this function depends on the [current locale][setlocale].

utf8CollateKeyForFilename

utf8CollateKeyForFilename Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string.

-> Int64

len: length of str, in bytes, or -1 if str is nul-terminated.

-> m Text

Returns: a newly allocated string. This string should be freed with free when you are done with it.

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".

Note that this function depends on the [current locale][setlocale].

Since: 2.8

utf8FindNextChar

utf8FindNextChar Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: a pointer to a position within a UTF-8 encoded string

-> Maybe Text

end: a pointer to the byte following the end of the string, or Nothing to indicate that the string is nul-terminated

-> m (Maybe Text)

Returns: a pointer to the found character or Nothing if end is set and is reached

Finds the start of the next UTF-8 character in the string after p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

If end is Nothing, the return value will never be Nothing: if the end of the string is reached, a pointer to the terminating nul byte is returned. If end is non-Nothing, the return value will be Nothing if the end of the string is reached.

utf8FindPrevChar

utf8FindPrevChar Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: pointer to the beginning of a UTF-8 encoded string

-> Text

p: pointer to some position within str

-> m Text

Returns: a pointer to the found character or Nothing.

Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns Nothing if no UTF-8 characters are present in str before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

utf8GetChar

utf8GetChar Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: a pointer to Unicode character encoded as UTF-8

-> m Char

Returns: the resulting character

Converts a sequence of bytes encoded as UTF-8 to a Unicode character.

If p does not point to a valid UTF-8 encoded character, results are undefined. If you are not sure that the bytes are complete valid Unicode characters, you should use utf8GetCharValidated instead.

utf8GetCharValidated

utf8GetCharValidated Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: a pointer to Unicode character encoded as UTF-8

-> Int64

maxLen: the maximum number of bytes to read, or -1 if p is nul-terminated

-> m Char

Returns: the resulting character. If p points to a partial sequence at the end of a string that could begin a valid character (or if maxLen is zero), returns (gunichar)-2; otherwise, if p does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.

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 returns (gunichar)-2 if maxLen is positive and any of the bytes in the first UTF-8 character sequence are nul.

utf8MakeValid

utf8MakeValid Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: string to coerce into UTF-8

-> Int64

len: the maximum length of str to use, in bytes. If len < 0, then the string is nul-terminated.

-> m Text

Returns: a valid UTF-8 string whose content resembles str

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.

Since: 2.52

utf8Normalize

utf8Normalize Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string.

-> Int64

len: length of str, in bytes, or -1 if str is nul-terminated.

-> NormalizeMode

mode: the type of normalization to perform.

-> m Text

Returns: a newly allocated string, that is the normalized form of str, or Nothing if str is not valid UTF-8.

Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. The string has to be valid UTF-8, otherwise Nothing is returned. You should generally call utf8Normalize before comparing two Unicode strings.

The normalization mode NormalizeModeDefault only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. NormalizeModeAll also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.

NormalizeModeDefaultCompose and NormalizeModeAllCompose are like NormalizeModeDefault and NormalizeModeAll, 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.

utf8OffsetToPointer

utf8OffsetToPointer Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> CLong

offset: a character offset within str

-> m Text

Returns: the resulting pointer

Converts from an integer character offset to a pointer to a position within the string.

Since 2.10, this function allows to pass a negative offset to step backwards. It is usually worth stepping backwards from the end instead of forwards if offset is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.

Note that this function doesn't abort when reaching the end of str. Therefore you should be sure that offset is within string boundaries before calling that function. Call utf8Strlen when unsure. This limitation exists as this function is called frequently during text rendering and therefore has to be as fast as possible.

utf8PointerToOffset

utf8PointerToOffset Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> Text

pos: a pointer to a position within str

-> m CLong

Returns: the resulting character offset

Converts from a pointer to position within a string to a integer character offset.

Since 2.10, this function allows pos to be before str, and returns a negative offset in this case.

utf8PrevChar

utf8PrevChar Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: a pointer to a position within a UTF-8 encoded string

-> m Text

Returns: a pointer to the found character

Finds the previous UTF-8 character in the string before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If p might be the first character of the string, you must use utf8FindPrevChar instead.

utf8Strchr

utf8Strchr Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: a nul-terminated UTF-8 encoded string

-> Int64

len: the maximum length of p

-> Char

c: a Unicode character

-> m Text

Returns: Nothing if the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.

Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.

utf8Strdown

utf8Strdown Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> Int64

len: length of str, in bytes, or -1 if str is nul-terminated.

-> m Text

Returns: a newly allocated string, with all characters converted to lowercase.

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.

utf8Strlen

utf8Strlen Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: pointer to the start of a UTF-8 encoded string

-> Int64

max: the maximum number of bytes to examine. If max is less than 0, then the string is assumed to be nul-terminated. If max is 0, p will not be examined and may be Nothing. If max is greater than 0, up to max bytes are examined

-> m CLong

Returns: the length of the string in characters

Computes the length of the string in characters, not including the terminating nul character. If the max'th byte falls in the middle of a character, the last (partial) character is not counted.

utf8Strncpy

utf8Strncpy Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

dest: buffer to fill with characters from src

-> Text

src: UTF-8 encoded string

-> Word64

n: character count

-> m Text

Returns: dest

Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes. The src string must be valid UTF-8 encoded text. (Use utf8Validate on all text before trying to use UTF-8 utility functions with it.)

Note you must ensure dest is at least 4 * n to fit the largest possible UTF-8 characters

utf8Strrchr

utf8Strrchr Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

p: a nul-terminated UTF-8 encoded string

-> Int64

len: the maximum length of p

-> Char

c: a Unicode character

-> m Text

Returns: Nothing if the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.

Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.

utf8Strreverse

utf8Strreverse Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> Int64

len: the maximum length of str to use, in bytes. If len < 0, then the string is nul-terminated.

-> m Text

Returns: a newly-allocated string which is the reverse of str

Reverses a UTF-8 string. str must be valid UTF-8 encoded text. (Use utf8Validate 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, this function returns newly-allocated memory, which should be freed with free when no longer needed.

Since: 2.2

utf8Strup

utf8Strup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> Int64

len: length of str, in bytes, or -1 if str is nul-terminated.

-> m Text

Returns: a newly allocated string, with all characters converted to uppercase.

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.)

utf8Substring

utf8Substring Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a UTF-8 encoded string

-> CLong

startPos: a character offset within str

-> CLong

endPos: another character offset within str

-> m Text

Returns: a newly allocated copy of the requested substring. Free with free when no longer needed.

Copies a substring out of a UTF-8 encoded string. The substring will contain endPos - startPos characters.

Since: 2.30

utf8Validate

utf8Validate Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> ByteString

str: a pointer to character data

-> m (Bool, Text)

Returns: True if the text was valid UTF-8

Validates UTF-8 encoded text. str is the text to validate; if str is nul-terminated, then maxLen can be -1, otherwise maxLen should be the number of bytes to validate. If end is non-Nothing, then the end of the valid range will be stored there (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).

Note that utf8Validate returns False if maxLen is positive and any of the maxLen bytes are nul.

Returns True if all of str was valid. Many GLib and GTK+ routines require valid UTF-8 as input; so data read from a file or the network should be checked with utf8Validate before doing anything else with it.

uuidStringIsValid

uuidStringIsValid Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> Text

str: a string representing a UUID

-> m Bool

Returns: True if str is a valid UUID, False otherwise.

Parses the string str and verify if it is a UUID.

The function accepts the following syntax:

  • simple forms (e.g. f81d4fae-7dec-11d0-a765-00a0c91e6bf6)

Note that hyphens are required within the UUID string itself, as per the aforementioned RFC.

Since: 2.52

uuidStringRandom

uuidStringRandom Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> m Text

Returns: A string that should be freed with free.

Generates a random UUID (RFC 4122 version 4) as a string.

Since: 2.52

variantGetGtype

variantGetGtype :: (HasCallStack, MonadIO m) => m GType Source #

No description available in the introspection data.