Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Put mounted drives list into Glist

Function that gets list of mounted drives from '/etc/fstab' and '/etc/mtab' files and puts data in the GList object (from GLib library) that can be further used in GTK.

#include <glib.h>
#include <mntent.h>
#include <string.h>

GList * g_get_drives_list(GList * g) {
	FILE *fstab = NULL;
	struct mntent *part = NULL;
	gchar *mntp = NULL;
	
	if ((fstab = setmntent( "/etc/fstab", "r" )) != NULL) {
		while ((part = getmntent(fstab))  != NULL) {
			if((strcmp(part->mnt_type, "proc")) != 0 && (strcmp(part->mnt_type, "devpts")) != 0 
																					&& (strcmp(part->mnt_type, "swap")) != 0) {
				mntp = g_strdup(part->mnt_dir);
				g=g_list_append(g, mntp);
			}
		}
		endmntent(fstab);
	}
	
	if ((fstab = setmntent( "/etc/mtab", "r")) != NULL) {
		while ((part = getmntent(fstab)) != NULL) {
			if (part->mnt_type != NULL) {
				if((strcmp(part->mnt_type, "proc")) != 0 && (strcmp(part->mnt_type, "devpts")) != 0
						&& (strcmp(part->mnt_type, "swap")) != 0 && (strcmp(part->mnt_type, "sysfs")) != 0
						&& (strcmp(part->mnt_type, "tmpfs")) != 0 && (strcmp(part->mnt_type, "fuseblk")) != 0
						&& (strcmp(part->mnt_type, "securityfs")) != 0) {
					if((g_list_find_custom(g, part->mnt_dir, (GCompareFunc)strcmp)) == 0) {
						mntp=g_strdup(part->mnt_dir);
						g=g_list_append(g, mntp);
					}
				}
			}
		}
		endmntent(fstab);
	}
	return g;
}

A Glade 'Hello World' application

- getting started - (Using Ubuntu Linux 7.10)
1) Installed glade-3,libglade2-ruby
2) Executed glade-3

- Within glade-3 -
1) Selected from the glade-3 top menu View -> Palette appearance -> Text beside icons
2) Created a window (Toplevels)
3) Created a button on the window (Control and Display)
3) With button selected, from the properties panel I selected the Signals tab and chose 'clicked', then for the Handler -> on_button1_clicked and pressed enter.
4) With window select, from the properties panel I select the Signals tab and chose GtkWidget->delete-event, then for the Handler I typed on_quit and pressed enter.

- Generating and editing the code

-- From the command line -
1) Typed ruby-glade-create-template helloworld3.glade > helloworld3.rb

-- From the file helloworld3.rb - (see helloworld3.rb and how it relates to helloworld3.glade)
1) Implemented the initialise window routine
2) Implemented the button event handler

- Running the application
1) From the command line I typed ruby helloworld3.rb
2) stretched the window to a comfortable dimension.
3) clicked the button and observed the Window title change to 'Hello World!'

file: helloworld3.glade
#!/usr/bin/env ruby
#
# This file is generated by ruby-glade-create-template 1.1.4.
#
require 'libglade2'

class Helloworld3Glade
  include GetText

  attr :glade
  
  def initialize(path_or_data, root = nil, domain = nil, localedir = nil, flag = GladeXML::FILE)
    bindtextdomain(domain, localedir, nil, "UTF-8")
    @glade = GladeXML.new(path_or_data, root, domain, localedir, flag) {|handler| method(handler)}
    @window1 = @glade.get_widget("window1") # hand coded
    @window1.show # hand coded      
  end
  
  def on_button1_clicked(widget)
    #puts "on_button1_clicked() is not implemented yet." # removed this code by hand
    @window1.title = 'Hello World!' # hand coded  
  end
  def on_quit(widget, arg0)
    #puts "on_quit() is not implemented yet." # removed this code by hand
    Gtk.main_quit # hand coded
  end
end

# Main program
if __FILE__ == $0
  # Set values as your own application. 
  PROG_PATH = "helloworld3.glade"
  PROG_NAME = "YOUR_APPLICATION_NAME"
  Helloworld3Glade.new(PROG_PATH, nil, PROG_NAME)
  Gtk.main
end

file: helloworld3.glade
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
<!--Generated with glade3 3.4.0 on Tue Mar 18 17:39:53 2008 -->
<glade-interface>
  <widget class="GtkWindow" id="window1">
    <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
    <signal name="delete_event" handler="on_quit"/>
    <child>
      <widget class="GtkButton" id="button1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <property name="receives_default">True</property>
        <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
        <property name="label" translatable="yes">button</property>
        <property name="response_id">0</property>
        <signal name="clicked" handler="on_button1_clicked"/>
      </widget>
    </child>
  </widget>
</glade-interface>

Python - Example Simple ImageView

import pygtk; pygtk.require('2.0')
import gtk

class Image_Example(object):

	def pressButton(self, widget, data=None):
		print "Pressed"

	def delete_event(self, widget, event, data=None):
		print "delete event occured"

		return False

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("delete_event", self.delete_event)
		self.window.connect("destroy", self.destroy)
		self.window.set_border_width(10)

		self.button = gtk.Button()
		self.button.connect("clicked", self.pressButton, None)
		self.button.connect_object("clicked", gtk.Widget.destroy, self.window)

		self.image = gtk.Image()
		self.image.set_from_file("/tmp/f27.jpg")
		self.image.show()

		self.button.add(self.image)
		self.window.add(self.button)
		self.button.show()
		self.window.show()

	def main(self):
		gtk.main()


if __name__ == '__main__':

	Image_Example().main()

C - Simple Example GTK

// gcc file.c -o file.o `pkg-config --libs --cflags gtk+-2.0`

#include <gtk/gtk.h>
#include <stdlib.h>

void displayUI()
{
	GtkWidget* mainWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
	gtk_window_set_title(GTK_WINDOW(mainWindow), "GTK Simple Example");
	gtk_window_set_position(GTK_WINDOW(mainWindow), GTK_WIN_POS_CENTER_ALWAYS);

	gtk_signal_connect(GTK_OBJECT(mainWindow), "destroy", G_CALLBACK(gtk_main_quit), NULL);

	gtk_widget_show_all(mainWindow);
}

int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	displayUI();

	gtk_main();

	return EXIT_SUCCESS;
}

Python - change_color_entry

// Cambia il colore di sfondo di una gtk.Entry, ma il discorso vale anche
// per la gtk.TextView...

import gtk

def change_color_entry(entry, color):
    entry.modify_base(gk.STATE_NORMAL, gtk.gdk.color_parse(color))

GtkEditable insert handler which filters certain characters

This is an example of a signal handler for GtkEditable::insert-text which filters out certain characters as the user types.

static void
insert_filtered (GtkEditable *entry, gchar *new_text, gint new_text_length, gint *position, gpointer data)
{
        gchar *clean_text;
        gint   i, j;

        clean_text = g_strndup (new_text, new_text_length);
        for (i = 0, j = 0; i < new_text_length; i++) {
                gchar c = new_text[i];
                if (c == '\t' || c == '\n' || c == '\r' || c == '(' ||
                    c == ')'  || c == '['  || c == ']'  || c == '<' ||
                    c == '>'  || c == '+'  || c == '\'' || c == '"')
                        continue;
                clean_text[j] = c;
                j++;
        }
        clean_text[j] = '\0';

        /* Call the default handler directly and stop the emission */
        g_signal_stop_emission_by_name (G_OBJECT (entry), "insert-text");
        if (clean_text[0] != '\0') {
                GtkEditableClass *klass;
                klass = GTK_EDITABLE_GET_CLASS (entry);
                klass->insert_text (entry, clean_text, j, position);
        }

        g_free (clean_text);
}


Example usage:
...
        GtkWidget *entry;

        entry = gtk_entry_new ();
        g_signal_connect (G_OBJECT (entry), "insert-text", G_CALLBACK (insert_filtered), NULL);
...

convert a PIL image to a GTK pixbuf

free adaptation of http://slugathon.python-hosting.com/changeset/205

import gtk
import Image

def image2pixbuf(im):  
    file1 = StringIO.StringIO()  
    im.save(file1, "ppm")  
    contents = file1.getvalue()  
    file1.close()  
    loader = gtk.gdk.PixbufLoader("pnm")  
    loader.write(contents, len(contents))  
    pixbuf = loader.get_pixbuf()  
    loader.close()  
    return pixbuf  

convert a GTK pixbuf to a PIL image

import gtk
import Image

def pixbuf2Image(pb):
   width,height = pb.get_width(),pb.get_height()
   return Image.fromstring("RGB",(width,height),pb.get_pixels() )

pb = gtk.gdk.pixbuf_new_from_file( "p20050424_160333.jpg" )
im = pixbuf2Image(pb)
im.save("welldone.jpg", "JPEG",quality=80)

Using glade interface file in ruby-gnome2.

require 'gtk2'
require 'libglade2'

class SignalHandler
  def method_missing(method, *args)
    puts "#{method}: #{args}"
  end
end
sigmap = SignalHandler.new

Gtk.init
glade = GladeXML.new('hello.glade', nil, 'helloglade')
window = glade['main_window']
window.signal_connect("destroy") { Gtk.main_quit }
glade.signal_autoconnect_full do |source, target, signal, handler, data|
  source.signal_connect(signal) { sigmap.send(handler, data) }
end

window.show
Gtk.main


I did not know what file should I require. :(
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS