Add copy of glib-sharp from trunk

This is for internal usage only and will be removed once
there's a working glib-sharp release.

This also contains the required patches from README.
This commit is contained in:
Sebastian Dröge 2009-07-31 10:16:55 +02:00
parent 92b2a3214b
commit a4e2955c7c
59 changed files with 7730 additions and 0 deletions

View file

@ -0,0 +1,89 @@
// GLib.Argv.cs : Argv marshaling class
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class Argv {
IntPtr[] arg_ptrs;
IntPtr handle;
bool add_progname = false;
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_malloc(IntPtr size);
[DllImport("libglib-2.0-0.dll")]
static extern void g_free (IntPtr mem);
~Argv ()
{
foreach (IntPtr arg in arg_ptrs)
g_free (arg);
g_free (handle);
}
public Argv (string[] args) : this (args, false) {}
public Argv (string[] args, bool add_program_name)
{
add_progname = add_program_name;
if (add_progname) {
string[] full = new string [args.Length + 1];
full [0] = System.Environment.GetCommandLineArgs ()[0];
args.CopyTo (full, 1);
args = full;
}
arg_ptrs = new IntPtr [args.Length];
for (int i = 0; i < args.Length; i++)
arg_ptrs [i] = Marshaller.StringToPtrGStrdup (args[i]);
handle = g_malloc (new IntPtr (IntPtr.Size * args.Length));
for (int i = 0; i < args.Length; i++)
Marshal.WriteIntPtr (handle, i * IntPtr.Size, arg_ptrs [i]);
}
public IntPtr Handle {
get {
return handle;
}
}
public string[] GetArgs (int argc)
{
int count = add_progname ? argc - 1 : argc;
int idx = add_progname ? 1 : 0;
string[] result = new string [count];
for (int i = 0; i < count; i++, idx++)
result [i] = Marshaller.Utf8PtrToString (Marshal.ReadIntPtr (handle, idx * IntPtr.Size));
return result;
}
}
}

View file

@ -0,0 +1,62 @@
// GtkSharp.Boxed.cs - Base class for deriving marshallable structures.
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001-2002 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[Obsolete]
public class Boxed {
object obj;
IntPtr raw;
public Boxed (object o)
{
this.obj = o;
}
public Boxed (IntPtr ptr)
{
this.raw = ptr;
}
public virtual IntPtr Handle {
get {
return raw;
}
set {
raw = value;
}
}
public static explicit operator System.IntPtr (Boxed boxed) {
return boxed.Handle;
}
public virtual object Obj {
get {
return obj;
}
set {
obj = value;
}
}
}
}

View file

@ -0,0 +1,30 @@
// CDeclCallbackAttribute.cs
//
// Author: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[Obsolete ("Use System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute instead")]
public sealed class CDeclCallbackAttribute : Attribute
{
}
}

View file

@ -0,0 +1,31 @@
// ClassInitializerAttribute.cs
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[Obsolete ("Replaced by TypeInitializerAttribute")]
public sealed class ClassInitializerAttribute : Attribute
{
public ClassInitializerAttribute () {}
}
}

View file

@ -0,0 +1,30 @@
// ConnectBeforeAttribute.cs
//
// Author: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
public sealed class ConnectBeforeAttribute : Attribute
{
public ConnectBeforeAttribute () {}
}
}

View file

@ -0,0 +1,53 @@
// DefaultSignalHandlerAttribute.cs
//
// Author: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2003 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
public sealed class DefaultSignalHandlerAttribute : Attribute
{
private string method;
private System.Type type;
public DefaultSignalHandlerAttribute () {}
public string ConnectionMethod
{
get {
return method;
}
set {
method = value;
}
}
public System.Type Type
{
get {
return type;
}
set {
type = value;
}
}
}
}

View file

@ -0,0 +1,111 @@
// DelegateWrapper.cs - Delegate wrapper implementation
//
// Authors:
// Rachel Hestilow <hestilow@ximian.com>
// Gonzalo Panigua Javier <gonzalo@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
// Copyright (c) 2003 Ximian, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public class DelegateWrapper
{
// Keys in the hashtable are instances of classes derived from this one.
// Values are each instance's destroy notification delegate
static Hashtable instances = new Hashtable ();
// This list holds references to wrappers for static
// methods. These will never expire.
static ArrayList static_instances = new ArrayList ();
static int notify_count = 0;
// The object 'o' is the object that creates the instance of the DelegateWrapper
// derived class or null if created from a static method.
// Note that the instances will never be disposed if they are created in a static
// method.
[Obsolete ("Callback wrappers should be manually managed for persistence.")]
protected DelegateWrapper (object o)
{
if (o != null) {
// If o is a GObject, we can get
// destroy notification. Otherwise
// no additional references to
// the wrapper are kept.
// FIXME: This should work because
// currently only GObjects store
// callbacks over the long-term
if (o is GLib.Object) {
AddDestroyNotify ((GLib.Object) o);
}
} else {
// If o is null, we cannot ask for a destroy
// notification, so the wrapper never expires.
lock (typeof (DelegateWrapper)) {
static_instances.Add (this);
}
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
private delegate void DestroyNotify (IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
private static extern void g_object_set_data_full (IntPtr obj, IntPtr name, IntPtr data, DestroyNotify destroy);
private void AddDestroyNotify (GLib.Object o) {
// This is a bit of an ugly hack. There is no
// way of getting a destroy notification
// explicitly, so we set some data and ask
// for notification when it is removed
IntPtr name = Marshaller.StringToPtrGStrdup (String.Format ("_GtkSharpDelegateWrapper_{0}", notify_count));
DestroyNotify destroy = new DestroyNotify (this.OnDestroy);
g_object_set_data_full (o.Handle, name, IntPtr.Zero, destroy);
Marshaller.Free (name);
lock (typeof (DelegateWrapper)) {
instances[this] = destroy;
notify_count++;
}
}
// This callback is invoked by GLib to indicate that the
// object that owned the native delegate wrapper no longer
// exists and the instance of the delegate itself is removed from the hash table.
private void OnDestroy (IntPtr data) {
try {
lock (typeof (DelegateWrapper)) {
if (instances.ContainsKey (this)) {
instances.Remove (this);
}
}
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
}
}
}

View file

@ -0,0 +1,52 @@
// GLib.DestroyNotify.cs - internal DestroyNotify helper
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
public delegate void DestroyNotify (IntPtr data);
public class DestroyHelper {
private DestroyHelper () {}
static void ReleaseGCHandle (IntPtr data)
{
if (data == IntPtr.Zero)
return;
GCHandle gch = (GCHandle) data;
gch.Free ();
}
static DestroyNotify release_gchandle;
public static DestroyNotify NotifyHandler {
get {
if (release_gchandle == null)
release_gchandle = new DestroyNotify (ReleaseGCHandle);
return release_gchandle;
}
}
}
}

View file

@ -0,0 +1,42 @@
// EnumWrapper.cs - Class to hold arbitrary glib enums
//
// Author: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
[Obsolete ("Replaced by direct enum type casts to/from GLib.Value")]
public class EnumWrapper {
int val;
public bool flags;
public EnumWrapper (int val, bool flags) {
this.val = val;
this.flags = flags;
}
public static explicit operator int (EnumWrapper wrap) {
return wrap.val;
}
}
}

View file

@ -0,0 +1,74 @@
// GLib.Application.cs - static Application class
//
// Authors: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
public delegate void UnhandledExceptionHandler (UnhandledExceptionArgs args);
public class UnhandledExceptionArgs : System.UnhandledExceptionEventArgs {
bool exit_app = false;
public UnhandledExceptionArgs (Exception e, bool is_terminal) : base (e, is_terminal) {}
public bool ExitApplication {
get {
return exit_app;
}
set {
if (value)
exit_app = value;
}
}
}
public class ExceptionManager {
private ExceptionManager () {}
public static event UnhandledExceptionHandler UnhandledException;
public static void RaiseUnhandledException (Exception e, bool is_terminal)
{
if (UnhandledException == null) {
Console.Error.WriteLine ("Exception in Gtk# callback delegate");
Console.Error.WriteLine (" Note: Applications can use GLib.ExceptionManager.UnhandledException to handle the exception.");
Console.Error.WriteLine (e);
Console.Error.WriteLine (new System.Diagnostics.StackTrace (true));
Environment.Exit (1);
}
UnhandledExceptionArgs args = new UnhandledExceptionArgs (e, is_terminal);
try {
UnhandledException (args);
} catch (Exception ex) {
Console.Error.WriteLine (ex);
Environment.Exit (1);
}
if (is_terminal || args.ExitApplication)
Environment.Exit (1);
}
}
}

View file

@ -0,0 +1,48 @@
// GLib.FileUtils.cs - GFileUtils class implementation
//
// Author: Martin Baulig <martin@gnome.org>
//
// Copyright (c) 2002 Ximian, Inc
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Text;
using System.Runtime.InteropServices;
public class FileUtils
{
[DllImport("libglib-2.0-0.dll")]
extern static bool g_file_get_contents (IntPtr filename, out IntPtr contents, out int length, out IntPtr error);
public static string GetFileContents (string filename)
{
int length;
IntPtr contents, error;
IntPtr native_filename = Marshaller.StringToPtrGStrdup (filename);
if (!g_file_get_contents (native_filename, out contents, out length, out error))
throw new GException (error);
Marshaller.Free (native_filename);
return Marshaller.Utf8PtrToString (contents);
}
private FileUtils () {}
}
}

View file

@ -0,0 +1,39 @@
// Format.cs: Wrapper for the g_format code in Glib
//
// Authors:
// Stephane Delcroix (stephane@delcroix.org)
//
// Copyright (c) 2008 Novell, Inc.
//
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Runtime.InteropServices;
namespace GLib {
#if GTK_SHARP_2_14
public class Format {
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_format_size_for_display (long size);
static public string SizeForDisplay (long size)
{
string result = Marshaller.PtrToStringGFree (g_format_size_for_display (size));
return result;
}
}
#endif
}

View file

@ -0,0 +1,57 @@
// GException.cs : GError handling
//
// Authors: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class GException : Exception
{
IntPtr errptr;
public GException (IntPtr errptr) : base ()
{
this.errptr = errptr;
}
struct GError {
public int Domain;
public int Code;
public IntPtr Msg;
}
public override string Message {
get {
GError err = (GError) Marshal.PtrToStructure (errptr, typeof (GError));
return Marshaller.Utf8PtrToString (err.Msg);
}
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_clear_error (ref IntPtr errptr);
~GException ()
{
g_clear_error (ref errptr);
}
}
}

View file

@ -0,0 +1,64 @@
// GInterfaceAdapter.cs
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public delegate void GInterfaceInitHandler (IntPtr iface_ptr, IntPtr data);
internal delegate void GInterfaceFinalizeHandler (IntPtr iface_ptr, IntPtr data);
internal struct GInterfaceInfo {
internal GInterfaceInitHandler InitHandler;
internal GInterfaceFinalizeHandler FinalizeHandler;
internal IntPtr Data;
}
public abstract class GInterfaceAdapter {
GInterfaceInfo info;
protected GInterfaceAdapter ()
{
}
protected GInterfaceInitHandler InitHandler {
set {
info.InitHandler = value;
}
}
public abstract GType GType { get; }
public abstract IntPtr Handle { get; }
internal GInterfaceInfo Info {
get {
if (info.Data == IntPtr.Zero)
info.Data = (IntPtr) GCHandle.Alloc (this);
return info;
}
}
}
}

View file

@ -0,0 +1,42 @@
// GInterfaceAttribute.cs
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[AttributeUsage (AttributeTargets.Interface)]
public sealed class GInterfaceAttribute : Attribute {
Type adapter_type;
public GInterfaceAttribute (Type adapter_type)
{
this.adapter_type = adapter_type;
}
public Type AdapterType {
get {
return adapter_type;
}
set {
adapter_type = value;
}
}
}
}

View file

@ -0,0 +1,60 @@
// GLib.GString.cs : Marshaler for GStrings
//
// Author: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class GString : GLib.IWrapper {
IntPtr handle;
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_string_free (IntPtr mem, bool free_segments);
~GString ()
{
g_string_free (handle, true);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_string_new (IntPtr text);
public GString (string text)
{
IntPtr native_text = Marshaller.StringToPtrGStrdup (text);
handle = g_string_new (native_text);
Marshaller.Free (native_text);
}
public IntPtr Handle {
get {
return handle;
}
}
public static string PtrToString (IntPtr ptr)
{
return Marshaller.Utf8PtrToString (ptr);
}
}
}

View file

@ -0,0 +1,426 @@
// GLib.Type.cs - GLib GType class implementation
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2003 Mike Kestner
// Copyright (c) 2003 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
public delegate System.Type TypeResolutionHandler (GLib.GType gtype, string gtype_name);
[StructLayout(LayoutKind.Sequential)]
public struct GType {
IntPtr val;
struct GTypeInfo {
public ushort class_size;
IntPtr base_init;
IntPtr base_finalize;
IntPtr class_init;
IntPtr class_finalize;
IntPtr class_data;
public ushort instance_size;
ushort n_preallocs;
IntPtr instance_init;
IntPtr value_table;
}
struct GTypeQuery {
public IntPtr type;
public IntPtr type_name;
public uint class_size;
public uint instance_size;
}
public GType (IntPtr val)
{
this.val = val;
}
public static GType FromName (string native_name)
{
return new GType (g_type_from_name (native_name));
}
public static readonly GType Invalid = new GType ((IntPtr) TypeFundamentals.TypeInvalid);
public static readonly GType None = new GType ((IntPtr) TypeFundamentals.TypeNone);
public static readonly GType Interface = new GType ((IntPtr) TypeFundamentals.TypeInterface);
public static readonly GType Char = new GType ((IntPtr) TypeFundamentals.TypeChar);
public static readonly GType UChar = new GType ((IntPtr) TypeFundamentals.TypeUChar);
public static readonly GType Boolean = new GType ((IntPtr) TypeFundamentals.TypeBoolean);
public static readonly GType Int = new GType ((IntPtr) TypeFundamentals.TypeInt);
public static readonly GType UInt = new GType ((IntPtr) TypeFundamentals.TypeUInt);
public static readonly GType Long = new GType ((IntPtr) TypeFundamentals.TypeLong);
public static readonly GType ULong = new GType ((IntPtr) TypeFundamentals.TypeULong);
public static readonly GType Int64 = new GType ((IntPtr) TypeFundamentals.TypeInt64);
public static readonly GType UInt64 = new GType ((IntPtr) TypeFundamentals.TypeUInt64);
public static readonly GType Enum = new GType ((IntPtr) TypeFundamentals.TypeEnum);
public static readonly GType Flags = new GType ((IntPtr) TypeFundamentals.TypeFlags);
public static readonly GType Float = new GType ((IntPtr) TypeFundamentals.TypeFloat);
public static readonly GType Double = new GType ((IntPtr) TypeFundamentals.TypeDouble);
public static readonly GType String = new GType ((IntPtr) TypeFundamentals.TypeString);
public static readonly GType Pointer = new GType ((IntPtr) TypeFundamentals.TypePointer);
public static readonly GType Boxed = new GType ((IntPtr) TypeFundamentals.TypeBoxed);
public static readonly GType Param = new GType ((IntPtr) TypeFundamentals.TypeParam);
public static readonly GType Object = new GType ((IntPtr) TypeFundamentals.TypeObject);
static Hashtable types = new Hashtable ();
static Hashtable gtypes = new Hashtable ();
public static void Register (GType native_type, System.Type type)
{
if (native_type != GType.Pointer && native_type != GType.Boxed && native_type != ManagedValue.GType)
types[native_type.Val] = type;
if (type != null)
gtypes[type] = native_type;
}
static GType ()
{
if (!GLib.Thread.Supported)
GLib.Thread.Init ();
g_type_init ();
Register (GType.Char, typeof (sbyte));
Register (GType.UChar, typeof (byte));
Register (GType.Boolean, typeof (bool));
Register (GType.Int, typeof (int));
Register (GType.UInt, typeof (uint));
Register (GType.Int64, typeof (long));
Register (GType.UInt64, typeof (ulong));
Register (GType.Float, typeof (float));
Register (GType.Double, typeof (double));
Register (GType.String, typeof (string));
Register (GType.Pointer, typeof (IntPtr));
Register (GType.Object, typeof (GLib.Object));
Register (GType.Pointer, typeof (IntPtr));
// One-way mapping
gtypes[typeof (char)] = GType.UInt;
}
public static explicit operator GType (System.Type type)
{
GType gtype;
if (gtypes.Contains (type))
return (GType)gtypes[type];
if (type.IsSubclassOf (typeof (GLib.Object))) {
gtype = GLib.Object.LookupGType (type);
Register (gtype, type);
return gtype;
}
PropertyInfo pi = type.GetProperty ("GType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (pi != null)
gtype = (GType) pi.GetValue (null, null);
else if (type.IsDefined (typeof (GTypeAttribute), false)) {
GTypeAttribute gattr = (GTypeAttribute)Attribute.GetCustomAttribute (type, typeof (GTypeAttribute), false);
pi = gattr.WrapperType.GetProperty ("GType", BindingFlags.Public | BindingFlags.Static);
gtype = (GType) pi.GetValue (null, null);
} else if (type.IsSubclassOf (typeof (GLib.Opaque)))
gtype = GType.Pointer;
else
gtype = ManagedValue.GType;
Register (gtype, type);
return gtype;
}
static string GetQualifiedName (string cname)
{
for (int i = 1; i < cname.Length; i++) {
if (System.Char.IsUpper (cname[i])) {
if (i == 1 && cname [0] == 'G')
return "GLib." + cname.Substring (1);
else
return cname.Substring (0, i) + "." + cname.Substring (i);
}
}
return null;
}
public static explicit operator Type (GType gtype)
{
return LookupType (gtype.Val);
}
public static void Init ()
{
// cctor already calls g_type_init.
}
public static event TypeResolutionHandler ResolveType;
public static Type LookupType (IntPtr typeid)
{
if (types.Contains (typeid))
return (Type)types[typeid];
string native_name = Marshaller.Utf8PtrToString (g_type_name (typeid));
if (ResolveType != null) {
GLib.GType gt = new GLib.GType (typeid);
Delegate[] invocation_list = ResolveType.GetInvocationList ();
foreach (Delegate d in invocation_list) {
TypeResolutionHandler handler = (TypeResolutionHandler) d;
System.Type tmp = handler (gt, native_name);
if (tmp != null) {
Register (gt, tmp);
return tmp;
}
}
}
string type_name = GetQualifiedName (native_name);
if (type_name == null)
return null;
Type result = null;
Assembly[] assemblies = (Assembly[]) AppDomain.CurrentDomain.GetAssemblies ().Clone ();
foreach (Assembly asm in assemblies) {
result = asm.GetType (type_name);
if (result != null)
break;
}
if (result == null) {
// Because of lazy loading of references, it's possible the type's assembly
// needs to be loaded. We will look for it by name in the references of
// the currently loaded assemblies. Hopefully a recursive traversal is
// not needed. We avoid one for now because of problems experienced
// in a patch from bug #400595, and a desire to keep memory usage low
// by avoiding a complete loading of all dependent assemblies.
string ns = type_name.Substring (0, type_name.LastIndexOf ('.'));
string asm_name = ns.ToLower ().Replace ('.', '-') + "-sharp";
foreach (Assembly asm in assemblies) {
foreach (AssemblyName ref_name in asm.GetReferencedAssemblies ()) {
if (ref_name.Name != asm_name)
continue;
string asm_dir = Path.GetDirectoryName (asm.Location);
try {
Assembly ref_asm;
if (File.Exists (Path.Combine (asm_dir, ref_name.Name + ".dll")))
ref_asm = Assembly.LoadFrom (Path.Combine (asm_dir, ref_name.Name + ".dll"));
else
ref_asm = Assembly.Load (ref_name);
result = ref_asm.GetType (type_name);
if (result != null)
break;
} catch (Exception) {
/* Failure to load a referenced assembly is not an error */
}
}
if (result != null)
break;
}
}
Register (new GType (typeid), result);
return result;
}
public IntPtr Val {
get { return val; }
}
public static bool operator == (GType a, GType b)
{
return a.Val == b.Val;
}
public static bool operator != (GType a, GType b)
{
return a.Val != b.Val;
}
public override bool Equals (object o)
{
if (!(o is GType))
return false;
return ((GType) o) == this;
}
public override int GetHashCode ()
{
return val.GetHashCode ();
}
public override string ToString ()
{
return Marshaller.Utf8PtrToString (g_type_name (val));
}
public IntPtr ClassPtr {
get {
IntPtr klass = g_type_class_peek (val);
if (klass == IntPtr.Zero)
klass = g_type_class_ref (val);
return klass;
}
}
public GType BaseType {
get {
IntPtr parent = g_type_parent (this.Val);
if (parent == IntPtr.Zero)
return GType.None;
else
return new GType (parent);
}
}
public GType ThresholdType {
get {
GLib.GType curr_type = this;
while (curr_type.ToString ().StartsWith ("__gtksharp_")) {
curr_type = curr_type.BaseType;
}
return curr_type;
}
}
public uint ClassSize {
get {
GTypeQuery query;
g_type_query (this.Val, out query);
return query.class_size;
}
}
internal void EnsureClass ()
{
if (g_type_class_peek (val) == IntPtr.Zero)
g_type_class_ref (val);
}
static int type_uid;
static string BuildEscapedName (System.Type t)
{
string qn = t.FullName;
// Just a random guess
StringBuilder sb = new StringBuilder (20 + qn.Length);
sb.Append ("__gtksharp_");
sb.Append (type_uid++);
sb.Append ("_");
foreach (char c in qn) {
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
sb.Append (c);
else if (c == '.')
sb.Append ('_');
else if ((uint) c <= byte.MaxValue) {
sb.Append ('+');
sb.Append (((byte) c).ToString ("x2"));
} else {
sb.Append ('-');
sb.Append (((uint) c).ToString ("x4"));
}
}
return sb.ToString ();
}
internal static GType RegisterGObjectType (System.Type t)
{
GType parent_gtype = LookupGObjectType (t.BaseType);
string name = BuildEscapedName (t);
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name);
GTypeQuery query;
g_type_query (parent_gtype.Val, out query);
GTypeInfo info = new GTypeInfo ();
info.class_size = (ushort) query.class_size;
info.instance_size = (ushort) query.instance_size;
GType gtype = new GType (g_type_register_static (parent_gtype.Val, native_name, ref info, 0));
GLib.Marshaller.Free (native_name);
Register (gtype, t);
return gtype;
}
internal static GType LookupGObjectType (System.Type t)
{
if (gtypes.Contains (t))
return (GType) gtypes [t];
PropertyInfo pi = t.GetProperty ("GType", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
if (pi != null)
return (GType) pi.GetValue (null, null);
return GLib.Object.RegisterGType (t);
}
internal static IntPtr ValFromInstancePtr (IntPtr handle)
{
if (handle == IntPtr.Zero)
return IntPtr.Zero;
// First field of instance is a GTypeClass*.
IntPtr klass = Marshal.ReadIntPtr (handle);
// First field of GTypeClass is a GType.
return Marshal.ReadIntPtr (klass);
}
internal static bool Is (IntPtr type, GType is_a_type)
{
return g_type_is_a (type, is_a_type.Val);
}
public bool IsInstance (IntPtr raw)
{
return GType.Is (ValFromInstancePtr (raw), this);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_class_peek (IntPtr gtype);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_class_ref (IntPtr gtype);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_from_name (string name);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_type_init ();
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_name (IntPtr raw);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_parent (IntPtr type);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_type_query (IntPtr type, out GTypeQuery query);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_register_static (IntPtr parent, IntPtr name, ref GTypeInfo info, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_type_is_a (IntPtr type, IntPtr is_a_type);
}
}

View file

@ -0,0 +1,42 @@
// GTypeAttribute.cs
//
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[AttributeUsage (AttributeTargets.Enum)]
public sealed class GTypeAttribute : Attribute {
Type wrapper_type;
public GTypeAttribute (Type wrapper_type)
{
this.wrapper_type = wrapper_type;
}
public Type WrapperType {
get {
return wrapper_type;
}
set {
wrapper_type = value;
}
}
}
}

View file

@ -0,0 +1,68 @@
// GLib.Global.cs - Global glib properties and methods.
//
// Author: Andres G. Aragoneses <aaragoneses@novell.com>
//
// Copyright (c) 2008 Novell, Inc
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Text;
using System.Runtime.InteropServices;
public class Global
{
//this is a static class
private Global () {}
public static string ProgramName {
get {
return GLib.Marshaller.PtrToStringGFree(g_get_prgname());
}
set {
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (value);
g_set_prgname (native_name);
GLib.Marshaller.Free (native_name);
}
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_set_prgname (IntPtr name);
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_get_prgname ();
public static string ApplicationName {
get {
return GLib.Marshaller.PtrToStringGFree(g_get_application_name());
}
set {
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (value);
g_set_application_name (native_name);
GLib.Marshaller.Free (native_name);
}
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_set_application_name (IntPtr name);
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_get_application_name ();
}
}

View file

@ -0,0 +1,469 @@
// glib/IOChannel.cs : IOChannel API wrapper
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLibSharp {
using System;
using System.Runtime.InteropServices;
using GLib;
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
internal delegate bool IOFuncNative(IntPtr source, int condition, IntPtr data);
internal class IOFuncWrapper {
IOFunc managed;
public IOFuncNative NativeDelegate;
public IOFuncWrapper (IOFunc managed)
{
this.managed = managed;
NativeDelegate = new IOFuncNative (NativeCallback);
}
bool NativeCallback (IntPtr source, int condition, IntPtr data)
{
try {
return managed (IOChannel.FromHandle (source), (IOCondition) condition);
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
return false;
}
}
}
}
namespace GLib {
using System;
using System.Runtime.InteropServices;
using GLibSharp;
public class IOChannel : IDisposable, IWrapper {
IntPtr handle;
private IOChannel(IntPtr handle)
{
this.handle = handle;
}
public IOChannel (int fd) : this (g_io_channel_unix_new (fd)) {}
public IOChannel (string filename, string mode)
{
IntPtr native_filename = Marshaller.StringToPtrGStrdup (filename);
IntPtr native_mode = Marshaller.StringToPtrGStrdup (mode);
IntPtr error;
handle = g_io_channel_new_file(native_filename, native_mode, out error);
Marshaller.Free (native_filename);
Marshaller.Free (native_mode);
if (error != IntPtr.Zero) throw new GException (error);
}
public IOCondition BufferCondition
{
get {
return (IOCondition) g_io_channel_get_buffer_condition (Handle);
}
}
public bool Buffered
{
get {
return g_io_channel_get_buffered (Handle);
}
set {
g_io_channel_set_buffered (Handle, value);
}
}
public ulong BufferSize
{
get {
return (ulong) g_io_channel_get_buffer_size (Handle);
}
set {
g_io_channel_set_buffer_size (Handle, new UIntPtr (value));
}
}
public bool CloseOnUnref
{
get {
return g_io_channel_get_close_on_unref (Handle);
}
set {
g_io_channel_set_close_on_unref (Handle, value);
}
}
public string Encoding
{
get {
return Marshaller.Utf8PtrToString (g_io_channel_get_encoding (Handle));
}
set {
IntPtr native_encoding = Marshaller.StringToPtrGStrdup (value);
IntPtr error;
g_io_channel_set_encoding (Handle, native_encoding, out error);
Marshaller.Free (native_encoding);
if (error != IntPtr.Zero) throw new GException (error);
}
}
public IOFlags Flags
{
get {
return (IOFlags) g_io_channel_get_flags(Handle);
}
set {
IntPtr error;
g_io_channel_set_flags(Handle, (int) value, out error);
if (error != IntPtr.Zero) throw new GException (error);
}
}
public char[] LineTerminator {
get {
int length;
IntPtr raw = g_io_channel_get_line_term (Handle, out length);
if (length == -1)
return Marshaller.Utf8PtrToString (raw).ToCharArray ();
byte[] buffer = new byte [length];
return System.Text.Encoding.UTF8.GetChars (buffer);
}
set {
byte[] buffer = System.Text.Encoding.UTF8.GetBytes (value);
g_io_channel_set_line_term (Handle, buffer, buffer.Length);
}
}
public IntPtr Handle {
get {
return handle;
}
}
public int UnixFd {
get {
return g_io_channel_unix_get_fd (Handle);
}
}
protected void Init ()
{
g_io_channel_init (Handle);
}
public void Dispose ()
{
g_io_channel_unref (Handle);
}
public uint AddWatch (int priority, IOCondition condition, IOFunc func)
{
IOFuncWrapper func_wrapper = null;
IntPtr user_data = IntPtr.Zero;
DestroyNotify notify = null;
if (func != null) {
func_wrapper = new IOFuncWrapper (func);
user_data = (IntPtr) GCHandle.Alloc (func_wrapper);
notify = DestroyHelper.NotifyHandler;
}
return g_io_add_watch_full (Handle, priority, (int) condition, func_wrapper.NativeDelegate, user_data, notify);
}
public IOStatus Flush ()
{
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_flush (Handle, out error);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus ReadChars (byte[] buf, out ulong bytes_read)
{
UIntPtr native_bytes_read;
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_read_chars (Handle, buf, new UIntPtr ((ulong) buf.Length), out native_bytes_read, out error);
bytes_read = (ulong) native_bytes_read;
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus ReadLine (out string str_return)
{
ulong dump;
return ReadLine (out str_return, out dump);
}
public IOStatus ReadLine (out string str_return, out ulong terminator_pos)
{
IntPtr native_string;
UIntPtr native_terminator_pos;
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_read_line (Handle, out native_string, IntPtr.Zero, out native_terminator_pos, out error);
terminator_pos = (ulong) native_terminator_pos;
str_return = null;
if (ret == IOStatus.Normal)
str_return = Marshaller.PtrToStringGFree (native_string);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus ReadToEnd (out string str_return)
{
IntPtr native_str;
UIntPtr native_length;
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_read_to_end (Handle, out native_str, out native_length, out error);
str_return = null;
if (ret == IOStatus.Normal) {
byte[] buffer = new byte [(ulong) native_length];
Marshal.Copy (native_str, buffer, 0, (int)(ulong) native_length);
str_return = System.Text.Encoding.UTF8.GetString (buffer);
}
Marshaller.Free (native_str);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus ReadUnichar (out uint thechar)
{
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_read_unichar (Handle, out thechar, out error);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus SeekPosition (long offset, SeekType type)
{
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_seek_position (Handle, offset, (int) type, out error);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus Shutdown (bool flush)
{
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_shutdown (Handle, flush, out error);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus WriteChars (string str, out string remainder)
{
ulong written;
System.Text.Encoding enc = System.Text.Encoding.UTF8;
byte[] buffer = enc.GetBytes (str);
IOStatus ret = WriteChars (buffer, out written);
remainder = null;
if ((int) written == buffer.Length)
return ret;
int count = buffer.Length - (int) written;
byte[] rem = new byte [count];
Array.Copy (buffer, (int) written, rem, 0, count);
remainder = enc.GetString (rem);
return ret;
}
public IOStatus WriteChars (byte[] buf, out ulong bytes_written)
{
UIntPtr native_bytes_written;
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_write_chars (Handle, buf, new IntPtr (buf.Length), out native_bytes_written, out error);
bytes_written = (ulong) native_bytes_written;
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public IOStatus WriteUnichar (uint thechar)
{
IntPtr error;
IOStatus ret = (IOStatus) g_io_channel_write_unichar (Handle, thechar, out error);
if (error != IntPtr.Zero) throw new GException (error);
return ret;
}
public static IOChannel FromHandle (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
g_io_channel_ref (handle);
return new IOChannel (handle);
}
public static IOChannelError ErrorFromErrno (int en)
{
return (IOChannelError) g_io_channel_error_from_errno (en);
}
const string libname = "libglib-2.0-0.dll";
[DllImport (libname)]
static extern IntPtr g_io_channel_unix_new (int fd);
[DllImport (libname)]
static extern IntPtr g_io_channel_new_file (IntPtr filename, IntPtr mode, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_error_quark ();
[DllImport(libname)]
static extern int g_io_channel_error_from_errno (int en);
[DllImport (libname)]
static extern int g_io_channel_flush (IntPtr raw, out IntPtr error);
[DllImport (libname)]
static extern void g_io_channel_init (IntPtr raw);
[DllImport (libname)]
static extern int g_io_channel_read_chars (IntPtr raw, byte[] buf, UIntPtr count, out UIntPtr bytes_read, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_read_line (IntPtr raw, out IntPtr str_return, IntPtr length, out UIntPtr terminator_pos, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_read_to_end (IntPtr raw, out IntPtr str_return, out UIntPtr length, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_read_unichar (IntPtr raw, out uint thechar, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_seek_position (IntPtr raw, long offset, int type, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_shutdown (IntPtr raw, bool flush, out IntPtr err);
[DllImport (libname)]
static extern int g_io_channel_write_chars (IntPtr raw, byte[] buf, IntPtr count, out UIntPtr bytes_written, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_write_unichar (IntPtr raw, uint thechar, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_get_buffer_condition (IntPtr raw);
[DllImport (libname)]
static extern bool g_io_channel_get_buffered (IntPtr raw);
[DllImport (libname)]
static extern void g_io_channel_set_buffered (IntPtr raw, bool buffered);
[DllImport (libname)]
static extern UIntPtr g_io_channel_get_buffer_size (IntPtr raw);
[DllImport (libname)]
static extern void g_io_channel_set_buffer_size (IntPtr raw, UIntPtr size);
[DllImport (libname)]
static extern bool g_io_channel_get_close_on_unref (IntPtr raw);
[DllImport (libname)]
static extern void g_io_channel_set_close_on_unref (IntPtr raw, bool do_close);
[DllImport (libname)]
static extern IntPtr g_io_channel_get_encoding (IntPtr raw);
[DllImport (libname)]
static extern int g_io_channel_set_encoding (IntPtr raw, IntPtr encoding, out IntPtr error);
[DllImport (libname)]
static extern int g_io_channel_get_flags (IntPtr raw);
[DllImport (libname)]
static extern int g_io_channel_set_flags (IntPtr raw, int flags, out IntPtr error);
[DllImport (libname)]
static extern IntPtr g_io_channel_get_line_term (IntPtr raw, out int length);
[DllImport (libname)]
static extern void g_io_channel_set_line_term (IntPtr raw, byte[] term, int length);
[DllImport (libname)]
static extern int g_io_channel_unix_get_fd (IntPtr raw);
[DllImport (libname)]
static extern IntPtr g_io_channel_ref (IntPtr raw);
[DllImport (libname)]
static extern void g_io_channel_unref (IntPtr raw);
[DllImport (libname)]
static extern uint g_io_add_watch_full (IntPtr raw, int priority, int condition, IOFuncNative func, IntPtr user_data, DestroyNotify notify);
[DllImport (libname)]
static extern IntPtr g_io_create_watch (IntPtr raw, int condition);
}
public delegate bool IOFunc (IOChannel source, IOCondition condition);
public enum IOChannelError {
FileTooBig,
Inval,
IO,
IsDir,
NoSpace,
Nxio,
Overflow,
Pipe,
Failed,
}
[Flags]
public enum IOCondition {
In = 1 << 0,
Out = 1 << 2,
Pri = 1 << 1,
Err = 1 << 3,
Hup = 1 << 4,
Nval = 1 << 5,
}
[Flags]
public enum IOFlags {
Append = 1 << 0,
Nonblock = 1 << 1,
IsReadable = 1 << 2,
IsWriteable = 1 << 3,
IsSeekable = 1 << 4,
Mask = 1 << 5- 1,
GetMask = Mask,
SetMask = Append | Nonblock,
}
public enum IOStatus {
Error,
Normal,
Eof,
Again,
}
public enum SeekType {
Cur,
Set,
End,
}
}

View file

@ -0,0 +1,30 @@
// IWrapper.cs - Common code for GInterfaces and GObjects
//
// Author: Rachel Hestilow <hesitlow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib
{
using System;
public interface IWrapper
{
IntPtr Handle { get; }
}
}

View file

@ -0,0 +1,125 @@
// GLib.Idle.cs - Idle class implementation
//
// Author(s):
// Mike Kestner <mkestner@speakeasy.net>
// Rachel Hestilow <hestilow@ximian.com>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (c) 2002 Mike Kestner
// Copyright (c) Rachel Hestilow
// Copyright (c) 2009 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public delegate bool IdleHandler ();
public class Idle {
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate bool IdleHandlerInternal ();
internal class IdleProxy : SourceProxy {
public IdleProxy (IdleHandler real)
{
real_handler = real;
proxy_handler = new IdleHandlerInternal (Handler);
}
public bool Handler ()
{
try {
IdleHandler idle_handler = (IdleHandler) real_handler;
bool cont = idle_handler ();
if (!cont)
Remove ();
return cont;
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
return false;
}
}
private Idle ()
{
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_idle_add (IdleHandlerInternal d, IntPtr data);
public static uint Add (IdleHandler hndlr)
{
IdleProxy p = new IdleProxy (hndlr);
p.ID = g_idle_add ((IdleHandlerInternal) p.proxy_handler, IntPtr.Zero);
lock (Source.source_handlers)
Source.source_handlers [p.ID] = p;
return p.ID;
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_idle_add_full (int priority, IdleHandlerInternal d, IntPtr data, DestroyNotify notify);
public static uint Add (IdleHandler hndlr, Priority priority)
{
IdleProxy p = new IdleProxy (hndlr);
p.ID = g_idle_add_full ((int)priority, (IdleHandlerInternal)p.proxy_handler, IntPtr.Zero, null);
lock (Source.source_handlers)
Source.source_handlers [p.ID] = p;
return p.ID;
}
[DllImport("libglib-2.0-0.dll")]
static extern bool g_source_remove_by_funcs_user_data (Delegate d, IntPtr data);
public static void Remove (uint id)
{
Source.Remove (id);
}
public static bool Remove (IdleHandler hndlr)
{
bool result = false;
ArrayList keys = new ArrayList ();
lock (Source.source_handlers) {
foreach (uint code in Source.source_handlers.Keys) {
IdleProxy p = Source.source_handlers [code] as IdleProxy;
if (p != null && p.real_handler == hndlr) {
keys.Add (code);
result = g_source_remove_by_funcs_user_data (p.proxy_handler, IntPtr.Zero);
}
}
foreach (object key in keys)
Source.source_handlers.Remove (key);
}
return result;
}
}
}

View file

@ -0,0 +1,31 @@
// IgnoreClassInitializersAttribute.cs
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[AttributeUsage (AttributeTargets.Assembly)]
public sealed class IgnoreClassInitializersAttribute : Attribute
{
public IgnoreClassInitializersAttribute () {}
}
}

View file

@ -0,0 +1,46 @@
// InitiallyUnowned.cs - GInitiallyUnowned class wrapper implementation
//
// Authors: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2004-2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
#if GTK_SHARP_2_10
namespace GLib {
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
public class InitiallyUnowned : Object {
protected InitiallyUnowned (IntPtr raw) : base (raw) {}
[Obsolete]
protected InitiallyUnowned (GType gtype) : base (gtype) {}
public new static GLib.GType GType {
get {
return GType.Object;
}
}
}
}
#endif

View file

@ -0,0 +1,97 @@
// List.cs - GList class wrapper implementation
//
// Authors: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2002 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class List : ListBase {
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_list_copy (IntPtr l);
public override object Clone ()
{
return new List (g_list_copy (Handle));
}
[DllImport("libglib-2.0-0.dll")]
static extern int g_list_length (IntPtr l);
internal override int Length (IntPtr list)
{
return g_list_length (list);
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_list_free(IntPtr l);
internal override void Free (IntPtr list)
{
if (list != IntPtr.Zero)
g_list_free (list);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_list_append (IntPtr l, IntPtr raw);
internal override IntPtr Append (IntPtr list, IntPtr raw)
{
return g_list_append (list, raw);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_list_prepend (IntPtr l, IntPtr raw);
internal override IntPtr Prepend (IntPtr list, IntPtr raw)
{
return g_list_prepend (list, raw);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_list_nth_data (IntPtr l, uint n);
internal override IntPtr NthData (uint n)
{
return g_list_nth_data (Handle, n);
}
public List (IntPtr raw) : this (raw, null) {}
public List (System.Type element_type) : this (IntPtr.Zero, element_type) {}
public List (IntPtr raw, System.Type element_type) : this (raw, element_type, false, false) {}
public List (IntPtr raw, System.Type element_type, bool owned, bool elements_owned) : base (raw, element_type, owned, elements_owned) {}
public List (object[] elements, System.Type element_type, bool owned, bool elements_owned) : this (IntPtr.Zero, element_type, owned, elements_owned)
{
foreach (object o in elements)
Append (o);
}
public List (Array elements, System.Type element_type, bool owned, bool elements_owned) : this (IntPtr.Zero, element_type, owned, elements_owned)
{
foreach (object o in elements)
Append (o);
}
}
}

View file

@ -0,0 +1,279 @@
// ListBase.cs - List base class implementation
//
// Authors: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2002 Mike Kestner
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public abstract class ListBase : IDisposable, ICollection, GLib.IWrapper, ICloneable {
private IntPtr list_ptr = IntPtr.Zero;
private int length = -1;
private bool managed = false;
internal bool elements_owned = false;
protected System.Type element_type = null;
abstract internal IntPtr NthData (uint index);
abstract internal int Length (IntPtr list);
abstract internal void Free (IntPtr list);
abstract internal IntPtr Append (IntPtr current, IntPtr raw);
abstract internal IntPtr Prepend (IntPtr current, IntPtr raw);
internal ListBase (IntPtr list, System.Type element_type, bool owned, bool elements_owned)
{
list_ptr = list;
this.element_type = element_type;
managed = owned;
this.elements_owned = elements_owned;
}
~ListBase ()
{
Dispose (false);
}
[Obsolete ("Replaced by owned parameter on ctor.")]
public bool Managed {
set { managed = value; }
}
public IntPtr Handle {
get {
return list_ptr;
}
}
public void Append (IntPtr raw)
{
list_ptr = Append (list_ptr, raw);
}
public void Append (string item)
{
this.Append (Marshaller.StringToPtrGStrdup (item));
}
public void Append (object item)
{
this.Append (AllocNativeElement (item));
}
public void Prepend (IntPtr raw)
{
list_ptr = Prepend (list_ptr, raw);
}
// ICollection
public int Count {
get {
if (length == -1)
length = Length (list_ptr);
return length;
}
}
public object this [int index] {
get {
IntPtr data = NthData ((uint) index);
object ret = null;
ret = DataMarshal (data);
return ret;
}
}
// Synchronization could be tricky here. Hmm.
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return null; }
}
public void CopyTo (Array array, int index)
{
object[] orig = new object[Count];
int i = 0;
foreach (object o in this)
orig [i++] = o;
orig.CopyTo (array, index);
}
public class FilenameString {
private FilenameString () {}
}
IntPtr AllocNativeElement (object element)
{
if (element_type == null) {
if (element is IWrapper)
return (element as IWrapper).Handle;
else
return (IntPtr) GCHandle.Alloc (element);
} else {
if (element_type == typeof (string))
return Marshaller.StringToPtrGStrdup (element as string);
else if (element_type == typeof (FilenameString))
return Marshaller.StringToFilenamePtr (element as string);
else if (element_type == typeof (IntPtr))
return (IntPtr) GCHandle.Alloc (element);
else if (typeof (IWrapper).IsAssignableFrom (element_type))
return (element as IWrapper).Handle;
else if (element_type == typeof (int))
return new IntPtr ((int) element);
else if (element_type.IsValueType)
return Marshaller.StructureToPtrAlloc (element);
}
return IntPtr.Zero;
}
internal object DataMarshal (IntPtr data)
{
object ret = null;
if (element_type != null) {
if (element_type == typeof (string))
ret = Marshaller.Utf8PtrToString (data);
else if (element_type == typeof (FilenameString))
ret = Marshaller.FilenamePtrToString (data);
else if (element_type == typeof (IntPtr))
ret = data;
else if (element_type.IsSubclassOf (typeof (GLib.Object)))
ret = GLib.Object.GetObject (data, false);
else if (element_type.IsSubclassOf (typeof (GLib.Opaque)))
ret = GLib.Opaque.GetOpaque (data, element_type, elements_owned);
else if (element_type == typeof (int))
ret = (int) data;
else if (element_type.IsValueType)
ret = Marshal.PtrToStructure (data, element_type);
else if (element_type.IsInterface) {
Type adapter_type = element_type.Assembly.GetType (element_type.FullName + "Adapter");
System.Reflection.MethodInfo method = adapter_type.GetMethod ("GetObject", new Type[] {typeof(IntPtr), typeof(bool)});
ret = method.Invoke (null, new object[] {data, false});
} else
ret = Activator.CreateInstance (element_type, new object[] {data});
} else if (Object.IsObject (data))
ret = GLib.Object.GetObject (data, false);
return ret;
}
[DllImport ("libglib-2.0-0.dll")]
static extern void g_free (IntPtr item);
[DllImport ("libgobject-2.0-0.dll")]
static extern void g_object_unref (IntPtr item);
public void Empty ()
{
if (elements_owned)
for (uint i = 0; i < Count; i++)
if (typeof (GLib.Object).IsAssignableFrom (element_type))
g_object_unref (NthData (i));
else if (typeof (GLib.Opaque).IsAssignableFrom (element_type))
GLib.Opaque.GetOpaque (NthData (i), element_type, true).Dispose ();
else
g_free (NthData (i));
if (managed)
FreeList ();
}
IntPtr GetData (IntPtr current)
{
// data field is at offset 0 for GList and GSList
return Marshal.ReadIntPtr (current);
}
IntPtr Next (IntPtr current)
{
// next field follows gpointer data field for GList and GSList
return Marshal.ReadIntPtr (current, IntPtr.Size);
}
private class ListEnumerator : IEnumerator
{
private IntPtr current = IntPtr.Zero;
private ListBase list;
public ListEnumerator (ListBase list)
{
this.list = list;
}
public object Current {
get {
IntPtr data = list.GetData (current);
object ret = null;
ret = list.DataMarshal (data);
return ret;
}
}
public bool MoveNext ()
{
if (current == IntPtr.Zero)
current = list.list_ptr;
else
current = list.Next (current);
return (current != IntPtr.Zero);
}
public void Reset ()
{
current = IntPtr.Zero;
}
}
// IEnumerable
public IEnumerator GetEnumerator ()
{
return new ListEnumerator (this);
}
// IDisposable
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
Empty ();
}
void FreeList ()
{
if (list_ptr != IntPtr.Zero)
Free (list_ptr);
list_ptr = IntPtr.Zero;
length = -1;
}
// ICloneable
abstract public object Clone ();
}
}

View file

@ -0,0 +1,191 @@
// Log.cs - Wrapper for message logging functions
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
//
// Copyright (c) 2002 Gonzalo Paniagua
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public delegate void LogFunc (string log_domain, LogLevelFlags log_level, string message);
public delegate void PrintFunc (string message);
[Flags]
public enum LogLevelFlags : int
{
/* log flags */
FlagRecursion = 1 << 0,
FlagFatal = 1 << 1,
/* GLib log levels */
Error = 1 << 2, /* always fatal */
Critical = 1 << 3,
Warning = 1 << 4,
Message = 1 << 5,
Info = 1 << 6,
Debug = 1 << 7,
/* Convenience values */
AllButFatal = 253,
AllButRecursion = 254,
All = 255,
FlagMask = 3,
LevelMask = unchecked ((int) 0xFFFFFFFC)
}
public class Log {
static Hashtable handlers;
static void EnsureHash ()
{
if (handlers == null)
handlers = new Hashtable ();
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_logv (IntPtr log_domain, LogLevelFlags flags, IntPtr message);
public void WriteLog (string logDomain, LogLevelFlags flags, string format, params object [] args)
{
IntPtr ndom = Marshaller.StringToPtrGStrdup (logDomain);
IntPtr nmessage = Marshaller.StringToPtrGStrdup (String.Format (format, args));
g_logv (ndom, flags, nmessage);
Marshaller.Free (ndom);
Marshaller.Free (nmessage);
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_log_set_handler (IntPtr log_domain, LogLevelFlags flags, LogFunc log_func, IntPtr user_data);
public static uint SetLogHandler (string logDomain, LogLevelFlags flags, LogFunc logFunc)
{
IntPtr ndom = Marshaller.StringToPtrGStrdup (logDomain);
uint result = g_log_set_handler (ndom, flags, logFunc, IntPtr.Zero);
Marshaller.Free (ndom);
EnsureHash ();
handlers [result] = logFunc;
return result;
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_log_remove_handler (IntPtr log_domain, uint handler_id);
public static void RemoveLogHandler (string logDomain, uint handlerID)
{
if (handlers != null && handlers.ContainsKey (handlerID))
handlers.Remove (handlerID);
IntPtr ndom = Marshaller.StringToPtrGStrdup (logDomain);
g_log_remove_handler (ndom, handlerID);
Marshaller.Free (ndom);
}
[DllImport("libglib-2.0-0.dll")]
static extern PrintFunc g_set_print_handler (PrintFunc handler);
public static PrintFunc SetPrintHandler (PrintFunc handler)
{
EnsureHash ();
handlers ["PrintHandler"] = handler;
return g_set_print_handler (handler);
}
[DllImport("libglib-2.0-0.dll")]
static extern PrintFunc g_set_printerr_handler (PrintFunc handler);
public static PrintFunc SetPrintErrorHandler (PrintFunc handler)
{
EnsureHash ();
handlers ["PrintErrorHandler"] = handler;
return g_set_printerr_handler (handler);
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_log_default_handler (IntPtr log_domain, LogLevelFlags log_level, IntPtr message, IntPtr unused_data);
public static void DefaultHandler (string logDomain, LogLevelFlags logLevel, string message)
{
IntPtr ndom = Marshaller.StringToPtrGStrdup (logDomain);
IntPtr nmess = Marshaller.StringToPtrGStrdup (message);
g_log_default_handler (ndom, logLevel, nmess, IntPtr.Zero);
Marshaller.Free (ndom);
Marshaller.Free (nmess);
}
[DllImport("libglib-2.0-0.dll")]
extern static LogLevelFlags g_log_set_always_fatal (LogLevelFlags fatal_mask);
public static LogLevelFlags SetAlwaysFatal (LogLevelFlags fatalMask)
{
return g_log_set_always_fatal (fatalMask);
}
[DllImport("libglib-2.0-0.dll")]
extern static LogLevelFlags g_log_set_fatal_mask (IntPtr log_domain, LogLevelFlags fatal_mask);
public static LogLevelFlags SetAlwaysFatal (string logDomain, LogLevelFlags fatalMask)
{
IntPtr ndom = Marshaller.StringToPtrGStrdup (logDomain);
LogLevelFlags result = g_log_set_fatal_mask (ndom, fatalMask);
Marshaller.Free (ndom);
return result;
}
/*
* Some common logging methods.
*
* Sample usage:
*
* // Print the messages for the NULL domain
* LogFunc logFunc = new LogFunc (Log.PrintLogFunction);
* Log.SetLogHandler (null, LogLevelFlags.All, logFunc);
*
* // Print messages and stack trace for Gtk critical messages
* logFunc = new LogFunc (Log.PrintTraceLogFunction);
* Log.SetLogHandler ("Gtk", LogLevelFlags.Critical, logFunc);
*
*/
public static void PrintLogFunction (string domain, LogLevelFlags level, string message)
{
Console.WriteLine ("Domain: '{0}' Level: {1}", domain, level);
Console.WriteLine ("Message: {0}", message);
}
public static void PrintTraceLogFunction (string domain, LogLevelFlags level, string message)
{
PrintLogFunction (domain, level, message);
Console.WriteLine ("Trace follows:\n{0}", new System.Diagnostics.StackTrace ());
}
}
}

View file

@ -0,0 +1,56 @@
// GLib.MainContext.cs - mainContext class implementation
//
// Author: Radek Doulik <rodo@matfyz.cz>
//
// Copyright (c) 2003 Radek Doulik
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class MainContext {
[DllImport("libglib-2.0-0.dll")]
static extern int g_main_depth ();
public static int Depth {
get { return g_main_depth (); }
}
[DllImport("libglib-2.0-0.dll")]
static extern bool g_main_context_iteration (IntPtr Raw, bool MayBlock);
public static bool Iteration ()
{
return g_main_context_iteration (IntPtr.Zero, false);
}
public static bool Iteration (bool MayBlock)
{
return g_main_context_iteration (IntPtr.Zero, MayBlock);
}
[DllImport("libglib-2.0-0.dll")]
static extern bool g_main_context_pending (IntPtr Raw);
public static bool Pending ()
{
return g_main_context_pending (IntPtr.Zero);
}
}
}

View file

@ -0,0 +1,71 @@
// GLib.MainLoop.cs - g_main_loop class implementation
//
// Author: Jeroen Zwartepoorte <jeroen@xs4all.nl>
//
// Copyright (c) 2004 Jeroen Zwartepoorte
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Runtime.InteropServices;
namespace GLib {
public class MainLoop {
private IntPtr handle;
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_main_loop_new (IntPtr context, bool isRunning);
public MainLoop ()
{
handle = g_main_loop_new (IntPtr.Zero, false);
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_main_loop_unref (IntPtr loop);
~MainLoop ()
{
g_main_loop_unref (handle);
handle = IntPtr.Zero;
}
[DllImport("libglib-2.0-0.dll")]
static extern bool g_main_loop_is_running (IntPtr loop);
public bool IsRunning {
get {
return g_main_loop_is_running (handle);
}
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_main_loop_run (IntPtr loop);
public void Run ()
{
g_main_loop_run (handle);
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_main_loop_quit (IntPtr loop);
public void Quit ()
{
g_main_loop_quit (handle);
}
}
}

View file

@ -0,0 +1,149 @@
// GLib.ManagedValue.cs : Managed types boxer
//
// Author: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
using GLib;
internal class ManagedValue {
GCHandle gch;
object instance;
int ref_count = 1;
private ManagedValue (object instance)
{
this.instance = instance;
gch = GCHandle.Alloc (this);
}
IntPtr Handle {
get { return (IntPtr) gch; }
}
object Instance {
get { return instance; }
}
void Ref ()
{
ref_count++;
}
void Unref ()
{
if (--ref_count == 0) {
instance = null;
gch.Free ();
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate IntPtr CopyFunc (IntPtr gch);
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void FreeFunc (IntPtr gch);
static CopyFunc copy;
static FreeFunc free;
static GType boxed_type = GType.Invalid;
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_boxed_type_register_static (IntPtr typename, CopyFunc copy_func, FreeFunc free_func);
public static GType GType {
get {
if (boxed_type == GType.Invalid) {
copy = new CopyFunc (Copy);
free = new FreeFunc (Free);
IntPtr name = Marshaller.StringToPtrGStrdup ("GtkSharpValue");
boxed_type = new GLib.GType (g_boxed_type_register_static (name, copy, free));
Marshaller.Free (name);
}
return boxed_type;
}
}
static ManagedValue FromHandle (IntPtr ptr)
{
GCHandle gch = (GCHandle) ptr;
ManagedValue val = gch.Target as ManagedValue;
if (val == null)
throw new Exception ("Unexpected GCHandle received.");
return val;
}
static IntPtr Copy (IntPtr ptr)
{
try {
if (ptr == IntPtr.Zero)
return ptr;
ManagedValue val = FromHandle (ptr);
val.Ref ();
return ptr;
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
return IntPtr.Zero;
}
static void Free (IntPtr ptr)
{
try {
if (ptr == IntPtr.Zero)
return;
ManagedValue val = FromHandle (ptr);
val.Unref ();
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
}
public static IntPtr WrapObject (object obj)
{
if (obj == null)
return IntPtr.Zero;
return new ManagedValue (obj).Handle;
}
public static object ObjectForWrapper (IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
ManagedValue val = FromHandle (ptr);
return val == null ? null : val.Instance;
}
public static void ReleaseWrapper (IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return;
ManagedValue val = FromHandle (ptr);
val.Unref ();
}
}
}

View file

@ -0,0 +1,46 @@
// Markup.cs: Wrapper for the Markup code in Glib
//
// Authors:
// Miguel de Icaza (miguel@ximian.com)
//
// Copyright (c) 2003 Ximian, Inc.
//
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Runtime.InteropServices;
namespace GLib {
public class Markup {
private Markup () {}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_markup_escape_text (IntPtr text, int len);
static public string EscapeText (string s)
{
if (s == null)
return String.Empty;
IntPtr native = Marshaller.StringToPtrGStrdup (s);
string result = Marshaller.PtrToStringGFree (g_markup_escape_text (native, -1));
Marshaller.Free (native);
return result;
}
}
}

View file

@ -0,0 +1,413 @@
// GLibSharp.Marshaller.cs : Marshalling utils
//
// Author: Rachel Hestilow <rachel@nullenvoid.com>
// Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2002, 2003 Rachel Hestilow
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class Marshaller {
private Marshaller () {}
[DllImport("libglib-2.0-0.dll")]
static extern void g_free (IntPtr mem);
public static void Free (IntPtr ptr)
{
g_free (ptr);
}
public static void Free (IntPtr[] ptrs)
{
if (ptrs == null)
return;
for (int i = 0; i < ptrs.Length; i++)
g_free (ptrs [i]);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_filename_to_utf8 (IntPtr mem, int len, IntPtr read, out IntPtr written, out IntPtr error);
public static string FilenamePtrToString (IntPtr ptr)
{
if (ptr == IntPtr.Zero) return null;
IntPtr dummy, error;
IntPtr utf8 = g_filename_to_utf8 (ptr, -1, IntPtr.Zero, out dummy, out error);
if (error != IntPtr.Zero)
throw new GLib.GException (error);
return Utf8PtrToString (utf8);
}
public static string FilenamePtrToStringGFree (IntPtr ptr)
{
string ret = FilenamePtrToString (ptr);
g_free (ptr);
return ret;
}
static unsafe ulong strlen (IntPtr s)
{
ulong cnt = 0;
byte *b = (byte *)s;
while (*b != 0) {
b++;
cnt++;
}
return cnt;
}
public static string Utf8PtrToString (IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
int len = (int) (uint) strlen (ptr);
byte[] bytes = new byte [len];
Marshal.Copy (ptr, bytes, 0, len);
return System.Text.Encoding.UTF8.GetString (bytes);
}
public static string[] Utf8PtrToString (IntPtr[] ptrs) {
// The last pointer is a null terminator.
string[] ret = new string[ptrs.Length - 1];
for (int i = 0; i < ret.Length; i++)
ret[i] = Utf8PtrToString (ptrs[i]);
return ret;
}
public static string PtrToStringGFree (IntPtr ptr)
{
string ret = Utf8PtrToString (ptr);
g_free (ptr);
return ret;
}
public static string[] PtrToStringGFree (IntPtr[] ptrs) {
// The last pointer is a null terminator.
string[] ret = new string[ptrs.Length - 1];
for (int i = 0; i < ret.Length; i++) {
ret[i] = Utf8PtrToString (ptrs[i]);
g_free (ptrs[i]);
}
return ret;
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_filename_from_utf8 (IntPtr mem, int len, IntPtr read, out IntPtr written, out IntPtr error);
public static IntPtr StringToFilenamePtr (string str)
{
if (str == null)
return IntPtr.Zero;
IntPtr dummy, error;
IntPtr utf8 = StringToPtrGStrdup (str);
IntPtr result = g_filename_from_utf8 (utf8, -1, IntPtr.Zero, out dummy, out error);
g_free (utf8);
if (error != IntPtr.Zero)
throw new GException (error);
return result;
}
public static IntPtr StringToPtrGStrdup (string str) {
if (str == null)
return IntPtr.Zero;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes (str);
IntPtr result = g_malloc (new UIntPtr ((ulong)bytes.Length + 1));
Marshal.Copy (bytes, 0, result, bytes.Length);
Marshal.WriteByte (result, bytes.Length, 0);
return result;
}
public static string StringFormat (string format, params object[] args) {
string ret = String.Format (format, args);
if (ret.IndexOf ('%') == -1)
return ret;
else
return ret.Replace ("%", "%%");
}
public static IntPtr[] StringArrayToNullTermPointer (string[] strs)
{
if (strs == null)
return null;
IntPtr[] result = new IntPtr [strs.Length + 1];
for (int i = 0; i < strs.Length; i++)
result [i] = StringToPtrGStrdup (strs [i]);
result [strs.Length] = IntPtr.Zero;
return result;
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_strfreev (IntPtr mem);
public static void StrFreeV (IntPtr null_term_array)
{
g_strfreev (null_term_array);
}
public static string[] NullTermPtrToStringArray (IntPtr null_term_array, bool owned)
{
if (null_term_array == IntPtr.Zero)
return new string [0];
int count = 0;
System.Collections.ArrayList result = new System.Collections.ArrayList ();
IntPtr s = Marshal.ReadIntPtr (null_term_array, count++ * IntPtr.Size);
while (s != IntPtr.Zero) {
result.Add (Utf8PtrToString (s));
s = Marshal.ReadIntPtr (null_term_array, count++ * IntPtr.Size);
}
if (owned)
g_strfreev (null_term_array);
return (string[]) result.ToArray (typeof(string));
}
public static string[] PtrToStringArrayGFree (IntPtr string_array)
{
if (string_array == IntPtr.Zero)
return new string [0];
int count = 0;
while (Marshal.ReadIntPtr (string_array, count*IntPtr.Size) != IntPtr.Zero)
++count;
string[] members = new string[count];
for (int i = 0; i < count; ++i) {
IntPtr s = Marshal.ReadIntPtr (string_array, i * IntPtr.Size);
members[i] = GLib.Marshaller.PtrToStringGFree (s);
}
GLib.Marshaller.Free (string_array);
return members;
}
// Argv marshalling -- unpleasantly complex, but
// don't know of a better way to do it.
//
// Currently, the 64-bit cleanliness is
// hypothetical. It's also ugly, but I don't know of a
// construct to handle both 32 and 64 bitness
// transparently, since we need to alloc buffers of
// [native pointer size] * [count] bytes.
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_malloc(UIntPtr size);
public static IntPtr Malloc (ulong size)
{
return g_malloc (new UIntPtr (size));
}
static bool check_sixtyfour () {
int szint = Marshal.SizeOf (typeof (int));
int szlong = Marshal.SizeOf (typeof (long));
int szptr = IntPtr.Size;
if (szptr == szint)
return false;
if (szptr == szlong)
return true;
throw new Exception ("Pointers are neither int- nor long-sized???");
}
static IntPtr make_buf_32 (string[] args)
{
int[] ptrs = new int[args.Length];
for (int i = 0; i < args.Length; i++)
ptrs[i] = (int) Marshal.StringToHGlobalAuto (args[i]);
IntPtr buf = g_malloc (new UIntPtr ((ulong) Marshal.SizeOf(typeof(int)) *
(ulong) args.Length));
Marshal.Copy (ptrs, 0, buf, ptrs.Length);
return buf;
}
static IntPtr make_buf_64 (string[] args)
{
long[] ptrs = new long[args.Length];
for (int i = 0; i < args.Length; i++)
ptrs[i] = (long) Marshal.StringToHGlobalAuto (args[i]);
IntPtr buf = g_malloc (new UIntPtr ((ulong) Marshal.SizeOf(typeof(long)) *
(ulong) args.Length));
Marshal.Copy (ptrs, 0, buf, ptrs.Length);
return buf;
}
[Obsolete ("Use GLib.Argv instead to avoid leaks.")]
public static IntPtr ArgvToArrayPtr (string[] args)
{
if (args.Length == 0)
return IntPtr.Zero;
if (check_sixtyfour ())
return make_buf_64 (args);
return make_buf_32 (args);
}
// should we be freeing these pointers? they're marshalled
// from our own strings, so I think not ...
static string[] unmarshal_32 (IntPtr buf, int argc)
{
int[] ptrs = new int[argc];
string[] args = new string[argc];
Marshal.Copy (buf, ptrs, 0, argc);
for (int i = 0; i < ptrs.Length; i++)
args[i] = Marshal.PtrToStringAuto ((IntPtr) ptrs[i]);
return args;
}
static string[] unmarshal_64 (IntPtr buf, int argc)
{
long[] ptrs = new long[argc];
string[] args = new string[argc];
Marshal.Copy (buf, ptrs, 0, argc);
for (int i = 0; i < ptrs.Length; i++)
args[i] = Marshal.PtrToStringAuto ((IntPtr) ptrs[i]);
return args;
}
[Obsolete ("Use GLib.Argv instead to avoid leaks.")]
public static string[] ArrayPtrToArgv (IntPtr array, int argc)
{
if (argc == 0)
return new string[0];
if (check_sixtyfour ())
return unmarshal_64 (array, argc);
return unmarshal_32 (array, argc);
}
static DateTime local_epoch = new DateTime (1970, 1, 1, 0, 0, 0);
static int utc_offset = (int) (TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now)).TotalSeconds;
public static IntPtr DateTimeTotime_t (DateTime time)
{
return new IntPtr (((long)time.Subtract (local_epoch).TotalSeconds) - utc_offset);
}
public static DateTime time_tToDateTime (IntPtr time_t)
{
return local_epoch.AddSeconds (time_t.ToInt64 () + utc_offset);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_malloc0 (UIntPtr size);
[DllImport("libglib-2.0-0.dll")]
static extern int g_unichar_to_utf8 (uint c, IntPtr buf);
public static char GUnicharToChar (uint ucs4_char)
{
if (ucs4_char == 0)
return (char) 0;
string ret = GUnicharToString (ucs4_char);
if (ret.Length != 1)
throw new ArgumentOutOfRangeException ("ucs4char is not representable by a char.");
return ret [0];
}
public static string GUnicharToString (uint ucs4_char)
{
if (ucs4_char == 0)
return String.Empty;
IntPtr buf = g_malloc0 (new UIntPtr (7));
g_unichar_to_utf8 (ucs4_char, buf);
return PtrToStringGFree (buf);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_utf16_to_ucs4 (ref ushort c, IntPtr len, IntPtr d1, IntPtr d2, IntPtr d3);
public static uint CharToGUnichar (char c)
{
ushort val = (ushort) c;
IntPtr ucs4_str = g_utf16_to_ucs4 (ref val, new IntPtr (1), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
uint result = (uint) Marshal.ReadInt32 (ucs4_str);
g_free (ucs4_str);
return result;
}
public static IntPtr StructureToPtrAlloc (object o)
{
IntPtr result = Marshal.AllocHGlobal (Marshal.SizeOf (o));
Marshal.StructureToPtr (o, result, false);
return result;
}
public static Array ListPtrToArray (IntPtr list_ptr, Type list_type, bool owned, bool elements_owned, Type elem_type)
{
Type array_type = elem_type == typeof (ListBase.FilenameString) ? typeof (string) : elem_type;
ListBase list;
if (list_type == typeof(GLib.List))
list = new GLib.List (list_ptr, elem_type, owned, elements_owned);
else
list = new GLib.SList (list_ptr, elem_type, owned, elements_owned);
using (list)
return ListToArray (list, array_type);
}
public static Array PtrArrayToArray (IntPtr list_ptr, bool owned, bool elements_owned, Type elem_type)
{
GLib.PtrArray array = new GLib.PtrArray (list_ptr, elem_type, owned, elements_owned);
Array ret = Array.CreateInstance (elem_type, array.Count);
array.CopyTo (ret, 0);
array.Dispose ();
return ret;
}
public static Array ListToArray (ListBase list, System.Type type)
{
Array result = Array.CreateInstance (type, list.Count);
if (list.Count > 0)
list.CopyTo (result, 0);
if (type.IsSubclassOf (typeof (GLib.Opaque)))
list.elements_owned = false;
return result;
}
}
}

View file

@ -0,0 +1,35 @@
// MissingIntPtrCtorException.cs : Exception for missing IntPtr ctors
//
// Authors: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class MissingIntPtrCtorException : Exception
{
public MissingIntPtrCtorException (string msg) : base (msg)
{
}
}
}

View file

@ -0,0 +1,35 @@
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public delegate void NotifyHandler (object o, NotifyArgs args);
public class NotifyArgs : GLib.SignalArgs {
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_get_name (IntPtr pspec);
public string Property {
get {
IntPtr raw_ret = g_param_spec_get_name ((IntPtr) Args[0]);
return Marshaller.Utf8PtrToString (raw_ret);
}
}
}
}

View file

@ -0,0 +1,738 @@
// Object.cs - GObject class wrapper implementation
//
// Authors: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001-2003 Mike Kestner
// Copyright (c) 2004-2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
public class Object : IWrapper, IDisposable {
IntPtr handle;
ToggleRef tref;
bool disposed = false;
Hashtable data;
static Hashtable Objects = new Hashtable();
static ArrayList PendingDestroys = new ArrayList ();
static bool idle_queued;
~Object ()
{
lock (PendingDestroys) {
lock (Objects) {
if (Objects[Handle] is ToggleRef)
PendingDestroys.Add (Objects [Handle]);
Objects.Remove (Handle);
}
if (!idle_queued){
Timeout.Add (50, new TimeoutHandler (PerformQueuedUnrefs));
idle_queued = true;
}
}
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_unref (IntPtr raw);
static bool PerformQueuedUnrefs ()
{
object [] references;
lock (PendingDestroys){
references = new object [PendingDestroys.Count];
PendingDestroys.CopyTo (references, 0);
PendingDestroys.Clear ();
idle_queued = false;
}
foreach (ToggleRef r in references)
r.Free ();
return false;
}
public virtual void Dispose ()
{
if (disposed)
return;
disposed = true;
ToggleRef toggle_ref = Objects [Handle] as ToggleRef;
Objects.Remove (Handle);
try {
if (toggle_ref != null)
toggle_ref.Free ();
} catch (Exception e) {
Console.WriteLine ("Exception while disposing a " + this + " in Gtk#");
throw e;
}
handle = IntPtr.Zero;
GC.SuppressFinalize (this);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_object_ref (IntPtr raw);
public static Object GetObject(IntPtr o, bool owned_ref)
{
if (o == IntPtr.Zero)
return null;
Object obj = null;
if (Objects.Contains (o)) {
ToggleRef toggle_ref = Objects [o] as ToggleRef;
if (toggle_ref != null && toggle_ref.IsAlive)
obj = toggle_ref.Target;
}
if (obj != null && obj.Handle == o) {
if (owned_ref)
g_object_unref (obj.Handle);
return obj;
}
if (!owned_ref)
g_object_ref (o);
obj = GLib.ObjectManager.CreateObject(o);
if (obj == null) {
g_object_unref (o);
return null;
}
return obj;
}
public static Object GetObject(IntPtr o)
{
return GetObject (o, false);
}
private static void ConnectDefaultHandlers (GType gtype, System.Type t)
{
foreach (MethodInfo minfo in t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)) {
MethodInfo baseinfo = minfo.GetBaseDefinition ();
if (baseinfo == minfo)
continue;
foreach (object attr in baseinfo.GetCustomAttributes (typeof (DefaultSignalHandlerAttribute), false)) {
DefaultSignalHandlerAttribute sigattr = attr as DefaultSignalHandlerAttribute;
MethodInfo connector = sigattr.Type.GetMethod (sigattr.ConnectionMethod, BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeof (GType) }, new ParameterModifier [0]);
object[] parms = new object [1];
parms [0] = gtype;
connector.Invoke (null, parms);
break;
}
}
}
private static void InvokeClassInitializers (GType gtype, System.Type t)
{
object[] parms = {gtype, t};
BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic;
foreach (TypeInitializerAttribute tia in t.GetCustomAttributes (typeof (TypeInitializerAttribute), true)) {
MethodInfo m = tia.Type.GetMethod (tia.MethodName, flags);
if (m != null)
m.Invoke (null, parms);
}
for (Type curr = t; curr != typeof(GLib.Object); curr = curr.BaseType) {
if (curr.Assembly.IsDefined (typeof (IgnoreClassInitializersAttribute), false))
continue;
foreach (MethodInfo minfo in curr.GetMethods(flags))
if (minfo.IsDefined (typeof (ClassInitializerAttribute), true))
minfo.Invoke (null, parms);
}
}
// Key: The pointer to the ParamSpec of the property
// Value: The corresponding PropertyInfo object
static Hashtable properties;
static Hashtable Properties {
get {
if (properties == null)
properties = new Hashtable ();
return properties;
}
}
[StructLayout(LayoutKind.Sequential)]
struct GTypeClass {
public IntPtr gtype;
}
[StructLayout(LayoutKind.Sequential)]
struct GObjectClass {
GTypeClass type_class;
IntPtr construct_props;
public ConstructorDelegate constructor_cb;
public SetPropertyDelegate set_prop_cb;
public GetPropertyDelegate get_prop_cb;
IntPtr dispose;
IntPtr finalize;
IntPtr dispatch_properties_changed;
IntPtr notify;
public ConstructedDelegate constructed_cb;
IntPtr dummy1;
IntPtr dummy2;
IntPtr dummy3;
IntPtr dummy4;
IntPtr dummy5;
IntPtr dummy6;
IntPtr dummy7;
}
static Hashtable class_structs;
static GObjectClass GetClassStruct (GLib.GType gtype, bool use_cache)
{
if (class_structs == null)
class_structs = new Hashtable ();
if (use_cache && class_structs.Contains (gtype))
return (GObjectClass) class_structs [gtype];
else {
IntPtr class_ptr = gtype.ClassPtr;
GObjectClass class_struct = (GObjectClass) Marshal.PtrToStructure (class_ptr, typeof (GObjectClass));
if (use_cache)
class_structs.Add (gtype, class_struct);
return class_struct;
}
}
static void OverrideClassStruct (GLib.GType gtype, GObjectClass class_struct)
{
IntPtr class_ptr = gtype.ClassPtr;
Marshal.StructureToPtr (class_struct, class_ptr, false);
}
static void OverridePropertyHandlers (GType gtype, GetPropertyDelegate get_cb, SetPropertyDelegate set_cb)
{
GObjectClass klass = GetClassStruct (gtype, false);
klass.get_prop_cb = get_cb;
klass.set_prop_cb = set_cb;
OverrideClassStruct (gtype, klass);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_class_install_property (IntPtr klass, uint prop_id, IntPtr param_spec);
static IntPtr RegisterProperty (GType type, string name, string nick, string blurb, uint property_id, GType property_type, bool can_read, bool can_write)
{
IntPtr declaring_class = type.ClassPtr;
ParamSpec pspec = new ParamSpec (name, nick, blurb, property_type, can_read, can_write);
g_object_class_install_property (declaring_class, property_id, pspec.Handle);
return pspec.Handle;
}
static ConstructorDelegate Constructor_cb = new ConstructorDelegate (constructor_cb);
delegate IntPtr ConstructorDelegate (IntPtr gtype, uint n_construct_properties, IntPtr construct_properties);
[StructLayout(LayoutKind.Sequential)]
struct GObjectConstructParam {
public IntPtr pspec;
public IntPtr value;
}
static IntPtr constructor_cb (IntPtr gtype, uint n_construct_properties, IntPtr construct_properties)
{
GType type = new GLib.GType (gtype);
IntPtr instance = GetClassStruct (type.ThresholdType, false).constructor_cb (gtype, n_construct_properties, construct_properties);
for (int i = 0; i < n_construct_properties; i++) {
IntPtr p = new IntPtr ((long) construct_properties + i * Marshal.SizeOf (typeof (GObjectConstructParam)));
GObjectConstructParam cparam = (GObjectConstructParam) Marshal.PtrToStructure (p, typeof (GObjectConstructParam));
ParamSpec pspec = new ParamSpec (cparam.pspec);
GLib.Value val = (Value) Marshal.PtrToStructure (cparam.value, typeof (Value));
if (pspec.Name == "gtk-sharp-managed-instance" && (IntPtr) val.Val != IntPtr.Zero) {
GCHandle gch = (GCHandle) (IntPtr) val.Val;
Object o = (GLib.Object) gch.Target;
o.Raw = instance;
}
}
return instance;
}
static ConstructedDelegate Constructed_cb = new ConstructedDelegate (constructed_cb);
[GLib.CDeclCallback]
delegate void ConstructedDelegate (IntPtr o);
static void constructed_cb (IntPtr o)
{
GLib.Object __obj = GLib.Object.GetObject (o, false) as GLib.Object;
ConstructedDelegate unmanaged = GetClassStruct (__obj.LookupGType ().ThresholdType, true).constructed_cb;
if (unmanaged != null)
unmanaged (__obj.Handle);
}
static SetPropertyDelegate Set_prop_dummy_cb = new SetPropertyDelegate (set_prop_dummy_cb);
static void set_prop_dummy_cb (IntPtr GObject, uint property_id, ref GLib.Value value, IntPtr pspec) {}
static void AddProperties (GType gtype, System.Type t)
{
uint idx = 1;
if (gtype.BaseType == gtype.ThresholdType) {
GObjectClass gobject_class = GetClassStruct (gtype, false);
gobject_class.constructor_cb = Constructor_cb;
gobject_class.constructed_cb = Constructed_cb;
gobject_class.set_prop_cb = Set_prop_dummy_cb;
OverrideClassStruct (gtype, gobject_class);
IntPtr declaring_class = gtype.ClassPtr;
ParamSpec pspec = new ParamSpec ("gtk-sharp-managed-instance", "", "", GType.Pointer, ParamFlags.Writable | ParamFlags.ConstructOnly);
g_object_class_install_property (declaring_class, idx, pspec.Handle);
idx++;
}
bool handlers_overridden = false;
foreach (PropertyInfo pinfo in t.GetProperties (BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) {
foreach (object attr in pinfo.GetCustomAttributes (typeof (PropertyAttribute), false)) {
if(pinfo.GetIndexParameters().Length > 0)
throw(new InvalidOperationException(String.Format("GLib.RegisterPropertyAttribute cannot be applied to property {0} of type {1} because the property expects one or more indexed parameters", pinfo.Name, t.FullName)));
PropertyAttribute property_attr = attr as PropertyAttribute;
if (!handlers_overridden) {
OverridePropertyHandlers (gtype, GetPropertyHandler, SetPropertyHandler);
handlers_overridden = true;
}
try {
IntPtr param_spec = RegisterProperty (gtype, property_attr.Name, property_attr.Nickname, property_attr.Blurb, idx, (GType) pinfo.PropertyType, pinfo.CanRead, pinfo.CanWrite);
Properties.Add (param_spec, pinfo);
idx++;
} catch (ArgumentException) {
throw new InvalidOperationException (String.Format ("GLib.PropertyAttribute cannot be applied to property {0} of type {1} because the return type of the property is not supported", pinfo.Name, t.FullName));
}
}
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void GetPropertyDelegate (IntPtr GObject, uint property_id, ref GLib.Value value, IntPtr pspec);
static void GetPropertyCallback (IntPtr handle, uint property_id, ref GLib.Value value, IntPtr param_spec)
{
if (!Properties.Contains (param_spec))
return;
GLib.Object obj = GLib.Object.GetObject (handle, false);
value.Val = (Properties [param_spec] as PropertyInfo).GetValue (obj, new object [0]);
}
static GetPropertyDelegate get_property_handler;
static GetPropertyDelegate GetPropertyHandler {
get {
if (get_property_handler == null)
get_property_handler = new GetPropertyDelegate (GetPropertyCallback);
return get_property_handler;
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void SetPropertyDelegate (IntPtr GObject, uint property_id, ref GLib.Value value, IntPtr pspec);
static void SetPropertyCallback(IntPtr handle, uint property_id, ref GLib.Value value, IntPtr param_spec)
{
if (!Properties.Contains (param_spec))
return;
GLib.Object obj = GLib.Object.GetObject (handle, false);
(Properties [param_spec] as PropertyInfo).SetValue (obj, value.Val, new object [0]);
}
static SetPropertyDelegate set_property_handler;
static SetPropertyDelegate SetPropertyHandler {
get {
if (set_property_handler == null)
set_property_handler = new SetPropertyDelegate (SetPropertyCallback);
return set_property_handler;
}
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_type_add_interface_static (IntPtr gtype, IntPtr iface_type, ref GInterfaceInfo info);
static void AddInterfaces (GType gtype, Type t)
{
foreach (Type iface in t.GetInterfaces ()) {
if (!iface.IsDefined (typeof (GInterfaceAttribute), true) || iface.IsAssignableFrom (t.BaseType))
continue;
GInterfaceAttribute attr = iface.GetCustomAttributes (typeof (GInterfaceAttribute), false) [0] as GInterfaceAttribute;
GInterfaceAdapter adapter = Activator.CreateInstance (attr.AdapterType, null) as GInterfaceAdapter;
GInterfaceInfo info = adapter.Info;
g_type_add_interface_static (gtype.Val, adapter.GType.Val, ref info);
}
}
protected internal static GType RegisterGType (System.Type t)
{
GType gtype = GType.RegisterGObjectType (t);
AddProperties (gtype, t);
ConnectDefaultHandlers (gtype, t);
InvokeClassInitializers (gtype, t);
AddInterfaces (gtype, t);
return gtype;
}
protected GType LookupGType ()
{
if (Handle != IntPtr.Zero) {
GTypeInstance obj = (GTypeInstance) Marshal.PtrToStructure (Handle, typeof (GTypeInstance));
GTypeClass klass = (GTypeClass) Marshal.PtrToStructure (obj.g_class, typeof (GTypeClass));
return new GLib.GType (klass.gtype);
} else {
return LookupGType (GetType ());
}
}
protected internal static GType LookupGType (System.Type t)
{
return GType.LookupGObjectType (t);
}
protected Object (IntPtr raw)
{
Raw = raw;
}
protected Object ()
{
CreateNativeObject (new string [0], new GLib.Value [0]);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_object_new (IntPtr gtype, IntPtr dummy);
[Obsolete]
protected Object (GType gtype)
{
Raw = g_object_new (gtype.Val, IntPtr.Zero);
}
struct GParameter {
public IntPtr name;
public GLib.Value val;
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_object_newv (IntPtr gtype, int n_params, GParameter[] parms);
protected virtual void CreateNativeObject (string[] names, GLib.Value[] vals)
{
GLib.GType gtype = LookupGType ();
bool managed_type = gtype.ToString().StartsWith ("__gtksharp_");
GParameter[] parms = new GParameter [names.Length + ((managed_type) ? 1 : 0)];
for (int i = 0; i < names.Length; i++) {
parms [i].name = GLib.Marshaller.StringToPtrGStrdup (names [i]);
parms [i].val = vals [i];
}
if (managed_type) {
GCHandle gch = GCHandle.Alloc (this);
parms[names.Length].name = GLib.Marshaller.StringToPtrGStrdup ("gtk-sharp-managed-instance");
parms[names.Length].val = new GLib.Value ((IntPtr) gch);
Raw = g_object_newv (gtype.Val, parms.Length, parms);
gch.Free ();
} else {
Raw = g_object_newv (gtype.Val, parms.Length, parms);
}
foreach (GParameter p in parms)
GLib.Marshaller.Free (p.name);
}
protected virtual IntPtr Raw {
get {
return handle;
}
set {
if (handle == value)
return;
if (handle != IntPtr.Zero) {
Objects.Remove (handle);
if (tref != null) {
tref.Free ();
tref = null;
}
}
handle = value;
if (value != IntPtr.Zero) {
tref = new ToggleRef (this);
Objects [value] = tref;
}
}
}
public static GLib.GType GType {
get {
return GType.Object;
}
}
protected string TypeName {
get {
return NativeType.ToString ();
}
}
internal GLib.GType NativeType {
get {
return LookupGType ();
}
}
internal ToggleRef ToggleRef {
get {
return tref;
}
}
public IntPtr Handle {
get {
return handle;
}
}
public IntPtr OwnedHandle {
get {
return g_object_ref (handle);
}
}
Hashtable before_signals;
[Obsolete ("Replaced by GLib.Signal marshaling mechanism.")]
protected internal Hashtable BeforeSignals {
get {
if (before_signals == null)
before_signals = new Hashtable ();
return before_signals;
}
}
Hashtable after_signals;
[Obsolete ("Replaced by GLib.Signal marshaling mechanism.")]
protected internal Hashtable AfterSignals {
get {
if (after_signals == null)
after_signals = new Hashtable ();
return after_signals;
}
}
EventHandlerList before_handlers;
[Obsolete ("Replaced by GLib.Signal marshaling mechanism.")]
protected EventHandlerList BeforeHandlers {
get {
if (before_handlers == null)
before_handlers = new EventHandlerList ();
return before_handlers;
}
}
EventHandlerList after_handlers;
[Obsolete ("Replaced by GLib.Signal marshaling mechanism.")]
protected EventHandlerList AfterHandlers {
get {
if (after_handlers == null)
after_handlers = new EventHandlerList ();
return after_handlers;
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void NotifyDelegate (IntPtr handle, IntPtr pspec, IntPtr gch);
void NotifyCallback (IntPtr handle, IntPtr pspec, IntPtr gch)
{
try {
GLib.Signal sig = ((GCHandle) gch).Target as GLib.Signal;
if (sig == null)
throw new Exception("Unknown signal GC handle received " + gch);
NotifyArgs args = new NotifyArgs ();
args.Args = new object[1];
args.Args[0] = pspec;
NotifyHandler handler = (NotifyHandler) sig.Handler;
handler (GLib.Object.GetObject (handle), args);
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
}
void ConnectNotification (string signal, NotifyHandler handler)
{
Signal sig = Signal.Lookup (this, signal, new NotifyDelegate (NotifyCallback));
sig.AddDelegate (handler);
}
public void AddNotification (string property, NotifyHandler handler)
{
ConnectNotification ("notify::" + property, handler);
}
public void AddNotification (NotifyHandler handler)
{
ConnectNotification ("notify", handler);
}
void DisconnectNotification (string signal, NotifyHandler handler)
{
Signal sig = Signal.Lookup (this, signal, new NotifyDelegate (NotifyCallback));
sig.RemoveDelegate (handler);
}
public void RemoveNotification (string property, NotifyHandler handler)
{
DisconnectNotification ("notify::" + property, handler);
}
public void RemoveNotification (NotifyHandler handler)
{
DisconnectNotification ("notify", handler);
}
public override int GetHashCode ()
{
return Handle.GetHashCode ();
}
public Hashtable Data {
get {
if (data == null)
data = new Hashtable ();
return data;
}
}
Hashtable persistent_data;
protected Hashtable PersistentData {
get {
if (persistent_data == null)
persistent_data = new Hashtable ();
return persistent_data;
}
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_get_property (IntPtr obj, IntPtr name, ref GLib.Value val);
protected GLib.Value GetProperty (string name)
{
Value val = new Value (this, name);
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name);
g_object_get_property (Raw, native_name, ref val);
GLib.Marshaller.Free (native_name);
return val;
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_set_property (IntPtr obj, IntPtr name, ref GLib.Value val);
protected void SetProperty (string name, GLib.Value val)
{
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name);
g_object_set_property (Raw, native_name, ref val);
GLib.Marshaller.Free (native_name);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_notify (IntPtr obj, IntPtr property_name);
protected void Notify (string property_name)
{
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (property_name);
g_object_notify (Handle, native_name);
GLib.Marshaller.Free (native_name);
}
protected static void OverrideVirtualMethod (GType gtype, string name, Delegate cb)
{
Signal.OverrideDefaultHandler (gtype, name, cb);
}
[DllImport("libgobject-2.0-0.dll")]
protected static extern void g_signal_chain_from_overridden (IntPtr args, ref GLib.Value retval);
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_type_check_instance_is_a (IntPtr obj, IntPtr gtype);
internal static bool IsObject (IntPtr obj)
{
return g_type_check_instance_is_a (obj, GType.Object.Val);
}
[StructLayout(LayoutKind.Sequential)]
struct GTypeInstance {
public IntPtr g_class;
}
[StructLayout(LayoutKind.Sequential)]
struct GObject {
public GTypeInstance type_instance;
public uint ref_count;
public IntPtr qdata;
}
protected int RefCount {
get {
GObject native = (GObject) Marshal.PtrToStructure (Handle, typeof (GObject));
return (int) native.ref_count;
}
}
internal void Harden ()
{
tref.Harden ();
}
static Object ()
{
if (Environment.GetEnvironmentVariable ("GTK_SHARP_DEBUG") != null)
GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.All, new GLib.LogFunc (GLib.Log.PrintTraceLogFunction));
}
}
}

View file

@ -0,0 +1,89 @@
// GLib.ObjectManager.cs - GLib ObjectManager class implementation
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright <c> 2001-2002 Mike Kestner
// Copyright <c> 2004-2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
using System.Reflection;
public class ObjectManager {
static BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
public static GLib.Object CreateObject (IntPtr raw)
{
if (raw == IntPtr.Zero)
return null;
Type type = GetTypeOrParent (raw);
if (type == null)
return null;
GLib.Object obj;
try {
obj = Activator.CreateInstance (type, flags, null, new object[] {raw}, null) as GLib.Object;
} catch (MissingMethodException) {
throw new GLib.MissingIntPtrCtorException ("GLib.Object subclass " + type + " must provide a protected or public IntPtr ctor to support wrapping of native object handles.");
}
return obj;
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (string native_name, string managed_name, string assembly)
{
RegisterType (native_name, managed_name + "," + assembly);
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (string native_name, string mangled)
{
RegisterType (GType.FromName (native_name), Type.GetType (mangled));
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (GType native_type, System.Type type)
{
GType.Register (native_type, type);
}
static Type GetTypeOrParent (IntPtr obj)
{
IntPtr typeid = GType.ValFromInstancePtr (obj);
if (typeid == GType.Invalid.Val)
return null;
Type result = GType.LookupType (typeid);
while (result == null) {
typeid = g_type_parent (typeid);
if (typeid == IntPtr.Zero)
return null;
result = GType.LookupType (typeid);
}
return result;
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_type_parent (IntPtr typ);
}
}

View file

@ -0,0 +1,150 @@
// Opaque .cs - Opaque struct wrapper implementation
//
// Authors: Bob Smith <bob@thestuff.net>
// Mike Kestner <mkestner@speakeasy.net>
// Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2001 Bob Smith
// Copyright (c) 2001 Mike Kestner
// Copyright (c) 2002 Rachel Hestilow
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
public class Opaque : IWrapper, IDisposable {
IntPtr _obj;
bool owned;
[Obsolete ("Use more explicit overload. This method always returns null")]
public static Opaque GetOpaque (IntPtr o)
{
return null;
}
public static Opaque GetOpaque (IntPtr o, Type type, bool owned)
{
if (o == IntPtr.Zero)
return null;
Opaque opaque = (Opaque)Activator.CreateInstance (type, new object[] { o });
if (owned) {
if (opaque.owned) {
// The constructor took a Ref it shouldn't have, so undo it
opaque.Unref (o);
}
opaque.owned = true;
} else
opaque = opaque.Copy (o);
return opaque;
}
public Opaque ()
{
owned = true;
}
public Opaque (IntPtr raw)
{
owned = false;
Raw = raw;
}
protected IntPtr Raw {
get {
return _obj;
}
set {
if (_obj != IntPtr.Zero) {
Unref (_obj);
if (owned)
Free (_obj);
}
_obj = value;
if (_obj != IntPtr.Zero) {
Ref (_obj);
}
}
}
~Opaque ()
{
// for compat. All subclasses should have
// generated finalizers if needed now.
}
public virtual void Dispose ()
{
Raw = IntPtr.Zero;
GC.SuppressFinalize (this);
}
// These take an IntPtr arg so we don't get conflicts if we need
// to have an "[Obsolete] public void Ref ()"
protected virtual void Ref (IntPtr raw) {}
protected virtual void Unref (IntPtr raw) {}
protected virtual void Free (IntPtr raw) {}
protected virtual Opaque Copy (IntPtr raw)
{
return this;
}
public IntPtr Handle {
get {
return _obj;
}
}
public IntPtr OwnedCopy {
get {
Opaque result = Copy (Handle);
result.Owned = false;
return result.Handle;
}
}
public bool Owned {
get {
return owned;
}
set {
owned = value;
}
}
public override bool Equals (object o)
{
if (!(o is Opaque))
return false;
return (Handle == ((Opaque) o).Handle);
}
public override int GetHashCode ()
{
return Handle.GetHashCode ();
}
}
}

View file

@ -0,0 +1,206 @@
// ParamSpec.cs - GParamSpec class wrapper implementation
//
// Authors: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2008 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
internal enum ParamFlags {
None = 0,
Readable = 1 << 0,
Writable = 1 << 1,
Construct = 1 << 2,
ConstructOnly = 1 << 3,
}
public class ParamSpec {
IntPtr handle;
private static IntPtr CreateParamSpec (string name, string nick, string blurb, GType type, ParamFlags pflags) {
int flags = (int) pflags;
IntPtr ret;
IntPtr p_name = GLib.Marshaller.StringToPtrGStrdup (name);
IntPtr p_nick = GLib.Marshaller.StringToPtrGStrdup (nick);
IntPtr p_blurb = GLib.Marshaller.StringToPtrGStrdup (blurb);
if (type == GType.Char)
ret = g_param_spec_char (p_name, p_nick, p_blurb, SByte.MinValue, SByte.MaxValue, 0, flags);
else if (type == GType.UChar)
ret = g_param_spec_uchar (p_name, p_nick, p_blurb, Byte.MinValue, Byte.MaxValue, 0, flags);
else if (type == GType.Boolean)
ret = g_param_spec_boolean (p_name, p_nick, p_blurb, false, flags);
else if (type == GType.Int)
ret = g_param_spec_int (p_name, p_nick, p_blurb, Int32.MinValue, Int32.MaxValue, 0, flags);
else if (type == GType.UInt)
ret = g_param_spec_uint (p_name, p_nick, p_blurb, 0, UInt32.MaxValue, 0, flags);
else if (type == GType.Long)
ret = g_param_spec_long (p_name, p_nick, p_blurb, IntPtr.Zero, IntPtr.Size == 4 ? new IntPtr (Int32.MaxValue) : new IntPtr (Int64.MaxValue), IntPtr.Zero, flags);
else if (type == GType.ULong)
ret = g_param_spec_ulong (p_name, p_nick, p_blurb, UIntPtr.Zero, UIntPtr.Size == 4 ? new UIntPtr (UInt32.MaxValue) : new UIntPtr (UInt64.MaxValue), UIntPtr.Zero, flags);
else if (type == GType.Int64)
ret = g_param_spec_int64 (p_name, p_nick, p_blurb, Int64.MinValue, Int64.MaxValue, 0, flags);
else if (type == GType.UInt64)
ret = g_param_spec_uint64 (p_name, p_nick, p_blurb, 0, UInt64.MaxValue, 0, flags);
/*
else if (type == GType.Enum)
else if (type == GType.Flags)
* TODO:
* Both g_param_spec_enum and g_param_spec_flags expect default property values and the members of the enum seemingly cannot be enumerated
*/
else if (type == GType.Float)
ret = g_param_spec_float (p_name, p_nick, p_blurb, Single.MinValue, Single.MaxValue, 0.0f, flags);
else if (type == GType.Double)
ret = g_param_spec_double (p_name, p_nick, p_blurb, Double.MinValue, Double.MaxValue, 0.0, flags);
else if (type == GType.String)
ret = g_param_spec_string (p_name, p_nick, p_blurb, IntPtr.Zero, flags);
else if (type == GType.Pointer)
ret = g_param_spec_pointer (p_name, p_nick, p_blurb, flags);
else if (type.Val == g_gtype_get_type ())
ret = g_param_spec_gtype (p_name, p_nick, p_blurb, GType.None.Val, flags);
else if (g_type_is_a (type.Val, GType.Boxed.Val))
ret = g_param_spec_boxed (p_name, p_nick, p_blurb, type.Val, flags);
else if (g_type_is_a (type.Val, GType.Object.Val))
ret = g_param_spec_object (p_name, p_nick, p_blurb, type.Val, flags);
else
throw new ArgumentException ("type");
GLib.Marshaller.Free (p_name);
GLib.Marshaller.Free (p_nick);
GLib.Marshaller.Free (p_blurb);
return ret;
}
internal ParamSpec (string name, string nick, string blurb, GType type, ParamFlags pflags) {
handle = CreateParamSpec (name, nick, blurb, type, pflags);
}
public ParamSpec (string name, string nick, string blurb, GType type, bool readable, bool writable)
{
ParamFlags pflags = ParamFlags.None;
if (readable) pflags |= ParamFlags.Readable;
if (writable) pflags |= ParamFlags.Writable;
handle = CreateParamSpec (name, nick, blurb, type, pflags);
}
public ParamSpec (IntPtr native)
{
handle = native;
}
public IntPtr Handle {
get { return handle; }
}
public GType ValueType {
get {
GParamSpec spec = (GParamSpec) Marshal.PtrToStructure (Handle, typeof (GParamSpec));
return new GType (spec.value_type);
}
}
public string Name {
get {
GParamSpec spec = (GParamSpec) Marshal.PtrToStructure (Handle, typeof (GParamSpec));
return GLib.Marshaller.Utf8PtrToString (spec.name);
}
}
struct GTypeInstance {
IntPtr g_class;
}
struct GParamSpec {
GTypeInstance g_type_instance;
public IntPtr name;
ParamFlags flags;
public IntPtr value_type;
IntPtr owner_type;
IntPtr _nick;
IntPtr _blurb;
IntPtr qdata;
uint ref_count;
uint param_id;
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_char (IntPtr name, IntPtr nick, IntPtr blurb, sbyte min, sbyte max, sbyte dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_uchar (IntPtr name, IntPtr nick, IntPtr blurb, byte min, byte max, byte dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_boolean (IntPtr name, IntPtr nick, IntPtr blurb, bool dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_int (IntPtr name, IntPtr nick, IntPtr blurb, int min, int max, int dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_uint (IntPtr name, IntPtr nick, IntPtr blurb, uint min, uint max, uint dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_long (IntPtr name, IntPtr nick, IntPtr blurb, IntPtr min, IntPtr max, IntPtr dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_ulong (IntPtr name, IntPtr nick, IntPtr blurb, UIntPtr min, UIntPtr max, UIntPtr dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_int64 (IntPtr name, IntPtr nick, IntPtr blurb, long min, long max, long dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_uint64 (IntPtr name, IntPtr nick, IntPtr blurb, ulong min, ulong max, ulong dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_float (IntPtr name, IntPtr nick, IntPtr blurb, float min, float max, float dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_double (IntPtr name, IntPtr nick, IntPtr blurb, double min, double max, double dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_string (IntPtr name, IntPtr nick, IntPtr blurb, IntPtr dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_pointer (IntPtr name, IntPtr nick, IntPtr blurb, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_gtype (IntPtr name, IntPtr nick, IntPtr blurb, IntPtr dval, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_boxed (IntPtr name, IntPtr nick, IntPtr blurb, IntPtr return_type, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_param_spec_object (IntPtr name, IntPtr nick, IntPtr blurb, IntPtr return_type, int flags);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_gtype_get_type ();
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_type_is_a (IntPtr a, IntPtr b);
}
}

View file

@ -0,0 +1,31 @@
// GLib.Priority.cs
//
// Author(s):
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (c) 2009 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
public enum Priority
{
High = -100,
Default = 0,
HighIdle = 100,
DefaultIdle = 200,
Low = 300,
}
}

View file

@ -0,0 +1,69 @@
// PropertyAttribute.cs
//
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
public sealed class PropertyAttribute : Attribute {
string blurb;
string nickname;
string name;
public PropertyAttribute (string name)
{
this.name = name;
}
public PropertyAttribute (string name, string nickname, string blurb)
{
this.name = name;
this.nickname = nickname;
this.blurb = blurb;
}
public string Blurb {
get {
return blurb;
}
set {
blurb = value;
}
}
public string Name {
get {
return name;
}
set {
name = value;
}
}
public string Nickname {
get {
return nickname;
}
set {
nickname = value;
}
}
}
}

View file

@ -0,0 +1,272 @@
// PtrArray.cs - PtrArray wrapper implementation
//
// Authors: Mike Gorse <mgorse@novell.com>
//
// Copyright (c) 2008 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public class PtrArray : IDisposable, ICollection, ICloneable, IWrapper {
private IntPtr handle = IntPtr.Zero;
private bool managed = false;
internal bool elements_owned = false;
protected System.Type element_type = null;
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_ptr_array_sized_new (uint n_preallocs);
public PtrArray (uint n_preallocs, System.Type element_type, bool owned, bool elements_owned)
{
handle = g_ptr_array_sized_new (n_preallocs);
this.element_type = element_type;
managed = owned;
this.elements_owned = elements_owned;
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_ptr_array_new ();
public PtrArray (System.Type element_type, bool owned, bool elements_owned)
{
handle = g_ptr_array_new ();
this.element_type = element_type;
managed = owned;
this.elements_owned = elements_owned;
}
internal PtrArray (IntPtr raw, System.Type element_type, bool owned, bool elements_owned)
{
handle = raw;
this.element_type = element_type;
managed = owned;
this.elements_owned = elements_owned;
}
public PtrArray (IntPtr raw, System.Type element_type) : this (raw, element_type, false, false) {}
public PtrArray (IntPtr raw) : this (raw, null) {}
~PtrArray ()
{
Dispose (false);
}
// IDisposable
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_ptr_array_free (IntPtr raw, bool free_seg);
[DllImport ("libglib-2.0-0.dll")]
static extern void g_object_unref (IntPtr item);
[DllImport ("libglib-2.0-0.dll")]
static extern void g_free (IntPtr item);
void Dispose (bool disposing)
{
if (Handle == IntPtr.Zero)
return;
if (elements_owned) {
int count = Count;
for (uint i = 0; i < count; i++)
if (typeof (GLib.Object).IsAssignableFrom (element_type))
g_object_unref (NthData (i));
else if (typeof (GLib.Opaque).IsAssignableFrom (element_type))
GLib.Opaque.GetOpaque (NthData (i), element_type, true).Dispose ();
else
g_free (NthData (i));
}
if (managed)
g_ptr_array_free (Handle, true);
handle = IntPtr.Zero;
}
public IntPtr Handle {
get {
return handle;
}
}
public IntPtr ArrayPtr {
get {
return Marshal.ReadIntPtr (Handle);
}
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_ptr_array_add (IntPtr raw, IntPtr val);
public void Add (IntPtr val)
{
g_ptr_array_add (Handle, val);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_ptr_array_remove (IntPtr raw, IntPtr data);
public void Remove (IntPtr data)
{
g_ptr_array_remove (Handle, data);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_ptr_array_remove_range (IntPtr raw, uint index, uint length);
public void RemoveRange (IntPtr data, uint index, uint length)
{
g_ptr_array_remove_range (Handle, index, length);
}
struct GPtrArray {
IntPtr pdata;
public uint len;
}
// ICollection
public int Count {
get {
GPtrArray native = (GPtrArray) Marshal.PtrToStructure (Handle, typeof (GPtrArray));
return (int) native.len;
}
}
public object this [int index] {
get {
IntPtr data = NthData ((uint) index);
object ret = null;
ret = DataMarshal (data);
return ret;
}
}
internal object DataMarshal (IntPtr data)
{
object ret = null;
if (element_type != null) {
if (element_type == typeof (string))
ret = Marshaller.Utf8PtrToString (data);
else if (element_type == typeof (IntPtr))
ret = data;
else if (element_type.IsSubclassOf (typeof (GLib.Object)))
ret = GLib.Object.GetObject (data, false);
else if (element_type.IsSubclassOf (typeof (GLib.Opaque)))
ret = GLib.Opaque.GetOpaque (data, element_type, elements_owned);
else if (element_type == typeof (int))
ret = (int) data;
else if (element_type.IsValueType)
ret = Marshal.PtrToStructure (data, element_type);
else
ret = Activator.CreateInstance (element_type, new object[] {data});
} else if (Object.IsObject (data))
ret = GLib.Object.GetObject (data, false);
return ret;
}
internal IntPtr NthData (uint index)
{
return Marshal.ReadIntPtr (ArrayPtr, (int) index * IntPtr.Size);;
}
// Synchronization could be tricky here. Hmm.
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return null; }
}
public void CopyTo (Array array, int index)
{
if (array == null)
throw new ArgumentNullException ("Array can't be null.");
if (index < 0)
throw new ArgumentOutOfRangeException ("Index must be greater than 0.");
if (index + Count < array.Length)
throw new ArgumentException ("Array not large enough to copy into starting at index.");
for (int i = 0; i < Count; i++)
((IList) array) [index + i] = this [i];
}
private class ListEnumerator : IEnumerator
{
private int current = -1;
private PtrArray vals;
public ListEnumerator (PtrArray vals)
{
this.vals = vals;
}
public object Current {
get {
if (current == -1)
return null;
return vals [current];
}
}
public bool MoveNext ()
{
if (++current >= vals.Count) {
current = -1;
return false;
}
return true;
}
public void Reset ()
{
current = -1;
}
}
// IEnumerable
public IEnumerator GetEnumerator ()
{
return new ListEnumerator (this);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_ptr_array_copy (IntPtr raw);
// ICloneable
public object Clone ()
{
return new PtrArray (g_ptr_array_copy (Handle), element_type, false, false);
}
}
}

View file

@ -0,0 +1,99 @@
// SList.cs - GSList class wrapper implementation
//
// Authors: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2002 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public class SList : ListBase {
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_slist_copy (IntPtr l);
public override object Clone ()
{
return new SList (g_slist_copy (Handle));
}
[DllImport("libglib-2.0-0.dll")]
static extern int g_slist_length (IntPtr l);
internal override int Length (IntPtr list)
{
return g_slist_length (list);
}
[DllImport("libglib-2.0-0.dll")]
static extern void g_slist_free(IntPtr l);
internal override void Free (IntPtr list)
{
if (list != IntPtr.Zero)
g_slist_free (list);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_slist_append (IntPtr l, IntPtr raw);
internal override IntPtr Append (IntPtr list, IntPtr raw)
{
return g_slist_append (list, raw);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_slist_prepend (IntPtr l, IntPtr raw);
internal override IntPtr Prepend (IntPtr list, IntPtr raw)
{
return g_slist_prepend (list, raw);
}
[DllImport("libglib-2.0-0.dll")]
static extern IntPtr g_slist_nth_data (IntPtr l, uint n);
internal override IntPtr NthData (uint n)
{
return g_slist_nth_data (Handle, n);
}
public SList (IntPtr raw) : this (raw, null) {}
public SList (System.Type element_type) : this (IntPtr.Zero, element_type) {}
public SList (IntPtr raw, System.Type element_type) : this (raw, element_type, false, false) {}
public SList (IntPtr raw, System.Type element_type, bool owned, bool elements_owned) : base (raw, element_type, false, false) {}
public SList (object[] members, System.Type element_type, bool owned, bool elements_owned) : this (IntPtr.Zero, element_type, owned, elements_owned)
{
foreach (object o in members)
Append (o);
}
public SList (Array members, System.Type element_type, bool owned, bool elements_owned) : this (IntPtr.Zero, element_type, owned, elements_owned)
{
foreach (object o in members)
Append (o);
}
}
}

View file

@ -0,0 +1,421 @@
// GLib.Signal.cs - signal marshaling class
//
// Authors: Mike Kestner <mkestner@novell.com>
// Andrés G. Aragoneses <aaragoneses@novell.com>
//
// Copyright (c) 2005,2008 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
[Flags]
public enum ConnectFlags {
After = 1 << 0,
Swapped = 1 << 1,
}
public class Signal {
[Flags]
public enum Flags {
RunFirst = 1 << 0,
RunLast = 1 << 1,
RunCleanup = 1 << 2,
NoRecurse = 1 << 3,
Detailed = 1 << 4,
Action = 1 << 5,
NoHooks = 1 << 6
}
[StructLayout (LayoutKind.Sequential)]
public struct InvocationHint {
public uint signal_id;
public uint detail;
public Flags run_type;
}
[StructLayout (LayoutKind.Sequential)]
struct Query {
public uint signal_id;
public IntPtr signal_name;
public IntPtr itype;
public Flags signal_flags;
public IntPtr return_type;
public uint n_params;
public IntPtr param_types;
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
public delegate bool EmissionHookNative (ref InvocationHint hint, uint n_pvals, IntPtr pvals, IntPtr data);
public delegate bool EmissionHook (InvocationHint ihint, object[] inst_and_param_values);
public class EmissionHookMarshaler {
EmissionHook handler;
EmissionHookNative cb;
IntPtr user_data;
GCHandle gch;
public EmissionHookMarshaler (EmissionHook handler)
{
this.handler = handler;
cb = new EmissionHookNative (NativeCallback);
gch = GCHandle.Alloc (this);
}
public EmissionHookMarshaler (EmissionHookNative callback, IntPtr user_data)
{
cb = callback;
this.user_data = user_data;
handler = new EmissionHook (NativeInvoker);
}
bool NativeCallback (ref InvocationHint hint, uint n_pvals, IntPtr pvals_ptr, IntPtr data)
{
object[] pvals = new object [n_pvals];
for (int i = 0; i < n_pvals; i++) {
IntPtr p = new IntPtr ((long) pvals_ptr + i * Marshal.SizeOf (typeof (Value)));
Value v = (Value) Marshal.PtrToStructure (p, typeof (Value));
pvals [i] = v.Val;
}
bool result = handler (hint, pvals);
if (!result)
gch.Free ();
return result;
}
public EmissionHookNative Callback {
get {
return cb;
}
}
bool NativeInvoker (InvocationHint ihint, object[] pvals)
{
int val_sz = Marshal.SizeOf (typeof (Value));
IntPtr buf = Marshal.AllocHGlobal (pvals.Length * val_sz);
Value[] vals = new Value [pvals.Length];
for (int i = 0; i < pvals.Length; i++) {
vals [i] = new Value (pvals [i]);
IntPtr p = new IntPtr ((long) buf + i * val_sz);
Marshal.StructureToPtr (vals [i], p, false);
}
bool result = cb (ref ihint, (uint) pvals.Length, buf, user_data);
foreach (Value v in vals)
v.Dispose ();
Marshal.FreeHGlobal (buf);
return result;
}
public EmissionHook Invoker {
get {
return handler;
}
}
}
ToggleRef tref;
string name;
Type args_type;
SignalClosure before_closure;
SignalClosure after_closure;
Delegate marshaler;
private Signal (GLib.Object obj, string signal_name, Delegate marshaler)
{
tref = obj.ToggleRef;
name = signal_name;
tref.Signals [name] = this;
this.marshaler = marshaler;
}
private Signal (GLib.Object obj, string signal_name, Type args_type)
{
tref = obj.ToggleRef;
name = signal_name;
this.args_type = args_type;
tref.Signals [name] = this;
}
internal void Free ()
{
if (before_closure != null)
before_closure.Dispose ();
if (after_closure != null)
after_closure.Dispose ();
GC.SuppressFinalize (this);
}
void ClosureDisposedCB (object o, EventArgs args)
{
if (o == before_closure) {
before_closure.Disposed -= new EventHandler (ClosureDisposedHandler);
before_closure.Invoked -= new ClosureInvokedHandler (ClosureInvokedCB);
if (tref.Target != null)
tref.Target.BeforeSignals.Remove (name);
before_closure = null;
} else if (o == after_closure) {
after_closure.Disposed -= new EventHandler (ClosureDisposedHandler);
after_closure.Invoked -= new ClosureInvokedHandler (ClosureInvokedCB);
if (tref.Target != null)
tref.Target.AfterSignals.Remove (name);
after_closure = null;
}
if (before_closure == null && after_closure == null)
tref.Signals.Remove (name);
}
EventHandler closure_disposed_cb;
EventHandler ClosureDisposedHandler {
get {
if (closure_disposed_cb == null)
closure_disposed_cb = new EventHandler (ClosureDisposedCB);
return closure_disposed_cb;
}
}
void ClosureInvokedCB (object o, ClosureInvokedArgs args)
{
Delegate handler;
if (o == before_closure)
handler = args.Target.BeforeSignals [name] as Delegate;
else
handler = args.Target.AfterSignals [name] as Delegate;
if (handler != null)
handler.DynamicInvoke (new object[] {args.Target, args.Args});
}
ClosureInvokedHandler closure_invoked_cb;
ClosureInvokedHandler ClosureInvokedHandler {
get {
if (closure_invoked_cb == null)
closure_invoked_cb = new ClosureInvokedHandler (ClosureInvokedCB);
return closure_invoked_cb;
}
}
public static Signal Lookup (GLib.Object obj, string name)
{
return Lookup (obj, name, typeof (EventArgs));
}
public static Signal Lookup (GLib.Object obj, string name, Delegate marshaler)
{
Signal result = obj.ToggleRef.Signals [name] as Signal;
if (result == null)
result = new Signal (obj, name, marshaler);
return result;
}
public static Signal Lookup (GLib.Object obj, string name, Type args_type)
{
Signal result = obj.ToggleRef.Signals [name] as Signal;
if (result == null)
result = new Signal (obj, name, args_type);
return result;
}
public Delegate Handler {
get {
InvocationHint hint = (InvocationHint) Marshal.PtrToStructure (g_signal_get_invocation_hint (tref.Handle), typeof (InvocationHint));
if (hint.run_type == Flags.RunFirst)
return tref.Target.BeforeSignals [name] as Delegate;
else
return tref.Target.AfterSignals [name] as Delegate;
}
}
public void AddDelegate (Delegate d)
{
if (args_type == null)
args_type = d.Method.GetParameters ()[1].ParameterType;
if (d.Method.IsDefined (typeof (ConnectBeforeAttribute), false)) {
tref.Target.BeforeSignals [name] = Delegate.Combine (tref.Target.BeforeSignals [name] as Delegate, d);
if (before_closure == null) {
if (marshaler == null)
before_closure = new SignalClosure (tref.Handle, name, args_type);
else
before_closure = new SignalClosure (tref.Handle, name, marshaler, this);
before_closure.Disposed += ClosureDisposedHandler;
before_closure.Invoked += ClosureInvokedHandler;
before_closure.Connect (false);
}
} else {
tref.Target.AfterSignals [name] = Delegate.Combine (tref.Target.AfterSignals [name] as Delegate, d);
if (after_closure == null) {
if (marshaler == null)
after_closure = new SignalClosure (tref.Handle, name, args_type);
else
after_closure = new SignalClosure (tref.Handle, name, marshaler, this);
after_closure.Disposed += ClosureDisposedHandler;
after_closure.Invoked += ClosureInvokedHandler;
after_closure.Connect (true);
}
}
}
public void RemoveDelegate (Delegate d)
{
if (tref.Target == null)
return;
if (d.Method.IsDefined (typeof (ConnectBeforeAttribute), false)) {
tref.Target.BeforeSignals [name] = Delegate.Remove (tref.Target.BeforeSignals [name] as Delegate, d);
if (tref.Target.BeforeSignals [name] == null && before_closure != null) {
before_closure.Dispose ();
before_closure = null;
}
} else {
tref.Target.AfterSignals [name] = Delegate.Remove (tref.Target.AfterSignals [name] as Delegate, d);
if (tref.Target.AfterSignals [name] == null && after_closure != null) {
after_closure.Dispose ();
after_closure = null;
}
}
}
// format: children-changed::add
private static void ParseSignalDetail (string signal_detail, out string signal_name, out uint gquark)
{
//can't use String.Split because it doesn't accept a string arg (only char) in the 1.x profile
int link_pos = signal_detail.IndexOf ("::");
if (link_pos < 0) {
gquark = 0;
signal_name = signal_detail;
} else if (link_pos == 0) {
throw new FormatException ("Invalid detailed signal: " + signal_detail);
} else {
signal_name = signal_detail.Substring (0, link_pos);
gquark = GetGQuarkFromString (signal_detail.Substring (link_pos + 2));
}
}
public static object Emit (GLib.Object instance, string detailed_signal, params object[] args)
{
uint gquark, signal_id;
string signal_name;
ParseSignalDetail (detailed_signal, out signal_name, out gquark);
signal_id = GetSignalId (signal_name, instance);
if (signal_id <= 0)
throw new ArgumentException ("Invalid signal name: " + signal_name);
GLib.Value[] vals = new GLib.Value [args.Length + 1];
GLib.ValueArray inst_and_params = new GLib.ValueArray ((uint) args.Length + 1);
vals [0] = new GLib.Value (instance);
inst_and_params.Append (vals [0]);
for (int i = 1; i < vals.Length; i++) {
vals [i] = new GLib.Value (args [i - 1]);
inst_and_params.Append (vals [i]);
}
object ret_obj = null;
Query query;
g_signal_query (signal_id, out query);
if (query.return_type != GType.None.Val) {
GLib.Value ret = GLib.Value.Empty;
g_signal_emitv (inst_and_params.ArrayPtr, signal_id, gquark, ref ret);
ret_obj = ret.Val;
ret.Dispose ();
} else
g_signal_emitv (inst_and_params.ArrayPtr, signal_id, gquark, IntPtr.Zero);
foreach (GLib.Value val in vals)
val.Dispose ();
return ret_obj;
}
private static uint GetGQuarkFromString (string str) {
IntPtr native_string = GLib.Marshaller.StringToPtrGStrdup (str);
uint ret = g_quark_from_string (native_string);
GLib.Marshaller.Free (native_string);
return ret;
}
private static uint GetSignalId (string signal_name, GLib.Object obj)
{
IntPtr typeid = GType.ValFromInstancePtr (obj.Handle);
return GetSignalId (signal_name, typeid);
}
private static uint GetSignalId (string signal_name, IntPtr typeid)
{
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (signal_name);
uint signal_id = g_signal_lookup (native_name, typeid);
GLib.Marshaller.Free (native_name);
return signal_id;
}
public static ulong AddEmissionHook (string detailed_signal, GLib.GType type, EmissionHook handler_func)
{
uint gquark;
string signal_name;
ParseSignalDetail (detailed_signal, out signal_name, out gquark);
uint signal_id = GetSignalId (signal_name, type.Val);
if (signal_id <= 0)
throw new Exception ("Invalid signal name: " + signal_name);
return g_signal_add_emission_hook (signal_id, gquark, new EmissionHookMarshaler (handler_func).Callback, IntPtr.Zero, IntPtr.Zero);
}
internal static void OverrideDefaultHandler (GType gtype, string name, Delegate cb)
{
IntPtr closure = g_cclosure_new (cb, IntPtr.Zero, IntPtr.Zero);
gtype.EnsureClass ();
uint id = GetSignalId (name, gtype.Val);
g_signal_override_class_closure (id, gtype.Val, closure);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_cclosure_new (Delegate cb, IntPtr data, IntPtr notify);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_signal_get_invocation_hint (IntPtr instance);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_signal_emitv (IntPtr instance_and_params, uint signal_id, uint gquark_detail, ref GLib.Value return_value);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_signal_emitv (IntPtr instance_and_params, uint signal_id, uint gquark_detail, IntPtr return_value);
[DllImport("libgobject-2.0-0.dll")]
static extern uint g_signal_lookup (IntPtr name, IntPtr itype);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_signal_override_class_closure (uint id, IntPtr gtype, IntPtr closure);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_signal_query (uint signal_id, out Query query);
//better not to expose g_quark_from_static_string () due to memory allocation issues
[DllImport("libglib-2.0-0.dll")]
static extern uint g_quark_from_string (IntPtr str);
[DllImport("libgobject-2.0-0.dll")]
static extern ulong g_signal_add_emission_hook (uint signal_id, uint gquark_detail, EmissionHookNative hook_func, IntPtr hook_data, IntPtr data_destroy);
}
}

View file

@ -0,0 +1,68 @@
// GLib.SignalArgs.cs - Signal argument class implementation
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001 Mike Kestner
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
public class SignalArgs : EventArgs {
private object _ret;
private object[] _args;
public SignalArgs()
{
_ret = null;
_args = null;
}
public SignalArgs(object retval)
{
_ret = retval;
_args = null;
}
public SignalArgs(object retval, object[] args)
{
_ret = retval;
_args = args;
}
public object[] Args {
get {
return _args;
}
set {
_args = value;
}
}
public object RetVal {
get {
return _ret;
}
set {
_ret = value;
}
}
}
}

View file

@ -0,0 +1,47 @@
// SignalAttribute.cs
//
// Author:
// Ricardo Fernández Pascual <ric@users.sourceforge.net>
//
// Copyright (c) Ricardo Fernández Pascual <ric@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[Serializable]
[AttributeUsage (AttributeTargets.Event, Inherited=false)]
public sealed class SignalAttribute : Attribute
{
private string cname;
public SignalAttribute (string cname)
{
this.cname = cname;
}
private SignalAttribute () {}
public string CName
{
get {
return cname;
}
}
}
}

View file

@ -0,0 +1,106 @@
// GLib.SignalCallback.cs - Signal callback base class implementation
//
// Authors: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2001 Mike Kestner
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
[Obsolete ("Replaced by GLib.Signal.")]
public abstract class SignalCallback : IDisposable {
// A counter used to produce unique keys for instances.
protected static int _NextKey = 0;
// Hashtable containing refs to all current instances.
protected static Hashtable _Instances = new Hashtable ();
// protected instance members
protected GLib.Object _obj;
protected Delegate _handler;
protected int _key;
protected System.Type _argstype;
protected uint _HandlerID;
protected SignalCallback (GLib.Object obj, Delegate eh, System.Type argstype)
{
_key = _NextKey++;
_obj = obj;
_handler = eh;
_argstype = argstype;
_Instances [_key] = this;
}
public void AddDelegate (Delegate d)
{
_handler = Delegate.Combine (_handler, d);
}
public void RemoveDelegate (Delegate d)
{
_handler = Delegate.Remove (_handler, d);
}
[DllImport("libgobject-2.0-0.dll")]
static extern uint g_signal_connect_data(IntPtr obj, IntPtr name, Delegate cb, int key, IntPtr p, int flags);
protected void Connect (string name, Delegate cb, int flags)
{
IntPtr native_name = Marshaller.StringToPtrGStrdup (name);
_HandlerID = g_signal_connect_data(_obj.Handle, native_name, cb, _key, new IntPtr(0), flags);
Marshaller.Free (native_name);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_signal_handler_disconnect (IntPtr instance, uint handler);
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_signal_handler_is_connected (IntPtr instance, uint handler);
protected void Disconnect ()
{
if (g_signal_handler_is_connected (_obj.Handle, _HandlerID))
g_signal_handler_disconnect (_obj.Handle, _HandlerID);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (disposing) {
_obj = null;
_handler = null;
_argstype = null;
}
}
~SignalCallback ()
{
Dispose (false);
}
}
}

View file

@ -0,0 +1,227 @@
// SignalClosure.cs - signal marshaling class
//
// Authors: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2008 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
internal class ClosureInvokedArgs : EventArgs {
EventArgs args;
GLib.Object obj;
object result;
public ClosureInvokedArgs (GLib.Object obj, EventArgs args)
{
this.obj = obj;
this.args = args;
}
public EventArgs Args {
get {
return args;
}
}
public GLib.Object Target {
get {
return obj;
}
}
}
struct GClosure {
long fields;
IntPtr marshaler;
IntPtr data;
IntPtr notifiers;
}
internal delegate void ClosureInvokedHandler (object o, ClosureInvokedArgs args);
internal class SignalClosure : IDisposable {
IntPtr handle;
IntPtr raw_closure;
string name;
uint id = UInt32.MaxValue;
System.Type args_type;
Delegate custom_marshaler;
GCHandle gch;
static Hashtable closures = new Hashtable ();
public SignalClosure (IntPtr obj, string signal_name, System.Type args_type)
{
raw_closure = g_closure_new_simple (Marshal.SizeOf (typeof (GClosure)), IntPtr.Zero);
g_closure_set_marshal (raw_closure, Marshaler);
g_closure_add_finalize_notifier (raw_closure, IntPtr.Zero, Notify);
closures [raw_closure] = this;
handle = obj;
name = signal_name;
this.args_type = args_type;
}
public SignalClosure (IntPtr obj, string signal_name, Delegate custom_marshaler, Signal signal)
{
gch = GCHandle.Alloc (signal);
raw_closure = g_cclosure_new (custom_marshaler, (IntPtr) gch, Notify);
closures [raw_closure] = this;
handle = obj;
name = signal_name;
this.custom_marshaler = custom_marshaler;
}
public event EventHandler Disposed;
public event ClosureInvokedHandler Invoked;
public void Connect (bool is_after)
{
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name);
id = g_signal_connect_closure (handle, native_name, raw_closure, is_after);
GLib.Marshaller.Free (native_name);
}
public void Disconnect ()
{
if (id != UInt32.MaxValue && g_signal_handler_is_connected (handle, id))
g_signal_handler_disconnect (handle, id);
}
public void Dispose ()
{
Disconnect ();
closures.Remove (raw_closure);
if (custom_marshaler != null)
gch.Free ();
custom_marshaler = null;
if (Disposed != null)
Disposed (this, EventArgs.Empty);
GC.SuppressFinalize (this);
}
public void Invoke (ClosureInvokedArgs args)
{
if (Invoked == null)
return;
Invoked (this, args);
}
static ClosureMarshal marshaler;
static ClosureMarshal Marshaler {
get {
if (marshaler == null)
marshaler = new ClosureMarshal (MarshalCallback);
return marshaler;
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void ClosureMarshal (IntPtr closure, IntPtr return_val, uint n_param_vals, IntPtr param_values, IntPtr invocation_hint, IntPtr marshal_data);
static void MarshalCallback (IntPtr raw_closure, IntPtr return_val, uint n_param_vals, IntPtr param_values, IntPtr invocation_hint, IntPtr marshal_data)
{
string message = String.Empty;
try {
SignalClosure closure = closures [raw_closure] as SignalClosure;
message = "Marshaling " + closure.name + " signal";
Value objval = (Value) Marshal.PtrToStructure (param_values, typeof (Value));
GLib.Object __obj = objval.Val as GLib.Object;
if (__obj == null)
return;
if (closure.args_type == typeof (EventArgs)) {
closure.Invoke (new ClosureInvokedArgs (__obj, EventArgs.Empty));
return;
}
SignalArgs args = Activator.CreateInstance (closure.args_type, new object [0]) as SignalArgs;
args.Args = new object [n_param_vals - 1];
GLib.Value[] vals = new GLib.Value [n_param_vals - 1];
for (int i = 1; i < n_param_vals; i++) {
IntPtr ptr = new IntPtr (param_values.ToInt64 () + i * Marshal.SizeOf (typeof (Value)));
vals [i - 1] = (Value) Marshal.PtrToStructure (ptr, typeof (Value));
args.Args [i - 1] = vals [i - 1].Val;
}
ClosureInvokedArgs ci_args = new ClosureInvokedArgs (__obj, args);
closure.Invoke (ci_args);
for (int i = 1; i < n_param_vals; i++) {
vals [i - 1].Update (args.Args [i - 1]);
IntPtr ptr = new IntPtr (param_values.ToInt64 () + i * Marshal.SizeOf (typeof (Value)));
Marshal.StructureToPtr (vals [i - 1], ptr, false);
}
if (return_val == IntPtr.Zero || args.RetVal == null)
return;
Value ret = (Value) Marshal.PtrToStructure (return_val, typeof (Value));
ret.Val = args.RetVal;
Marshal.StructureToPtr (ret, return_val, false);
} catch (Exception e) {
Console.WriteLine (message);
ExceptionManager.RaiseUnhandledException (e, false);
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void ClosureNotify (IntPtr data, IntPtr closure);
static void NotifyCallback (IntPtr data, IntPtr raw_closure)
{
SignalClosure closure = closures [raw_closure] as SignalClosure;
if (closure != null)
closure.Dispose ();
}
static ClosureNotify notify_handler;
static ClosureNotify Notify {
get {
if (notify_handler == null)
notify_handler = new ClosureNotify (NotifyCallback);
return notify_handler;
}
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_cclosure_new (Delegate cb, IntPtr user_data, ClosureNotify notify);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_closure_new_simple (int closure_size, IntPtr dummy);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_closure_set_marshal (IntPtr closure, ClosureMarshal marshaler);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_closure_add_finalize_notifier (IntPtr closure, IntPtr dummy, ClosureNotify notify);
[DllImport("libgobject-2.0-0.dll")]
static extern uint g_signal_connect_closure (IntPtr obj, IntPtr name, IntPtr closure, bool is_after);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_signal_handler_disconnect (IntPtr instance, uint handler);
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_signal_handler_is_connected (IntPtr instance, uint handler);
}
}

View file

@ -0,0 +1,62 @@
// GLib.Source.cs - Source class implementation
//
// Author: Duncan Mak <duncan@ximian.com>
//
// Copyright (c) 2002 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public delegate bool GSourceFunc ();
//
// Base class for IdleProxy and TimeoutProxy
//
internal class SourceProxy {
internal Delegate real_handler;
internal Delegate proxy_handler;
internal uint ID;
internal void Remove ()
{
lock (Source.source_handlers)
Source.source_handlers.Remove (ID);
real_handler = null;
proxy_handler = null;
}
}
public class Source {
private Source () {}
internal static Hashtable source_handlers = new Hashtable ();
[DllImport("libglib-2.0-0.dll")]
static extern bool g_source_remove (uint tag);
public static bool Remove (uint tag)
{
lock (Source.source_handlers)
source_handlers.Remove (tag);
return g_source_remove (tag);
}
}
}

View file

@ -0,0 +1,216 @@
// glib/Spawn.cs : Spawn g_spawn API wrapper
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public enum SpawnError {
Fork,
Read,
Chdir,
Acces,
Perm,
TooBig,
NoExec,
NameTooLong,
NoEnt,
NoMem,
NotDir,
Loop,
TxtBusy,
IO,
NFile,
MFile,
Inval,
IsDir,
LibBad,
Failed,
}
[Flags]
public enum SpawnFlags {
LeaveDescriptorsOpen = 1 << 0,
DoNotReapChild = 1 << 1,
SearchPath = 1 << 2,
StdoutToDevNull = 1 << 3,
StderrToDevNull = 1 << 4,
ChildInheritsStdin = 1 << 5,
FileAndArgvZero = 1 << 6,
}
public delegate void SpawnChildSetupFunc ();
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
internal delegate void SpawnChildSetupFuncNative (IntPtr gch);
internal class SpawnChildSetupWrapper {
SpawnChildSetupFunc handler;
public SpawnChildSetupWrapper (SpawnChildSetupFunc handler)
{
if (handler == null)
return;
this.handler = handler;
Data = (IntPtr) GCHandle.Alloc (this);
NativeCallback = new SpawnChildSetupFuncNative (InvokeHandler);
}
public IntPtr Data;
public SpawnChildSetupFuncNative NativeCallback;
static void InvokeHandler (IntPtr data)
{
if (data == IntPtr.Zero)
return;
GCHandle gch = (GCHandle) data;
(gch.Target as SpawnChildSetupWrapper).handler ();
gch.Free ();
}
}
public class Process {
public const int IgnorePipe = Int32.MaxValue;
public const int RequestPipe = 0;
long pid;
private Process (int pid)
{
this.pid = pid;
}
[DllImport ("libglib-2.0-0.dll")]
static extern void g_spawn_close_pid (int pid);
public void Close ()
{
g_spawn_close_pid ((int) pid);
}
[DllImport ("libglib-2.0-0.dll")]
static extern bool g_spawn_async (IntPtr dir, IntPtr[] argv, IntPtr[] envp, int flags, SpawnChildSetupFuncNative func, IntPtr data, out int pid, out IntPtr error);
public static bool SpawnAsync (string working_directory, string[] argv, string[] envp, SpawnFlags flags, SpawnChildSetupFunc child_setup, out Process child_process)
{
int pid;
IntPtr error;
IntPtr native_dir = Marshaller.StringToPtrGStrdup (working_directory);
IntPtr[] native_argv = Marshaller.StringArrayToNullTermPointer (argv);
IntPtr[] native_envp = Marshaller.StringArrayToNullTermPointer (envp);
SpawnChildSetupWrapper wrapper = new SpawnChildSetupWrapper (child_setup);
bool result = g_spawn_async (native_dir, native_argv, native_envp, (int) flags, wrapper.NativeCallback, wrapper.Data, out pid, out error);
child_process = new Process (pid);
Marshaller.Free (native_dir);
Marshaller.Free (native_argv);
Marshaller.Free (native_envp);
if (error != IntPtr.Zero) throw new GLib.GException (error);
return result;
}
[DllImport ("libglib-2.0-0.dll")]
static extern bool g_spawn_async_with_pipes (IntPtr dir, IntPtr[] argv, IntPtr[] envp, int flags, SpawnChildSetupFuncNative func, IntPtr data, out int pid, IntPtr stdin, IntPtr stdout, IntPtr stderr, out IntPtr error);
public static bool SpawnAsyncWithPipes (string working_directory, string[] argv, string[] envp, SpawnFlags flags, SpawnChildSetupFunc child_setup, out Process child_process, ref int stdin, ref int stdout, ref int stderr)
{
int pid;
IntPtr error;
IntPtr native_dir = Marshaller.StringToPtrGStrdup (working_directory);
IntPtr[] native_argv = Marshaller.StringArrayToNullTermPointer (argv);
IntPtr[] native_envp = Marshaller.StringArrayToNullTermPointer (envp);
SpawnChildSetupWrapper wrapper = new SpawnChildSetupWrapper (child_setup);
IntPtr in_ptr = stdin == IgnorePipe ? IntPtr.Zero : Marshal.AllocHGlobal (4);
IntPtr out_ptr = stdout == IgnorePipe ? IntPtr.Zero : Marshal.AllocHGlobal (4);
IntPtr err_ptr = stderr == IgnorePipe ? IntPtr.Zero : Marshal.AllocHGlobal (4);
bool result = g_spawn_async_with_pipes (native_dir, native_argv, native_envp, (int) flags, wrapper.NativeCallback, wrapper.Data, out pid, in_ptr, out_ptr, err_ptr, out error);
child_process = new Process (pid);
if (in_ptr != IntPtr.Zero) {
stdin = Marshal.ReadInt32 (in_ptr);
Marshal.FreeHGlobal (in_ptr);
}
if (out_ptr != IntPtr.Zero) {
stdout = Marshal.ReadInt32 (out_ptr);
Marshal.FreeHGlobal (out_ptr);
}
if (err_ptr != IntPtr.Zero) {
stderr = Marshal.ReadInt32 (err_ptr);
Marshal.FreeHGlobal (err_ptr);
}
Marshaller.Free (native_dir);
Marshaller.Free (native_argv);
Marshaller.Free (native_envp);
if (error != IntPtr.Zero) throw new GLib.GException (error);
return result;
}
[DllImport ("libglib-2.0-0.dll")]
static extern bool g_spawn_sync (IntPtr dir, IntPtr[] argv, IntPtr[] envp, int flags, SpawnChildSetupFuncNative func, IntPtr data, out IntPtr stdout, out IntPtr stderr, out int exit_status, out IntPtr error);
public static bool SpawnSync (string working_directory, string[] argv, string[] envp, SpawnFlags flags, SpawnChildSetupFunc child_setup, out string stdout, out string stderr, out int exit_status)
{
IntPtr native_stdout, native_stderr, error;
IntPtr native_dir = Marshaller.StringToPtrGStrdup (working_directory);
IntPtr[] native_argv = Marshaller.StringArrayToNullTermPointer (argv);
IntPtr[] native_envp = Marshaller.StringArrayToNullTermPointer (envp);
SpawnChildSetupWrapper wrapper = new SpawnChildSetupWrapper (child_setup);
bool result = g_spawn_sync (native_dir, native_argv, native_envp, (int) flags, wrapper.NativeCallback, wrapper.Data, out native_stdout, out native_stderr, out exit_status, out error);
Marshaller.Free (native_dir);
Marshaller.Free (native_argv);
Marshaller.Free (native_envp);
stdout = Marshaller.PtrToStringGFree (native_stdout);
stderr = Marshaller.PtrToStringGFree (native_stderr);
if (error != IntPtr.Zero) throw new GLib.GException (error);
return result;
}
[DllImport ("libglib-2.0-0.dll")]
static extern bool g_spawn_command_line_async (IntPtr cmdline, out IntPtr error);
public static bool SpawnCommandLineAsync (string command_line)
{
IntPtr error;
IntPtr native_cmd = Marshaller.StringToPtrGStrdup (command_line);
bool result = g_spawn_command_line_async (native_cmd, out error);
Marshaller.Free (native_cmd);
if (error != IntPtr.Zero) throw new GLib.GException (error);
return result;
}
[DllImport ("libglib-2.0-0.dll")]
static extern bool g_spawn_command_line_sync (IntPtr cmdline, out IntPtr stdout, out IntPtr stderr, out int exit_status, out IntPtr error);
public static bool SpawnCommandLineSync (string command_line, out string stdout, out string stderr, out int exit_status)
{
IntPtr error, native_stdout, native_stderr;
IntPtr native_cmd = Marshaller.StringToPtrGStrdup (command_line);
bool result = g_spawn_command_line_sync (native_cmd, out native_stdout, out native_stderr, out exit_status, out error);
Marshaller.Free (native_cmd);
stdout = Marshaller.PtrToStringGFree (native_stdout);
stderr = Marshaller.PtrToStringGFree (native_stderr);
if (error != IntPtr.Zero) throw new GLib.GException (error);
return result;
}
}
}

View file

@ -0,0 +1,49 @@
// Thread.cs - thread awareness
//
// Author: Alp Toker <alp@atoker.com>
//
// Copyright (c) 2002 Alp Toker
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib
{
using System;
using System.Runtime.InteropServices;
public class Thread
{
private Thread () {}
[DllImport("libgthread-2.0-0.dll")]
static extern void g_thread_init (IntPtr i);
public static void Init ()
{
g_thread_init (IntPtr.Zero);
}
[DllImport("glibsharpglue-2")]
static extern bool glibsharp_g_thread_supported ();
public static bool Supported
{
get {
return glibsharp_g_thread_supported ();
}
}
}
}

View file

@ -0,0 +1,135 @@
// GLib.Timeout.cs - Timeout class implementation
//
// Author(s):
// Mike Kestner <mkestner@speakeasy.net>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (c) 2002 Mike Kestner
// Copyright (c) 2009 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public delegate bool TimeoutHandler ();
public class Timeout {
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate bool TimeoutHandlerInternal ();
internal class TimeoutProxy : SourceProxy {
public TimeoutProxy (TimeoutHandler real)
{
real_handler = real;
proxy_handler = new TimeoutHandlerInternal (Handler);
}
public bool Handler ()
{
try {
TimeoutHandler timeout_handler = (TimeoutHandler) real_handler;
bool cont = timeout_handler ();
if (!cont)
Remove ();
return cont;
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
return false;
}
}
private Timeout () {}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_timeout_add (uint interval, TimeoutHandlerInternal d, IntPtr data);
public static uint Add (uint interval, TimeoutHandler hndlr)
{
TimeoutProxy p = new TimeoutProxy (hndlr);
p.ID = g_timeout_add (interval, (TimeoutHandlerInternal) p.proxy_handler, IntPtr.Zero);
lock (Source.source_handlers)
Source.source_handlers [p.ID] = p;
return p.ID;
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_timeout_add_full (int priority, uint interval, TimeoutHandlerInternal d, IntPtr data, DestroyNotify notify);
public static uint Add (uint interval, TimeoutHandler hndlr, Priority priority)
{
TimeoutProxy p = new TimeoutProxy (hndlr);
p.ID = g_timeout_add_full ((int)priority, interval, (TimeoutHandlerInternal) p.proxy_handler, IntPtr.Zero, null);
lock (Source.source_handlers)
Source.source_handlers [p.ID] = p;
return p.ID;
}
[DllImport("libglib-2.0-0.dll")]
static extern uint g_timeout_add_seconds (uint interval, TimeoutHandlerInternal d, IntPtr data);
public static uint AddSeconds (uint interval, TimeoutHandler hndlr)
{
TimeoutProxy p = new TimeoutProxy (hndlr);
p.ID = g_timeout_add_seconds (interval, (TimeoutHandlerInternal) p.proxy_handler, IntPtr.Zero);
lock (Source.source_handlers)
Source.source_handlers [p.ID] = p;
return p.ID;
}
public static void Remove (uint id)
{
Source.Remove (id);
}
[DllImport("libglib-2.0-0.dll")]
static extern bool g_source_remove_by_funcs_user_data (Delegate d, IntPtr data);
public static bool Remove (TimeoutHandler hndlr)
{
bool result = false;
ArrayList keys = new ArrayList ();
lock (Source.source_handlers) {
foreach (uint code in Source.source_handlers.Keys) {
TimeoutProxy p = Source.source_handlers [code] as TimeoutProxy;
if (p != null && p.real_handler == hndlr) {
keys.Add (code);
result = g_source_remove_by_funcs_user_data (p.proxy_handler, IntPtr.Zero);
}
}
foreach (object key in keys)
Source.source_handlers.Remove (key);
}
return result;
}
}
}

View file

@ -0,0 +1,159 @@
// GLib.ToggleRef.cs - GLib ToggleRef class implementation
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright <c> 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
internal class ToggleRef {
bool hardened;
IntPtr handle;
object reference;
GCHandle gch;
Hashtable signals;
public ToggleRef (GLib.Object target)
{
handle = target.Handle;
gch = GCHandle.Alloc (this);
reference = target;
g_object_add_toggle_ref (target.Handle, ToggleNotifyCallback, (IntPtr) gch);
g_object_unref (target.Handle);
}
public bool IsAlive {
get {
if (reference is WeakReference) {
WeakReference weak = reference as WeakReference;
return weak.IsAlive;
} else if (reference == null)
return false;
return true;
}
}
public IntPtr Handle {
get {
return handle;
}
}
public Hashtable Signals {
get {
if (signals == null)
signals = new Hashtable ();
return signals;
}
}
public GLib.Object Target {
get {
if (reference == null)
return null;
else if (reference is GLib.Object)
return reference as GLib.Object;
WeakReference weak = reference as WeakReference;
return weak.Target as GLib.Object;
}
}
public void Free ()
{
Signal[] signals = new Signal [Signals.Count];
Signals.Values.CopyTo (signals, 0);
foreach (Signal s in signals)
s.Free ();
if (hardened)
g_object_unref (handle);
else
g_object_remove_toggle_ref (handle, ToggleNotifyCallback, (IntPtr) gch);
reference = null;
gch.Free ();
}
internal void Harden ()
{
// Added for the benefit of GnomeProgram. It releases a final ref in
// an atexit handler which causes toggle ref notifications to occur after
// our delegates are gone, so we need a mechanism to override the
// notifications. This method effectively leaks all objects which invoke it,
// but since it is only used by Gnome.Program, which is a singleton object
// with program duration persistence, who cares.
g_object_ref (handle);
g_object_remove_toggle_ref (handle, ToggleNotifyCallback, (IntPtr) gch);
if (reference is WeakReference)
reference = (reference as WeakReference).Target;
hardened = true;
}
void Toggle (bool is_last_ref)
{
if (is_last_ref && reference is GLib.Object)
reference = new WeakReference (reference);
else if (!is_last_ref && reference is WeakReference) {
WeakReference weak = reference as WeakReference;
if (weak.IsAlive)
reference = weak.Target;
}
}
[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
delegate void ToggleNotifyHandler (IntPtr data, IntPtr handle, bool is_last_ref);
static void RefToggled (IntPtr data, IntPtr handle, bool is_last_ref)
{
try {
GCHandle gch = (GCHandle) data;
ToggleRef tref = gch.Target as ToggleRef;
tref.Toggle (is_last_ref);
} catch (Exception e) {
ExceptionManager.RaiseUnhandledException (e, false);
}
}
static ToggleNotifyHandler toggle_notify_callback;
static ToggleNotifyHandler ToggleNotifyCallback {
get {
if (toggle_notify_callback == null)
toggle_notify_callback = new ToggleNotifyHandler (RefToggled);
return toggle_notify_callback;
}
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_add_toggle_ref (IntPtr raw, ToggleNotifyHandler notify_cb, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_remove_toggle_ref (IntPtr raw, ToggleNotifyHandler notify_cb, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_object_ref (IntPtr raw);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_object_unref (IntPtr raw);
}
}

View file

@ -0,0 +1,36 @@
// GLib.TypeConverter.cs : Convert between fundamental and .NET types
//
// Author: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
public class TypeConverter {
private TypeConverter () {}
[Obsolete ("Replaced by explicit (GType) cast")]
public static GType LookupType (System.Type type)
{
return (GType) type;
}
}
}

View file

@ -0,0 +1,47 @@
// GLib.TypeFundamentals.cs : Standard Types enumeration
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
public enum TypeFundamentals {
TypeInvalid = 0 << 2,
TypeNone = 1 << 2,
TypeInterface = 2 << 2,
TypeChar = 3 << 2,
TypeUChar = 4 << 2,
TypeBoolean = 5 << 2,
TypeInt = 6 << 2,
TypeUInt = 7 << 2,
TypeLong = 8 << 2,
TypeULong = 9 << 2,
TypeInt64 = 10 << 2,
TypeUInt64 = 11 << 2,
TypeEnum = 12 << 2,
TypeFlags = 13 << 2,
TypeFloat = 14 << 2,
TypeDouble = 15 << 2,
TypeString = 16 << 2,
TypePointer = 17 << 2,
TypeBoxed = 18 << 2,
TypeParam = 19 << 2,
TypeObject = 20 << 2,
}
}

View file

@ -0,0 +1,48 @@
// TypeInitializerAttribute.cs
//
// Author: Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2007 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
[AttributeUsage (AttributeTargets.Class)]
public sealed class TypeInitializerAttribute : Attribute
{
string method_name;
Type type;
public TypeInitializerAttribute (Type type, string method_name)
{
this.type = type;
this.method_name = method_name;
}
public string MethodName {
get { return method_name; }
set { method_name = value; }
}
public Type Type {
get { return type; }
set { type = value; }
}
}
}

View file

@ -0,0 +1,40 @@
// UnwrappedObject.cs - Class which holds an IntPtr without resolving it:
//
// Author: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
[Obsolete ("Replaced by direct object-type casts to/from GLib.Value")]
public class UnwrappedObject {
IntPtr obj;
public UnwrappedObject (IntPtr obj) {
this.obj = obj;
}
public static explicit operator System.IntPtr (UnwrappedObject obj) {
return obj.obj;
}
}
}

View file

@ -0,0 +1,675 @@
// GLib.Value.cs - GLib Value class implementation
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001 Mike Kestner
// Copyright (c) 2003-2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
[StructLayout (LayoutKind.Sequential)]
public struct Value : IDisposable {
[StructLayout(LayoutKind.Explicit)]
struct Padding {
[FieldOffset (0)] int v_int;
[FieldOffset (0)] uint v_uint;
[FieldOffset (0)] int v_long;
[FieldOffset (0)] uint v_ulong;
[FieldOffset (0)] long v_int64;
[FieldOffset (0)] ulong v_uint64;
[FieldOffset (0)] float v_float;
[FieldOffset (0)] double v_double;
[FieldOffset (0)] IntPtr v_pointer;
}
IntPtr type;
Padding pad1;
Padding pad2;
public static Value Empty;
public Value (GLib.GType gtype)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
g_value_init (ref this, gtype.Val);
}
public Value (object obj)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
GType gtype = (GType) obj.GetType ();
g_value_init (ref this, gtype.Val);
Val = obj;
}
public Value (bool val) : this (GType.Boolean)
{
g_value_set_boolean (ref this, val);
}
public Value (byte val) : this (GType.UChar)
{
g_value_set_uchar (ref this, val);
}
public Value (sbyte val) : this (GType.Char)
{
g_value_set_char (ref this, val);
}
public Value (int val) : this (GType.Int)
{
g_value_set_int (ref this, val);
}
public Value (uint val) : this (GType.UInt)
{
g_value_set_uint (ref this, val);
}
public Value (ushort val) : this (GType.UInt)
{
g_value_set_uint (ref this, val);
}
public Value (long val) : this (GType.Int64)
{
g_value_set_int64 (ref this, val);
}
public Value (ulong val) : this (GType.UInt64)
{
g_value_set_uint64 (ref this, val);
}
[Obsolete ("Replaced by Value(object) constructor")]
public Value (EnumWrapper wrap, string type_name)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
g_value_init (ref this, GType.FromName (type_name).Val);
if (wrap.flags)
g_value_set_flags (ref this, (uint) (int) wrap);
else
g_value_set_enum (ref this, (int) wrap);
}
public Value (float val) : this (GType.Float)
{
g_value_set_float (ref this, val);
}
public Value (double val) : this (GType.Double)
{
g_value_set_double (ref this, val);
}
public Value (string val) : this (GType.String)
{
IntPtr native_val = GLib.Marshaller.StringToPtrGStrdup (val);
g_value_set_string (ref this, native_val);
GLib.Marshaller.Free (native_val);
}
public Value (ValueArray val) : this (ValueArray.GType)
{
g_value_set_boxed (ref this, val.Handle);
}
public Value (IntPtr val) : this (GType.Pointer)
{
g_value_set_pointer (ref this, val);
}
public Value (Opaque val, string type_name)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
g_value_init (ref this, GType.FromName (type_name).Val);
g_value_set_boxed (ref this, val.Handle);
}
public Value (GLib.Object val) : this (val == null ? GType.Object : val.NativeType)
{
g_value_set_object (ref this, val == null ? IntPtr.Zero : val.Handle);
}
public Value (GLib.GInterfaceAdapter val) : this (val == null ? GType.Object : val.GType)
{
g_value_set_object (ref this, val == null ? IntPtr.Zero : val.Handle);
}
public Value (GLib.Object obj, string prop_name)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
InitForProperty (obj, prop_name);
}
[Obsolete]
public Value (GLib.Object obj, string prop_name, EnumWrapper wrap)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
InitForProperty (obj.NativeType, prop_name);
if (wrap.flags)
g_value_set_flags (ref this, (uint) (int) wrap);
else
g_value_set_enum (ref this, (int) wrap);
}
[Obsolete]
public Value (IntPtr obj, string prop_name, Opaque val)
{
type = IntPtr.Zero;
pad1 = new Padding ();
pad2 = new Padding ();
InitForProperty (GLib.Object.GetObject (obj), prop_name);
g_value_set_boxed (ref this, val.Handle);
}
public Value (string[] val) : this (new GLib.GType (g_strv_get_type ()))
{
if (val == null) {
g_value_set_boxed (ref this, IntPtr.Zero);
return;
}
IntPtr native_array = Marshal.AllocHGlobal ((val.Length + 1) * IntPtr.Size);
for (int i = 0; i < val.Length; i++)
Marshal.WriteIntPtr (native_array, i * IntPtr.Size, GLib.Marshaller.StringToPtrGStrdup (val[i]));
Marshal.WriteIntPtr (native_array, val.Length * IntPtr.Size, IntPtr.Zero);
g_value_set_boxed (ref this, native_array);
for (int i = 0; i < val.Length; i++)
GLib.Marshaller.Free (Marshal.ReadIntPtr (native_array, i * IntPtr.Size));
Marshal.FreeHGlobal (native_array);
}
public void Dispose ()
{
g_value_unset (ref this);
}
public void Init (GLib.GType gtype)
{
g_value_init (ref this, gtype.Val);
}
public static explicit operator bool (Value val)
{
return g_value_get_boolean (ref val);
}
public static explicit operator byte (Value val)
{
return g_value_get_uchar (ref val);
}
public static explicit operator sbyte (Value val)
{
return g_value_get_char (ref val);
}
public static explicit operator int (Value val)
{
return g_value_get_int (ref val);
}
public static explicit operator uint (Value val)
{
return g_value_get_uint (ref val);
}
public static explicit operator ushort (Value val)
{
return (ushort) g_value_get_uint (ref val);
}
public static explicit operator long (Value val)
{
return g_value_get_int64 (ref val);
}
public static explicit operator ulong (Value val)
{
return g_value_get_uint64 (ref val);
}
[Obsolete ("Replaced by Enum cast")]
public static explicit operator EnumWrapper (Value val)
{
if (val.HoldsFlags)
return new EnumWrapper ((int)g_value_get_flags (ref val), true);
else
return new EnumWrapper (g_value_get_enum (ref val), false);
}
public static explicit operator Enum (Value val)
{
if (val.HoldsFlags)
return (Enum)Enum.ToObject (GType.LookupType (val.type), g_value_get_flags (ref val));
else
return (Enum)Enum.ToObject (GType.LookupType (val.type), g_value_get_enum (ref val));
}
public static explicit operator float (Value val)
{
return g_value_get_float (ref val);
}
public static explicit operator double (Value val)
{
return g_value_get_double (ref val);
}
public static explicit operator string (Value val)
{
IntPtr str = g_value_get_string (ref val);
return str == IntPtr.Zero ? null : GLib.Marshaller.Utf8PtrToString (str);
}
public static explicit operator ValueArray (Value val)
{
return new ValueArray (g_value_get_boxed (ref val));
}
public static explicit operator IntPtr (Value val)
{
return g_value_get_pointer (ref val);
}
public static explicit operator GLib.Opaque (Value val)
{
return GLib.Opaque.GetOpaque (g_value_get_boxed (ref val), (Type) new GType (val.type), false);
}
public static explicit operator GLib.Boxed (Value val)
{
return new GLib.Boxed (g_value_get_boxed (ref val));
}
public static explicit operator GLib.Object (Value val)
{
return GLib.Object.GetObject (g_value_get_object (ref val), false);
}
[Obsolete ("Replaced by GLib.Object cast")]
public static explicit operator GLib.UnwrappedObject (Value val)
{
return new UnwrappedObject (g_value_get_object (ref val));
}
public static explicit operator string[] (Value val)
{
IntPtr native_array = g_value_get_boxed (ref val);
if (native_array == IntPtr.Zero)
return null;
int count = 0;
while (Marshal.ReadIntPtr (native_array, count * IntPtr.Size) != IntPtr.Zero)
count++;
string[] strings = new string[count];
for (int i = 0; i < count; i++)
strings[i] = GLib.Marshaller.Utf8PtrToString (Marshal.ReadIntPtr (native_array, i * IntPtr.Size));
return strings;
}
object ToRegisteredType () {
Type t = GLib.GType.LookupType (type);
ConstructorInfo ci = null;
try {
while (ci == null && t != null) {
if (!t.IsAbstract)
ci = t.GetConstructor (new Type[] { typeof (GLib.Value) });
if (ci == null)
t = t.BaseType;
}
} catch (Exception) {
ci = null;
}
if (ci == null)
throw new Exception ("Unknown type " + new GType (type).ToString ());
return ci.Invoke (new object[] {this});
}
void FromRegisteredType (object val) {
Type t = GLib.GType.LookupType (type);
MethodInfo mi = null;
try {
while (mi == null && t != null) {
mi = t.GetMethod ("SetGValue", new Type[] { Type.GetType ("GLib.Value&") });
if (mi != null && (mi.IsAbstract || mi.ReturnType != typeof (void)))
mi = null;
if (mi == null)
t = t.BaseType;
}
} catch (Exception) {
mi = null;
}
if (mi == null)
throw new Exception ("Unknown type " + new GType (type).ToString ());
object[] parameters = new object[] { this };
mi.Invoke (val, parameters);
this = (GLib.Value) parameters[0];
}
object ToEnum ()
{
Type t = GType.LookupType (type);
if (t == null) {
if (HoldsFlags)
return g_value_get_flags (ref this);
else
return g_value_get_enum (ref this);
} else {
return (Enum) this;
}
}
object ToBoxed ()
{
IntPtr boxed_ptr = g_value_get_boxed (ref this);
Type t = GType.LookupType (type);
if (t == null)
throw new Exception ("Unknown type " + new GType (type).ToString ());
else if (t.IsSubclassOf (typeof (GLib.Opaque)))
return (GLib.Opaque) this;
MethodInfo mi = t.GetMethod ("New", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
if (mi == null)
return Marshal.PtrToStructure (boxed_ptr, t);
else
return mi.Invoke (null, new object[] {boxed_ptr});
}
public object Val
{
get {
if (type == GType.Boolean.Val)
return (bool) this;
else if (type == GType.UChar.Val)
return (byte) this;
else if (type == GType.Char.Val)
return (sbyte) this;
else if (type == GType.Int.Val)
return (int) this;
else if (type == GType.UInt.Val)
return (uint) this;
else if (type == GType.Int64.Val)
return (long) this;
else if (type == GType.UInt64.Val)
return (ulong) this;
else if (GType.Is (type, GType.Enum) ||
GType.Is (type, GType.Flags))
return ToEnum ();
else if (type == GType.Float.Val)
return (float) this;
else if (type == GType.Double.Val)
return (double) this;
else if (type == GType.String.Val)
return (string) this;
else if (type == GType.Pointer.Val)
return (IntPtr) this;
else if (type == GType.Param.Val)
return g_value_get_param (ref this);
else if (type == ValueArray.GType.Val)
return new ValueArray (g_value_get_boxed (ref this));
else if (type == ManagedValue.GType.Val)
return ManagedValue.ObjectForWrapper (g_value_get_boxed (ref this));
else if (GType.Is (type, GType.Object))
return (GLib.Object) this;
else if (GType.Is (type, GType.Boxed))
return ToBoxed ();
else if (GType.LookupType (type) != null)
return ToRegisteredType ();
else if (type == IntPtr.Zero)
return null;
else
throw new Exception ("Unknown type " + new GType (type).ToString ());
}
set {
if (type == GType.Boolean.Val)
g_value_set_boolean (ref this, (bool) value);
else if (type == GType.UChar.Val)
g_value_set_uchar (ref this, (byte) value);
else if (type == GType.Char.Val)
g_value_set_char (ref this, (sbyte) value);
else if (type == GType.Int.Val)
g_value_set_int (ref this, (int) value);
else if (type == GType.UInt.Val)
g_value_set_uint (ref this, (uint) value);
else if (type == GType.Int64.Val)
g_value_set_int64 (ref this, (long) value);
else if (type == GType.UInt64.Val)
g_value_set_uint64 (ref this, (ulong) value);
else if (GType.Is (type, GType.Enum))
g_value_set_enum (ref this, (int)value);
else if (GType.Is (type, GType.Flags))
g_value_set_flags (ref this, (uint)(int)value);
else if (type == GType.Float.Val)
g_value_set_float (ref this, (float) value);
else if (type == GType.Double.Val)
g_value_set_double (ref this, (double) value);
else if (type == GType.String.Val) {
IntPtr native = GLib.Marshaller.StringToPtrGStrdup ((string)value);
g_value_set_string (ref this, native);
GLib.Marshaller.Free (native);
} else if (type == GType.Pointer.Val) {
if (value.GetType () == typeof (IntPtr)) {
g_value_set_pointer (ref this, (IntPtr) value);
return;
} else if (value is IWrapper) {
g_value_set_pointer (ref this, ((IWrapper)value).Handle);
return;
}
IntPtr buf = Marshal.AllocHGlobal (Marshal.SizeOf (value.GetType()));
Marshal.StructureToPtr (value, buf, false);
g_value_set_pointer (ref this, buf);
} else if (type == GType.Param.Val) {
g_value_set_param (ref this, (IntPtr) value);
} else if (type == ValueArray.GType.Val) {
g_value_set_boxed (ref this, ((ValueArray) value).Handle);
} else if (type == ManagedValue.GType.Val) {
IntPtr wrapper = ManagedValue.WrapObject (value);
g_value_set_boxed (ref this, wrapper);
ManagedValue.ReleaseWrapper (wrapper);
} else if (GType.Is (type, GType.Object))
if(value is GLib.Object)
g_value_set_object (ref this, (value as GLib.Object).Handle);
else
g_value_set_object (ref this, (value as GLib.GInterfaceAdapter).Handle);
else if (GType.Is (type, GType.Boxed)) {
if (value is IWrapper) {
g_value_set_boxed (ref this, ((IWrapper)value).Handle);
return;
}
IntPtr buf = Marshaller.StructureToPtrAlloc (value);
g_value_set_boxed (ref this, buf);
Marshal.FreeHGlobal (buf);
} else if (GLib.GType.LookupType (type) != null) {
FromRegisteredType (value);
} else
throw new Exception ("Unknown type " + new GType (type).ToString ());
}
}
internal void Update (object val)
{
if (GType.Is (type, GType.Boxed) && !(val is IWrapper))
Marshal.StructureToPtr (val, g_value_get_boxed (ref this), false);
}
bool HoldsFlags {
get { return g_type_check_value_holds (ref this, GType.Flags.Val); }
}
void InitForProperty (Object obj, string name)
{
GType gtype = obj.NativeType;
InitForProperty (gtype, name);
}
void InitForProperty (GType gtype, string name)
{
IntPtr p_name = Marshaller.StringToPtrGStrdup (name);
IntPtr spec_ptr = g_object_class_find_property (gtype.ClassPtr, p_name);
Marshaller.Free (p_name);
if (spec_ptr == IntPtr.Zero)
throw new Exception (String.Format ("No property with name '{0}' in type '{1}'", name, gtype.ToString()));
ParamSpec spec = new ParamSpec (spec_ptr);
g_value_init (ref this, spec.ValueType.Val);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_object_class_find_property (IntPtr klass, IntPtr name);
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_type_check_value_holds (ref Value val, IntPtr gtype);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_init (ref GLib.Value val, IntPtr gtype);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_unset (ref GLib.Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_boolean (ref Value val, bool data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_uchar (ref Value val, byte data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_char (ref Value val, sbyte data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_boxed (ref Value val, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_double (ref Value val, double data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_float (ref Value val, float data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_int (ref Value val, int data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_int64 (ref Value val, long data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_uint64 (ref Value val, ulong data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_object (ref Value val, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_param (ref Value val, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_pointer (ref Value val, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_string (ref Value val, IntPtr data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_uint (ref Value val, uint data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_enum (ref Value val, int data);
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_set_flags (ref Value val, uint data);
[DllImport("libgobject-2.0-0.dll")]
static extern bool g_value_get_boolean (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern byte g_value_get_uchar (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern sbyte g_value_get_char (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_get_boxed (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern double g_value_get_double (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern float g_value_get_float (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern int g_value_get_int (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern long g_value_get_int64 (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern ulong g_value_get_uint64 (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_get_object (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_get_param (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_get_pointer (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_get_string (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern uint g_value_get_uint (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern int g_value_get_enum (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern uint g_value_get_flags (ref Value val);
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_strv_get_type ();
}
}

View file

@ -0,0 +1,247 @@
// ValueArray.cs - ValueArray wrapper implementation
//
// Authors: Mike Kestner <mkestner@ximian.com>
//
// Copyright (c) 2003 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
public class ValueArray : IDisposable, ICollection, ICloneable, IWrapper {
private IntPtr handle = IntPtr.Zero;
static private ArrayList PendingFrees = new ArrayList ();
static private bool idle_queued = false;
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_array_new (uint n_preallocs);
public ValueArray (uint n_preallocs)
{
handle = g_value_array_new (n_preallocs);
}
public ValueArray (IntPtr raw)
{
handle = raw;
}
~ValueArray ()
{
Dispose (false);
}
// IDisposable
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_array_free (IntPtr raw);
void Dispose (bool disposing)
{
if (Handle == IntPtr.Zero)
return;
lock (PendingFrees) {
PendingFrees.Add (handle);
if (! idle_queued) {
Timeout.Add (50, new TimeoutHandler (PerformFrees));
idle_queued = true;
}
}
handle = IntPtr.Zero;
}
static bool PerformFrees ()
{
IntPtr[] handles;
lock (PendingFrees) {
idle_queued = false;
handles = new IntPtr [PendingFrees.Count];
PendingFrees.CopyTo (handles, 0);
PendingFrees.Clear ();
}
foreach (IntPtr h in handles)
g_value_array_free (h);
return false;
}
public IntPtr Handle {
get {
return handle;
}
}
struct NativeStruct {
public uint n_values;
public IntPtr values;
public uint n_prealloced;
}
NativeStruct Native {
get { return (NativeStruct) Marshal.PtrToStructure (Handle, typeof(NativeStruct)); }
}
public IntPtr ArrayPtr {
get { return Native.values; }
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_array_append (IntPtr raw, ref GLib.Value val);
public void Append (GLib.Value val)
{
g_value_array_append (Handle, ref val);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_array_insert (IntPtr raw, uint idx, ref GLib.Value val);
public void Insert (uint idx, GLib.Value val)
{
g_value_array_insert (Handle, idx, ref val);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_array_prepend (IntPtr raw, ref GLib.Value val);
public void Prepend (GLib.Value val)
{
g_value_array_prepend (Handle, ref val);
}
[DllImport("libgobject-2.0-0.dll")]
static extern void g_value_array_remove (IntPtr raw, uint idx);
public void Remove (uint idx)
{
g_value_array_remove (Handle, idx);
}
// ICollection
public int Count {
get { return (int) Native.n_values; }
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_array_get_nth (IntPtr raw, uint idx);
public object this [int index] {
get {
IntPtr raw_val = g_value_array_get_nth (Handle, (uint) index);
return Marshal.PtrToStructure (raw_val, typeof (GLib.Value));
}
}
// Synchronization could be tricky here. Hmm.
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return null; }
}
public void CopyTo (Array array, int index)
{
if (array == null)
throw new ArgumentNullException ("Array can't be null.");
if (index < 0)
throw new ArgumentOutOfRangeException ("Index must be greater than 0.");
if (index + Count < array.Length)
throw new ArgumentException ("Array not large enough to copy into starting at index.");
for (int i = 0; i < Count; i++)
((IList) array) [index + i] = this [i];
}
private class ListEnumerator : IEnumerator
{
private int current = -1;
private ValueArray vals;
public ListEnumerator (ValueArray vals)
{
this.vals = vals;
}
public object Current {
get {
if (current == -1)
return null;
return vals [current];
}
}
public bool MoveNext ()
{
if (++current >= vals.Count) {
current = -1;
return false;
}
return true;
}
public void Reset ()
{
current = -1;
}
}
// IEnumerable
public IEnumerator GetEnumerator ()
{
return new ListEnumerator (this);
}
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_value_array_copy (IntPtr raw);
// ICloneable
public object Clone ()
{
return new ValueArray (g_value_array_copy (Handle));
}
[DllImport ("libgobject-2.0-0.dll")]
static extern IntPtr g_value_array_get_type ();
public static GLib.GType GType {
get {
return new GLib.GType (g_value_array_get_type ());
}
}
}
}

View file