1 /*
2  * This file is part of gtkD.
3  *
4  * gtkD is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License
6  * as published by the Free Software Foundation; either version 3
7  * of the License, or (at your option) any later version, with
8  * some exceptions, please read the COPYING file.
9  *
10  * gtkD is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with gtkD; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
18  */
19 
20 // generated automatically - do not change
21 // find conversion definition on APILookup.txt
22 // implement new conversion functionalities on the wrap.utils pakage
23 
24 
25 module gio.Cancellable;
26 
27 private import gio.c.functions;
28 public  import gio.c.types;
29 private import glib.ConstructionException;
30 private import glib.ErrorG;
31 private import glib.GException;
32 private import glib.Source;
33 private import gobject.ObjectG;
34 private import gobject.Signals;
35 public  import gtkc.giotypes;
36 private import std.algorithm;
37 
38 
39 /**
40  * GCancellable is a thread-safe operation cancellation stack used
41  * throughout GIO to allow for cancellation of synchronous and
42  * asynchronous operations.
43  */
44 public class Cancellable : ObjectG
45 {
46 	/** the main Gtk struct */
47 	protected GCancellable* gCancellable;
48 
49 	/** Get the main Gtk struct */
50 	public GCancellable* getCancellableStruct(bool transferOwnership = false)
51 	{
52 		if (transferOwnership)
53 			ownedRef = false;
54 		return gCancellable;
55 	}
56 
57 	/** the main Gtk struct as a void* */
58 	protected override void* getStruct()
59 	{
60 		return cast(void*)gCancellable;
61 	}
62 
63 	protected override void setStruct(GObject* obj)
64 	{
65 		gCancellable = cast(GCancellable*)obj;
66 		super.setStruct(obj);
67 	}
68 
69 	/**
70 	 * Sets our main struct and passes it to the parent class.
71 	 */
72 	public this (GCancellable* gCancellable, bool ownedRef = false)
73 	{
74 		this.gCancellable = gCancellable;
75 		super(cast(GObject*)gCancellable, ownedRef);
76 	}
77 
78 
79 	/** */
80 	public static GType getType()
81 	{
82 		return g_cancellable_get_type();
83 	}
84 
85 	/**
86 	 * Creates a new #GCancellable object.
87 	 *
88 	 * Applications that want to start one or more operations
89 	 * that should be cancellable should create a #GCancellable
90 	 * and pass it to the operations.
91 	 *
92 	 * One #GCancellable can be used in multiple consecutive
93 	 * operations or in multiple concurrent operations.
94 	 *
95 	 * Returns: a #GCancellable.
96 	 *
97 	 * Throws: ConstructionException GTK+ fails to create the object.
98 	 */
99 	public this()
100 	{
101 		auto p = g_cancellable_new();
102 
103 		if(p is null)
104 		{
105 			throw new ConstructionException("null returned by new");
106 		}
107 
108 		this(cast(GCancellable*) p, true);
109 	}
110 
111 	/**
112 	 * Gets the top cancellable from the stack.
113 	 *
114 	 * Returns: a #GCancellable from the top
115 	 *     of the stack, or %NULL if the stack is empty.
116 	 */
117 	public static Cancellable getCurrent()
118 	{
119 		auto p = g_cancellable_get_current();
120 
121 		if(p is null)
122 		{
123 			return null;
124 		}
125 
126 		return ObjectG.getDObject!(Cancellable)(cast(GCancellable*) p);
127 	}
128 
129 	/**
130 	 * Will set @cancellable to cancelled, and will emit the
131 	 * #GCancellable::cancelled signal. (However, see the warning about
132 	 * race conditions in the documentation for that signal if you are
133 	 * planning to connect to it.)
134 	 *
135 	 * This function is thread-safe. In other words, you can safely call
136 	 * it from a thread other than the one running the operation that was
137 	 * passed the @cancellable.
138 	 *
139 	 * If @cancellable is %NULL, this function returns immediately for convenience.
140 	 *
141 	 * The convention within GIO is that cancelling an asynchronous
142 	 * operation causes it to complete asynchronously. That is, if you
143 	 * cancel the operation from the same thread in which it is running,
144 	 * then the operation's #GAsyncReadyCallback will not be invoked until
145 	 * the application returns to the main loop.
146 	 */
147 	public void cancel()
148 	{
149 		g_cancellable_cancel(gCancellable);
150 	}
151 
152 	/**
153 	 * Convenience function to connect to the #GCancellable::cancelled
154 	 * signal. Also handles the race condition that may happen
155 	 * if the cancellable is cancelled right before connecting.
156 	 *
157 	 * @callback is called at most once, either directly at the
158 	 * time of the connect if @cancellable is already cancelled,
159 	 * or when @cancellable is cancelled in some thread.
160 	 *
161 	 * @data_destroy_func will be called when the handler is
162 	 * disconnected, or immediately if the cancellable is already
163 	 * cancelled.
164 	 *
165 	 * See #GCancellable::cancelled for details on how to use this.
166 	 *
167 	 * Since GLib 2.40, the lock protecting @cancellable is not held when
168 	 * @callback is invoked.  This lifts a restriction in place for
169 	 * earlier GLib versions which now makes it easier to write cleanup
170 	 * code that unconditionally invokes e.g. g_cancellable_cancel().
171 	 *
172 	 * Params:
173 	 *     callback = The #GCallback to connect.
174 	 *     data = Data to pass to @callback.
175 	 *     dataDestroyFunc = Free function for @data or %NULL.
176 	 *
177 	 * Returns: The id of the signal handler or 0 if @cancellable has already
178 	 *     been cancelled.
179 	 *
180 	 * Since: 2.22
181 	 */
182 	public gulong connect(GCallback callback, void* data, GDestroyNotify dataDestroyFunc)
183 	{
184 		return g_cancellable_connect(gCancellable, callback, data, dataDestroyFunc);
185 	}
186 
187 	/**
188 	 * Disconnects a handler from a cancellable instance similar to
189 	 * g_signal_handler_disconnect().  Additionally, in the event that a
190 	 * signal handler is currently running, this call will block until the
191 	 * handler has finished.  Calling this function from a
192 	 * #GCancellable::cancelled signal handler will therefore result in a
193 	 * deadlock.
194 	 *
195 	 * This avoids a race condition where a thread cancels at the
196 	 * same time as the cancellable operation is finished and the
197 	 * signal handler is removed. See #GCancellable::cancelled for
198 	 * details on how to use this.
199 	 *
200 	 * If @cancellable is %NULL or @handler_id is %0 this function does
201 	 * nothing.
202 	 *
203 	 * Params:
204 	 *     handlerId = Handler id of the handler to be disconnected, or %0.
205 	 *
206 	 * Since: 2.22
207 	 */
208 	public void disconnect(gulong handlerId)
209 	{
210 		g_cancellable_disconnect(gCancellable, handlerId);
211 	}
212 
213 	/**
214 	 * Gets the file descriptor for a cancellable job. This can be used to
215 	 * implement cancellable operations on Unix systems. The returned fd will
216 	 * turn readable when @cancellable is cancelled.
217 	 *
218 	 * You are not supposed to read from the fd yourself, just check for
219 	 * readable status. Reading to unset the readable status is done
220 	 * with g_cancellable_reset().
221 	 *
222 	 * After a successful return from this function, you should use
223 	 * g_cancellable_release_fd() to free up resources allocated for
224 	 * the returned file descriptor.
225 	 *
226 	 * See also g_cancellable_make_pollfd().
227 	 *
228 	 * Returns: A valid file descriptor. %-1 if the file descriptor
229 	 *     is not supported, or on errors.
230 	 */
231 	public int getFd()
232 	{
233 		return g_cancellable_get_fd(gCancellable);
234 	}
235 
236 	/**
237 	 * Checks if a cancellable job has been cancelled.
238 	 *
239 	 * Returns: %TRUE if @cancellable is cancelled,
240 	 *     FALSE if called with %NULL or if item is not cancelled.
241 	 */
242 	public bool isCancelled()
243 	{
244 		return g_cancellable_is_cancelled(gCancellable) != 0;
245 	}
246 
247 	/**
248 	 * Creates a #GPollFD corresponding to @cancellable; this can be passed
249 	 * to g_poll() and used to poll for cancellation. This is useful both
250 	 * for unix systems without a native poll and for portability to
251 	 * windows.
252 	 *
253 	 * When this function returns %TRUE, you should use
254 	 * g_cancellable_release_fd() to free up resources allocated for the
255 	 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
256 	 *
257 	 * If this function returns %FALSE, either no @cancellable was given or
258 	 * resource limits prevent this function from allocating the necessary
259 	 * structures for polling. (On Linux, you will likely have reached
260 	 * the maximum number of file descriptors.) The suggested way to handle
261 	 * these cases is to ignore the @cancellable.
262 	 *
263 	 * You are not supposed to read from the fd yourself, just check for
264 	 * readable status. Reading to unset the readable status is done
265 	 * with g_cancellable_reset().
266 	 *
267 	 * Params:
268 	 *     pollfd = a pointer to a #GPollFD
269 	 *
270 	 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
271 	 *     failure to prepare the cancellable.
272 	 *
273 	 * Since: 2.22
274 	 */
275 	public bool makePollfd(GPollFD* pollfd)
276 	{
277 		return g_cancellable_make_pollfd(gCancellable, pollfd) != 0;
278 	}
279 
280 	/**
281 	 * Pops @cancellable off the cancellable stack (verifying that @cancellable
282 	 * is on the top of the stack).
283 	 */
284 	public void popCurrent()
285 	{
286 		g_cancellable_pop_current(gCancellable);
287 	}
288 
289 	/**
290 	 * Pushes @cancellable onto the cancellable stack. The current
291 	 * cancellable can then be received using g_cancellable_get_current().
292 	 *
293 	 * This is useful when implementing cancellable operations in
294 	 * code that does not allow you to pass down the cancellable object.
295 	 *
296 	 * This is typically called automatically by e.g. #GFile operations,
297 	 * so you rarely have to call this yourself.
298 	 */
299 	public void pushCurrent()
300 	{
301 		g_cancellable_push_current(gCancellable);
302 	}
303 
304 	/**
305 	 * Releases a resources previously allocated by g_cancellable_get_fd()
306 	 * or g_cancellable_make_pollfd().
307 	 *
308 	 * For compatibility reasons with older releases, calling this function
309 	 * is not strictly required, the resources will be automatically freed
310 	 * when the @cancellable is finalized. However, the @cancellable will
311 	 * block scarce file descriptors until it is finalized if this function
312 	 * is not called. This can cause the application to run out of file
313 	 * descriptors when many #GCancellables are used at the same time.
314 	 *
315 	 * Since: 2.22
316 	 */
317 	public void releaseFd()
318 	{
319 		g_cancellable_release_fd(gCancellable);
320 	}
321 
322 	/**
323 	 * Resets @cancellable to its uncancelled state.
324 	 *
325 	 * If cancellable is currently in use by any cancellable operation
326 	 * then the behavior of this function is undefined.
327 	 *
328 	 * Note that it is generally not a good idea to reuse an existing
329 	 * cancellable for more operations after it has been cancelled once,
330 	 * as this function might tempt you to do. The recommended practice
331 	 * is to drop the reference to a cancellable after cancelling it,
332 	 * and let it die with the outstanding async operations. You should
333 	 * create a fresh cancellable for further async operations.
334 	 */
335 	public void reset()
336 	{
337 		g_cancellable_reset(gCancellable);
338 	}
339 
340 	/**
341 	 * If the @cancellable is cancelled, sets the error to notify
342 	 * that the operation was cancelled.
343 	 *
344 	 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
345 	 *
346 	 * Throws: GException on failure.
347 	 */
348 	public bool setErrorIfCancelled()
349 	{
350 		GError* err = null;
351 
352 		auto p = g_cancellable_set_error_if_cancelled(gCancellable, &err) != 0;
353 
354 		if (err !is null)
355 		{
356 			throw new GException( new ErrorG(err) );
357 		}
358 
359 		return p;
360 	}
361 
362 	/**
363 	 * Creates a source that triggers if @cancellable is cancelled and
364 	 * calls its callback of type #GCancellableSourceFunc. This is
365 	 * primarily useful for attaching to another (non-cancellable) source
366 	 * with g_source_add_child_source() to add cancellability to it.
367 	 *
368 	 * For convenience, you can call this with a %NULL #GCancellable,
369 	 * in which case the source will never trigger.
370 	 *
371 	 * The new #GSource will hold a reference to the #GCancellable.
372 	 *
373 	 * Returns: the new #GSource.
374 	 *
375 	 * Since: 2.28
376 	 */
377 	public Source sourceNew()
378 	{
379 		auto p = g_cancellable_source_new(gCancellable);
380 
381 		if(p is null)
382 		{
383 			return null;
384 		}
385 
386 		return new Source(cast(GSource*) p, true);
387 	}
388 
389 	protected class OnCancelledDelegateWrapper
390 	{
391 		void delegate(Cancellable) dlg;
392 		gulong handlerId;
393 
394 		this(void delegate(Cancellable) dlg)
395 		{
396 			this.dlg = dlg;
397 			onCancelledListeners ~= this;
398 		}
399 
400 		void remove(OnCancelledDelegateWrapper source)
401 		{
402 			foreach(index, wrapper; onCancelledListeners)
403 			{
404 				if (wrapper.handlerId == source.handlerId)
405 				{
406 					onCancelledListeners[index] = null;
407 					onCancelledListeners = std.algorithm.remove(onCancelledListeners, index);
408 					break;
409 				}
410 			}
411 		}
412 	}
413 	OnCancelledDelegateWrapper[] onCancelledListeners;
414 
415 	/**
416 	 * Emitted when the operation has been cancelled.
417 	 *
418 	 * Can be used by implementations of cancellable operations. If the
419 	 * operation is cancelled from another thread, the signal will be
420 	 * emitted in the thread that cancelled the operation, not the
421 	 * thread that is running the operation.
422 	 *
423 	 * Note that disconnecting from this signal (or any signal) in a
424 	 * multi-threaded program is prone to race conditions. For instance
425 	 * it is possible that a signal handler may be invoked even after
426 	 * a call to g_signal_handler_disconnect() for that handler has
427 	 * already returned.
428 	 *
429 	 * There is also a problem when cancellation happens right before
430 	 * connecting to the signal. If this happens the signal will
431 	 * unexpectedly not be emitted, and checking before connecting to
432 	 * the signal leaves a race condition where this is still happening.
433 	 *
434 	 * In order to make it safe and easy to connect handlers there
435 	 * are two helper functions: g_cancellable_connect() and
436 	 * g_cancellable_disconnect() which protect against problems
437 	 * like this.
438 	 *
439 	 * An example of how to us this:
440 	 * |[<!-- language="C" -->
441 	 * // Make sure we don't do unnecessary work if already cancelled
442 	 * if (g_cancellable_set_error_if_cancelled (cancellable, error))
443 	 * return;
444 	 *
445 	 * // Set up all the data needed to be able to handle cancellation
446 	 * // of the operation
447 	 * my_data = my_data_new (...);
448 	 *
449 	 * id = 0;
450 	 * if (cancellable)
451 	 * id = g_cancellable_connect (cancellable,
452 	 * G_CALLBACK (cancelled_handler)
453 	 * data, NULL);
454 	 *
455 	 * // cancellable operation here...
456 	 *
457 	 * g_cancellable_disconnect (cancellable, id);
458 	 *
459 	 * // cancelled_handler is never called after this, it is now safe
460 	 * // to free the data
461 	 * my_data_free (my_data);
462 	 * ]|
463 	 *
464 	 * Note that the cancelled signal is emitted in the thread that
465 	 * the user cancelled from, which may be the main thread. So, the
466 	 * cancellable signal should not do something that can block.
467 	 */
468 	gulong addOnCancelled(void delegate(Cancellable) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
469 	{
470 		auto wrapper = new OnCancelledDelegateWrapper(dlg);
471 		wrapper.handlerId = Signals.connectData(
472 			this,
473 			"cancelled",
474 			cast(GCallback)&callBackCancelled,
475 			cast(void*)wrapper,
476 			cast(GClosureNotify)&callBackCancelledDestroy,
477 			connectFlags);
478 		return wrapper.handlerId;
479 	}
480 
481 	extern(C) static void callBackCancelled(GCancellable* cancellableStruct, OnCancelledDelegateWrapper wrapper)
482 	{
483 		wrapper.dlg(wrapper.outer);
484 	}
485 
486 	extern(C) static void callBackCancelledDestroy(OnCancelledDelegateWrapper wrapper, GClosure* closure)
487 	{
488 		wrapper.remove(wrapper);
489 	}
490 }