Class IOChannel

All Implemented Interfaces:
Proxy

@Generated("org.javagi.JavaGI") public class IOChannel extends ProxyInstance

The GIOChannel data type aims to provide a portable method for using file descriptors, pipes, and sockets, and integrating them into the main event loop (see GLib.MainContext). Currently, full support is available on UNIX platforms; support for Windows is only partially complete.

To create a new GIOChannel on UNIX systems use unixNew(int). This works for plain file descriptors, pipes and sockets. Alternatively, a channel can be created for a file in a system independent manner using file(String, String).

Once a GIOChannel has been created, it can be used in a generic manner with the functions readChars(Out, Out), writeChars(byte[], long, Out), seekPosition(long, SeekType), and shutdown(boolean).

To add a GIOChannel to the main event loop, use GLib.ioAddWatch(IOChannel, int, Set, IOFunc) or GLib.ioAddWatchFull. Here you specify which events you are interested in on the GIOChannel, and provide a function to be called whenever these events occur.

GIOChannel instances are created with an initial reference count of 1. ref() and unref() can be used to increment or decrement the reference count respectively. When the reference count falls to 0, the GIOChannel is freed. (Though it isn’t closed automatically, unless it was created using file(String, String).) Using GLib.ioAddWatch(IOChannel, int, Set, IOFunc) or GLib.ioAddWatchFull increments a channel’s reference count.

The new functions readChars(Out, Out), readLine(Out, Out, Out), readLineString(String, MemorySegment), readToEnd(Out), writeChars(byte[], long, Out), seekPosition(long, SeekType), and flush() should not be mixed with the deprecated functions read(String, long, MemorySegment), write(String, long, MemorySegment), and seek(long, SeekType) on the same channel.

  • Constructor Details

    • IOChannel

      public IOChannel(MemorySegment address)
      Create a IOChannel proxy instance for the provided memory address.
      Parameters:
      address - the memory address of the native object
  • Method Details

    • getType

      public static @Nullable Type getType()
      Get the GType of the IOChannel class.
      Returns:
      the GType
    • getMemoryLayout

      public static MemoryLayout getMemoryLayout()
      The memory layout of the native struct.
      Returns:
      the memory layout
    • file

      public static IOChannel file(String filename, String mode) throws GErrorException
      Open a file filename as a GIOChannel using mode mode. This channel will be closed when the last reference to it is dropped, so there is no need to call g_io_channel_close() (though doing so will not cause problems, as long as no attempt is made to access the channel after it is closed).
      Parameters:
      filename - A string containing the name of a file
      mode - One of "r", "w", "a", "r+", "w+", "a+". These have the same meaning as in fopen()
      Returns:
      A GIOChannel on success, null on failure.
      Throws:
      GErrorException - see GError
    • unixNew

      public static IOChannel unixNew(int fd)

      Creates a new GIOChannel given a file descriptor. On UNIX systems this works for plain files, pipes, and sockets.

      The returned GIOChannel has a reference count of 1.

      The default encoding for GIOChannel is UTF-8. If your application is reading output from a command using via pipe, you may need to set the encoding to the encoding of the current locale (see g_get_charset()) with the g_io_channel_set_encoding() function. By default, the fd passed will not be closed when the final reference to the GIOChannel data structure is dropped.

      If you want to read raw binary data without interpretation, then call the g_io_channel_set_encoding() function with null for the encoding argument.

      This function is available in GLib on Windows, too, but you should avoid using it on Windows. The domain of file descriptors and sockets overlap. There is no way for GLib to know which one you mean in case the argument you pass to this function happens to be both a valid file descriptor and socket. If that happens a warning is issued, and GLib assumes that it is the file descriptor you mean.

      Parameters:
      fd - a file descriptor.
      Returns:
      a new GIOChannel.
    • win32NewFd

      public static IOChannel win32NewFd(int fd)

      Creates a new GIOChannel given a file descriptor on Windows. This works for file descriptors from the C runtime.

      This function works for file descriptors as returned by the open(), creat(), pipe() and fileno() calls in the Microsoft C runtime. In order to meaningfully use this function your code should use the same C runtime as GLib uses, which is msvcrt.dll. Note that in current Microsoft compilers it is near impossible to convince it to build code that would use msvcrt.dll. The last Microsoft compiler version that supported using msvcrt.dll as the C runtime was version 6. The GNU compiler and toolchain for Windows, also known as Mingw, fully supports msvcrt.dll.

      If you have created a GIOChannel for a file descriptor and started watching (polling) it, you shouldn't call read() on the file descriptor. This is because adding polling for a file descriptor is implemented in GLib on Windows by starting a thread that sits blocked in a read() from the file descriptor most of the time. All reads from the file descriptor should be done by this internal GLib thread. Your code should call only g_io_channel_read().

      This function is available only in GLib on Windows.

      Parameters:
      fd - a C library file descriptor.
      Returns:
      a new GIOChannel.
    • win32NewMessages

      public static IOChannel win32NewMessages(long hwnd)

      Creates a new GIOChannel given a window handle on Windows.

      This function creates a GIOChannel that can be used to poll for Windows messages for the window in question.

      Parameters:
      hwnd - a window handle.
      Returns:
      a new GIOChannel.
    • win32NewSocket

      public static IOChannel win32NewSocket(int socket)

      Creates a new GIOChannel given a socket on Windows.

      This function works for sockets created by Winsock. It's available only in GLib on Windows.

      Polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

      Parameters:
      socket - a Winsock socket
      Returns:
      a new GIOChannel
    • win32NewStreamSocket

      public static IOChannel win32NewStreamSocket(int socket)
    • errorFromErrno

      public static IOChannelError errorFromErrno(int en)
      Converts an errno error number to a GIOChannelError.
      Parameters:
      en - an errno error number, e.g. EINVAL
      Returns:
      a GIOChannelError error number, e.g. IOChannelError.INVAL.
    • errorQuark

      public static Quark errorQuark()
    • win32Poll

      public static int win32Poll(PollFD fds, int nFds, int timeout)
    • close

      @Deprecated public void close()
      Deprecated.
      Use g_io_channel_shutdown() instead.
      Close an IO channel. Any pending data to be written will be flushed, ignoring errors. The channel will not be freed until the last reference is dropped using g_io_channel_unref().
    • flush

      public IOStatus flush() throws GErrorException
      Flushes the write buffer for the GIOChannel.
      Returns:
      the status of the operation: One of IOStatus.NORMAL, IOStatus.AGAIN, or IOStatus.ERROR.
      Throws:
      GErrorException - see GError
    • getBufferCondition

      public Set<IOCondition> getBufferCondition()
      This function returns a GIOCondition depending on whether there is data to be read/space to write data in the internal buffers in the GIOChannel. Only the flags IOCondition.IN and IOCondition.OUT may be set.
      Returns:
      A GIOCondition
    • getBufferSize

      public long getBufferSize()
      Gets the buffer size.
      Returns:
      the size of the buffer.
    • getBuffered

      public boolean getBuffered()
      Returns whether this IOChannel is buffered.
      Returns:
      true if the this IOChannel is buffered.
    • getCloseOnUnref

      public boolean getCloseOnUnref()
      Returns whether the file/socket/whatever associated with this IOChannel will be closed when this IOChannel receives its final unref and is destroyed. The default value of this is true for channels created by g_io_channel_new_file (), and false for all other channels.
      Returns:
      true if the channel will be closed, false otherwise.
    • getEncoding

      public String getEncoding()
      Gets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The encoding null makes the channel safe for binary data.
      Returns:
      A string containing the encoding, this string is owned by GLib and must not be freed.
    • getFlags

      public Set<IOFlags> getFlags()

      Gets the current flags for a GIOChannel, including read-only flags such as IOFlags.IS_READABLE.

      The values of the flags IOFlags.IS_READABLE and IOFlags.IS_WRITABLE are cached for internal use by the channel when it is created. If they should change at some later point (e.g. partial shutdown of a socket with the UNIX shutdown() function), the user should immediately call g_io_channel_get_flags() to update the internal values of these flags.

      Returns:
      the flags which are set on the channel
    • getLineTerm

      public String getLineTerm(@Nullable Out<Integer> length)
      This returns the string that GIOChannel uses to determine where in the file a line break occurs. A value of null indicates autodetection. Since 2.84, the return value is always nul-terminated.
      Parameters:
      length - a location to return the length of the line terminator
      Returns:
      The line termination string. This value is owned by GLib and must not be freed.
    • init

      public void init()

      Initializes a GIOChannel struct.

      This is called by each of the above functions when creating a GIOChannel, and so is not often needed by the application programmer (unless you are creating a new type of GIOChannel).

    • read

      @Deprecated public IOError read(String buf, long count, MemorySegment bytesRead)
      Deprecated.
      Use g_io_channel_read_chars() instead.
      Reads data from a GIOChannel.
      Parameters:
      buf - a buffer to read the data into (which should be at least count bytes long)
      count - the number of bytes to read from the GIOChannel
      bytesRead - returns the number of bytes actually read
      Returns:
      IOError.NONE if the operation was successful.
    • readChars

      public IOStatus readChars(@Nullable Out<byte[]> buf, @Nullable Out<Long> bytesRead) throws GErrorException
      Replacement for g_io_channel_read() with the new API.
      Parameters:
      buf - a buffer to read data into
      bytesRead - The number of bytes read. This may be zero even on success if count < 6 and the channel's encoding is non-null. This indicates that the next UTF-8 character is too wide for the buffer.
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • readLine

      public IOStatus readLine(Out<String> strReturn, @Nullable Out<Long> length, @Nullable Out<Long> terminatorPos) throws GErrorException
      Reads a line, including the terminating character(s), from a GIOChannel into a newly-allocated string. strReturn will contain allocated memory if the return is IOStatus.NORMAL.
      Parameters:
      strReturn - The line read from the GIOChannel, including the line terminator. This data should be freed with g_free() when no longer needed. This is a nul-terminated string. If a length of zero is returned, this will be null instead.
      length - location to store length of the read data, or null
      terminatorPos - location to store position of line terminator, or null
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • readLineString

      public IOStatus readLineString(String buffer, @Nullable MemorySegment terminatorPos) throws GErrorException
      Reads a line from a GIOChannel, using a GString as a buffer.
      Parameters:
      buffer - a GString into which the line will be written. If buffer already contains data, the old data will be overwritten.
      terminatorPos - location to store position of line terminator, or null
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • readToEnd

      public IOStatus readToEnd(@Nullable Out<byte[]> strReturn) throws GErrorException
      Reads all the remaining data from the file.
      Parameters:
      strReturn - Location to store a pointer to a string holding the remaining data in the GIOChannel. This data should be freed with g_free() when no longer needed. This data is terminated by an extra nul character, but there may be other nuls in the intervening data.
      Returns:
      IOStatus.NORMAL on success. This function never returns IOStatus.EOF.
      Throws:
      GErrorException - see GError
    • readUnichar

      public IOStatus readUnichar(Out<Integer> thechar) throws GErrorException
      Reads a Unicode character from channel. This function cannot be called on a channel with null encoding.
      Parameters:
      thechar - a location to return a character
      Returns:
      a GIOStatus
      Throws:
      GErrorException - see GError
    • ref

      public IOChannel ref()
      Increments the reference count of a GIOChannel.
      Returns:
      the this IOChannel that was passed in (since 2.6)
    • seek

      @Deprecated public IOError seek(long offset, SeekType type)
      Deprecated.
      Use g_io_channel_seek_position() instead.
      Sets the current position in the GIOChannel, similar to the standard library function fseek().
      Parameters:
      offset - an offset, in bytes, which is added to the position specified by type
      type - the position in the file, which can be SeekType.CUR (the current position), SeekType.SET (the start of the file), or SeekType.END (the end of the file)
      Returns:
      IOError.NONE if the operation was successful.
    • seekPosition

      public IOStatus seekPosition(long offset, SeekType type) throws GErrorException
      Replacement for g_io_channel_seek() with the new API.
      Parameters:
      offset - The offset in bytes from the position specified by type
      type - a GSeekType. The type SeekType.CUR is only allowed in those cases where a call to g_io_channel_set_encoding () is allowed. See the documentation for g_io_channel_set_encoding () for details.
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • setBufferSize

      public void setBufferSize(long size)
      Sets the buffer size.
      Parameters:
      size - the size of the buffer, or 0 to let GLib pick a good size
    • setBuffered

      public void setBuffered(boolean buffered)

      The buffering state can only be set if the channel's encoding is null. For any other encoding, the channel must be buffered.

      A buffered channel can only be set unbuffered if the channel's internal buffers have been flushed. Newly created channels or channels which have returned IOStatus.EOF not require such a flush. For write-only channels, a call to g_io_channel_flush () is sufficient. For all other channels, the buffers may be flushed by a call to g_io_channel_seek_position (). This includes the possibility of seeking with seek type SeekType.CUR and an offset of zero. Note that this means that socket-based channels cannot be set unbuffered once they have had data read from them.

      On unbuffered channels, it is safe to mix read and write calls from the new and old APIs, if this is necessary for maintaining old code.

      The default state of the channel is buffered.

      Parameters:
      buffered - whether to set the channel buffered or unbuffered
    • setCloseOnUnref

      public void setCloseOnUnref(boolean doClose)

      Whether to close the channel on the final unref of the GIOChannel data structure. The default value of this is true for channels created by g_io_channel_new_file (), and false for all other channels.

      Setting this flag to true for a channel you have already closed can cause problems when the final reference to the GIOChannel is dropped.

      Parameters:
      doClose - Whether to close the channel on the final unref of the GIOChannel data structure.
    • setEncoding

      public IOStatus setEncoding(@Nullable String encoding) throws GErrorException

      Sets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The default encoding for the external file is UTF-8.

      The encoding null is safe to use with binary data.

      The encoding can only be set if one of the following conditions is true:

      • The channel was just created, and has not been written to or read from yet.

      • The channel is write-only.

      • The channel is a file, and the file pointer was just repositioned by a call to g_io_channel_seek_position(). (This flushes all the internal buffers.)

      • The current encoding is null or UTF-8.

      • One of the (new API) read functions has just returned IOStatus.EOF (or, in the case of g_io_channel_read_to_end(), IOStatus.NORMAL).

      • One of the functions g_io_channel_read_chars() or g_io_channel_read_unichar() has returned IOStatus.AGAIN or IOStatus.ERROR. This may be useful in the case of ConvertError.ILLEGAL_SEQUENCE. Returning one of these statuses from g_io_channel_read_line(), g_io_channel_read_line_string(), or g_io_channel_read_to_end() does not guarantee that the encoding can be changed.

      Channels which do not meet one of the above conditions cannot call g_io_channel_seek_position() with an offset of SeekType.CUR, and, if they are "seekable", cannot call g_io_channel_write_chars() after calling one of the API "read" functions.

      Parameters:
      encoding - the encoding type
      Returns:
      IOStatus.NORMAL if the encoding was successfully set
      Throws:
      GErrorException - see GError
    • setFlags

      public IOStatus setFlags(Set<IOFlags> flags) throws GErrorException
      Sets the (writeable) flags in this IOChannel to (flags & IOFlags.SET_MASK).
      Parameters:
      flags - the flags to set on the IO channel
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • setFlags

      public IOStatus setFlags(IOFlags... flags) throws GErrorException
      Sets the (writeable) flags in this IOChannel to (flags & IOFlags.SET_MASK).
      Parameters:
      flags - the flags to set on the IO channel
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • setLineTerm

      public void setLineTerm(@Nullable String lineTerm, int length)
      This sets the string that GIOChannel uses to determine where in the file a line break occurs.
      Parameters:
      lineTerm - The line termination string. Use null for autodetect. Autodetection breaks on "\n", "\r\n", "\r", "\0", and the Unicode paragraph separator. Autodetection should not be used for anything other than file-based channels.
      length - The length of the termination string. If -1 is passed, the string is assumed to be nul-terminated. This option allows termination strings with embedded nuls.
    • shutdown

      public IOStatus shutdown(boolean flush) throws GErrorException
      Close an IO channel. Any pending data to be written will be flushed if flush is true. The channel will not be freed until the last reference is dropped using g_io_channel_unref().
      Parameters:
      flush - if true, flush pending
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • unixGetFd

      public int unixGetFd()

      Returns the file descriptor of the GIOChannel.

      On Windows this function returns the file descriptor or socket of the GIOChannel.

      Returns:
      the file descriptor of the GIOChannel.
    • unref

      public void unref()
      Decrements the reference count of a GIOChannel.
    • write

      @Deprecated public IOError write(String buf, long count, MemorySegment bytesWritten)
      Deprecated.
      Use g_io_channel_write_chars() instead.
      Writes data to a GIOChannel.
      Parameters:
      buf - the buffer containing the data to write
      count - the number of bytes to write
      bytesWritten - the number of bytes actually written
      Returns:
      IOError.NONE if the operation was successful.
    • writeChars

      public IOStatus writeChars(@Nullable byte @Nullable [] buf, long count, Out<Long> bytesWritten) throws GErrorException

      Replacement for g_io_channel_write() with the new API.

      On seekable channels with encodings other than null or UTF-8, generic mixing of reading and writing is not allowed. A call to g_io_channel_write_chars () may only be made on a channel from which data has been read in the cases described in the documentation for g_io_channel_set_encoding ().

      Parameters:
      buf - a buffer to write data from
      count - the size of the buffer. If -1, the buffer is taken to be a nul-terminated string.
      bytesWritten - The number of bytes written. This can be nonzero even if the return value is not IOStatus.NORMAL. If the return value is IOStatus.NORMAL and the channel is blocking, this will always be equal to count if count >= 0.
      Returns:
      the status of the operation.
      Throws:
      GErrorException - see GError
    • writeUnichar

      public IOStatus writeUnichar(int thechar) throws GErrorException
      Writes a Unicode character to channel. This function cannot be called on a channel with null encoding.
      Parameters:
      thechar - a character
      Returns:
      a GIOStatus
      Throws:
      GErrorException - see GError
    • win32GetFd

      public int win32GetFd()
    • win32MakePollfd

      public void win32MakePollfd(Set<IOCondition> condition, PollFD fd)
    • win32MakePollfd

      public void win32MakePollfd(IOCondition condition, PollFD fd)
    • win32SetDebug

      public void win32SetDebug(boolean flag)