GithubHelp home page GithubHelp logo

gtksharp / gtksharp Goto Github PK

View Code? Open in Web Editor NEW
870.0 31.0 97.0 27.54 MB

.NET wrapper for Gtk and other related libraries

License: Other

Shell 0.01% C# 95.48% Meson 0.06% Perl 2.39% CSS 0.09% JavaScript 0.64% Makefile 0.03% XSLT 0.74% Python 0.04% F# 0.22% Visual Basic .NET 0.31%
gtk csharp

gtksharp's Introduction

GtkSharp

GtkSharp is a C# wrapper for Gtk and its related components. The component list includes the following libraries: glib, gio, cairo, pango, atk, gdk. This is a fork of https://github.com/mono/gtk-sharp and is maintained completely separately from that project.

Differences can be seen with the following table:

Target framework Target Gtk Version Extra notes
GtkSharp .NET Standard 2.0 Gtk 3.22 Does not need glue libraries.
mono/gtksharp .NET Framework 4.5 Gtk 2 (also Gtk 3.0 but never officially released)

Building from source

Pre requirements for building from source are that you have .Net 6 installed on the system.

To build the repository, simply do:

git clone https://github.com/GtkSharp/GtkSharp.git
cd GtkSharp
dotnet tool restore
dotnet cake build.cake

A breakdown on how the source is structured:

  • Tools that are needed to generate wrapper code are found in Tools folder
  • The actual wrappers code is found in Libs folder
  • Templates are located in Templates folder
  • Build script is separated between build.cake and CakeScripts folder

Using the library

On macOS, you'll need to manually install Gtk, see Installing Gtk on Mac wiki page for more details on how to do it.

Available NuGet packages:

To create a new gtk app project, simply use dotnet new templating engine:

  • install: dotnet new --install GtkSharp.Template.CSharp
  • uninstall: dotnet new --uninstall GtkSharp.Template.CSharp
  • generate project: dotnet new gtkapp

License

GtkSharp and its related components are licensed under LGPL v2.0 license, while Samples are licenced under The Unlicense.

gtksharp's People

Contributors

awittaker avatar bl8 avatar btaylor avatar cameronwhite avatar gonzalop avatar grendello avatar harry-cpp avatar hecatron avatar hectoregm avatar illupus avatar joeshaw avatar jstedfast avatar kant2002 avatar knocte avatar lewing avatar lytico avatar madsjohnsen avatar mhutch avatar migueldeicaza avatar mikkeljohnsen avatar mkestner avatar pedrohex avatar radekdoulik avatar slluis avatar sundermann avatar thiblahute avatar vargaz avatar xclaesse avatar zbowling avatar zii-dmg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gtksharp's Issues

PopupMenu with Actions/Accel and glade

I try to make a popupmenu with actions and accel using the glade designer with no success,
the entry's always stay gray!

A lot of examples uses deprecated functions and i don't know what's the "right" way.
Please give me a hand!

Drawing hierarchy is messed up

Consider the following gtk example:

#include <cairo.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>

gboolean draw_layout1(GtkWidget *, cairo_t *, gpointer);
gboolean draw_layout2(GtkWidget *, cairo_t *, gpointer);
void layout1_size_allocated(GtkWidget *, GdkRectangle *, gpointer);

int main()
{
	gtk_init(nullptr,nullptr);

	auto win = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	auto layout1 = gtk_layout_new(nullptr,nullptr);
	auto layout2 = gtk_layout_new(nullptr,nullptr);

	gtk_container_add(GTK_CONTAINER(win),layout1);
	gtk_container_add(GTK_CONTAINER(layout1),layout2);

	g_signal_connect(layout1, "size-allocate", G_CALLBACK(layout1_size_allocated), layout2);
	g_signal_connect(layout1, "draw", G_CALLBACK(draw_layout1), nullptr);
	g_signal_connect(layout2, "draw", G_CALLBACK(draw_layout2), nullptr);

	gtk_widget_show_all(win);

	gtk_main();
}

gboolean draw_layout1(GtkWidget * widget, cairo_t * cr, gpointer user_data)
{
	GtkAllocation alloc;

	gtk_widget_get_allocation(widget,&alloc);

	cairo_set_source_rgb(cr,1.0,0.0,0.0);
	cairo_rectangle(cr,alloc.x,alloc.y,alloc.width,alloc.height);
	cairo_fill(cr);
}

gboolean draw_layout2(GtkWidget * widget, cairo_t * cr, gpointer user_data)
{
	GtkAllocation alloc;

	gtk_widget_get_allocation(widget,&alloc);

	cairo_set_source_rgb(cr,0.0,1.0,0.0);
	cairo_rectangle(cr,alloc.x,alloc.y,alloc.width,alloc.height);
	cairo_fill(cr);
}

void layout1_size_allocated(GtkWidget * widget, GdkRectangle * allocation, gpointer user_data)
{
	auto layout2 = reinterpret_cast<GtkWidget *>(user_data);

	GtkAllocation alloc;
	alloc.x = 0;
	alloc.y = 0;
	alloc.width = allocation->width/2;
	alloc.height = allocation->height/2;

	gtk_widget_size_allocate(layout2,&alloc);
}

You get:

image

When you do the same in GtkSharp:

using System;

namespace GtkSharpTest4
{
   class Program
   {
      static void Main(string[] args)
      {
         string originalPath = Environment.GetEnvironmentVariable("PATH");

         Environment.SetEnvironmentVariable("PATH", @"C:\msys64\mingw64\bin" + ";" + originalPath);

         Gtk.Application.Init();

         var win = new Gtk.Window(Gtk.WindowType.Toplevel);

         var layout1 = new Gtk.Layout(null,null);
         var layout2 = new Gtk.Layout(null,null);

         win.Add(layout1);
         layout1.Add(layout2);

         layout1.SizeAllocated += 
            (o,e) => layout2.SizeAllocate(new Gdk.Rectangle(0,0,layout1.AllocatedWidth/2,layout1.AllocatedHeight/2));

         layout1.Drawn += 
            (o,e) =>
            {
               e.Cr.SetSourceRGB(1.0,0.0,0.0);
               e.Cr.Rectangle(0,0,layout1.AllocatedWidth,layout1.AllocatedHeight);
               e.Cr.Fill();
            };

         layout2.Drawn +=
            (o, e) =>
            {
               e.Cr.SetSourceRGB(0.0, 1.0, 0.0);
               e.Cr.Rectangle(0, 0, layout2.AllocatedWidth, layout2.AllocatedHeight);
               e.Cr.Fill();
            };

         win.ShowAll();

         Gtk.Application.Run();
      }
   }
}

you get:
image

If you turn off drawing the outer layout you can the inner one...so it's as if the drawing is reversed.

Application.AddActionEntries has wrong arguments

I'm trying to pass an ActionEntry[] to the entries parameter of GLib.Application.AddActionEntries, but the method only accepts a single ActionEntry. I think this is an error in the code generation because the original C method expects a pointer to the first element.

MotionNotifyEventArgs doesn't work properly on Windows (segfaults)

I've got a laptop that has one of those pressure pen screens. I wanted to play around with the pressure pen API in Gtk. There is this block of code attached to a GtkDrawingArea:

private void onMotionNotifyEvent(object sender, MotionNotifyEventArgs args)
{
    // Update Info UI
    xPosLabel.Text = ((int)args.Event.X).ToString();
    yPosLabel.Text = ((int)args.Event.Y).ToString();
    pressureLabel.Text = args.Event.Axes[(int)Gdk.AxisFlags.Pressure - 1].ToString("0.00");
    xTiltLabel.Text = args.Event.Axes[(int)Gdk.AxisFlags.Xtilt- 1].ToString("0.00");
    yTiltLabel.Text = args.Event.Axes[(int)Gdk.AxisFlags.Ytilt- 1].ToString("0.00");

    if (penDown)
    {
        activeLine.Add(new Point(
            (float)args.Event.X,
            (float)args.Event.Y,
            (float)args.Event.Axes[(int)Gdk.AxisFlags.Pressure - 1]
        ));
        drawingArea.QueueDraw();

        Console.WriteLine("name = {0}", args.Event.Device.Name);
        Console.WriteLine("inputSrc = {0}", args.Event.Device.InputSource);
        Console.WriteLine("AxisFlags: {0}", args.Event.Device.Axes);
        Console.WriteLine("Axes: {0}", string.Join(" ", args.Event.Axes));
        Console.WriteLine((double)args.Event.Time / 1000.0);
        Console.WriteLine("--------");
    }
}

When I was on (Xubuntu) Linux, it worked fine and was reporting info about the pen state when moving over the area, but on Windows, I was getting a segfault whenever I moved the mouse over the area.

I found out that the args.Event.Axes field is set to null, whereas on Linux it's a populated double[] array. Do you think that this is more of a native GTK3 library issue or a GtkSharp one? I haven't written any C code to test this.

Clarify the status of this project

Hello,
I saw nowhere what's the status of this project versus the https://github.com/mono/gtk-sharp repository.

Is that a fork? The new official repository?

When looking on NuGet and on https://github.com/dotnet/templating/wiki/Available-templates-for-dotnet-new , I was under the impression that this was the official repository, and I was confused later when I found mono/gtk-sharp, which seems to be used by Xamarin.Forms' GTK platform.

Could you clear that up in the readme please?

SimpleAction with parameter "VariantType" failed

I try to pass a value with a action, i have this
...
action = new GLib.SimpleAction("MyAction", GLib.VariantType.Int32);
action.Activated += OnMyAction;
but all the static members of "GLib.VariantType" are null !!!

If i use a "new GLib.VariantType("i")" i get
Object reference not set to an instance of an object
at GLib.VariantType..ctor (System.String type_string) [0x0000d] in :0
at GLib.VariantType..cctor () [0x00000] in :0

What i'm doing wrong, or is there a other way to pass a value with an action?!

Can't use GtkSharp on macOS

Good day!

I have installed the gtk3 package via MacPorts and run the following commands:

$ dotnet new sln -n HelloGTK
$ dotnet new gtkapp -o HelloGTK
$ dotnet sln HelloGTK.sln add HelloGTK
$ cd HelloGTK
$ dotnet run

On Linux as well as Windows, the sample Window shows up but on macOS, the following exception is thrown:

Unhandled Exception: System.TypeInitializationException: The type initializer for 'Gtk.Application' threw an exception. ---> System.DllNotFoundException: Gtk
   at GLibrary.Load(Library library)
   at Gtk.Application..cctor()
   --- End of inner exception stack trace ---
   at Gtk.Application.Init()
   at HelloGTK.Program.Main(String[] args) in /Users/luser/dotnets/HelloGTK/Program.cs:line 11

Any hints for making Gtk being found?

How to deal with custom images/icons

Hi. First of all, thank you for making this. I really like being able to use a more up to date version of Gtk & .NET Core to write my application, as well as being able to use Glade to design GUIs.

Though, I'm getting a bit stuck on one part, and that's using custom images for icons (on things such as buttons). For example, in my glade file, I added this section to the top

<object class="GtkImage" id="gear">
  <property name="visible">True</property>
  <property name="can_focus">False</property>
  <property name="pixbuf">../../Media/Icons/gear.png</property>
</object>

And then in the main application window, there this button:

<object class="GtkButton" id="gearButton">
  <property name="visible">True</property>
  <property name="can_focus">True</property>
  <property name="receives_default">True</property>
  <property name="image">gear</property>
  <property name="always_show_image">True</property>
</object>

My solution is structured as follows:

.
├── Solution.sln
├── MyApp
│   ├── MyApp.csproj
│   ├── Program.cs
│   ├── Widgets
│   │   ├── MainWindow.cs
│   │   ├── MainWindow.glade
├── Media
│   └── Icons
└       └── gear.png

So I know that Glade is referencing the icon relative form it's position, and it shows up when I'm adjusting the designer file. Though when running the app from either the solution level folder, or the project level folder, it's giving me that "image not found" icon instead.

I'm still not too familiar with .NET Core (or the finer parts of Glade and resources), but is there something where I can embed my image resources (similar to how the .glade files are embedded), so my application can find them when running, but also have the Glade application be able to find them at "design time"?

(I'm talking about this:)

  <ItemGroup>
    <None Remove="**\*.glade" />
    <EmbeddedResource Include="**\*.glade">
      <LogicalName>%(Filename)%(Extension)</LogicalName>
    </EmbeddedResource>
  </ItemGroup>

How to install the Monodevelop addin?

Hi,

I seem to be a bit thick when it comes to getting the Monodevelop addin to install within Monodevelop.

How would I go about to do that?

thanks,

Tobias

Create a native dependency package for Windows

Currently, the setup process for GTK on Windows is not very kind to end users. It would be great to have an official nuget package which bundles the native dependencies and related files (GSettings schemas and the like) for quick and easy inclusion in C# projects.

There's already an unofficial package on nuget (GtkSharp.Win32), but having an official one would be more preferable.

How to get the DeltaX and DeltaY from a scroll event ?

It seems that the current version of GtkSharp have not implemented the delta_x and delta_y values in the EventScroll event args, but they exist in the native structure:

struct GdkEventScroll {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  gdouble x;
  gdouble y;
  guint state;
  GdkScrollDirection direction;
  GdkDevice *device;
  gdouble x_root, y_root;
  gdouble delta_x;
  gdouble delta_y;
  guint is_stop : 1;
};

So there is another way to get these values ?

Exception thrown when subclassing Gtk.Window

Hey.

I'm experiencing an issue when subclassing Gtk.Window running MacOS X .Net Core.

This minimal example launches a window fine:

public static void Main() {
    Application.Init();
    var window = new Window("Title");
    window.Show();
    Application.Run();
}

The same fails if I attempt to subclass Gtk.Window:

class TestWindow : Gtk.Window {
    public TestWindow()
        : base("Title") {
    }
}

public static void Main() {
    Application.Init();
    var window = new TestWindow();
    window.Show();
    Application.Run();
}

The error thrown is of type GLib.MissingIntPtrCtorException:
"Unable to construct instance of type Test.Program+TestWindow from native object handle. Instance of managed subclass may have been prematurely disposed."

Cannot run gtk template using dotnet run

I tried to create a new gtkapp project using dotnet cli, but I cannot run it, even after a dotnet restore.

  • MSYS2 and GTK are installed
  • Build without problems

the error is the following:

$ dotnet run

Unhandled Exception: System.TypeInitializationException: The type initializer for 'Gtk.Application' threw an exception. ---> System.DllNotFoundException: Gtk
   at GLibrary.Load(Library library)
   at Gtk.Application..cctor()
   --- End of inner exception stack trace ---
   at Gtk.Application.Init()
   at NetCore_GTK_Playground.Program.Main(String[] args) in C:\[...]\Git\NetCore-GTK-Playground\Program.cs:line 11

Doesn't work with flatpak dotnet

This is just a warning for people using flatpak dotnet. If you have flatpak (19.04) it will throw an error saying "GTK" not installed. This is due to the paths dotnet is installed with flatpak.

A workaround is to install it in your $HOME folder

downloads="$HOME/Downloads"
location="$HOME/dotnet"

#########################
# Download dotnet if not 
# already downloaded
#########################
if [ ! -e $downloads/dotnet-sdk-2.2.106-linux-x64.tar.gz ]; then
    wget https://download.visualstudio.microsoft.com/download/pr/9bef40df-fd90-4693-a16f-76fd40358c89/13e2cbd999ab248e9cf5d10d98d3e5fc/dotnet-sdk-2.2.106-linux-x64.tar.gz -P $downloads
fi

if [ ! -e $downloads/dotnet-sdk-3.0.100-preview3-010431-linux-x64.tar.gz ]; then
    wget https://download.visualstudio.microsoft.com/download/pr/35c9c95a-535e-4f00-ace0-4e1686e33c6e/b9787e68747a7e8a2cf8cc530f4b2f88/dotnet-sdk-3.0.100-preview3-010431-linux-x64.tar.gz -P $downloads
fi

######################
# Make the main dir
######################
if [ ! -d "$location" ]; then mkdir $location; fi

#####################
# Install version 2
#####################
if [ ! -d "$location/2" ]; then 
    mkdir $location/2; tar xf $downloads/dotnet-sdk-2.2.106-linux-x64.tar.gz -C $location/2 
fi

#####################
# Install version 3
#####################
if [ ! -d "$location/3" ]; then
    mkdir $location/3; tar xf $downloads/dotnet-sdk-3.0.100-preview3-010431-linux-x64.tar.gz -C $location/3
fi

Then add the dotnet folder to your path:

export PATH=$PATH:$HOME/dotnet/2

Investigate use of ADL instead of manual delegate declaration

I'm an avid user of GtkSharp on Linux, Mac, and Windows, and having it support .NET Standard is great. However, from reading through the source, I can see that it's being done through manual delegate declaration and then loading live delegates from function pointers.

Full disclaimer - I am the author of the library in question, so this is a plug, but the library is made for exactly this purpose.

The ADL library abstracts this away from the end user, and also provides options for using even faster implementations behind the scenes, while maintaining a flexible and efficient end-user interface.

It would allow a significant reduction in boilerplate code - for example, taking the Accel.cs class (purely as a quick example). Using ADL, it would be reduced to this:

https://gist.github.com/Nihlus/01f2457406aa5776a7502d371cba6d29

Further reductions could be made by providing ADL with extensions to support marshalling GLib strings and GLib objects down to IntPtrs automatically.

I'd be more than happy to look into this closer, if the maintenance team thinks it could be worthwhile.

Builder.Autoconnect() crashes the app if a (mismatching) signal isn't found

So in my app, I originally had one glade file per widget, but Glade is able to handle multiple widgets in a single file fine. So I did a refactor and put all of my widgets into a single Widgets.glade file. Then I refactored the widget's .cs files, so they kind of look like this:

public MyMainWindow()
    : this(new Builder("Widgets.glade"))
{
    // ...
}



private MyMainWindow(Builder builder)
    : base(builder.GetObject("MyMainWindow").Handle)
{
    builder.Autoconnect(this);
}

private MyDialog(Builder builder)
    : base(builder.GetObject("MyDialog").Handle)
{
    builder.Autoconnect(this);
}

The my MyDialog widget/window has some child widgets which are looking for functions e.g. onOkayPressed(). The problem is though that the call to build.Autoconnect(this) in MyMainWindow is looking for an onOkayPressed() method (which isn't supposed to exist for that window).

If you want me to, I can create a project that reproduces this error.

Add Method/Property/etc descriptions

Currently you have to inspect the source, find the C call, and then look that up. Would be much better for productivity if you could just see the descriptions directly in the IDE.

Add support for .NET 4 in the NuGet packages

When I try installing GtkSharp from its NuGet in a .NET 4 project, I get:

NU1202: Package GtkSharp 3.22.24.36 is not compatible with net40 (.NETFramework,Version=v4.0) / win-x86. Package GtkSharp 3.22.24.36 supports: netstandard2.0 (.NETStandard,Version=v2.0)

Please add support for .NET 4. It is important because it's the last .NET to run on Windows XP which is still used in many parts of the world. Building the bindings should pose no effort so the only thing to do would be reconfiguring the NuGet.

Drag and Drop

Hello. I'm reimplementing 9.8.4. Drag and Drop example from here: https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview-examples.html.en
I have succeeded in translating to Vala but failed with C#. (Vala code is almost the same as the C# code, but Vala program works same as the C++ original program)
What's wrong?
Program.cs

using System;
using Gtk;

namespace SimpleExample
{
    class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            Application.Init();

            var app = new Application("org.SimpleExample.SimpleExample", GLib.ApplicationFlags.NonUnique);
            app.Register(GLib.Cancellable.Current);

            var window = new ExampleWindow("Gtk::TreeView (Drag and Drop) example");
            app.AddWindow(window);

            window.Show();
            Application.Run();
        }
    }
}

ExampleWindow.cs

using Gtk;
using System;

namespace SimpleExample
{
    class ExampleWindow : Window
    {
        //Child widgets:
        private Box m_VBox;

        private ScrolledWindow m_ScrolledWindow;
        private TreeView m_TreeView;
        private TreeModel_Dnd m_refTreeModel;

        private ButtonBox m_ButtonBox;
        private Button m_Button_Quit;

        private CellRendererToggle m_cellrenderer_draggable;
        private CellRendererToggle m_cellrenderer_receivesdrags;

        private readonly TargetEntry[] targets = new TargetEntry[] { new TargetEntry("GTK_TREE_MODEL_ROW", TargetFlags.Widget, 0) };

        public ExampleWindow(string title) : base(title)
        {
            // create all widgets
            m_VBox = new Box(Orientation.Vertical, 0);
            m_ScrolledWindow = new ScrolledWindow();
            m_TreeView = new TreeView();
            m_refTreeModel = new TreeModel_Dnd(typeof(uint), typeof(string), typeof(bool), typeof(bool));
            m_ButtonBox = new ButtonBox(Orientation.Horizontal);
            m_Button_Quit = Button.NewWithLabel("Quit");
            m_cellrenderer_draggable = new CellRendererToggle();
            m_cellrenderer_receivesdrags = new CellRendererToggle();

            DeleteEvent += WindowDeleteEvent;
            BorderWidth = 5;
            SetDefaultSize(400, 200);

            Add(m_VBox);

            //Add the TreeView, inside a ScrolledWindow, with the button underneath:
            m_ScrolledWindow.Add(m_TreeView);

            //Only show the scrollbars when they are necessary:
            m_ScrolledWindow.SetPolicy(PolicyType.Automatic, PolicyType.Automatic);

            m_VBox.PackStart(m_ScrolledWindow, true, true, 0);
            m_VBox.PackStart(m_ButtonBox, false, false, 0);

            m_ButtonBox.PackStart(m_Button_Quit, false, false, 0);
            m_ButtonBox.BorderWidth = 5;
            m_ButtonBox.Layout = ButtonBoxStyle.End;
            m_Button_Quit.Clicked += OnButtonClicked;

            //Fill the TreeView's model
            var parent1 = m_refTreeModel.AppendValues(1, "Billy Bob", true, true);
            m_refTreeModel.AppendValues(parent1, 11, "Billy Bob Junior", true, true);
            m_refTreeModel.AppendValues(parent1, 12, "Sue Bob", true, true);

            m_refTreeModel.AppendValues(2, "Joey Jojo", true, true);

            var parent2 = m_refTreeModel.AppendValues(3, "Rob McRoberts", true, true);
            m_refTreeModel.AppendValues(parent2, 31, "Xavier McRoberts", true, true);

            m_TreeView.Model = m_refTreeModel;

            //Enable Drag-and-Drop of TreeView rows:
            //See also the derived TreeModel's *_vfunc overrides.
            m_TreeView.EnableModelDragSource(Gdk.ModifierType.ModifierMask,
                targets,
                Gdk.DragAction.Copy | Gdk.DragAction.Move);
            m_TreeView.EnableModelDragDest(targets, Gdk.DragAction.Copy | Gdk.DragAction.Move);


            //Add the TreeView's view columns:
            m_TreeView.AppendColumn("ID", new CellRendererText(), "text", 0);
            m_TreeView.AppendColumn("Name", new CellRendererText(), "text", 1);

            m_cellrenderer_draggable.Toggled += DraggableOnToggled;
            m_TreeView.AppendColumn("Draggable", m_cellrenderer_draggable, "active", 2);

            m_cellrenderer_receivesdrags.Toggled += ReceiveDragsOnToggled;
            m_TreeView.AppendColumn("Receives Drags", m_cellrenderer_receivesdrags, "active", 3);

            ShowAll();
        }

        private void ReceiveDragsOnToggled(object o, ToggledArgs args)
        {
            var tree_path = new TreePath(args.Path);
            TreeIter iter;
            if (m_refTreeModel.GetIter(out iter, tree_path))
            {
                bool toggled = bool.Parse(m_refTreeModel.GetValue(iter, 3).ToString());
                m_refTreeModel.SetValue(iter, 3, !toggled);
            }
        }

        private void DraggableOnToggled(object o, ToggledArgs args)
        {
            var tree_path = new TreePath(args.Path);
            TreeIter iter;
            if (m_refTreeModel.GetIter(out iter, tree_path))
            {
                bool toggled = bool.Parse(m_refTreeModel.GetValue(iter, 2).ToString());
                m_refTreeModel.SetValue(iter, 2, !toggled);
            }
        }

        private void OnButtonClicked(object sender, EventArgs e)
        {
            Application.Quit();
        }

        private void WindowDeleteEvent(object sender, DeleteEventArgs a)
        {
            Application.Quit();
        }
    }
}

TreeModel_Dnd.cs

using Gtk;
using System;

namespace SimpleExample
{
    class TreeModel_Dnd : TreeStore, ITreeDragSource, ITreeDragDest
    {
        public TreeModel_Dnd(params Type[] types) : base(types)
        {
        }

        bool ITreeDragSource.RowDraggable(TreePath path)
        {
            // Make the value of the "draggable" column determine whether this row can
            // be dragged:
            TreeIter iter;
            if (GetIter(out iter, path))
            {
                bool is_draggable = bool.Parse(GetValue(iter, 2).ToString());
                return is_draggable;
            }

            return RowDraggable(path);
        }

        bool ITreeDragDest.RowDropPossible(TreePath dest_path, SelectionData selection_data)
        {
            //Make the value of the "receives drags" column determine whether a row can be
            //dragged into it:
            //dest is the path that the row would have after it has been dropped:
            //But in this case we are more interested in the parent row:
            TreePath dest_parent = dest_path.Copy();
            bool dest_is_not_top_level = dest_parent.Up();
            if (!dest_is_not_top_level || dest_parent.Depth == 0)
            {
                //The user wants to move something to the top-level.
                //Let's always allow that.
            }
            else
            {
                TreeIter iter_dest_parent;
                if (GetIter(out iter_dest_parent, dest_parent))
                {
                    bool receives_drags = bool.Parse(GetValue(iter_dest_parent, 3).ToString());
                    return receives_drags;
                }
            }
            return RowDropPossible(dest_path, selection_data);
        }
    }
}

Maybe RowDraggable and RowDropPossible shoud be virtual in the GtkSharp?
Also "Drag and Drop" example is a good candidate for adding to the GtkSharp Samples...

Segfaults with a Slider's "format-changed` signal

I had a slider, and was using the format-changed signal to have a custom output right next to the slider. E.g, in my .glade file this line exists (on a Slider widget): <signal name="format-value" handler="onSliderFormatValue" swapped="no"/>

While it did work for a few seconds, it would then crash whenever the slider was changed. Either via user input, or via code. The error on the console was this:

FailFast:
A callback was made on a garbage collected delegate of type 'MyProject!MyProject.Native+Callback::Invoke'.

After removing the signal handler, I wasn't getting any crashes when adjusting the slider.

GSettings Schemas are not included in GtkSharp.Win32

In order for applications that depend on gsettings schemas to run on Windows, compiled schemas must be bundled with the application or installed on the system.

These files are not included in the binary package.

Is it possible to access glade files from another folder?

Say I have all of my glade files in Layouts is it possible to access them from another folder

- app
    - Layouts
        - Window.glade
        - AWidget.glade
    - Window.cs

I have tried to add the builder pointing to the Layouts folder, but that doesn't work:

        public MainWindow() : this(
            new Builder("Layouts/Window.glade")
        ) { }

Unhandled Exception: System.ArgumentException: Cannot get resource file 'Layouts/Window.glade'

Any ideas how to achieve this?

Style property properties don't work

var sb = new Gtk.Scrollbar(Gtk.Orientation.Vertical,new Gtk.Adjustment(0,0,10,1,1,1));

//throws "No property with name 'has-backward-stepper' in type 'GtkScrollbar"
var hasit = sb.HasBackwardStepper;

//works
var ppp = sb.StyleGetProperty("has-backward-stepper");

Add a binding for Glade

The Mono bindings include glade-sharp, a C# binding for Glade. It's needed for interaction with interfaces designed with Glade. So it would nicely complement these bindings.

Memory leaks

We have a fairly large product written in GtkSharp using Mono (Linux and macOS) and .NET Framework (Windows).

We have been using Gtk3 for a very long time, but our application is now becoming very unstable because of memory leaks. GtkSharp is simple not able to release native memory.

I will upload test applications later. We have testet with native C gtk3 program, simple creating 1000 dialog boxes and calling Hide and Destroy on them. Valgrind is reporting no memory leaks. The same program creating 1000 dialogs using C#, valgrind is reporting massive native memory leaks, as do Memory Profiler on Windows.

We have been trying to solve this for some time, but have trouble finding the cause.

I hope that someone in here is able to help us, finding this bug in the GtkSharp (wrapper).

Wrong signature on TextView.GetIterAtPosition

Hi,
the signature for the follow method is wrong
class Textview
public bool GetIterAtPosition (TextIter iter, out int trailing, int x, int y);

should be out
public bool GetIterAtPosition (**out** TextIter iter, out int trailing, int x, int y);

System.DllNotFoundException when overriding CellRendererPixbuf

System.DllNotFoundException -> gtksharpglue-3
at (wrapper managed-to-native) Gtk.CellRenderer.gtksharp_cellrenderer_override_get_size(intptr,Gtk.CellRenderer/OnGetSizeDelegate)
at Gtk.CellRenderer.OverrideOnGetSize (GLib.GType gtype) [0x00023] in <74a3bfbb84a74da08945c94a73859366>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x0003b] in <3833a6edf2074b959d3dab898627f0ac>:0

var pixbuf = new SolutionCellRendererPixbuf(); <- **Exception**

....

class SolutionCellRendererPixbuf : CellRendererPixbuf
{
	protected override void OnGetSize(Widget widget, ref Gdk.Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height)
	{
		base.OnGetSize(widget, ref cell_area, out x_offset, out y_offset, out width, out height);
	}
	protected override void OnRender(Context cr, Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags)
	{
		base.OnRender(cr, widget, background_area, cell_area, flags);
	}
}

Xamarin.Forms support

Hi,

Any plans to make this binding a Xamarin.Forms compatible backend?

Happy new year!

Cheers.

Resizing the window doesn't work with HeaderBox

I have discovered the following problem.
When I create a window and replace the decorations with a HeaderBox. I can't change the size of my window with the mouse. The dragging of the window works.
I couldn't find anything on the internet.
I don't know if it's your libs or GtkSharp. win32. Or if it's just me.
The confusing is under Glade as prview everything works.

Thank you.
MadBit

Here's my class I'm trying it with.

public class TemplateForm0
{
    //private ApplicationWindow m_AppWindow;
    //private Window m_Window;
    //private Builder m_Builder;

    //[Builder.Object] private Notebook m_NotebookSource;


    //private Button m_Button1;

    public TemplateForm0()
    {
        Application.Init();
        Window win = new Window("Button Tester");
        win.DefaultWidth = 400;
        win.DefaultHeight = 200;
        win.BorderWidth = 10;

        HeaderBar hb = new HeaderBar();
        hb.ShowCloseButton = true;
        hb.Title = "HeaderBar example";
        hb.Subtitle = "An Example of HeaderBar";
        win.Titlebar = hb;

        Button button = new Button();
        Image img = Image.NewFromIconName("mail-send-receive-symbolic", IconSize.Button);
        button.Add(img);
        hb.PackEnd(button);

        Box box = new Box(Orientation.Horizontal, 6);

        button = new Button { new Arrow(ArrowType.Left, ShadowType.None) };
        box.Add(button);

        button = new Button { new Arrow(ArrowType.Right, ShadowType.None) };
        box.Add(button);

        hb.PackStart(box);

        win.Add(new TextView());

        win.DeleteEvent += new DeleteEventHandler(Window_Delete);

        win.ShowAll();

        //m_Builder = new Builder("GTKSharp_Template.AppTemplate.glade");
        //m_AppWindow = (ApplicationWindow)m_Builder.GetObject("m_AppWindowTemplate");

        //m_Builder.Autoconnect(this);

        //ScrolledWindow wnd0 = new ScrolledWindow();
        //TextView txt0 = new TextView();
        //wnd0.Add(new TextView());
        //m_NotebookSource.AppendPage(wnd0, new Label("SourceView0"));

        //Gtk.Settings.Default.XftRgba = "rgb";
        ////Gtk.Settings.Default.XftHinting = 1;
        ////Gtk.Settings.Default.XftHintstyle = "hintfull";

        //m_AppWindow.Resizable = true;

        //m_AppWindow.ShowAll();
    }

    static void btn_click(object obj, EventArgs args)
    {
        Console.WriteLine("Button Clicked");
    }

    static void Window_Delete(object obj, DeleteEventArgs args)
    {
        Application.Quit();
        args.RetVal = true;
    }

    protected void OnLocalDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }

}

Tutorial?

Hey! i've just found this project, and it appears to be much more up-to-date that the mono one. Unfortunately, I've got absolutely no clue how to use this library, and I can't find any documentation.

Is there some documentation I could review in order to get started building GUIs with this?

Exception in Gtk# callback delegate

Ubuntu 18.04 GtkSharp 3.22.24.36

Overriding Gtk.ApplicationWindow

protected override bool OnDeleteEvent(Event evnt)
{
	return base.OnDeleteEvent(evnt); <-- Exception !!!
}
Exception in Gtk# callback delegate
  Note: Applications can use GLib.ExceptionManager.UnhandledException to handle the exception.
System.ArgumentNullException: Value cannot be null.
Parameter name: ptr
  at System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer (System.IntPtr ptr, System.Type t) [0x00068] in <3833a6edf2074b959d3dab898627f0ac>:0 
  at Gtk.Widget.InternalDeleteEvent (Gdk.Event evnt) [0x00030] in <a4dd783280f04d7b947e5724c1e7ad56>:0 
  at Gtk.Widget.OnDeleteEvent (Gdk.Event evnt) [0x00000] in <a4dd783280f04d7b947e5724c1e7ad56>:0 
  at valaDevelop.ApplicationWindow.OnDeleteEvent (Gdk.Event evnt) [0x00001] in /home/wolfgang/Projects/valaDevelop/valaDevelop/ApplicationWindow.cs:179 
  at Gtk.Widget.DeleteEvent_cb (System.IntPtr inst, System.IntPtr evnt) [0x00012] in <a4dd783280f04d7b947e5724c1e7ad56>:0 
  at GLib.ExceptionManager.RaiseUnhandledException (System.Exception e, System.Boolean is_terminal) [0x00000] in <c00d5e4d00034a84be676c68138aa1a3>:0 
  at Gtk.Widget.DeleteEvent_cb (System.IntPtr inst, System.IntPtr evnt) [0x00000] in <a4dd783280f04d7b947e5724c1e7ad56>:0 
  at System.Object.wrapper_native_0x7f0613d02be0 (System.IntPtr , System.Int32 , System.IntPtr ) [0x00000] in <3833a6edf2074b959d3dab898627f0ac>:0 
  at GLib.Application.Run (System.String program_name, System.String[] args) [0x00000] in <31cd248b93444728a2070ad9ace1e0c8>:0 
  at valaDevelop.valaDevelop.Main (System.String[] args) [0x0000d] in /home/wolfgang/Projects/valaDevelop/valaDevelop/Program.cs:37

MacOS support

is MacOS supported? I installed dotnet CLI template and I get this error when try to run application:

Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'libglib-2.0-0.dll': The specified module or one of its dependencies could not be found.
 (Exception from HRESULT: 0x8007007E)
   at GLib.Marshaller.g_malloc(UIntPtr size)
   at GLib.Marshaller.StringToPtrGStrdup(String str)
   at GLib.Global.set_ProgramName(String value)
   at Gtk.Application.Init()
   at gtk_sandbox.Program.Main(String[] args) in /Users/davidnadaraia/tmp/gtk-sandbox/Program.cs:line 11

GTK+3 is already installed on my mac...

Can't use Cairo to draw a pixbuf (at the moment)

I need the gdk_set_source_pixbuf() function for something that I'm doing, but I doesn't look like a bound equivalent is available. This is pretty vital if someone wants to rendering images onto a custom widget.

Can't build from git

What are the system requirements to build with Ubuntu 18.04?
Which executable is missing?
I tried to build from git with follow error:

Feeds used:
  /home/wolfgang/.nuget/packages/
  https://api.nuget.org/v3/index.json

Alle in "/home/wolfgang/GtkSharp/tools/packages.config" aufgeführten Pakete sind bereits installiert.
Analyzing build script...
Processing build script...
Installing addins...
Compiling build script...

========================================
Init
========================================
Executing task: Init
Finished executing task: Init

========================================
Clean
========================================
Executing task: Clean
Finished executing task: Clean

========================================
Prepare
========================================
Executing task: Prepare
An error occurred when executing task 'Prepare'.
**Error: One or more errors occurred.
	.NET Core CLI: Could not locate executable.**

Installation (Ubuntu 18.04) ?

Is there a installation for GtkSharp?
I must deploy a application and don't know how to handle the "NuGet packages" ?
Don't like to have alle the assemblys in the application folder....

StyleContext.GetProperty is broken

In a derived class (e.g. Gtk.Window)

GLib.Value val = new GLib.Value();

//val is null after this
StyleContext.GetProperty("font",StateFlags.Normal,val);

//this works but is deprecated
var fd = StyleContext.GetFont(StateFlags.Normal);

The GetProperty implementation is:

public void GetProperty(string property, Gtk.StateFlags state, GLib.Value value) {
	IntPtr native_property = GLib.Marshaller.StringToPtrGStrdup (property);
	IntPtr native_value = GLib.Marshaller.StructureToPtrAlloc (value);
	gtk_style_context_get_property(Handle, native_property, (int) state, native_value);
	GLib.Marshaller.Free (native_property);
	Marshal.FreeHGlobal (native_value);
}

I think you need to Marshal.PtrToStructure before freeing native_property and then either change Glib.value to ref, or copy the values to value.

OpenGL & GLArea

@cra0zy I've been trying to get a GLArea widget to display that famous "Hello Triangle" OpenGL app. I was looking at the OpenGL.NET bindings and saw that you posted in the Issue Tracker, but you also mentioned that you switched to using OpenTK.

How far have you gotten with being able to use OpenGL and this Gtk binding together?

How to subclass a DrawingArea to implement a custom a widget

Sorry keep being a pest on the tracker here, but I'm really interested in using this library. Anyways...

When I was using the Gtk2/Mono, I wanted to use Skia as a rendering backend instead of Cairo. The SkiaSharp project has this thing called SKWidget: https://github.com/mono/SkiaSharp/blob/master/source/SkiaSharp.Views/SkiaSharp.Views.Gtk/SKWidget.cs

I was hoping to create my UI in glade, place a DrawingArea in that. Then swap it out with my SkiaDrawingArea widget. The OnExposed() virtual method no longer exists in this DrawingArea, so I've tried overriding the OnDrawn() method, but it's produced no results.

The only example I've see of subclassing a DrawingArea is here: https://github.com/GtkSharp/GtkSharp/blob/616f16d083d2c1d4c8d1643c1af5673baf1e41e4/Source/OldStuff/doc/en/Pango/Layout.xml But I also see that it's been marked in the "Old Stuff" section.

So how can I sublcass DrawingArea properly to create a custom widget?

Build fails on .NET Core 3 preview

build.sh:

...
Copying file GioSharp-api.xml to Source/Libs/GioSharp/Generated/GioSharp-api.xml
It was not possible to find any compatible framework version
The specified framework 'Microsoft.NETCore.App', version '2.0.0' was not found.
  - Check application dependencies and target a framework version installed at:
      /opt/dotnet-sdk/
  - The .NET Core Runtime and SDK can be installed from:
      https://aka.ms/dotnet-download
  - The following versions are installed:
      3.0.0-preview3-27503-5 at [/opt/dotnet-sdk/shared/Microsoft.NETCore.App]
  - Installing .NET Core prerequisites might help resolve this problem:
      https://go.microsoft.com/fwlink/?linkid=2063370
An error occurred when executing task 'Prepare'.
Error: One or more errors occurred. (.NET Core CLI: Process returned an error (exit code 150).)
	.NET Core CLI: Process returned an error (exit code 150).

I haven't been able to figure out if and where the required version is hardcoded.

Lack of documentation regarding versioning

Hey.

I can't seem to find any documentation on GtkSharp versioning, which matters, seeing as GTK+ seems to care little for backward compatibility.

It would be nice if the Readme.md answered the following:
Is GtkSharp currently only supporting Gtk3 or is there still Gtk2 support?

Whats the meaning of the release versioning numbers? How does the latest GtkSharp release version (3.22.24.36) relate to the latest gtk release (3.22.29) ?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.