/*
 * $Id: asyncore.hxx,v 4.1 2004/05/23 23:13:53 hut66au Exp $
 *
 * Imview, the portable image analysis application
 * http://www.cmis.csiro.au/Hugues.Talbot/imview
 * ----------------------------------------------------------
 *
 *  Imview is an attempt to provide an image display application
 *  suitable for professional image analysis. It was started in
 *  1997 and is mostly the result of the efforts of Hugues Talbot,
 *  Image Analysis Project, CSIRO Mathematical and Information
 *  Sciences, with help from others (see the CREDITS files for
 *  more information)
 *
 *  Imview is Copyrighted (C) 1997-2001 by Hugues Talbot and was
 *  supported in parts by the Australian Commonwealth Science and 
 *  Industry Research Organisation. Please see the COPYRIGHT file 
 *  for full details. Imview also includes the contributions of 
 *  many others. Please see the CREDITS file for full details.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 * */

// -*- Mode: C++; tab-width: 4 -*-

// ======================================================================
// Copyright 1996 by Sam Rushing
// 
//                         All Rights Reserved
// 
// Permission to use, copy, modify, and distribute this software and
// its documentation for any purpose and without fee is hereby
// granted, provided that the above copyright notice appear in all
// copies and that both that copyright notice and this permission
// notice appear in supporting documentation, and that the name of Sam
// Rushing not be used in advertising or publicity pertaining to
// distribution of the software without specific, written prior
// permission.
// 
// SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
// NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// ======================================================================


//
// slightly hacked by Hugues Talbot	29 Feb 2000
//   made it run with (more) standard C++ under gcc-2.95
//   changed the style somewhat
//   relied on mingw32 for WIN32 functionality: fewer #ifdef WIN32
//   

#ifndef ASYNCORE_H
#define ASYNCORE_H




// C++ version of asyncore

// Getting STL to work on multiple platforms can be quite a challenge,
// swimming in a sea of renamed and duplicated headers...

#include <imcfg.h>

#ifdef WIN32_NOTCYGWIN
#	include <winsock.h>
#	undef min
#	undef max
#else
#   include <sys/types.h>
#   include <sys/socket.h>
#   include <sys/un.h>
#   include <netinet/in.h>
#endif

#include "imunistd.h"
#ifdef HAVE_SYS_TIME_H
#   include <sys/time.h>
#else
#   include <time.h> // typically windows will be like that.
#endif
#include <errno.h>
#include <algorithm>
#include <map>
#include <list>
#include <iostream>
#include "imnmspc.hxx"

#include "imview.hxx"

using std::map;
using std::string;
using std::list;
using std::less;
using std::cerr;
using std::endl;

// horrible hack
extern int debugIsOn;
extern int serverDebug;
#define sdebug if (serverDebug) cerr << "Server> "
#define cdebug if (debugIsOn) cerr << "imview-server> "

class dispatcher;

typedef map<int, dispatcher*, less<int> > socket_map;

class dispatcher {

protected:
	int  fileno;
	bool accepting, connected, closed, write_blocked;

public:
	// constructor
	dispatcher () {
			fileno = 0;
			accepting = 0;
			connected = 0;
			closed = 0;
			write_blocked = 0;
	}

	static bool is_nonblocking_error (int error);

	// static functions [relevant to the active socket map]
	static socket_map channels;
	static void dump_channels (void);
	static void poll (struct timeval * timeout = 0);
	static int  loop1(struct timeval * timeout);
	static void loop (struct timeval * timeout = 0);
	static void delete_closed_channels ();
	void add_channel();
    bool is_closed(void) {return closed;}
	bool is_accepting(void) {return accepting;}
	void reopen_channel(void) {closed = 0;}

	int get_fileno () { return fileno; }

	// select() eligibility predicates
	virtual bool readable (void) { return (connected || accepting); }
	virtual bool writable (void) { return (!connected || write_blocked); }
  
	void set_blocking (bool blocking);

	// --------------------------------------------------
	// socket methods
	// --------------------------------------------------

	bool	create_socket	(int family, int type, int protocol = 0);
	void	set_fileno	(int fd, bool is_connected = 1);
	int	bind		(struct sockaddr * addr, size_t length);
	int	listen		(unsigned int n);
	int	accept		(struct sockaddr * addr, size_t * length_ptr);
	int	connect		(struct sockaddr * addr, size_t length);
	int	send		(const char * buffer, size_t size, int flags = 0);
	int	recv		(char * buffer, size_t size, int flags = 0);
	void	close		(void);

	// --------------------------------------------------
	// event handlers
	// --------------------------------------------------

	void handle_read_event (void);
	void handle_write_event (void);

	// These are meant to be overridden.
	virtual void handle_connect (void) {
		cerr << fileno << ":unhandled connect" << endl;
	}
	virtual void handle_read (void) {
		cerr << fileno << ":unhandled read" << endl;
	}
	virtual void handle_write (void) {
		cerr << fileno << ":unhandled write" << endl;
	}
	virtual void handle_close (void) {
		cerr << fileno << ":unhandled close" << endl;
	}
	virtual void handle_accept (void) {
		cerr << fileno << ":unhandled accept" << endl;
	}
#ifdef WIN32_NOTCYGWIN
	virtual void handle_error (int error) {
		cerr << fileno << ":unhandled error:" << error << " winsock error: " << WSAGetLastError() << endl;
	}
#else
	virtual void handle_error (int error) {
		cerr << fileno << ":unhandled error:" << error << " error: " << strerror(errno) << endl;
	}
#endif

};

#ifndef WIN32_NOTCYGWIN
inline bool dispatcher::is_nonblocking_error (int error)
{
  switch (errno) {
  case EWOULDBLOCK: // always == EAGAIN?
  case EALREADY:
  case EINPROGRESS:
	return true;
  default:
	return false;
  }
}
#else
inline bool dispatcher::is_nonblocking_error (int error)
{
  switch (WSAGetLastError()) {
  case WSAEWOULDBLOCK:
  case WSAEALREADY:
  case WSAEINPROGRESS:
	return true;
	break;
  default:
	return false;
  }
}
#endif

#endif // ASYNCORE_H
