summaryrefslogtreecommitdiffstats
path: root/gmcop/giomanager.cc
blob: 251800828af532e5b235d0456362e22f912e45d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    /*

    Copyright (C) 2001 Stefan Westerfeld
                       stefan@space.twc.de

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    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
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.
  
    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    */


#include "giomanager.h"
#include "notification.h"
#include "debug.h"
#include "dispatcher.h"
#include <glib.h>

using namespace Arts;
using namespace std;

/*
 * Fallback for the case where we should perform blocking
 */
namespace Arts {
class GIOManagerBlocking : public StdIOManager {
public:
	void setLevel(int newLevel) { level = newLevel; }
};
}

namespace Arts {
	struct GIOManagerSource
	{
		GSource source;
		GIOManager *ioManager;
	};
	struct GIOWatch
	{
		GPollFD gpollfd;	 /* <- must be the first data member */

	/* GPollFD =
  		gint          fd;
  		gushort       events;
  		gushort       revents;
  	*/
		GIOWatch(GIOManagerSource *source, int fd, int types, IONotify *notify)
			: types(types), registered(false), notify(notify), source(source)
		{
			gpollfd.fd = fd;
			setTypes(types);
		}
		void setTypes(int types)
		{
			this->types = types;
			gpollfd.events = gpollfd.revents = 0;

			if(types & IOType::read)
				gpollfd.events |= G_IO_IN | G_IO_HUP;
			if(types & IOType::write)
				gpollfd.events |= G_IO_OUT;
			if(types & IOType::except)
				gpollfd.events |= G_IO_ERR;

		}
		/* prepares source for running in event loop level "level"
		 * removes source unconditionally if level == -1
		 */
		void prepare(int level)
		{
			gpollfd.revents = 0;

			bool shouldRegister = true;
			if(level != 1 && (types & IOType::reentrant) == 0)
				shouldRegister = false;
			if(level == -1)
				shouldRegister = false;

			if(shouldRegister == registered)
				return;

			if(shouldRegister)
			{
				g_source_add_poll(&source->source, &this->gpollfd);
			}
			else
			{
				g_source_remove_poll(&source->source, &this->gpollfd);
			}

			registered = shouldRegister;
		}
		int check()
		{
			int result = 0;

			if(gpollfd.revents & (G_IO_IN | G_IO_HUP))
				result |= IOType::read;
			if(gpollfd.revents & G_IO_OUT)
				result |= IOType::write;
			if(gpollfd.revents & G_IO_ERR)
				result |= IOType::except;

			return result;
		}
		void destroy()
		{
			/* TODO: if active do this, else do that */
			delete this;
		}
		~GIOWatch()
		{
			prepare(-1);
		}

		int types;
		bool registered;
		IONotify *notify;
		GIOManagerSource *source;
	};

class GIOTimeWatch {
	int milliseconds;
	TimeNotify *_notify;
	timeval nextNotify;
	bool active, destroyed;
public:
	GIOTimeWatch(int milliseconds, TimeNotify *notify)
		: milliseconds(milliseconds), _notify(notify),
		  active(false),destroyed(false)
	{
		gettimeofday(&nextNotify,0);

		nextNotify.tv_usec += (milliseconds%1000)*1000;
		nextNotify.tv_sec += (milliseconds/1000)+(nextNotify.tv_usec/1000000);
		nextNotify.tv_usec %= 1000000;
	}
	int msUntilNextNotify(const timeval& now)
	{
		int result = (nextNotify.tv_sec - now.tv_sec)*1000
				   + (nextNotify.tv_usec - now.tv_usec)/1000;

		if(result < 0) result = 0;
		return result;
	}
	void advance(const timeval& currentTime)
	{
		active = true;
		while(msUntilNextNotify(currentTime) == 0)
		{
			nextNotify.tv_usec += (milliseconds%1000)*1000;
			nextNotify.tv_sec += (milliseconds/1000)
			                  +(nextNotify.tv_usec/1000000);
			nextNotify.tv_usec %= 1000000;

			_notify->notifyTime();

			if(destroyed)
			{
				delete this;
				return;
			}
		}
		active = false;
	}
	void destroy()
	{
		if(active)
		{
			destroyed = true;
		}
		else
		{
			delete this;
		}
	}
	TimeNotify *notify()
	{
		return _notify;
	}
};

static gboolean GIOManager_prepare(GSource *source, gint *timeout)
{
	return((GIOManagerSource *)source)->ioManager->prepare(timeout);
}

static gboolean GIOManager_check(GSource *source)
{
	return((GIOManagerSource *)source)->ioManager->check();
}

static gboolean GIOManager_dispatch(GSource *source, GSourceFunc callback,
											gpointer user_data)
{
	return((GIOManagerSource *)source)->ioManager->dispatch(callback,user_data);
}


}

GIOManager::GIOManager(GMainContext *context)
	: level(0), context(context)
{
	static GSourceFuncs funcs =
	{
		GIOManager_prepare,
		GIOManager_check,
		GIOManager_dispatch,
		0
	};

	source = (GIOManagerSource *)g_source_new(&funcs, sizeof(GIOManagerSource));
	source->ioManager = this;
	g_source_set_can_recurse(&source->source, true);
	g_source_attach(&source->source, context);

	gioManagerBlocking = new GIOManagerBlocking();
	_blocking = true;
	fileDescriptorsNeedRecheck = false;
}

GIOManager::~GIOManager()
{
	g_source_unref(&source->source);
	delete gioManagerBlocking;
}

void GIOManager::processOneEvent(bool blocking)
{
	if(_blocking)
	{
		level++;
		if(level == 1)
			Dispatcher::lock();

		/*
		 * we explicitly take the level to gioManagerBlocking, so that it
		 * will process reentrant watchFDs only
		 */
		fileDescriptorsNeedRecheck = true;
		gioManagerBlocking->setLevel(level);
		gioManagerBlocking->processOneEvent(blocking);

		if(level == 1)
			Dispatcher::unlock();
		level--;
	}
	else
	{
		g_main_context_iteration(context, blocking);
	}
}

void GIOManager::setBlocking(bool blocking)
{
	_blocking = blocking;
}

void GIOManager::run()
{
	arts_warning("GIOManager::run not implemented yet");
}

void GIOManager::terminate()
{
	arts_warning("GIOManager::terminate not implemented yet");
}

void GIOManager::watchFD(int fd, int types, IONotify * notify)
{
	fdList.push_back(new GIOWatch(source, fd, types, notify));

	if(types & IOType::reentrant)
		gioManagerBlocking->watchFD(fd, types, notify);
}

void GIOManager::remove(IONotify *notify, int types)
{
	list<GIOWatch *>::iterator i;

	i = fdList.begin();
	while(i != fdList.end())
	{
		GIOWatch *w = *i;

		if(w->notify == notify)
		{
			int newTypes = w->types & (~types);

			if(newTypes)
			{
				w->setTypes(newTypes);
			}
			else
			{
				w->destroy();
				fdList.erase(i);
				i = fdList.begin();
			}
		}
		else i++;
	}
	gioManagerBlocking->remove(notify, types);
}

void GIOManager::addTimer(int milliseconds, TimeNotify *notify)
{
	timeList.push_back(new GIOTimeWatch(milliseconds,notify));
}

void GIOManager::removeTimer(TimeNotify *notify)
{
	list<GIOTimeWatch *>::iterator i;

	i = timeList.begin();
	while(i != timeList.end())
	{
		GIOTimeWatch *w = *i;

		if(w->notify() == notify)
		{
			w->destroy();
			timeList.erase(i);
			i = timeList.begin();
		}
		else i++;
	}
}

gboolean GIOManager::prepare(gint *timeout)
{
	*timeout = 10000;

	level++;

	if(level == 1)
		Dispatcher::lock();

	/* handle timers - only at level 1 */
	if(level == 1 && timeList.size())
	{
		struct timeval currenttime;
		gettimeofday(&currenttime,0);

		list<GIOTimeWatch *>::iterator ti;

		ti = timeList.begin();
		while(ti != timeList.end())
		{
			GIOTimeWatch *w = *ti++;
			int ms = w->msUntilNextNotify(currenttime);

			if(ms < *timeout) *timeout = ms;
		}
	}

	list<GIOWatch *>::iterator i;
	for(i = fdList.begin(); i != fdList.end(); i++)
	{
		GIOWatch *w = *i;
		w->prepare(level);
	}
	fileDescriptorsNeedRecheck = false;

	if(level == 1 && NotificationManager::the()->pending())
		*timeout = 0;

	if(level == 1)
		Dispatcher::unlock();

	level--;

	return (*timeout == 0);
}

gboolean GIOManager::check()
{
	gboolean result = false;
	level++;

	if(level == 1)
		Dispatcher::lock();

	/*
	 * handle timers - only at level 1
	 */
	if(level == 1 && timeList.size())
	{
		struct timeval currenttime;
		gettimeofday(&currenttime,0);

		list<GIOTimeWatch *>::iterator ti;

		ti = timeList.begin();
		while(ti != timeList.end() && !result)
		{
			GIOTimeWatch *w = *ti++;
			if(w->msUntilNextNotify(currenttime) == 0)
				result = true;
		}
	}

	/*
	 * handle filedescriptors
	 */
	list<GIOWatch *>::iterator i;
	for(i = fdList.begin(); i != fdList.end(); i++) {
		GIOWatch *w = *i;
		int match = w->check();

		if((w->types & IOType::reentrant) == 0 && level != 1)
		{
			arts_assert(match == 0);
		}
		if(match)
		{
			result = true;
		}
	}
	fileDescriptorsNeedRecheck = false;

	/*
	 * check for notifications
	 */
	if(level == 1 && NotificationManager::the()->pending())
		result = true;

	if(level == 1)
		Dispatcher::unlock();

	level--;

	return result;
}

gboolean GIOManager::dispatch(GSourceFunc /* func */, gpointer /* user_data */)
{
	bool done = false;

	level++;

	if(level == 1)
		Dispatcher::lock();

	// notifications not carried out reentrant
	if(!done && level == 1 && NotificationManager::the()->pending())
	{
		NotificationManager::the()->run();
		done = true;
	}
	
	// handle filedescriptor things
	if(!done && !fileDescriptorsNeedRecheck)
	{
		list<GIOWatch *>::iterator i;
		for(i = fdList.begin(); i != fdList.end(); i++) {
			GIOWatch *w = *i;
			int match = w->check();

			if((w->types & IOType::reentrant) == 0 && level != 1)
			{
				arts_assert(match == 0);
			}
			if(match)
			{
				w->notify->notifyIO(w->gpollfd.fd,match);
				done = true;
				break;
			}
		}
	}

	// handle timers - only at level 1
	if(!done && level == 1 && timeList.size())
	{
		struct timeval currenttime;
		gettimeofday(&currenttime,0);

		list<GIOTimeWatch *>::iterator ti;

		ti = timeList.begin();
		while(ti != timeList.end())
		{
			GIOTimeWatch *w = *ti++;
			w->advance(currenttime);
		}
	}

	if(level == 1)
		Dispatcher::unlock();
	level--;

	return true;
}