giowin32.c 23.1 KB
Newer Older
1 2 3 4 5
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * giowin32.c: IO Channels for Win32.
 * Copyright 1998 Owen Taylor and Tor Lillqvist
6
 * Copyright 1999-2000 Tor Lillqvist and Craig Setera
7 8
 *
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10 11 12 13 14
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19 20 21 22 23
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

24
/*
25
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
26 27
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
28
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
29 30
 */

31
/* Define this to get (very) verbose logging of all channels */
32
/* #define G_IO_WIN32_DEBUG */
33

34
#include "glib.h"
35 36

#include <stdlib.h>
37
#include <windows.h>
38
#include <winsock.h>          /* Not everybody has winsock2 */
39 40
#include <fcntl.h>
#include <io.h>
41
#include <process.h>
42
#include <errno.h>
43
#include <sys/stat.h>
44 45 46 47

typedef struct _GIOWin32Channel GIOWin32Channel;
typedef struct _GIOWin32Watch GIOWin32Watch;

48
#define BUFFER_SIZE 4096
49 50 51

typedef enum {
  G_IO_WINDOWS_MESSAGES,	/* Windows messages */
52 53 54 55 56 57 58
  G_IO_FILE_DESC,		/* Unix-like file descriptors from
				 * _open() or _pipe(). Read with read().
				 * Have to create separate thread to read.
				 */
  G_IO_STREAM_SOCKET		/* Stream sockets. Similar as fds, but
				 * read with recv().
				 */
59 60 61 62 63 64 65 66 67
} GIOWin32ChannelType;

struct _GIOWin32Channel {
  GIOChannel channel;
  gint fd;			/* Either a Unix-like file handle as provided
				 * by the Microsoft C runtime, or a SOCKET
				 * as provided by WinSock.
				 */
  GIOWin32ChannelType type;
68
  
69 70
  gboolean debug;

71 72
  /* This is used by G_IO_WINDOWS_MESSAGES channels */
  HWND hwnd;			/* handle of window, or NULL */
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
  
  /* Following fields used by fd and socket channels for input */
  
  /* Data is kept in a circular buffer. To be able to distinguish between
   * empty and full buffer, we cannot fill it completely, but have to
   * leave a one character gap.
   *
   * Data available is between indexes rdp and wrp-1 (modulo BUFFER_SIZE).
   *
   * Empty:    wrp == rdp
   * Full:     (wrp + 1) % BUFFER_SIZE == rdp
   * Partial:  otherwise
   */
  guchar *buffer;		/* (Circular) buffer */
  gint wrp, rdp;		/* Buffer indices for writing and reading */
  gboolean running;		/* Is reader thread running. FALSE if
				 * EOF has been reached.
90
				 */
91 92 93 94 95 96 97 98
  guint thread_id;		/* If non-NULL has a reader thread, or has
				 * had.*/
  HANDLE data_avail_event;
  HANDLE space_avail_event;
  CRITICAL_SECTION mutex;
  
  /* Function that actually reads from fd */
  int (*reader) (int fd, guchar *buf, int len);
99 100
};

101 102 103
#define LOCK(mutex) EnterCriticalSection (&mutex)
#define UNLOCK(mutex) LeaveCriticalSection (&mutex)

104 105 106 107 108 109 110
struct _GIOWin32Watch {
  GPollFD       pollfd;
  GIOChannel   *channel;
  GIOCondition  condition;
  GIOFunc       callback;
};

111 112 113 114 115 116 117 118 119 120 121 122 123 124
static void
g_io_channel_win32_init (GIOWin32Channel *channel)
{
#ifdef G_IO_WIN32_DEBUG
  channel->debug = TRUE;
#else
  if (getenv ("G_IO_WIN32_DEBUG") != NULL)
    channel->debug = TRUE;
  else
    channel->debug = FALSE;
#endif
  channel->buffer = NULL;
  channel->running = FALSE;
  channel->thread_id = 0;
125 126
  channel->data_avail_event = NULL;
  channel->space_avail_event = NULL;
127 128
}

129 130 131 132 133 134 135 136
static void
create_events (GIOWin32Channel *channel)
{
  SECURITY_ATTRIBUTES sec_attrs;
  
  sec_attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
  sec_attrs.lpSecurityDescriptor = NULL;
  sec_attrs.bInheritHandle = FALSE;
137

138 139 140 141 142 143 144 145 146 147 148
  /* The data available event is manual reset, the space available event
   * is automatic reset.
   */
  if (!(channel->data_avail_event = CreateEvent (&sec_attrs, TRUE, FALSE, NULL))
      || !(channel->space_avail_event = CreateEvent (&sec_attrs, FALSE, FALSE, NULL)))
    {
      gchar *msg = g_win32_error_message (GetLastError ());
      g_error ("Error creating event: %s", msg);
    }
  InitializeCriticalSection (&channel->mutex);
}
149

150 151 152 153 154 155
static unsigned __stdcall
reader_thread (void *parameter)
{
  GIOWin32Channel *channel = parameter;
  guchar *buffer;
  guint nbytes;
156

157
  g_io_channel_ref ((GIOChannel *) channel);
158

159 160 161 162 163 164 165
  if (channel->debug)
    g_print ("thread %#x: starting. pid:%#x, fd:%d, data_avail:%#x, space_avail:%#x\n",
	     channel->thread_id,
	     (guint) GetCurrentProcessId (),
	     channel->fd,
	     (guint) channel->data_avail_event,
	     (guint) channel->space_avail_event);
166 167 168 169
  
  channel->buffer = g_malloc (BUFFER_SIZE);
  channel->rdp = channel->wrp = 0;
  channel->running = TRUE;
170

171 172 173 174 175
  SetEvent (channel->space_avail_event);
  
  while (channel->running)
    {
      LOCK (channel->mutex);
176 177 178
      if (channel->debug)
	g_print ("thread %#x: rdp=%d, wrp=%d\n",
		 channel->thread_id, channel->rdp, channel->wrp);
179 180 181
      if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
	{
	  /* Buffer is full */
182 183 184
	  if (channel->debug)
	    g_print ("thread %#x: resetting space_available\n",
		     channel->thread_id);
185
	  ResetEvent (channel->space_avail_event);
186 187
	  if (channel->debug)
	    g_print ("thread %#x: waiting for space\n", channel->thread_id);
188 189 190
	  UNLOCK (channel->mutex);
	  WaitForSingleObject (channel->space_avail_event, INFINITE);
	  LOCK (channel->mutex);
191 192 193
	  if (channel->debug)
	    g_print ("thread %#x: rdp=%d, wrp=%d\n",
		     channel->thread_id, channel->rdp, channel->wrp);
194 195 196 197 198 199 200 201 202
	}
      
      buffer = channel->buffer + channel->wrp;
      
      /* Always leave at least one byte unused gap to be able to
       * distinguish between the full and empty condition...
       */
      nbytes = MIN ((channel->rdp + BUFFER_SIZE - channel->wrp - 1) % BUFFER_SIZE,
		    BUFFER_SIZE - channel->wrp);
203

204
      UNLOCK (channel->mutex);
205

206 207 208 209
      nbytes = (*channel->reader) (channel->fd, buffer, nbytes);
      
      if (nbytes <= 0)
	break;
210

211
      LOCK (channel->mutex);
212 213 214
      if (channel->debug)
	g_print ("thread %#x: got %d bytes, rdp=%d, wrp=%d\n",
		 channel->thread_id, nbytes, channel->rdp, channel->wrp);
215
      channel->wrp = (channel->wrp + nbytes) % BUFFER_SIZE;
216 217 218
      if (channel->debug)
	g_print ("thread %#x: rdp=%d, wrp=%d, setting data available\n",
		 channel->thread_id, channel->rdp, channel->wrp);
219 220 221 222 223 224
      SetEvent (channel->data_avail_event);
      UNLOCK (channel->mutex);
    }
  
  LOCK (channel->mutex);
  channel->running = FALSE;
225 226 227
  if (channel->debug)
    g_print ("thread %#x: got EOF, rdp=%d, wrp=%d, setting data available\n",
	     channel->thread_id, channel->rdp, channel->wrp);
228 229 230 231 232 233 234 235 236 237 238 239
  SetEvent (channel->data_avail_event);
  UNLOCK (channel->mutex);
  
  g_io_channel_unref((GIOChannel *) channel);
  
  /* All of the Microsoft docs say we should explicitly
   * end the thread...
   */
  _endthreadex(1);
  
  return 0;
}
240

241 242 243 244 245
static void
create_reader_thread (GIOWin32Channel *channel,
		      gpointer         reader)
{
  channel->reader = reader;
246

247 248 249 250 251
  if (_beginthreadex (NULL, 0, reader_thread, channel, 0,
		      &channel->thread_id) == 0)
    g_warning ("Error creating reader thread: %s", strerror (errno));
  WaitForSingleObject (channel->space_avail_event, INFINITE);
}
252

253 254 255 256 257
static int
buffer_read (GIOWin32Channel *channel,
	     guchar          *dest,
	     guint            count,
	     GIOError        *error)
258
{
259 260 261 262
  guint nbytes;
  guint left = count;
  
  LOCK (channel->mutex);
263 264 265
  if (channel->debug)
    g_print ("reading from thread %#x %d bytes, rdp=%d, wrp=%d\n",
	     channel->thread_id, count, channel->rdp, channel->wrp);
266
  
267
  if (channel->rdp == channel->wrp)
268 269
    {
      UNLOCK (channel->mutex);
270 271 272
      if (channel->debug)
	g_print ("waiting for data from thread %#x\n", channel->thread_id);
      WaitForSingleObject (channel->data_avail_event, INFINITE);
273
      LOCK (channel->mutex);
274
      if (channel->rdp == channel->wrp && !channel->running)
275 276 277 278
	{
	  UNLOCK (channel->mutex);
	  return 0;
	}
279
    }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  
  if (channel->rdp < channel->wrp)
    nbytes = channel->wrp - channel->rdp;
  else
    nbytes = BUFFER_SIZE - channel->rdp;
  UNLOCK (channel->mutex);
  nbytes = MIN (left, nbytes);
  if (channel->debug)
    g_print ("moving %d bytes from thread %#x\n",
	     nbytes, channel->thread_id);
  memcpy (dest, channel->buffer + channel->rdp, nbytes);
  dest += nbytes;
  left -= nbytes;
  LOCK (channel->mutex);
  channel->rdp = (channel->rdp + nbytes) % BUFFER_SIZE;
  if (channel->debug)
    g_print ("setting space available for thread %#x\n", channel->thread_id);
  SetEvent (channel->space_avail_event);
  if (channel->debug)
    g_print ("for thread %#x: rdp=%d, wrp=%d\n",
	     channel->thread_id, channel->rdp, channel->wrp);
  if (channel->running && channel->rdp == channel->wrp)
    {
      if (channel->debug)
	g_print ("resetting data_available of thread %#x\n",
		 channel->thread_id);
      ResetEvent (channel->data_avail_event);
    };
308 309
  UNLOCK (channel->mutex);
  
310 311 312 313
  /* We have no way to indicate any errors form the actual
   * read() or recv() call in the reader thread. Should we have?
   */
  *error = G_IO_ERROR_NONE;
314 315
  return count - left;
}
316

317 318 319 320 321 322
static gboolean
g_io_win32_prepare (gpointer  source_data,
		    GTimeVal *current_time,
		    gint     *timeout,
		    gpointer  user_data)
{
323
  *timeout = -1;
324 325
  
  return FALSE;
326 327
}

328 329 330 331
static gboolean
g_io_win32_check (gpointer  source_data,
		  GTimeVal *current_time,
		  gpointer  user_data)
332 333
{
  GIOWin32Watch *data = source_data;
334 335 336 337 338 339 340
  GIOWin32Channel *channel = (GIOWin32Channel *) data->channel;
  
  /* If the thread has died, we have encountered EOF. If the buffer
   * also is emtpty set the HUP bit.
   */
  if (!channel->running && channel->rdp == channel->wrp)
    {
341 342 343
      if (channel->debug)
	g_print ("g_io_win32_check: setting G_IO_HUP thread %#x rdp=%d wrp=%d\n",
		 channel->thread_id, channel->rdp, channel->wrp);
344 345 346 347 348
      data->pollfd.revents |= G_IO_HUP;
      return TRUE;
    }
  
  return (data->pollfd.revents & data->condition);
349 350 351
}

static gboolean
352 353 354 355
g_io_win32_dispatch (gpointer  source_data,
		     GTimeVal *current_time,
		     gpointer  user_data)
     
356 357
{
  GIOWin32Watch *data = source_data;
358 359 360 361
  
  return (*data->callback) (data->channel,
			    data->pollfd.revents & data->condition,
			    user_data);
362 363 364 365 366 367
}

static void
g_io_win32_destroy (gpointer source_data)
{
  GIOWin32Watch *data = source_data;
368
  
369 370 371 372 373
  g_main_remove_poll (&data->pollfd);
  g_io_channel_unref (data->channel);
  g_free (data);
}

374 375 376 377 378 379
static GSourceFuncs win32_watch_funcs = {
  g_io_win32_prepare,
  g_io_win32_check,
  g_io_win32_dispatch,
  g_io_win32_destroy
};
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
static guint
g_io_win32_add_watch (GIOChannel    *channel,
		      gint           priority,
		      GIOCondition   condition,
		      GIOFunc        func,
		      gpointer       user_data,
		      GDestroyNotify notify,
		      int (*reader) (int, guchar *, int))
{
  GIOWin32Watch *watch = g_new (GIOWin32Watch, 1);
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  
  watch->channel = channel;
  g_io_channel_ref (channel);
  
  watch->callback = func;
  watch->condition = condition;
  
  if (win32_channel->data_avail_event == NULL)
    create_events (win32_channel);

  watch->pollfd.fd = (gint) win32_channel->data_avail_event;
  watch->pollfd.events = condition;
  
  if (win32_channel->debug)
    g_print ("g_io_win32_add_watch: fd:%d handle:%#x\n",
	     win32_channel->fd, watch->pollfd.fd);
  
  if (win32_channel->thread_id == 0)
    create_reader_thread (win32_channel, reader);

  g_main_add_poll (&watch->pollfd, priority);
  
  return g_source_add (priority, TRUE, &win32_watch_funcs, watch,
		       user_data, notify);
}

418
static GIOError
419 420 421 422
g_io_win32_msg_read (GIOChannel *channel,
		     gchar      *buf,
		     guint       count,
		     guint      *bytes_read)
423 424
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
425 426
  MSG msg;               /* In case of alignment problems */
  
427 428 429 430 431
  if (count < sizeof (MSG))
    return G_IO_ERROR_INVAL;
  
  if (!PeekMessage (&msg, win32_channel->hwnd, 0, 0, PM_REMOVE))
    return G_IO_ERROR_AGAIN;
432
  
433 434 435 436
  memmove (buf, &msg, sizeof (MSG));
  *bytes_read = sizeof (MSG);
  return G_IO_ERROR_NONE;
}
437 438 439 440 441 442

static GIOError
g_io_win32_msg_write (GIOChannel *channel,
		      gchar      *buf,
		      guint       count,
		      guint      *bytes_written)
443 444 445
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  MSG msg;
446
  
447 448
  if (count != sizeof (MSG))
    return G_IO_ERROR_INVAL;
449
  
450 451 452 453
  /* In case of alignment problems */
  memmove (&msg, buf, sizeof (MSG));
  if (!PostMessage (win32_channel->hwnd, msg.message, msg.wParam, msg.lParam))
    return G_IO_ERROR_UNKNOWN;
454
  
455
  *bytes_written = sizeof (MSG);
456
  return G_IO_ERROR_NONE;
457 458
}

459
static GIOError
460
g_io_win32_no_seek (GIOChannel *channel,
461 462
		    gint        offset,
		    GSeekType   type)
463 464 465 466
{
  return G_IO_ERROR_UNKNOWN;
}

467
static void
468 469 470 471 472
g_io_win32_msg_close (GIOChannel *channel)
{
  /* Nothing to be done. Or should we set hwnd to some invalid value? */
}

473
static void
474 475 476
g_io_win32_free (GIOChannel *channel)
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
477 478 479 480 481 482 483
  
  if (win32_channel->buffer)
    {
      CloseHandle (win32_channel->data_avail_event);
      CloseHandle (win32_channel->space_avail_event);
      DeleteCriticalSection (&win32_channel->mutex);
    }
484

485
  g_free (win32_channel->buffer);
486 487 488
  g_free (win32_channel);
}

489
static guint
490 491 492 493 494 495 496 497 498 499 500
g_io_win32_msg_add_watch (GIOChannel    *channel,
			  gint           priority,
			  GIOCondition   condition,
			  GIOFunc        func,
			  gpointer       user_data,
			  GDestroyNotify notify)
{
  GIOWin32Watch *watch = g_new (GIOWin32Watch, 1);
  
  watch->channel = channel;
  g_io_channel_ref (channel);
501
  
502 503
  watch->callback = func;
  watch->condition = condition;
504
  
505 506
  watch->pollfd.fd = G_WIN32_MSG_HANDLE;
  watch->pollfd.events = condition;
507
  
508
  g_main_add_poll (&watch->pollfd, priority);
509 510
  
  return g_source_add (priority, TRUE, &win32_watch_funcs,
511 512 513 514
		       watch, user_data, notify);
}

static GIOError
515
g_io_win32_fd_read (GIOChannel *channel,
516 517 518
		    gchar      *buf,
		    guint       count,
		    guint      *bytes_read)
519 520 521
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  gint result;
522 523
  GIOError error;
  
524 525 526 527
  if (win32_channel->debug)
    g_print ("g_io_win32_fd_read: fd:%d count:%d\n",
	     win32_channel->fd, count);
  
528 529 530 531 532 533 534 535 536 537 538 539 540 541
  if (win32_channel->thread_id)
    {
      result = buffer_read (win32_channel, buf, count, &error);
      if (result < 0)
	{
	  *bytes_read = 0;
	  return error;
	}
      else
	{
	  *bytes_read = result;
	  return G_IO_ERROR_NONE;
	}
    }
542 543

  result = read (win32_channel->fd, buf, count);
544

545 546 547
  if (result < 0)
    {
      *bytes_read = 0;
548 549 550 551
      if (errno == EINVAL)
	return G_IO_ERROR_INVAL;
      else
	return G_IO_ERROR_UNKNOWN;
552 553 554 555 556 557 558
    }
  else
    {
      *bytes_read = result;
      return G_IO_ERROR_NONE;
    }
}
559 560

static GIOError
561 562 563 564
g_io_win32_fd_write (GIOChannel *channel,
		     gchar      *buf,
		     guint       count,
		     guint      *bytes_written)
565 566 567
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  gint result;
568
  
569
  result = write (win32_channel->fd, buf, count);
570 571 572
  if (win32_channel->debug)
    g_print ("g_io_win32_fd_write: fd:%d count:%d = %d\n",
	     win32_channel->fd, count, result);
573
  
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
  if (result < 0)
    {
      *bytes_written = 0;
      switch (errno)
	{
	case EINVAL:
	  return G_IO_ERROR_INVAL;
	case EAGAIN:
	  return G_IO_ERROR_AGAIN;
	default:
	  return G_IO_ERROR_UNKNOWN;
	}
    }
  else
    {
      *bytes_written = result;
      return G_IO_ERROR_NONE;
    }
}

594
static GIOError
595
g_io_win32_fd_seek (GIOChannel *channel,
596 597
		    gint        offset,
		    GSeekType   type)
598 599 600 601
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  int whence;
  off_t result;
602
  
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  switch (type)
    {
    case G_SEEK_SET:
      whence = SEEK_SET;
      break;
    case G_SEEK_CUR:
      whence = SEEK_CUR;
      break;
    case G_SEEK_END:
      whence = SEEK_END;
      break;
    default:
      g_warning ("g_io_win32_fd_seek: unknown seek type");
      return G_IO_ERROR_UNKNOWN;
    }
  
  result = lseek (win32_channel->fd, offset, whence);
  
  if (result < 0)
    {
      switch (errno)
	{
	case EINVAL:
	  return G_IO_ERROR_INVAL;
	default:
	  return G_IO_ERROR_UNKNOWN;
	}
    }
  else
    return G_IO_ERROR_NONE;
}

635
static void
636 637 638
g_io_win32_fd_close (GIOChannel *channel)
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
639
  
640 641 642 643
  close (win32_channel->fd);
  return;
}

644 645 646 647 648
static int
fd_reader (int     fd,
	   guchar *buf,
	   int     len)
{
649
  return read (fd, buf, len);
650 651 652
}

static guint
653 654 655 656 657 658 659
g_io_win32_fd_add_watch (GIOChannel    *channel,
			 gint           priority,
			 GIOCondition   condition,
			 GIOFunc        func,
			 gpointer       user_data,
			 GDestroyNotify notify)
{
660 661
  return g_io_win32_add_watch (channel, priority, condition,
			       func, user_data, notify, fd_reader);
662 663 664
}

static GIOError
665 666 667 668
g_io_win32_sock_read (GIOChannel *channel,
		      gchar      *buf,
		      guint       count,
		      guint      *bytes_read)
669 670 671
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  gint result;
672 673 674
  GIOError error;
  
  if (win32_channel->thread_id)
675
    {
676 677
      result = buffer_read (win32_channel, buf, count, &error);
      if (result < 0)
678
	{
679 680
	  *bytes_read = 0;
	  return error;
681
	}
682
      else
683
	{
684 685
	  *bytes_read = result;
	  return G_IO_ERROR_NONE;
686 687 688 689
	}
    }

  result = recv (win32_channel->fd, buf, count, 0);
690 691

  if (result < 0)
692 693
    {
      *bytes_read = 0;
694
      return G_IO_ERROR_UNKNOWN;
695 696 697 698 699 700 701
    }
  else
    {
      *bytes_read = result;
      return G_IO_ERROR_NONE;
    }
}
702 703

static GIOError
704 705 706 707
g_io_win32_sock_write (GIOChannel *channel,
		       gchar      *buf,
		       guint       count,
		       guint      *bytes_written)
708 709 710
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
  gint result;
711
  
712
  result = send (win32_channel->fd, buf, count, 0);
713
  
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
  if (result == SOCKET_ERROR)
    {
      *bytes_written = 0;
      switch (WSAGetLastError ())
	{
	case WSAEINVAL:
	  return G_IO_ERROR_INVAL;
	case WSAEWOULDBLOCK:
	case WSAEINTR:
	  return G_IO_ERROR_AGAIN;
	default:
	  return G_IO_ERROR_UNKNOWN;
	}
    }
  else
    {
      *bytes_written = result;
      return G_IO_ERROR_NONE;
    }
}

735
static void
736 737 738 739 740 741 742
g_io_win32_sock_close (GIOChannel *channel)
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;

  closesocket (win32_channel->fd);
}

743 744 745 746 747 748 749 750 751
static int
sock_reader (int     fd,
	     guchar *buf,
	     int     len)
{
  return recv (fd, buf, len, 0);
}

static guint
752 753 754 755 756 757 758
g_io_win32_sock_add_watch (GIOChannel    *channel,
			   gint           priority,
			   GIOCondition   condition,
			   GIOFunc        func,
			   gpointer       user_data,
			   GDestroyNotify notify)
{
759 760
  return g_io_win32_add_watch (channel, priority, condition,
			       func, user_data, notify, sock_reader);
761 762
}

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
static GIOFuncs win32_channel_msg_funcs = {
  g_io_win32_msg_read,
  g_io_win32_msg_write,
  g_io_win32_no_seek,
  g_io_win32_msg_close,
  g_io_win32_msg_add_watch,
  g_io_win32_free
};

static GIOFuncs win32_channel_fd_funcs = {
  g_io_win32_fd_read,
  g_io_win32_fd_write,
  g_io_win32_fd_seek,
  g_io_win32_fd_close,
  g_io_win32_fd_add_watch,
  g_io_win32_free
};

static GIOFuncs win32_channel_sock_funcs = {
  g_io_win32_sock_read,
  g_io_win32_sock_write,
  g_io_win32_no_seek,
  g_io_win32_sock_close,
  g_io_win32_sock_add_watch,
  g_io_win32_free
};

790 791 792 793 794 795 796
GIOChannel *
g_io_channel_win32_new_messages (guint hwnd)
{
  GIOWin32Channel *win32_channel = g_new (GIOWin32Channel, 1);
  GIOChannel *channel = (GIOChannel *) win32_channel;

  g_io_channel_init (channel);
797
  g_io_channel_win32_init (win32_channel);
798 799 800 801 802 803 804 805
  channel->funcs = &win32_channel_msg_funcs;
  win32_channel->type = G_IO_WINDOWS_MESSAGES;
  win32_channel->hwnd = (HWND) hwnd;

  return channel;
}

GIOChannel *
806
g_io_channel_win32_new_fd (gint fd)
807
{
808 809 810 811 812 813 814 815 816 817 818 819
  GIOWin32Channel *win32_channel;
  GIOChannel *channel;
  struct stat st;

  if (fstat (fd, &st) == -1)
    {
      g_warning ("%d isn't a (emulated) file descriptor", fd);
      return NULL;
    }

  win32_channel = g_new (GIOWin32Channel, 1);
  channel = (GIOChannel *) win32_channel;
820 821

  g_io_channel_init (channel);
822
  g_io_channel_win32_init (win32_channel);
823 824
  channel->funcs = &win32_channel_fd_funcs;
  win32_channel->type = G_IO_FILE_DESC;
825
  win32_channel->fd = fd;
826 827 828 829 830

  return channel;
}

gint
831
g_io_channel_win32_get_fd (GIOChannel *channel)
832 833 834 835 836 837 838
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;

  return win32_channel->fd;
}

GIOChannel *
839
g_io_channel_win32_new_stream_socket (int socket)
840 841 842 843 844
{
  GIOWin32Channel *win32_channel = g_new (GIOWin32Channel, 1);
  GIOChannel *channel = (GIOChannel *) win32_channel;

  g_io_channel_init (channel);
845
  g_io_channel_win32_init (win32_channel);
846 847
  channel->funcs = &win32_channel_sock_funcs;
  win32_channel->type = G_IO_STREAM_SOCKET;
848
  win32_channel->fd = socket;
849 850 851 852 853

  return channel;
}

GIOChannel *
854
g_io_channel_unix_new (gint fd)
855
{
856 857
  return g_io_channel_win32_new_fd (fd);
}
858

859 860 861 862
gint
g_io_channel_unix_get_fd (GIOChannel *channel)
{
  return g_io_channel_win32_get_fd (channel);
863 864
}

865 866 867 868 869 870 871 872 873
void
g_io_channel_win32_set_debug (GIOChannel *channel,
			      gboolean    flag)
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;

  win32_channel->debug = flag;
}

874
gint
875 876 877
g_io_channel_win32_poll (GPollFD *fds,
			 gint     n_fds,
			 gint     timeout)
878
{
879
  int i;
880
  int result;
881
  gboolean debug = FALSE;
882

883
  g_return_val_if_fail (n_fds >= 0, 0);
884

885
  result = (*g_main_win32_get_poll_func ()) (fds, n_fds, timeout);
886 887

  return result;
888 889
}

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
void
g_io_channel_win32_make_pollfd (GIOChannel   *channel,
				GIOCondition  condition,
				GPollFD      *fd)
{
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;

  if (win32_channel->data_avail_event == NULL)
    create_events (win32_channel);
  
  fd->fd = win32_channel->data_avail_event;
  fd->events = condition;

  if (win32_channel->thread_id == 0)
    if (win32_channel->type == G_IO_FILE_DESC)
      create_reader_thread (win32_channel, fd_reader);
    else if (win32_channel->type == G_IO_STREAM_SOCKET)
      create_reader_thread (win32_channel, sock_reader);
}

910 911 912 913 914
gint
g_io_channel_win32_wait_for_condition (GIOChannel  *channel,
				       GIOCondition condition,
				       gint         timeout)
{
915 916 917
  GPollFD pollfd;
  GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;

918
  g_io_channel_win32_make_pollfd (channel, condition, &pollfd);
919
  
920
  return g_io_channel_win32_poll (&pollfd, 1, timeout);
921
}
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

/* This variable and the functions below are present just to be 
 * binary compatible with old clients... But note that in GIMP, the
 * libgimp/gimp.c:gimp_extension_process() function will have to be modified
 * anyhow for this new approach.
 *
 * These will be removed after some weeks.
 */
guint g_pipe_readable_msg = 0;

GIOChannel *
g_io_channel_win32_new_pipe (int fd)
{
  return g_io_channel_win32_new_fd (fd);
}

GIOChannel *
g_io_channel_win32_new_pipe_with_wakeups (int   fd,
940 941
					  guint peer,
					  int   peer_fd)
942
{
943
  return g_io_channel_win32_new_fd (fd);
944 945 946 947
}

void
g_io_channel_win32_pipe_request_wakeups (GIOChannel *channel,
948 949
					 guint       peer,
					 int         peer_fd)
950
{
951
  /* Nothing needed now */
952 953 954 955
}

void
g_io_channel_win32_pipe_readable (gint  fd,
956
				  guint offset)
957
{
958
  /* Nothing needed now */
959
}
960