* samples/GtkDemo/*.cs: General fixup and cleanup; Remove some

gratuitous differences from the C version. Make comment and indent
	style consistent. Don't use "this." where not needed. Override
	OnDeleteEvent rather than connecting one's own DeleteEvent signal.

	* sample/GtkDemo/DemoApplicationWindow.cs (static
	DemoApplicationWindow): register the Gtk logo icon with
	StockManager so it shows up correctly in the toolbar.
	(AddActions): Register the radio items as radio items so they work
	right.

	* sample/GtkDemo/DemoHyperText.cs (EventAfter): handle
	link-clicking from Widget.WidgetEventAfter (as in the C version),
	rather than ButtonRelease, now that WidgetEventAfter is wrapped.

	* sample/GtkDemo/DemoImages.cs (DemoImages): use
	Gtk.Image.LoadFromResource (particularly to make the animation
	work right).
	(OnDestroyed): handle clean up (remove the timeout, etc)

	* sample/GtkDemo/DemoMain.cs (LoadStream): Fix handling of blank
	lines and whitespace to match the C version.

	* sample/GtkDemo/DemoPixbuf.cs (Expose): Use
	System.Runtime.InteropServices.Marshal.Copy() to copy
	pixbuf.Pixels to pass to DrawRgbImageDithalign, to make this more
	like the C version (and probably faster?)
	(timeout): Remove the FIXME since it seems to work now

	* sample/GtkDemo/DemoStockBrowser.cs: Simplify a bunch. Use
	reflection to get the C# names of the stock icons rather than
	trying to correctly re-mangle the ids. Display the Label with the
	accelerator underlined.

	* sample/GtkDemo/DemoTextView.cs (AttachWidgets): use
	Gtk.Image.LoadFromResource, so the image is properly loaded as an
	animation, not a static image. Don't set the combobox's "Active"
	property (for consistency with the C version).
	(InsertText): Fix miscellaneous differences with the C version.
	Remove some leftover cruft from earlier workarounds for gtk# bugs.

	* sample/GtkDemo/DemoTreeStore.cs (AddColumns): Make this more
	like the C version so the checkboxes are sensitized and hidden
	correctly on a per-row basis.

	* sample/GtkDemo/DemoUIManager.cs: Make the radio menu items work.

	* sample/GtkDemo/README: 
	* sample/GtkDemo/TODO: update

svn path=/trunk/gtk-sharp/; revision=42481
This commit is contained in:
Dan Winship 2005-04-01 21:08:14 +00:00
parent 8a88e202e1
commit 246d4e1620
25 changed files with 1608 additions and 1776 deletions

View file

@ -1,3 +1,55 @@
2005-04-01 Dan Winship <danw@novell.com>
* samples/GtkDemo/*.cs: General fixup and cleanup; Remove some
gratuitous differences from the C version. Make comment and indent
style consistent. Don't use "this." where not needed. Override
OnDeleteEvent rather than connecting one's own DeleteEvent signal.
* sample/GtkDemo/DemoApplicationWindow.cs (static
DemoApplicationWindow): register the Gtk logo icon with
StockManager so it shows up correctly in the toolbar.
(AddActions): Register the radio items as radio items so they work
right.
* sample/GtkDemo/DemoHyperText.cs (EventAfter): handle
link-clicking from Widget.WidgetEventAfter (as in the C version),
rather than ButtonRelease, now that WidgetEventAfter is wrapped.
* sample/GtkDemo/DemoImages.cs (DemoImages): use
Gtk.Image.LoadFromResource (particularly to make the animation
work right).
(OnDestroyed): handle clean up (remove the timeout, etc)
* sample/GtkDemo/DemoMain.cs (LoadStream): Fix handling of blank
lines and whitespace to match the C version.
* sample/GtkDemo/DemoPixbuf.cs (Expose): Use
System.Runtime.InteropServices.Marshal.Copy() to copy
pixbuf.Pixels to pass to DrawRgbImageDithalign, to make this more
like the C version (and probably faster?)
(timeout): Remove the FIXME since it seems to work now
* sample/GtkDemo/DemoStockBrowser.cs: Simplify a bunch. Use
reflection to get the C# names of the stock icons rather than
trying to correctly re-mangle the ids. Display the Label with the
accelerator underlined.
* sample/GtkDemo/DemoTextView.cs (AttachWidgets): use
Gtk.Image.LoadFromResource, so the image is properly loaded as an
animation, not a static image. Don't set the combobox's "Active"
property (for consistency with the C version).
(InsertText): Fix miscellaneous differences with the C version.
Remove some leftover cruft from earlier workarounds for gtk# bugs.
* sample/GtkDemo/DemoTreeStore.cs (AddColumns): Make this more
like the C version so the checkboxes are sensitized and hidden
correctly on a per-row basis.
* sample/GtkDemo/DemoUIManager.cs: Make the radio menu items work.
* sample/GtkDemo/README:
* sample/GtkDemo/TODO: update
2005-04-01 Mike Kestner <mkestner@novell.com> 2005-04-01 Mike Kestner <mkestner@novell.com>
* gtk/TreeModelFilter.custom : manually implement SetVisibleFunc and * gtk/TreeModelFilter.custom : manually implement SetVisibleFunc and

View file

@ -1,12 +1,3 @@
//
// ApplicationWindow.cs, port of appwindow.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
// John Luke <john.luke@gmail.com>
//
// Copyright (C) 2003, Ximian Inc.
/* Application main window /* Application main window
* *
* Demonstrates a typical application window, with menubar, toolbar, statusbar. * Demonstrates a typical application window, with menubar, toolbar, statusbar.
@ -20,14 +11,23 @@ namespace GtkDemo
[Demo ("Application Window", "DemoApplicationWindow.cs")] [Demo ("Application Window", "DemoApplicationWindow.cs")]
public class DemoApplicationWindow : Window public class DemoApplicationWindow : Window
{ {
// for the statusbar
const int ctx = 1;
const string fmt = "Cursor at row {0} column {1} - {2} chars in document";
int row, column, count = 0;
Statusbar statusbar; Statusbar statusbar;
VBox vbox; VBox vbox;
static DemoApplicationWindow ()
{
// Register our custom toolbar icons, for themability
Gdk.Pixbuf pixbuf = Gdk.Pixbuf.LoadFromResource ("gtk-logo-rgb.gif");
Gdk.Pixbuf transparent = pixbuf.AddAlpha (true, 0xff, 0xff, 0xff);
IconFactory factory = new IconFactory ();
factory.Add ("demo-gtk-logo", new IconSet (transparent));
factory.AddDefault ();
StockManager.Add (new StockItem ("demo-gtk-logo", "_GTK#", 0, 0, null));
}
const string uiInfo = const string uiInfo =
"<ui>" + "<ui>" +
" <menubar name='MenuBar'>" + " <menubar name='MenuBar'>" +
@ -64,13 +64,12 @@ namespace GtkDemo
" </toolbar>" + " </toolbar>" +
"</ui>"; "</ui>";
public DemoApplicationWindow () : base ("Demo Application Window") public DemoApplicationWindow () : base ("Application Window")
{ {
this.SetDefaultSize (400, 300); SetDefaultSize (200, 200);
this.DeleteEvent += new DeleteEventHandler (WindowDelete);
vbox = new VBox (false, 0); vbox = new VBox (false, 0);
this.Add (vbox); Add (vbox);
AddActions (); AddActions ();
@ -78,11 +77,30 @@ namespace GtkDemo
UpdateStatus (); UpdateStatus ();
vbox.PackEnd (statusbar, false, false, 0); vbox.PackEnd (statusbar, false, false, 0);
TextView textview = new TextView (); ScrolledWindow sw = new ScrolledWindow ();
textview.Buffer.MarkSet += new MarkSetHandler (OnMarkSet); sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vbox.PackEnd (textview, true, true, 0); sw.ShadowType = ShadowType.In;
vbox.PackEnd (sw, true, true, 0);
this.ShowAll (); TextView textview = new TextView ();
textview.Buffer.MarkSet += new MarkSetHandler (MarkSet);
sw.Add (textview);
textview.GrabFocus ();
ShowAll ();
}
enum Color {
Red,
Green,
Blue
}
enum Shape {
Square,
Rectangle,
Oval
} }
void AddActions () void AddActions ()
@ -94,64 +112,94 @@ namespace GtkDemo
new ActionEntry ("ColorMenu", null, "_Color", null, null, null), new ActionEntry ("ColorMenu", null, "_Color", null, null, null),
new ActionEntry ("ShapeMenu", null, "_Shape", null, null, null), new ActionEntry ("ShapeMenu", null, "_Shape", null, null, null),
new ActionEntry ("HelpMenu", null, "_Help", null, null, null), new ActionEntry ("HelpMenu", null, "_Help", null, null, null),
new ActionEntry ("New", Stock.New, "_New", "<control>N", "Create a new file", new EventHandler (OnActionActivated)), new ActionEntry ("New", Stock.New, "_New", "<control>N", "Create a new file", new EventHandler (ActionActivated)),
new ActionEntry ("Open", Stock.Open, "_Open", "<control>O", "Open a file", new EventHandler (OnActionActivated)), new ActionEntry ("Open", Stock.Open, "_Open", "<control>O", "Open a file", new EventHandler (ActionActivated)),
new ActionEntry ("Save", Stock.Save, "_Save", "<control>S", "Save current file", new EventHandler (OnActionActivated)), new ActionEntry ("Save", Stock.Save, "_Save", "<control>S", "Save current file", new EventHandler (ActionActivated)),
new ActionEntry ("SaveAs", Stock.SaveAs, "Save _As", null, "Save to a file", new EventHandler (OnActionActivated)), new ActionEntry ("SaveAs", Stock.SaveAs, "Save _As", null, "Save to a file", new EventHandler (ActionActivated)),
new ActionEntry ("Quit", Stock.Quit, "_Quit", "<control>Q", "Quit", new EventHandler (OnActionActivated)), new ActionEntry ("Quit", Stock.Quit, "_Quit", "<control>Q", "Quit", new EventHandler (ActionActivated)),
new ActionEntry ("About", null, "_About", "<control>A", "About", new EventHandler (OnActionActivated)), new ActionEntry ("About", null, "_About", "<control>A", "About", new EventHandler (ActionActivated)),
new ActionEntry ("Logo", "demo-gtk-logo", "Gtk#", null, "Gtk#", new EventHandler (OnActionActivated)) new ActionEntry ("Logo", "demo-gtk-logo", null, null, "Gtk#", new EventHandler (ActionActivated))
}; };
ToggleActionEntry[] toggleActions = new ToggleActionEntry[] ToggleActionEntry[] toggleActions = new ToggleActionEntry[]
{ {
new ToggleActionEntry ("Bold", Stock.Bold, "_Bold", "<control>B", "Bold", new EventHandler (OnActionActivated), false) new ToggleActionEntry ("Bold", Stock.Bold, "_Bold", "<control>B", "Bold", new EventHandler (ActionActivated), true)
}; };
ActionEntry[] colorActions = new ActionEntry[] RadioActionEntry[] colorActions = new RadioActionEntry[]
{ {
new ActionEntry ("Red", null, "_Red", "<control>R", "Blood", null), new RadioActionEntry ("Red", null, "_Red", "<control>R", "Blood", (int)Color.Red),
new ActionEntry ("Green", null, "_Green", "<control>G", "Grass", null), new RadioActionEntry ("Green", null, "_Green", "<control>G", "Grass", (int)Color.Green),
new ActionEntry ("Blue", null, "_Blue", "<control>B", "Sky", null) new RadioActionEntry ("Blue", null, "_Blue", "<control>B", "Sky", (int)Color.Blue)
}; };
ActionEntry[] shapeActions = new ActionEntry[] RadioActionEntry[] shapeActions = new RadioActionEntry[]
{ {
new ActionEntry ("Square", null, "_Square", "<control>S", "Square", null), new RadioActionEntry ("Square", null, "_Square", "<control>S", "Square", (int)Shape.Square),
new ActionEntry ("Rectangle", null, "_Rectangle", "<control>R", "Rectangle", null), new RadioActionEntry ("Rectangle", null, "_Rectangle", "<control>R", "Rectangle", (int)Shape.Rectangle),
new ActionEntry ("Oval", null, "_Oval", "<control>O", "Oval", null) new RadioActionEntry ("Oval", null, "_Oval", "<control>O", "Egg", (int)Shape.Oval)
}; };
ActionGroup group = new ActionGroup ("group"); ActionGroup group = new ActionGroup ("AppWindowActions");
group.Add (actions); group.Add (actions);
group.Add (toggleActions); group.Add (toggleActions);
group.Add (colorActions); group.Add (colorActions, (int)Color.Red, new ChangedHandler (RadioActionActivated));
group.Add (shapeActions); group.Add (shapeActions, (int)Shape.Square, new ChangedHandler (RadioActionActivated));
UIManager uim = new UIManager (); UIManager uim = new UIManager ();
uim.InsertActionGroup (group, (int) uim.NewMergeId ()); uim.InsertActionGroup (group, 0);
uim.AddWidget += new AddWidgetHandler (OnAddWidget); uim.AddWidget += new AddWidgetHandler (AddWidget);
uim.AddUiFromString (uiInfo); uim.AddUiFromString (uiInfo);
AddAccelGroup (uim.AccelGroup);
} }
private void OnActionActivated (object sender, EventArgs a) private void ActionActivated (object sender, EventArgs a)
{ {
Action action = sender as Action; Action action = sender as Action;
MessageDialog md;
using (MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "You activated action: {0}", action.Name)) { md = new MessageDialog (this, DialogFlags.DestroyWithParent,
MessageType.Info, ButtonsType.Close,
"You activated action: \"{0}\" of type \"{1}\"",
action.Name, action.GetType ());
md.Run (); md.Run ();
md.Hide (); md.Destroy ();
}
} }
private void WindowDelete (object o, DeleteEventArgs args) private void RadioActionActivated (object sender, ChangedArgs args)
{ {
this.Hide (); RadioAction action = args.Current;
this.Destroy (); MessageDialog md;
args.RetVal = true;
if (action.Active) {
md = new MessageDialog (this, DialogFlags.DestroyWithParent,
MessageType.Info, ButtonsType.Close,
"You activated radio action: \"{0}\" of type \"{1}\".\nCurrent value: {2}",
action.Name, action.GetType (),
args.Current.Value);
md.Run ();
md.Destroy ();
}
} }
void OnMarkSet (object o, MarkSetArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{
Destroy ();
return true;
}
protected override bool OnWindowStateEvent (Gdk.EventWindowState evt)
{
if ((evt.ChangedMask & (Gdk.WindowState.Maximized | Gdk.WindowState.Fullscreen)) != 0)
statusbar.HasResizeGrip = (evt.NewWindowState & (Gdk.WindowState.Maximized | Gdk.WindowState.Fullscreen)) == 0;
return false;
}
const string fmt = "Cursor at row {0} column {1} - {2} chars in document";
int row, column, count = 0;
void MarkSet (object o, MarkSetArgs args)
{ {
TextIter iter = args.Location; TextIter iter = args.Location;
row = iter.Line + 1; row = iter.Line + 1;
@ -162,15 +210,14 @@ namespace GtkDemo
void UpdateStatus () void UpdateStatus ()
{ {
statusbar.Pop (ctx); statusbar.Pop (0);
statusbar.Push (ctx, String.Format (fmt, row, column, count)); statusbar.Push (0, String.Format (fmt, row, column, count));
} }
void OnAddWidget (object sender, AddWidgetArgs a) void AddWidget (object sender, AddWidgetArgs a)
{ {
a.Widget.Show (); a.Widget.Show ();
vbox.PackStart (a.Widget, false, true, 0); vbox.PackStart (a.Widget, false, true, 0);
} }
} }
} }

View file

@ -27,9 +27,7 @@ namespace GtkDemo
} }
public string Parent { public string Parent {
get { get { return parent; }
return parent;
}
} }
} }
} }

View file

@ -1,11 +1,3 @@
//
// DemoButtonBox.cs, port of buttonbox.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Button Boxes /* Button Boxes
* *
* The Button Box widgets are used to arrange buttons with padding. * The Button Box widgets are used to arrange buttons with padding.
@ -21,56 +13,51 @@ namespace GtkDemo
{ {
public DemoButtonBox () : base ("Button Boxes") public DemoButtonBox () : base ("Button Boxes")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete); BorderWidth = 10;
this.BorderWidth = 10;
// Add Vertical Box // Add Vertical Box
VBox mainVbox = new VBox (false,0); VBox mainVbox = new VBox (false,0);
this.Add (mainVbox); Add (mainVbox);
// Add Horizontal Frame // Add Horizontal Frame
Frame horizontalFrame = new Frame ("Horizontal Button Boxes"); Frame horizontalFrame = new Frame ("Horizontal Button Boxes");
mainVbox.PackStart (horizontalFrame); mainVbox.PackStart (horizontalFrame, true, true, 10);
VBox vbox = new VBox (false, 0); VBox vbox = new VBox (false, 0);
vbox.BorderWidth = 10; vbox.BorderWidth = 10;
horizontalFrame.Add (vbox); horizontalFrame.Add (vbox);
// Pack Buttons // Pack Buttons
vbox.PackStart(CreateButtonBox (true, "Spread (spacing 40)", 40, 85, 20, ButtonBoxStyle.Spread)); vbox.PackStart (CreateButtonBox (true, "Spread", 40, ButtonBoxStyle.Spread), true, true, 0);
vbox.PackStart(CreateButtonBox (true, "Edge (spacing 30)", 30, 85, 20, ButtonBoxStyle.Edge)); vbox.PackStart (CreateButtonBox (true, "Edge", 40, ButtonBoxStyle.Edge), true, true, 5);
vbox.PackStart(CreateButtonBox (true, "Start (spacing 20)", 20, 85, 20, ButtonBoxStyle.Start)); vbox.PackStart (CreateButtonBox (true, "Start", 40, ButtonBoxStyle.Start), true, true, 5);
vbox.PackStart(CreateButtonBox (true, "End (spacing 10)", 10, 85, 20, ButtonBoxStyle.End)); vbox.PackStart (CreateButtonBox (true, "End", 40, ButtonBoxStyle.End), true, true, 5);
// Add Vertical Frame // Add Vertical Frame
Frame verticalFrame = new Frame ("Vertical Button Boxes"); Frame verticalFrame = new Frame ("Vertical Button Boxes");
mainVbox.PackStart (verticalFrame); mainVbox.PackStart (verticalFrame, true, true, 10);
HBox hbox = new HBox (false, 0); HBox hbox = new HBox (false, 0);
hbox.BorderWidth = 10; hbox.BorderWidth = 10;
verticalFrame.Add (hbox); verticalFrame.Add (hbox);
// Pack Buttons // Pack Buttons
hbox.PackStart(CreateButtonBox (false, "Spread (spacing 5)", 5, 85, 20, ButtonBoxStyle.Spread)); hbox.PackStart(CreateButtonBox (false, "Spread", 30, ButtonBoxStyle.Spread), true, true, 0);
hbox.PackStart(CreateButtonBox (false, "Edge (spacing 30)", 30, 85, 20, ButtonBoxStyle.Edge)); hbox.PackStart(CreateButtonBox (false, "Edge", 30, ButtonBoxStyle.Edge), true, true, 5);
hbox.PackStart(CreateButtonBox (false, "Start (spacing 20)", 20, 85, 20, ButtonBoxStyle.Start)); hbox.PackStart(CreateButtonBox (false, "Start", 30, ButtonBoxStyle.Start), true, true, 5);
hbox.PackStart(CreateButtonBox (false, "End (spacing 20)", 20, 85, 20, ButtonBoxStyle.End)); hbox.PackStart(CreateButtonBox (false, "End", 30, ButtonBoxStyle.End), true, true, 5);
this.ShowAll (); ShowAll ();
} }
// Create a Button Box with the specified parameters // Create a Button Box with the specified parameters
private Frame CreateButtonBox (bool horizontal, string title, int spacing, int childW , int childH , ButtonBoxStyle layout) private Frame CreateButtonBox (bool horizontal, string title, int spacing, ButtonBoxStyle layout)
{ {
Frame frame = new Frame (title); Frame frame = new Frame (title);
Gtk.ButtonBox bbox ; Gtk.ButtonBox bbox ;
if (horizontal == true) if (horizontal)
{
bbox = new Gtk.HButtonBox (); bbox = new Gtk.HButtonBox ();
}
else else
{
bbox = new Gtk.VButtonBox (); bbox = new Gtk.VButtonBox ();
}
bbox.BorderWidth = 5; bbox.BorderWidth = 5;
frame.Add (bbox); frame.Add (bbox);
@ -79,21 +66,17 @@ namespace GtkDemo
bbox.Layout = layout; bbox.Layout = layout;
bbox.Spacing = spacing; bbox.Spacing = spacing;
Button buttonOk = new Button (Stock.Ok); bbox.Add (new Button (Stock.Ok));
bbox.Add (buttonOk); bbox.Add (new Button (Stock.Cancel));
Button buttonCancel = new Button (Stock.Cancel); bbox.Add (new Button (Stock.Help));
bbox.Add (buttonCancel);
Button buttonHelp = new Button (Stock.Help);
bbox.Add (buttonHelp);
return frame; return frame;
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
} }
} }

View file

@ -2,6 +2,9 @@
* *
* GtkClipboard is used for clipboard handling. This demo shows how to * GtkClipboard is used for clipboard handling. This demo shows how to
* copy and paste text to and from the clipboard. * copy and paste text to and from the clipboard.
*
* This is actually from gtk+ 2.6's gtk-demo, but doesn't use any 2.6
* functionality
*/ */
using System; using System;
using Gtk; using Gtk;
@ -15,8 +18,6 @@ namespace GtkDemo
public DemoClipboard () : base ("Demo Clipboard") public DemoClipboard () : base ("Demo Clipboard")
{ {
this.DeleteEvent += new DeleteEventHandler (OnDelete);
VBox vbox = new VBox (); VBox vbox = new VBox ();
vbox.BorderWidth = 8; vbox.BorderWidth = 8;
Label copyLabel = new Label ("\"Copy\" will copy the text\nin the entry to the clipboard"); Label copyLabel = new Label ("\"Copy\" will copy the text\nin the entry to the clipboard");
@ -27,8 +28,8 @@ namespace GtkDemo
vbox.PackStart (pasteLabel, false, false, 0); vbox.PackStart (pasteLabel, false, false, 0);
vbox.PackStart (CreatePasteBox (), false, false, 0); vbox.PackStart (CreatePasteBox (), false, false, 0);
this.Add (vbox); Add (vbox);
this.ShowAll (); ShowAll ();
} }
HBox CreateCopyBox () HBox CreateCopyBox ()
@ -37,7 +38,7 @@ namespace GtkDemo
hbox.BorderWidth = 8; hbox.BorderWidth = 8;
copyEntry = new Entry (); copyEntry = new Entry ();
Button copyButton = new Button (Stock.Copy); Button copyButton = new Button (Stock.Copy);
copyButton.Clicked += new EventHandler (OnCopyClicked); copyButton.Clicked += new EventHandler (CopyClicked);
hbox.PackStart (copyEntry, true, true, 0); hbox.PackStart (copyEntry, true, true, 0);
hbox.PackStart (copyButton, false, false, 0); hbox.PackStart (copyButton, false, false, 0);
return hbox; return hbox;
@ -49,30 +50,33 @@ namespace GtkDemo
hbox.BorderWidth = 8; hbox.BorderWidth = 8;
pasteEntry = new Entry (); pasteEntry = new Entry ();
Button pasteButton = new Button (Stock.Paste); Button pasteButton = new Button (Stock.Paste);
pasteButton.Clicked += new EventHandler (OnPasteClicked); pasteButton.Clicked += new EventHandler (PasteClicked);
hbox.PackStart (pasteEntry, true, true, 0); hbox.PackStart (pasteEntry, true, true, 0);
hbox.PackStart (pasteButton, false, false, 0); hbox.PackStart (pasteButton, false, false, 0);
return hbox; return hbox;
} }
void OnCopyClicked (object sender, EventArgs a) void CopyClicked (object obj, EventArgs args)
{ {
Clipboard clipboard = copyEntry.GetClipboard (Gdk.Selection.Clipboard); Clipboard clipboard = copyEntry.GetClipboard (Gdk.Selection.Clipboard);
clipboard.SetText (copyEntry.Text); clipboard.SetText (copyEntry.Text);
} }
void OnPasteClicked (object sender, EventArgs a) void PasteClicked (object obj, EventArgs args)
{ {
Clipboard clipboard = pasteEntry.GetClipboard (Gdk.Selection.Clipboard); Clipboard clipboard = pasteEntry.GetClipboard (Gdk.Selection.Clipboard);
pasteEntry.Text = clipboard.WaitForText (); clipboard.RequestText (new ClipboardTextReceivedFunc (PasteReceived));
} }
void OnDelete (object sender, DeleteEventArgs a) void PasteReceived (Clipboard clipboard, string text)
{ {
this.Hide (); pasteEntry.Text = text;
this.Destroy ();
a.RetVal = true;
}
}
} }
protected override bool OnDeleteEvent (Gdk.Event evt)
{
Destroy ();
return true;
}
}
}

View file

@ -1,10 +1,3 @@
//
// DemoColorSelection.cs, port of colorsel.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Color Selector /* Color Selector
* *
* GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is * GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is
@ -26,11 +19,10 @@ namespace GtkDemo
public DemoColorSelection () : base ("Color Selection") public DemoColorSelection () : base ("Color Selection")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete); BorderWidth = 8;
this.BorderWidth = 8;
VBox vbox = new VBox (false,8); VBox vbox = new VBox (false,8);
vbox.BorderWidth = 8; vbox.BorderWidth = 8;
this.Add (vbox); Add (vbox);
// Create the color swatch area // Create the color swatch area
Frame frame = new Frame (); Frame frame = new Frame ();
@ -52,14 +44,13 @@ namespace GtkDemo
alignment.Add (button); alignment.Add (button);
vbox.PackStart (alignment); vbox.PackStart (alignment);
this.ShowAll (); ShowAll ();
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
// Expose callback for the drawing area // Expose callback for the drawing area
@ -84,8 +75,7 @@ namespace GtkDemo
colorSelectionDialog.ColorSelection.CurrentColor = color; colorSelectionDialog.ColorSelection.CurrentColor = color;
colorSelectionDialog.ColorSelection.HasPalette = true; colorSelectionDialog.ColorSelection.HasPalette = true;
if (colorSelectionDialog.Run () == (int) ResponseType.Ok) if (colorSelectionDialog.Run () == (int) ResponseType.Ok) {
{
Gdk.Color selected = colorSelectionDialog.ColorSelection.CurrentColor; Gdk.Color selected = colorSelectionDialog.ColorSelection.CurrentColor;
drawingArea.ModifyBg (StateType.Normal, selected); drawingArea.ModifyBg (StateType.Normal, selected);
} }

View file

@ -1,10 +1,3 @@
//
// DemoDialog.cs, port of dialog.c from gtk-demo
//
// Author Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Dialog and Message Boxes /* Dialog and Message Boxes
* *
* Dialog widgets are used to pop up a transient window for user feedback. * Dialog widgets are used to pop up a transient window for user feedback.
@ -23,11 +16,10 @@ namespace GtkDemo
public DemoDialog () : base ("Dialogs") public DemoDialog () : base ("Dialogs")
{ {
this.DeleteEvent += new DeleteEventHandler(WindowDelete); BorderWidth = 8;
this.BorderWidth = 8;
Frame frame = new Frame ("Dialogs"); Frame frame = new Frame ("Dialogs");
this.Add (frame); Add (frame);
VBox vbox = new VBox (false, 8); VBox vbox = new VBox (false, 8);
vbox.BorderWidth = 8; vbox.BorderWidth = 8;
@ -39,7 +31,7 @@ namespace GtkDemo
Button button = new Button ("_Message Dialog"); Button button = new Button ("_Message Dialog");
button.Clicked += new EventHandler (MessageDialogClicked); button.Clicked += new EventHandler (MessageDialogClicked);
hbox.PackStart (button, false, false, 0); hbox.PackStart (button, false, false, 0);
vbox.PackStart (new HSeparator()); vbox.PackStart (new HSeparator(), false, false, 0);
// Interactive dialog // Interactive dialog
hbox = new HBox (false, 8); hbox = new HBox (false, 8);
@ -54,7 +46,7 @@ namespace GtkDemo
Table table = new Table (2, 2, false); Table table = new Table (2, 2, false);
table.RowSpacing = 4; table.RowSpacing = 4;
table.ColumnSpacing = 4; table.ColumnSpacing = 4;
hbox.PackStart (table); hbox.PackStart (table, false, false, 0);
Label label = new Label ("_Entry1"); Label label = new Label ("_Entry1");
table.Attach (label, 0, 1, 0, 1); table.Attach (label, 0, 1, 0, 1);
@ -68,14 +60,13 @@ namespace GtkDemo
table.Attach (entry2, 1, 2, 1, 2); table.Attach (entry2, 1, 2, 1, 2);
label.MnemonicWidget = entry2; label.MnemonicWidget = entry2;
this.ShowAll (); ShowAll ();
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
private int i = 1; private int i = 1;
@ -85,7 +76,7 @@ namespace GtkDemo
DialogFlags.Modal | DialogFlags.DestroyWithParent, DialogFlags.Modal | DialogFlags.DestroyWithParent,
MessageType.Info, MessageType.Info,
ButtonsType.Ok, ButtonsType.Ok,
"This message box has been popped up the following\n number of times:\n\n {0:D} ", "This message box has been popped up the following\nnumber of times:\n\n {0}",
i)) { i)) {
dialog.Run (); dialog.Run ();
dialog.Hide (); dialog.Hide ();
@ -96,16 +87,22 @@ namespace GtkDemo
private void InteractiveDialogClicked (object o, EventArgs args) private void InteractiveDialogClicked (object o, EventArgs args)
{ {
Dialog dialog = new Dialog ("Interactive Dialog", this, DialogFlags.Modal | DialogFlags.DestroyWithParent, Gtk.Stock.Ok, ResponseType.Ok, "_Non-stock Button", ResponseType.Cancel); Dialog dialog = new Dialog ("Interactive Dialog", this,
DialogFlags.Modal | DialogFlags.DestroyWithParent,
Gtk.Stock.Ok, ResponseType.Ok,
"_Non-stock Button", ResponseType.Cancel);
HBox hbox = new HBox (false, 8); HBox hbox = new HBox (false, 8);
hbox.BorderWidth = 8; hbox.BorderWidth = 8;
dialog.VBox.PackStart (hbox, false, false, 0); dialog.VBox.PackStart (hbox, false, false, 0);
Image stock = new Image (Stock.DialogQuestion, IconSize.Dialog);
hbox.PackStart (stock, false, false, 0);
Table table = new Table (2, 2, false); Table table = new Table (2, 2, false);
table.RowSpacing = 4; table.RowSpacing = 4;
table.ColumnSpacing = 4; table.ColumnSpacing = 4;
hbox.PackStart (table, false, false, 0); hbox.PackStart (table, true, true, 0);
Label label = new Label ("_Entry1"); Label label = new Label ("_Entry1");
table.Attach (label, 0, 1, 0, 1); table.Attach (label, 0, 1, 0, 1);
@ -134,4 +131,3 @@ namespace GtkDemo
} }
} }
} }

View file

@ -1,12 +1,3 @@
//
// DemoDrawingArea.cs, port of drawingarea.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
// Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (C) 2003, Ximian Inc.
//
/* Drawing Area /* Drawing Area
* *
* GtkDrawingArea is a blank area where you can draw custom displays * GtkDrawingArea is a blank area where you can draw custom displays
@ -31,109 +22,101 @@ namespace GtkDemo
[Demo ("Drawing Area", "DemoDrawingArea.cs")] [Demo ("Drawing Area", "DemoDrawingArea.cs")]
public class DemoDrawingArea : Gtk.Window public class DemoDrawingArea : Gtk.Window
{ {
private static Pixmap pixmap = null; private Pixmap pixmap = null;
private static DrawingArea drawingArea;
private static DrawingArea drawingArea1;
public DemoDrawingArea () : base ("Drawing Area") public DemoDrawingArea () : base ("Drawing Area")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete); BorderWidth = 8;
this.BorderWidth = 8;
VBox vbox = new VBox (false, 8); VBox vbox = new VBox (false, 8);
vbox.BorderWidth = 8; vbox.BorderWidth = 8;
this.Add (vbox); Add (vbox);
// Create the checkerboard area // Create the checkerboard area
Label label = new Label (); Label label = new Label ("<u>Checkerboard pattern</u>");
label.Markup = "<u>Checkerboard pattern</u>"; label.UseMarkup = true;
vbox.PackStart (label, false, false, 0); vbox.PackStart (label, false, false, 0);
Frame frame = new Frame (); Frame frame = new Frame ();
frame.ShadowType = ShadowType.In; frame.ShadowType = ShadowType.In;
vbox.PackStart (frame, true, true, 0); vbox.PackStart (frame, true, true, 0);
drawingArea = new DrawingArea (); DrawingArea da = new DrawingArea ();
// set a minimum size // set a minimum size
drawingArea.SetSizeRequest (100,100); da.SetSizeRequest (100,100);
frame.Add (drawingArea); frame.Add (da);
drawingArea.ExposeEvent += new ExposeEventHandler (CheckerboardExpose); da.ExposeEvent += new ExposeEventHandler (CheckerboardExpose);
// Create the scribble area // Create the scribble area
Label label1 = new Label ("<u>Scribble area</u>"); label = new Label ("<u>Scribble area</u>");
label1.UseMarkup = true; label.UseMarkup = true;
vbox.PackStart (label1, false, false, 0); vbox.PackStart (label, false, false, 0);
Frame frame1 = new Frame (); frame = new Frame ();
frame1.ShadowType = ShadowType.In; frame.ShadowType = ShadowType.In;
vbox.PackStart (frame1, true, true, 0); vbox.PackStart (frame, true, true, 0);
da = new DrawingArea ();
// set a minimum size
da.SetSizeRequest (100, 100);
frame.Add (da);
drawingArea1 = new DrawingArea ();
// set a minimun size
drawingArea1.SetSizeRequest (100, 100);
frame1.Add (drawingArea1);
// Signals used to handle backing pixmap // Signals used to handle backing pixmap
drawingArea1.ExposeEvent += new ExposeEventHandler (ScribbleExpose); da.ExposeEvent += new ExposeEventHandler (ScribbleExpose);
drawingArea1.ConfigureEvent += new ConfigureEventHandler (ScribbleConfigure); da.ConfigureEvent += new ConfigureEventHandler (ScribbleConfigure);
// Event signals // Event signals
drawingArea1.MotionNotifyEvent += new MotionNotifyEventHandler (ScribbleMotionNotify); da.MotionNotifyEvent += new MotionNotifyEventHandler (ScribbleMotionNotify);
drawingArea1.ButtonPressEvent += new ButtonPressEventHandler (ScribbleButtonPress); da.ButtonPressEvent += new ButtonPressEventHandler (ScribbleButtonPress);
// Ask to receive events the drawing area doesn't normally // Ask to receive events the drawing area doesn't normally
// subscribe to // subscribe to
da.Events |= EventMask.LeaveNotifyMask | EventMask.ButtonPressMask |
drawingArea1.Events = EventMask.LeaveNotifyMask | EventMask.ButtonPressMask |
EventMask.PointerMotionMask | EventMask.PointerMotionHintMask; EventMask.PointerMotionMask | EventMask.PointerMotionHintMask;
this.ShowAll (); ShowAll ();
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
private void CheckerboardExpose (object o, ExposeEventArgs args) private void CheckerboardExpose (object o, ExposeEventArgs args)
{ {
// Defining the size of the Checks
const int CheckSize = 10; const int CheckSize = 10;
const int Spacing = 2; const int Spacing = 2;
// Defining the color of the Checks DrawingArea da = o as DrawingArea;
// It would be a bit more efficient to keep these
// GC's around instead of recreating on each expose, but
// this is the lazy/slow way.
Gdk.GC gc1 = new Gdk.GC (da.GdkWindow);
gc1.RgbFgColor = new Gdk.Color (117, 0, 117);
Gdk.GC gc2 = new Gdk.GC (da.GdkWindow);
gc2.RgbFgColor = new Gdk.Color (255, 255, 255);
int i, j, xcount, ycount; int i, j, xcount, ycount;
Gdk.GC gc, gc1, gc2; Gdk.Rectangle alloc = da.Allocation;
Gdk.Color color = new Gdk.Color ();
EventExpose eventExpose = args.Event;
Gdk.Window window = eventExpose.Window;
gc1 = new Gdk.GC (window);
color.Red = 30000;
color.Green = 0;
color.Blue = 30000;
gc1.RgbFgColor = color;
gc2 = new Gdk.GC (window);
color.Red = 65535;
color.Green = 65535;
color.Blue = 65535;
gc2.RgbFgColor = color;
// Start redrawing the Checkerboard // Start redrawing the Checkerboard
xcount = 0; xcount = 0;
i = Spacing; i = Spacing;
while (i < drawingArea.Allocation.Width){ while (i < alloc.Width) {
j = Spacing; j = Spacing;
ycount = xcount % 2; // start with even/odd depending on row ycount = xcount % 2; // start with even/odd depending on row
while (j < drawingArea.Allocation.Height){ while (j < alloc.Height) {
gc = new Gdk.GC (window); Gdk.GC gc;
if (ycount % 2 != 0){ if (ycount % 2 != 0)
gc = gc1;} gc = gc1;
else{ else
gc = gc2;} gc = gc2;
window.DrawRectangle(gc, true, i, j, CheckSize, CheckSize); da.GdkWindow.DrawRectangle (gc, true, i, j,
CheckSize, CheckSize);
j += CheckSize + Spacing; j += CheckSize + Spacing;
++ycount; ++ycount;
@ -141,6 +124,7 @@ namespace GtkDemo
i += CheckSize + Spacing; i += CheckSize + Spacing;
++xcount; ++xcount;
} }
// return true because we've handled this event, so no // return true because we've handled this event, so no
// further processing is required. // further processing is required.
args.RetVal = true; args.RetVal = true;
@ -148,35 +132,32 @@ namespace GtkDemo
private void ScribbleExpose (object o, ExposeEventArgs args) private void ScribbleExpose (object o, ExposeEventArgs args)
{ {
Widget widget = o as Widget;
Gdk.Window window = widget.GdkWindow;
Rectangle area = args.Event.Area;
// We use the "ForegroundGC" for the widget since it already exists, // We use the "ForegroundGC" for the widget since it already exists,
// but honestly any GC would work. The only thing to worry about // but honestly any GC would work. The only thing to worry about
// is whether the GC has an inappropriate clip region set. // is whether the GC has an inappropriate clip region set.
window.DrawDrawable (widget.Style.ForegroundGC (StateType.Normal),
EventExpose eventExpose = args.Event;
Gdk.Window window = eventExpose.Window;
Rectangle area = eventExpose.Area;
window.DrawDrawable (drawingArea1.Style.ForegroundGC(StateType.Normal),
pixmap, pixmap,
area.X, area.Y, area.X, area.Y,
area.X, area.Y, area.X, area.Y,
area.Width, area.Height); area.Width, area.Height);
args.RetVal = false;
} }
// Create a new pixmap of the appropriate size to store our scribbles // Create a new pixmap of the appropriate size to store our scribbles
private void ScribbleConfigure (object o, ConfigureEventArgs args) private void ScribbleConfigure (object o, ConfigureEventArgs args)
{ {
EventConfigure eventConfigure = args.Event; Widget widget = o as Widget;
Gdk.Window window = eventConfigure.Window; Rectangle allocation = widget.Allocation;
Rectangle allocation = drawingArea1.Allocation;
pixmap = new Pixmap (window, pixmap = new Pixmap (widget.GdkWindow, allocation.Width, allocation.Height, -1);
allocation.Width,
allocation.Height,
-1);
// Initialize the pixmap to white // Initialize the pixmap to white
pixmap.DrawRectangle (drawingArea1.Style.WhiteGC, true, 0, 0, pixmap.DrawRectangle (widget.Style.WhiteGC, true, 0, 0,
allocation.Width, allocation.Height); allocation.Width, allocation.Height);
// We've handled the configure event, no need for further processing. // We've handled the configure event, no need for further processing.
args.RetVal = true; args.RetVal = true;
} }
@ -184,59 +165,52 @@ namespace GtkDemo
private void ScribbleMotionNotify (object o, MotionNotifyEventArgs args) private void ScribbleMotionNotify (object o, MotionNotifyEventArgs args)
{ {
// paranoia check, in case we haven't gotten a configure event
if (pixmap == null)
return;
// This call is very important; it requests the next motion event. // This call is very important; it requests the next motion event.
// If you don't call Window.GetPointer() you'll only get // If you don't call Window.GetPointer() you'll only get a single
// a single motion event. The reason is that we specified // motion event. The reason is that we specified PointerMotionHintMask
// PointerMotionHintMask in drawingArea1.Events. // in widget.Events. If we hadn't specified that, we could just use
// If we hadn't specified that, we could just use ExposeEvent.x, ExposeEvent.y // args.Event.X, args.Event.Y as the pointer location. But we'd also
// as the pointer location. But we'd also get deluged in events. // get deluged in events. By requesting the next event as we handle
// By requesting the next event as we handle the current one, // the current one, we avoid getting a huge number of events faster
// we avoid getting a huge number of events faster than we // than we can cope.
// can cope.
int x, y; int x, y;
ModifierType state; ModifierType state;
EventMotion ev = args.Event; args.Event.Window.GetPointer (out x, out y, out state);
Gdk.Window window = ev.Window;
if (ev.IsHint) { if ((state & ModifierType.Button1Mask) != 0)
ModifierType s; DrawBrush (o as Widget, x, y);
window.GetPointer (out x, out y, out s);
state = s;
} else {
x = (int) ev.X;
y = (int) ev.Y;
state = (ModifierType) ev.State;
}
if ((state & ModifierType.Button1Mask) != 0 && pixmap != null)
DrawBrush (x, y);
// We've handled it, stop processing // We've handled it, stop processing
args.RetVal = true; args.RetVal = true;
} }
// Draw a rectangle on the screen // Draw a rectangle on the screen
static void DrawBrush (double x, double y) private void DrawBrush (Widget widget, double x, double y)
{ {
Rectangle update_rect = new Rectangle (); Rectangle update_rect = new Rectangle ((int)x - 3, (int)y - 3, 6, 6);
update_rect.X = (int) x - 3;
update_rect.Y = (int) y - 3;
update_rect.Width = 6;
update_rect.Height = 6;
// Paint to the pixmap, where we store our state // Paint to the pixmap, where we store our state
pixmap.DrawRectangle (drawingArea1.Style.BlackGC, true, pixmap.DrawRectangle (widget.Style.BlackGC, true,
update_rect.X, update_rect.Y, update_rect.X, update_rect.Y,
update_rect.Width, update_rect.Height); update_rect.Width, update_rect.Height);
drawingArea1.QueueDrawArea (update_rect.X, update_rect.Y, widget.GdkWindow.InvalidateRect (update_rect, false);
update_rect.Width, update_rect.Height);
} }
private void ScribbleButtonPress (object o, ButtonPressEventArgs args) private void ScribbleButtonPress (object o, ButtonPressEventArgs args)
{ {
// paranoia check, in case we haven't gotten a configure event
if (pixmap == null)
return;
EventButton ev = args.Event; EventButton ev = args.Event;
if (ev.Button == 1 && pixmap != null) if (ev.Button == 1)
DrawBrush (ev.X, ev.Y); DrawBrush (o as Widget, ev.X, ev.Y);
// We've handled the event, stop processing // We've handled the event, stop processing
args.RetVal = true; args.RetVal = true;
} }

View file

@ -1,11 +1,3 @@
//
// DemoEditableCells.cs, port of appwindow.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Tree View/Editable Cells /* Tree View/Editable Cells
* *
* This demo demonstrates the use of editable cells in a Gtk.TreeView. If * This demo demonstrates the use of editable cells in a Gtk.TreeView. If
@ -27,25 +19,29 @@ namespace GtkDemo
private TreeView treeView; private TreeView treeView;
private ArrayList articles; private ArrayList articles;
public DemoEditableCells () : base ("Color Selection") public DemoEditableCells () : base ("Shopping list")
{ {
this.SetDefaultSize (320, 200); SetDefaultSize (320, 200);
this.DeleteEvent += new DeleteEventHandler (WindowDelete); BorderWidth = 5;
VBox vbox = new VBox (false, 5); VBox vbox = new VBox (false, 5);
this.Add (vbox); Add (vbox);
vbox.PackStart (new Label ("Shopping list (you can edit the cells!)"), false, false, 0); vbox.PackStart (new Label ("Shopping list (you can edit the cells!)"), false, false, 0);
ScrolledWindow scrolledWindow = new ScrolledWindow (null, null); ScrolledWindow scrolledWindow = new ScrolledWindow ();
scrolledWindow.ShadowType = ShadowType.In; scrolledWindow.ShadowType = ShadowType.EtchedIn;
scrolledWindow.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); scrolledWindow.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vbox.PackStart (scrolledWindow); vbox.PackStart (scrolledWindow, true, true, 0);
// create model
store = CreateModel ();
// create tree view // create tree view
treeView = new TreeView (); treeView = new TreeView (store);
CreateModel (); treeView.RulesHint = true;
treeView.Model = store ; treeView.Selection.Mode = SelectionMode.Single;
AddColumns (); AddColumns ();
scrolledWindow.Add (treeView); scrolledWindow.Add (treeView);
@ -61,17 +57,17 @@ namespace GtkDemo
button.Clicked += new EventHandler (RemoveItem); button.Clicked += new EventHandler (RemoveItem);
hbox.PackStart (button, true, true, 0); hbox.PackStart (button, true, true, 0);
this.ShowAll (); ShowAll ();
} }
private void AddColumns () private void AddColumns ()
{ {
CellRendererText renderer; CellRendererText renderer;
// number column
renderer = new CellRendererText (); renderer = new CellRendererText ();
renderer.Edited += new EditedHandler (NumberCellEdited); renderer.Edited += new EditedHandler (NumberCellEdited);
renderer.Editable = true; renderer.Editable = true;
// renderer.Data ("column", (int) Column.Number);
treeView.AppendColumn ("Number", renderer, treeView.AppendColumn ("Number", renderer,
"text", (int) Column.Number); "text", (int) Column.Number);
@ -79,89 +75,88 @@ namespace GtkDemo
renderer = new CellRendererText (); renderer = new CellRendererText ();
renderer.Edited += new EditedHandler (TextCellEdited); renderer.Edited += new EditedHandler (TextCellEdited);
renderer.Editable = true; renderer.Editable = true;
// renderer.Data ("column", (int) Column.Product);
treeView.AppendColumn ("Product", renderer , treeView.AppendColumn ("Product", renderer ,
"text", (int) Column.Product); "text", (int) Column.Product);
} }
private void CreateModel () private ListStore CreateModel ()
{ {
// create array // create array
articles = new ArrayList (); articles = new ArrayList ();
AddItems (); AddItems ();
// create list store // create list store
store = new ListStore (typeof (int), typeof (string), typeof (bool)); ListStore store = new ListStore (typeof (int), typeof (string), typeof (bool));
// add items // add items
foreach (Item item in articles) foreach (Item item in articles)
store.AppendValues (item.Number, item.Product, item.Editable); store.AppendValues (item.Number, item.Product);
return store;
} }
private void AddItems () private void AddItems ()
{ {
Item foo; Item foo;
foo = new Item (3, "bottles of coke", true); foo = new Item (3, "bottles of coke");
articles.Add (foo); articles.Add (foo);
foo = new Item (5, "packages of noodles", true); foo = new Item (5, "packages of noodles");
articles.Add (foo); articles.Add (foo);
foo = new Item (2, "packages of chocolate chip cookies", true); foo = new Item (2, "packages of chocolate chip cookies");
articles.Add (foo); articles.Add (foo);
foo = new Item (1, "can of vanilla ice cream", true); foo = new Item (1, "can vanilla ice cream");
articles.Add (foo); articles.Add (foo);
foo = new Item (6, "eggs", true); foo = new Item (6, "eggs");
articles.Add (foo); articles.Add (foo);
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
private void NumberCellEdited (object o, EditedArgs args) private void NumberCellEdited (object o, EditedArgs args)
{ {
int i; TreePath path = new TreePath (args.Path);
Item foo; TreeIter iter;
store.GetIter (out iter, path);
int i = path.Indices[0];
try Item foo;
{ try {
i = Convert.ToInt32 (args.Path);
foo = (Item) articles[i]; foo = (Item) articles[i];
foo.Number = int.Parse (args.NewText); foo.Number = int.Parse (args.NewText);
} } catch (Exception e) {
catch (Exception e) Console.WriteLine (e);
{
Console.WriteLine (e.ToString ());
return; return;
} }
TreeIter iter;
store.GetIterFromString (out iter, args.Path);
store.SetValue (iter, (int) Column.Number, foo.Number); store.SetValue (iter, (int) Column.Number, foo.Number);
} }
private void TextCellEdited (object o, EditedArgs args) private void TextCellEdited (object o, EditedArgs args)
{ {
int i = int.Parse (args.Path); TreePath path = new TreePath (args.Path);
TreeIter iter;
store.GetIter (out iter, path);
int i = path.Indices[0];
Item foo = (Item) articles[i]; Item foo = (Item) articles[i];
foo.Product = args.NewText; foo.Product = args.NewText;
TreeIter iter;
store.GetIterFromString (out iter, args.Path);
store.SetValue (iter, (int) Column.Product, foo.Product); store.SetValue (iter, (int) Column.Product, foo.Product);
} }
private void AddItem (object o, EventArgs args) private void AddItem (object o, EventArgs args)
{ {
Item foo = new Item (0, "Description here", true); Item foo = new Item (0, "Description here");
articles.Add (foo); articles.Add (foo);
store.AppendValues (foo.Number, foo.Product, foo.Editable); store.AppendValues (foo.Number, foo.Product);
} }
private void RemoveItem (object o, EventArgs args) private void RemoveItem (object o, EventArgs args)
@ -169,47 +164,38 @@ namespace GtkDemo
TreeIter iter; TreeIter iter;
TreeModel model; TreeModel model;
if (treeView.Selection.GetSelected (out model, out iter)) if (treeView.Selection.GetSelected (out model, out iter)) {
{ int position = store.GetPath (iter).Indices[0];
int position = int.Parse (store.GetPath (iter).ToString ());
store.Remove (ref iter); store.Remove (ref iter);
articles.RemoveAt (position); articles.RemoveAt (position);
} }
} }
} }
public enum Column enum Column
{ {
Number, Number,
Product, Product
Editable,
}; };
public struct Item struct Item
{ {
public int Number { public int Number {
get {return NumberItem;} get { return number; }
set {NumberItem = value;} set { number = value; }
} }
public string Product { public string Product {
get {return ProductItem;} get { return product; }
set {ProductItem = value;} set { product = value; }
} }
public bool Editable { private int number;
get {return EditableItem;} private string product;
set {EditableItem = value;}
}
private int NumberItem; public Item (int number, string product)
private string ProductItem;
private bool EditableItem;
public Item (int number, string product, bool editable)
{ {
NumberItem = number; this.number = number;
ProductItem = product; this.product = product;
EditableItem = editable;
} }
} }
} }

View file

@ -14,25 +14,28 @@ namespace GtkDemo
{ {
public DemoEntryCompletion () : base ("Demo Entry Completion", null, DialogFlags.DestroyWithParent) public DemoEntryCompletion () : base ("Demo Entry Completion", null, DialogFlags.DestroyWithParent)
{ {
this.BorderWidth = 10; Resizable = false;
this.Resizable = false;
VBox vbox = new VBox (false, 5);
vbox.BorderWidth = 5;
this.VBox.PackStart (vbox, true, true, 0);
Label label = new Label ("Completion demo, try writing <b>total</b> or <b>gnome</b> for example."); Label label = new Label ("Completion demo, try writing <b>total</b> or <b>gnome</b> for example.");
label.UseMarkup = true; label.UseMarkup = true;
this.VBox.PackStart (label, false, true, 0); vbox.PackStart (label, false, true, 0);
Entry entry = new Entry (); Entry entry = new Entry ();
vbox.PackStart (entry, false, true, 0);
entry.Completion = new EntryCompletion (); entry.Completion = new EntryCompletion ();
entry.Completion.Model = CreateCompletionModel (); entry.Completion.Model = CreateCompletionModel ();
entry.Completion.TextColumn = 0; entry.Completion.TextColumn = 0;
this.VBox.PackStart (entry, false, true, 0);
this.AddButton (Stock.Close, ResponseType.Close); AddButton (Stock.Close, ResponseType.Close);
this.ShowAll (); ShowAll ();
this.Run (); Run ();
this.Hide (); Destroy ();
this.Destroy ();
} }
TreeModel CreateCompletionModel () TreeModel CreateCompletionModel ()
@ -47,4 +50,3 @@ namespace GtkDemo
} }
} }
} }

View file

@ -14,11 +14,12 @@ namespace GtkDemo
{ {
public DemoExpander () : base ("Demo Expander", null, DialogFlags.DestroyWithParent) public DemoExpander () : base ("Demo Expander", null, DialogFlags.DestroyWithParent)
{ {
this.Resizable = false; Resizable = false;
this.BorderWidth = 10;
VBox vbox = new VBox (false, 5); VBox vbox = new VBox (false, 5);
this.VBox.PackStart (vbox, true, true, 0); this.VBox.PackStart (vbox, true, true, 0);
vbox.BorderWidth = 5; vbox.BorderWidth = 5;
vbox.PackStart (new Label ("Expander demo. Click on the triangle for details."), false, false, 0); vbox.PackStart (new Label ("Expander demo. Click on the triangle for details."), false, false, 0);
// Create the expander // Create the expander
@ -26,12 +27,11 @@ namespace GtkDemo
expander.Add (new Label ("Details can be shown or hidden.")); expander.Add (new Label ("Details can be shown or hidden."));
vbox.PackStart (expander, false, false, 0); vbox.PackStart (expander, false, false, 0);
this.AddButton (Stock.Close, ResponseType.Close); AddButton (Stock.Close, ResponseType.Close);
this.ShowAll (); ShowAll ();
this.Run (); Run ();
this.Hide (); Destroy ();
this.Destroy ();
} }
} }
} }

View file

@ -1,9 +1,3 @@
//
// Author: John Luke <john.luke@gmail.com>
// ported from gtk-demo in GTK+
// Demonstrates HyperLinks in the TextView
//
/* Text Widget/Hypertext /* Text Widget/Hypertext
* *
* Usually, tags modify the appearance of text in the view, e.g. making it * Usually, tags modify the appearance of text in the view, e.g. making it
@ -20,44 +14,30 @@ namespace GtkDemo
[Demo ("Hyper Text", "DemoHyperText.cs", "Text Widget")] [Demo ("Hyper Text", "DemoHyperText.cs", "Text Widget")]
public class DemoHyperText : Gtk.Window public class DemoHyperText : Gtk.Window
{ {
// FIXME: useless counter
int uid = 0;
bool hoveringOverLink = false; bool hoveringOverLink = false;
Gdk.Cursor handCursor, regularCursor; Gdk.Cursor handCursor, regularCursor;
public DemoHyperText () : base ("HyperText") public DemoHyperText () : base ("HyperText")
{
this.DeleteEvent += new DeleteEventHandler (OnWindowDelete);
this.SetDefaultSize (450, 450);
CreateCursors ();
this.Add (CreateScrolledWindow ());
this.ShowAll ();
}
void CreateCursors ()
{ {
handCursor = new Gdk.Cursor (Gdk.CursorType.Hand2); handCursor = new Gdk.Cursor (Gdk.CursorType.Hand2);
regularCursor = new Gdk.Cursor (Gdk.CursorType.Xterm); regularCursor = new Gdk.Cursor (Gdk.CursorType.Xterm);
}
ScrolledWindow CreateScrolledWindow () SetDefaultSize (450, 450);
{
ScrolledWindow sw = new ScrolledWindow ();
sw.Add (CreateTextView ());
return sw;
}
TextView CreateTextView ()
{
TextView view = new TextView (); TextView view = new TextView ();
view.WrapMode = WrapMode.Word; view.WrapMode = WrapMode.Word;
view.KeyPressEvent += new KeyPressEventHandler (OnKeyPress); view.KeyPressEvent += new KeyPressEventHandler (KeyPress);
view.MotionNotifyEvent += new MotionNotifyEventHandler (OnMotionNotify); view.WidgetEventAfter += new WidgetEventAfterHandler (EventAfter);
view.VisibilityNotifyEvent += new VisibilityNotifyEventHandler (OnVisibilityNotify); view.MotionNotifyEvent += new MotionNotifyEventHandler (MotionNotify);
view.ButtonReleaseEvent += new ButtonReleaseEventHandler (OnButtonRelease); view.VisibilityNotifyEvent += new VisibilityNotifyEventHandler (VisibilityNotify);
ScrolledWindow sw = new ScrolledWindow ();
sw.SetPolicy (Gtk.PolicyType.Automatic, Gtk.PolicyType.Automatic);
Add (sw);
sw.Add (view);
ShowPage (view.Buffer, 1); ShowPage (view.Buffer, 1);
return view; ShowAll ();
} }
// Inserts a piece of text into the buffer, giving it the usual // Inserts a piece of text into the buffer, giving it the usual
@ -66,7 +46,7 @@ namespace GtkDemo
// as a link. // as a link.
void InsertLink (TextBuffer buffer, ref TextIter iter, string text, int page) void InsertLink (TextBuffer buffer, ref TextIter iter, string text, int page)
{ {
TextTag tag = new TextTag ("link" + uid++); TextTag tag = new TextTag (null);
tag.Foreground = "blue"; tag.Foreground = "blue";
tag.Underline = Pango.Underline.Single; tag.Underline = Pango.Underline.Single;
tag.PersistentData.Add ("page", page); tag.PersistentData.Add ("page", page);
@ -79,18 +59,15 @@ namespace GtkDemo
void ShowPage (TextBuffer buffer, int page) void ShowPage (TextBuffer buffer, int page)
{ {
buffer.Text = ""; buffer.Text = "";
TextIter iter = buffer.GetIterAtOffset (0); TextIter iter = buffer.StartIter;
if (page == 1) if (page == 1) {
{
buffer.Insert (ref iter, "Some text to show that simple "); buffer.Insert (ref iter, "Some text to show that simple ");
InsertLink (buffer, ref iter, "hypertext", 3); InsertLink (buffer, ref iter, "hypertext", 3);
buffer.Insert (ref iter, " can easily be realized with "); buffer.Insert (ref iter, " can easily be realized with ");
InsertLink (buffer, ref iter, "tags", 2); InsertLink (buffer, ref iter, "tags", 2);
buffer.Insert (ref iter, "."); buffer.Insert (ref iter, ".");
} } else if (page == 2) {
else if (page == 2)
{
buffer.Insert (ref iter, buffer.Insert (ref iter,
"A tag is an attribute that can be applied to some range of text. " + "A tag is an attribute that can be applied to some range of text. " +
"For example, a tag might be called \"bold\" and make the text inside " + "For example, a tag might be called \"bold\" and make the text inside " +
@ -99,9 +76,7 @@ namespace GtkDemo
"behavior of mouse and key presses, \"lock\" a range of text so the " + "behavior of mouse and key presses, \"lock\" a range of text so the " +
"user can't edit it, or countless other things.\n"); "user can't edit it, or countless other things.\n");
InsertLink (buffer, ref iter, "Go back", 1); InsertLink (buffer, ref iter, "Go back", 1);
} } else if (page == 3) {
else if (page == 3)
{
TextTag tag = buffer.TagTable.Lookup ("bold"); TextTag tag = buffer.TagTable.Lookup ("bold");
if (tag == null) { if (tag == null) {
tag = new TextTag ("bold"); tag = new TextTag ("bold");
@ -121,11 +96,10 @@ namespace GtkDemo
// by the data attached to it. // by the data attached to it.
void FollowIfLink (TextView view, TextIter iter) void FollowIfLink (TextView view, TextIter iter)
{ {
foreach (TextTag tag in iter.Tags) foreach (TextTag tag in iter.Tags) {
{ object page = tag.PersistentData ["page"];
int page = (int) tag.PersistentData ["page"]; if (page is int)
if (page != 0) ShowPage (view.Buffer, (int)page);
ShowPage (view.Buffer, page);
} }
} }
@ -137,50 +111,30 @@ namespace GtkDemo
bool hovering = false; bool hovering = false;
TextIter iter = view.GetIterAtLocation (x, y); TextIter iter = view.GetIterAtLocation (x, y);
foreach (TextTag tag in iter.Tags) foreach (TextTag tag in iter.Tags) {
{ if (tag.PersistentData ["page"] is int) {
if (tag.PersistentData ["page"] != null && ((int) tag.PersistentData ["page"]) != 0) {
hovering = true; hovering = true;
break; break;
} }
} }
if (hovering != hoveringOverLink) if (hovering != hoveringOverLink) {
{ Gdk.Window window = view.GetWindow (Gtk.TextWindowType.Text);
hoveringOverLink = hovering; hoveringOverLink = hovering;
if (hoveringOverLink) if (hoveringOverLink)
view.GdkWindow.Cursor = handCursor; window.Cursor = handCursor;
else else
view.GdkWindow.Cursor = regularCursor; window.Cursor = regularCursor;
} }
} }
[GLib.ConnectBefore]
void OnButtonRelease (object sender, ButtonReleaseEventArgs a)
{
if (a.Event.Button != 1)
return;
TextView view = sender as TextView;
TextIter start, end, iter;
int x, y;
view.Buffer.GetSelectionBounds (out start, out end);
if (start.Offset != end.Offset)
return;
view.WindowToBufferCoords (TextWindowType.Widget, (int) a.Event.X, (int) a.Event.Y, out x, out y);
iter = view.GetIterAtLocation (x, y);
FollowIfLink (view, iter);
}
// Links can be activated by pressing Enter. // Links can be activated by pressing Enter.
void OnKeyPress (object sender, KeyPressEventArgs a) void KeyPress (object sender, KeyPressEventArgs args)
{ {
TextView view = sender as TextView; TextView view = sender as TextView;
switch ((Gdk.Key) a.Event.KeyValue) { switch ((Gdk.Key) args.Event.KeyValue) {
case Gdk.Key.Return: case Gdk.Key.Return:
case Gdk.Key.KP_Enter: case Gdk.Key.KP_Enter:
TextIter iter = view.Buffer.GetIterAtMark (view.Buffer.InsertMark); TextIter iter = view.Buffer.GetIterAtMark (view.Buffer.InsertMark);
@ -191,19 +145,48 @@ namespace GtkDemo
} }
} }
// Links can also be activated by clicking.
void EventAfter (object sender, WidgetEventAfterArgs args)
{
if (args.Event.Type != Gdk.EventType.ButtonRelease)
return;
Gdk.EventButton evt = (Gdk.EventButton)args.Event;
if (evt.Button != 1)
return;
TextView view = sender as TextView;
TextIter start, end, iter;
int x, y;
// we shouldn't follow a link if the user has selected something
view.Buffer.GetSelectionBounds (out start, out end);
if (start.Offset != end.Offset)
return;
view.WindowToBufferCoords (TextWindowType.Widget, (int) evt.X, (int) evt.Y, out x, out y);
iter = view.GetIterAtLocation (x, y);
FollowIfLink (view, iter);
}
// Update the cursor image if the pointer moved. // Update the cursor image if the pointer moved.
void OnMotionNotify (object sender, MotionNotifyEventArgs a) void MotionNotify (object sender, MotionNotifyEventArgs args)
{ {
TextView view = sender as TextView; TextView view = sender as TextView;
int x, y; int x, y;
Gdk.ModifierType state;
view.WindowToBufferCoords (TextWindowType.Widget, (int) a.Event.X, (int) a.Event.Y, out x, out y); view.WindowToBufferCoords (TextWindowType.Widget, (int) args.Event.X, (int) args.Event.Y, out x, out y);
SetCursorIfAppropriate (view, x, y); SetCursorIfAppropriate (view, x, y);
view.GdkWindow.GetPointer (out x, out y, out state);
} }
// Also update the cursor image if the window becomes visible // Also update the cursor image if the window becomes visible
// (e.g. when a window covering it got iconified). // (e.g. when a window covering it got iconified).
void OnVisibilityNotify (object sender, VisibilityNotifyEventArgs a) void VisibilityNotify (object sender, VisibilityNotifyEventArgs a)
{ {
TextView view = sender as TextView; TextView view = sender as TextView;
int wx, wy, bx, by; int wx, wy, bx, by;
@ -211,15 +194,12 @@ namespace GtkDemo
view.GetPointer (out wx, out wy); view.GetPointer (out wx, out wy);
view.WindowToBufferCoords (TextWindowType.Widget, wx, wy, out bx, out by); view.WindowToBufferCoords (TextWindowType.Widget, wx, wy, out bx, out by);
SetCursorIfAppropriate (view, bx, by); SetCursorIfAppropriate (view, bx, by);
} }
void OnWindowDelete (object sender, DeleteEventArgs a) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
a.RetVal = true;
} }
} }
} }

View file

@ -1,12 +1,3 @@
//
// DemoImages.cs - port of images.c gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
//
/* Images /* Images
* *
* Gtk.Image is used to display an image; the image can be in a number of formats. * Gtk.Image is used to display an image; the image can be in a number of formats.
@ -36,14 +27,13 @@ namespace GtkDemo
private VBox vbox; private VBox vbox;
BinaryReader imageStream; BinaryReader imageStream;
public DemoImages () : base ("images") public DemoImages () : base ("Images")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete); BorderWidth = 8;
this.BorderWidth = 8;
vbox = new VBox (false, 8); vbox = new VBox (false, 8);
vbox.BorderWidth = 8; vbox.BorderWidth = 8;
this.Add (vbox); Add (vbox);
Gtk.Label label = new Gtk.Label ("<u>Image loaded from a file</u>"); Gtk.Label label = new Gtk.Label ("<u>Image loaded from a file</u>");
label.UseMarkup = true; label.UseMarkup = true;
@ -58,13 +48,13 @@ namespace GtkDemo
alignment.Add (frame); alignment.Add (frame);
vbox.PackStart (alignment, false, false, 0); vbox.PackStart (alignment, false, false, 0);
Gtk.Image image = new Gtk.Image (Gdk.Pixbuf.LoadFromResource ("gtk-logo-rgb.gif")); Gtk.Image image = Gtk.Image.LoadFromResource ("gtk-logo-rgb.gif");
frame.Add (image); frame.Add (image);
// Animation // Animation
label = new Gtk.Label ("<u>Animation loaded from a file</u>"); label = new Gtk.Label ("<u>Animation loaded from a file</u>");
label.UseMarkup = true; label.UseMarkup = true;
vbox.PackStart (label); vbox.PackStart (label, false, false, 0);
frame = new Gtk.Frame (); frame = new Gtk.Frame ();
frame.ShadowType = ShadowType.In; frame.ShadowType = ShadowType.In;
@ -73,13 +63,13 @@ namespace GtkDemo
alignment.Add (frame); alignment.Add (frame);
vbox.PackStart (alignment, false, false, 0); vbox.PackStart (alignment, false, false, 0);
image = new Gtk.Image (Gdk.Pixbuf.LoadFromResource ("floppybuddy.gif")); image = Gtk.Image.LoadFromResource ("floppybuddy.gif");
frame.Add (image); frame.Add (image);
// Progressive // Progressive
label = new Gtk.Label ("<u>Progressive image loading</u>"); label = new Gtk.Label ("<u>Progressive image loading</u>");
label.UseMarkup = true; label.UseMarkup = true;
vbox.PackStart (label); vbox.PackStart (label, false, false, 0);
frame = new Gtk.Frame (); frame = new Gtk.Frame ();
frame.ShadowType = ShadowType.In; frame.ShadowType = ShadowType.In;
@ -90,7 +80,6 @@ namespace GtkDemo
// Create an empty image for now; the progressive loader // Create an empty image for now; the progressive loader
// will create the pixbuf and fill it in. // will create the pixbuf and fill it in.
//
progressiveImage = new Gtk.Image (); progressiveImage = new Gtk.Image ();
frame.Add (progressiveImage); frame.Add (progressiveImage);
@ -102,41 +91,62 @@ namespace GtkDemo
vbox.PackStart (button, false, false, 0); vbox.PackStart (button, false, false, 0);
button.Toggled += new EventHandler (ToggleSensitivity); button.Toggled += new EventHandler (ToggleSensitivity);
this.ShowAll (); ShowAll ();
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override void OnDestroyed ()
{ {
this.Hide (); if (timeout_id != 0) {
this.Destroy (); GLib.Source.Remove (timeout_id);
args.RetVal = true; timeout_id = 0;
}
if (pixbufLoader != null) {
pixbufLoader.Close ();
pixbufLoader = null;
}
if (imageStream != null) {
imageStream.Close ();
imageStream = null;
}
}
protected override bool OnDeleteEvent (Gdk.Event evt)
{
Destroy ();
return true;
} }
private void ToggleSensitivity (object o, EventArgs args) private void ToggleSensitivity (object o, EventArgs args)
{ {
ToggleButton toggle = o as ToggleButton;
Widget[] children = vbox.Children; Widget[] children = vbox.Children;
foreach (Widget widget in children) foreach (Widget widget in children) {
// don't disable our toggle // don't disable our toggle
if (widget.GetType () != o.GetType () ) if (widget != toggle)
widget.Sensitive = !widget.Sensitive; widget.Sensitive = !toggle.Active;
}
} }
private uint timeout_id; private uint timeout_id;
private void StartProgressiveLoading () private void StartProgressiveLoading ()
{ {
/* This is obviously totally contrived (we slow down loading // This is obviously totally contrived (we slow down loading
* on purpose to show how incremental loading works). // on purpose to show how incremental loading works).
* The real purpose of incremental loading is the case where // The real purpose of incremental loading is the case where
* you are reading data from a slow source such as the network. // you are reading data from a slow source such as the network.
* The timeout simply simulates a slow data source by inserting // The timeout simply simulates a slow data source by inserting
* pauses in the reading process. // pauses in the reading process.
*/
timeout_id = GLib.Timeout.Add (150, new GLib.TimeoutHandler (ProgressiveTimeout)); timeout_id = GLib.Timeout.Add (150, new GLib.TimeoutHandler (ProgressiveTimeout));
} }
Gdk.PixbufLoader pixbufLoader; Gdk.PixbufLoader pixbufLoader;
// TODO: Decide if we want to perform crazy error handling // TODO: Decide if we want to perform the same crazy error handling
// gtk-demo does
private bool ProgressiveTimeout () private bool ProgressiveTimeout ()
{ {
if (imageStream == null) { if (imageStream == null) {
@ -151,8 +161,7 @@ namespace GtkDemo
byte[] bytes = imageStream.ReadBytes (256); byte[] bytes = imageStream.ReadBytes (256);
pixbufLoader.Write (bytes, (uint) bytes.Length); pixbufLoader.Write (bytes, (uint) bytes.Length);
return true; // leave the timeout active return true; // leave the timeout active
} } else {
else {
imageStream.Close (); imageStream.Close ();
return false; // removes the timeout return false; // removes the timeout
} }

View file

@ -1,11 +1,4 @@
// /* Tree View/List Store
// DemoListItem.cs, port of tree_store.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* List View/List Store
* *
* The Gtk.ListStore is used to store data in tree form, to be * The Gtk.ListStore is used to store data in tree form, to be
* used later on by a Gtk.ListView to display it. This demo builds * used later on by a Gtk.ListView to display it. This demo builds
@ -28,40 +21,40 @@ namespace GtkDemo
public DemoListStore () : base ("ListStore Demo") public DemoListStore () : base ("ListStore Demo")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete); BorderWidth = 8;
VBox vbox = new VBox (false, 8); VBox vbox = new VBox (false, 8);
vbox.BorderWidth = 8; Add (vbox);
this.Add (vbox);
vbox.PackStart (new Label ("This is the bug list (note: not based on real data, it would be nice to have a nice ODBC interface to bugzilla or so, though)."), false, false, 0); Label label = new Label ("This is the bug list (note: not based on real data, it would be nice to have a nice ODBC interface to bugzilla or so, though).");
vbox.PackStart (label, false, false, 0);
ScrolledWindow sw = new ScrolledWindow ();
sw.ShadowType = ShadowType.EtchedIn;
sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vbox.PackStart (sw, true, true, 0);
ScrolledWindow scrolledWindow = new ScrolledWindow ();
scrolledWindow.ShadowType = ShadowType.EtchedIn;
scrolledWindow.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vbox.PackStart (scrolledWindow, true, true, 0);
// create model // create model
CreateModel (); store = CreateModel ();
// create tree view // create tree view
TreeView treeView = new TreeView (store); TreeView treeView = new TreeView (store);
treeView.RulesHint = true; treeView.RulesHint = true;
treeView.SearchColumn = (int) ColumnNumber.Description; treeView.SearchColumn = (int) Column.Description;
sw.Add (treeView);
AddColumns (treeView); AddColumns (treeView);
scrolledWindow.Add (treeView);
// finish & show // finish & show
this.SetDefaultSize (650, 400); SetDefaultSize (280, 250);
this.ShowAll (); ShowAll ();
} }
private void ItemToggled (object o, ToggledArgs args) private void FixedToggled (object o, ToggledArgs args)
{ {
Gtk.TreeIter iter; Gtk.TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) if (store.GetIterFromString (out iter, args.Path)) {
{
bool val = (bool) store.GetValue (iter, 0); bool val = (bool) store.GetValue (iter, 0);
Console.WriteLine ("toggled {0} with value {1}", args.Path, val);
store.SetValue (iter, 0, !val); store.SetValue (iter, 0, !val);
} }
} }
@ -70,43 +63,42 @@ namespace GtkDemo
{ {
// column for fixed toggles // column for fixed toggles
CellRendererToggle rendererToggle = new CellRendererToggle (); CellRendererToggle rendererToggle = new CellRendererToggle ();
rendererToggle.Toggled += new ToggledHandler (ItemToggled); rendererToggle.Toggled += new ToggledHandler (FixedToggled);
TreeViewColumn column = new TreeViewColumn ("Fixed", rendererToggle, "active", 0); TreeViewColumn column = new TreeViewColumn ("Fixed?", rendererToggle, "active", Column.Fixed);
rendererToggle.Active = true;
rendererToggle.Activatable = true;
rendererToggle.Visible = true;
// set this column to a fixed sizing (of 50 pixels) // set this column to a fixed sizing (of 50 pixels)
column.Sizing = TreeViewColumnSizing.Fixed; column.Sizing = TreeViewColumnSizing.Fixed;
column.FixedWidth = 50; column.FixedWidth = 50;
treeView.AppendColumn (column); treeView.AppendColumn (column);
// column for bug numbers // column for bug numbers
CellRendererText rendererText = new CellRendererText (); CellRendererText rendererText = new CellRendererText ();
column = new TreeViewColumn ("Bug number", rendererText, "text", ColumnNumber.Number); column = new TreeViewColumn ("Bug number", rendererText, "text", Column.Number);
column.SortColumnId = (int) ColumnNumber.Number; column.SortColumnId = (int) Column.Number;
treeView.AppendColumn (column); treeView.AppendColumn (column);
// column for severities // column for severities
rendererText = new CellRendererText (); rendererText = new CellRendererText ();
column = new TreeViewColumn ("Severity", rendererText, "text", ColumnNumber.Severity); column = new TreeViewColumn ("Severity", rendererText, "text", Column.Severity);
column.SortColumnId = (int) ColumnNumber.Severity; column.SortColumnId = (int) Column.Severity;
treeView.AppendColumn(column); treeView.AppendColumn(column);
// column for description // column for description
rendererText = new CellRendererText (); rendererText = new CellRendererText ();
column = new TreeViewColumn ("Description", rendererText, "text", ColumnNumber.Description); column = new TreeViewColumn ("Description", rendererText, "text", Column.Description);
column.SortColumnId = (int) ColumnNumber.Description; column.SortColumnId = (int) Column.Description;
treeView.AppendColumn (column); treeView.AppendColumn (column);
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
private void CreateModel () private ListStore CreateModel ()
{ {
store = new ListStore ( ListStore store = new ListStore (typeof(bool),
typeof(bool),
typeof(int), typeof(int),
typeof(string), typeof(string),
typeof(string)); typeof(string));
@ -118,16 +110,15 @@ namespace GtkDemo
bug.Description); bug.Description);
} }
return store;
} }
// FIXME: Instead of using number convert enum to array using private enum Column
// GetValues and then get the Length Property
public enum ColumnNumber
{ {
Fixed, Fixed,
Number, Number,
Severity, Severity,
Description, Description
} }
private static Bug[] bugs = private static Bug[] bugs =

View file

@ -1,10 +1,3 @@
//
// DemoMain.cs, port of main.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
using System; using System;
using System.Collections; using System.Collections;
using System.IO; using System.IO;
@ -50,7 +43,7 @@ namespace GtkDemo
notebook.AppendPage (CreateText (infoBuffer, false), new Label ("_Info")); notebook.AppendPage (CreateText (infoBuffer, false), new Label ("_Info"));
TextTag heading = new TextTag ("heading"); TextTag heading = new TextTag ("heading");
heading.Scale = heading.Scale * 2; heading.Font = "Sans 18";
infoBuffer.TagTable.Add (heading); infoBuffer.TagTable.Add (heading);
notebook.AppendPage (CreateText (sourceBuffer, true), new Label ("_Source")); notebook.AppendPage (CreateText (sourceBuffer, true), new Label ("_Source"));
@ -61,17 +54,12 @@ namespace GtkDemo
private void LoadFile (string filename) private void LoadFile (string filename)
{ {
Stream file = Assembly.GetExecutingAssembly ().GetManifestResourceStream (filename); Stream file = Assembly.GetExecutingAssembly ().GetManifestResourceStream (filename);
if (file != null) if (file != null) {
{
LoadStream (file); LoadStream (file);
} } else if (File.Exists (filename)) {
else if (File.Exists (filename))
{
file = File.OpenRead (filename); file = File.OpenRead (filename);
LoadStream (file); LoadStream (file);
} } else {
else
{
infoBuffer.Text = String.Format ("{0} was not found.", filename); infoBuffer.Text = String.Format ("{0} was not found.", filename);
sourceBuffer.Text = String.Empty; sourceBuffer.Text = String.Empty;
} }
@ -79,52 +67,64 @@ namespace GtkDemo
Fontify (); Fontify ();
} }
private enum LoadState {
Title,
Info,
SkipWhitespace,
Body
};
private void LoadStream (Stream file) private void LoadStream (Stream file)
{ {
StreamReader sr = new StreamReader (file); StreamReader sr = new StreamReader (file);
bool insideComment = false; LoadState state = LoadState.Title;
bool headingValid = true; bool inPara = false;
infoBuffer.Text = ""; infoBuffer.Text = "";
sourceBuffer.Text = ""; sourceBuffer.Text = "";
TextIter infoIter = infoBuffer.EndIter;
TextIter sourceIter = sourceBuffer.EndIter;
// mostly broken comment parsing for splitting // mostly broken comment parsing for splitting
// out the special comments to display in the infobuffer // out the special comments to display in the infobuffer
string line, trimmed; string line, trimmed;
while (sr.Peek () != -1) { while (sr.Peek () != -1) {
line = sr.ReadLine (); line = sr.ReadLine ();
trimmed = line.Trim (); trimmed = line.Trim ();
if (headingValid && line.Trim ().StartsWith ("//"))
{ switch (state) {
continue; case LoadState.Title:
if (trimmed.StartsWith ("/* ")) {
infoBuffer.InsertWithTagsByName (ref infoIter, trimmed.Substring (3), "heading");
state = LoadState.Info;
} }
else if (headingValid && trimmed.StartsWith ("/*")) break;
{
TextIter iter = infoBuffer.EndIter; case LoadState.Info:
infoBuffer.InsertWithTagsByName (ref iter, trimmed.Substring (2) + Environment.NewLine, "heading"); if (trimmed == "*") {
infoBuffer.Insert (ref iter, Environment.NewLine); infoBuffer.Insert (ref infoIter, "\n");
insideComment = true; inPara = false;
} } else if (trimmed.StartsWith ("* ")) {
else if (headingValid && trimmed.StartsWith ("*/")) if (inPara)
{ infoBuffer.Insert (ref infoIter, " ");
insideComment = false; infoBuffer.Insert (ref infoIter, trimmed.Substring (2));
headingValid = false; inPara = true;
} } else if (trimmed.StartsWith ("*/"))
else state = LoadState.SkipWhitespace;
{ break;
if (insideComment)
{ case LoadState.SkipWhitespace:
TextIter iter = infoBuffer.EndIter; if (trimmed != "") {
if (trimmed.StartsWith ("*")) state = LoadState.Body;
infoBuffer.Insert (ref iter, trimmed.Substring (1)); goto case LoadState.Body;
else
infoBuffer.Insert (ref iter, trimmed);
}
else
{
TextIter iter = sourceBuffer.EndIter;
sourceBuffer.Insert (ref iter, line + Environment.NewLine);
} }
break;
case LoadState.Body:
sourceBuffer.Insert (ref sourceIter, line + "\n");
break;
} }
} }
sr.Close (); sr.Close ();
@ -140,8 +140,7 @@ namespace GtkDemo
{ {
Gdk.Pixbuf pixbuf = Gdk.Pixbuf.LoadFromResource ("gtk-logo-rgb.gif"); Gdk.Pixbuf pixbuf = Gdk.Pixbuf.LoadFromResource ("gtk-logo-rgb.gif");
if (pixbuf != null) if (pixbuf != null) {
{
// The gtk-logo-rgb icon has a white background // The gtk-logo-rgb icon has a white background
// make it transparent instead // make it transparent instead
Pixbuf transparent = pixbuf.AddAlpha (true, 0xff, 0xff, 0xff); Pixbuf transparent = pixbuf.AddAlpha (true, 0xff, 0xff, 0xff);
@ -160,8 +159,8 @@ namespace GtkDemo
column.AddAttribute (cr, "style" , 2); column.AddAttribute (cr, "style" , 2);
view.AppendColumn (column); view.AppendColumn (column);
view.Selection.Changed += new EventHandler (OnTreeChanged); view.Selection.Changed += new EventHandler (TreeChanged);
view.RowActivated += new RowActivatedHandler (OnRowActivated); view.RowActivated += new RowActivatedHandler (RowActivated);
view.ExpandAll (); view.ExpandAll ();
view.SetSizeRequest (200, -1); view.SetSizeRequest (200, -1);
view.Selection.Mode = Gtk.SelectionMode.Browse; view.Selection.Mode = Gtk.SelectionMode.Browse;
@ -180,14 +179,11 @@ namespace GtkDemo
scrolledWindow.Add (textView); scrolledWindow.Add (textView);
if (IsSource) if (IsSource) {
{
FontDescription fontDescription = FontDescription.FromString ("Courier 12"); FontDescription fontDescription = FontDescription.FromString ("Courier 12");
textView.ModifyFont (fontDescription); textView.ModifyFont (fontDescription);
textView.WrapMode = Gtk.WrapMode.None; textView.WrapMode = Gtk.WrapMode.None;
} } else {
else
{
// Make it a bit nicer for text // Make it a bit nicer for text
textView.WrapMode = Gtk.WrapMode.Word; textView.WrapMode = Gtk.WrapMode.Word;
textView.PixelsAboveLines = 2; textView.PixelsAboveLines = 2;
@ -205,42 +201,32 @@ namespace GtkDemo
TreeIter parent; TreeIter parent;
Type[] types = Assembly.GetExecutingAssembly ().GetTypes (); Type[] types = Assembly.GetExecutingAssembly ().GetTypes ();
foreach (Type t in types) foreach (Type t in types) {
{
if (t.IsDefined (typeof (DemoAttribute), false))
{
object[] att = t.GetCustomAttributes (typeof (DemoAttribute), false); object[] att = t.GetCustomAttributes (typeof (DemoAttribute), false);
foreach (DemoAttribute demo in att) foreach (DemoAttribute demo in att) {
{ if (demo.Parent != null) {
if (demo.Parent != null)
{
if (!parents.Contains (demo.Parent)) if (!parents.Contains (demo.Parent))
parents.Add (demo.Parent, store.AppendValues (demo.Parent)); parents.Add (demo.Parent, store.AppendValues (demo.Parent));
parent = (TreeIter) parents[demo.Parent]; parent = (TreeIter) parents[demo.Parent];
store.AppendValues (parent, demo.Label, t, false); store.AppendValues (parent, demo.Label, t, false);
} } else {
else
{
store.AppendValues (demo.Label, t, false); store.AppendValues (demo.Label, t, false);
} }
} }
} }
}
store.SetSortColumnId (0, SortType.Ascending); store.SetSortColumnId (0, SortType.Ascending);
return store; return store;
} }
private void OnTreeChanged (object o, EventArgs args) private void TreeChanged (object o, EventArgs args)
{ {
TreeIter iter; TreeIter iter;
TreeModel model; TreeModel model;
if (treeView.Selection.GetSelected (out model, out iter)) if (treeView.Selection.GetSelected (out model, out iter)) {
{
Type type = (Type) model.GetValue (iter, 1); Type type = (Type) model.GetValue (iter, 1);
if (type != null) if (type != null) {
{
object[] atts = type.GetCustomAttributes (typeof (DemoAttribute), false); object[] atts = type.GetCustomAttributes (typeof (DemoAttribute), false);
string file = ((DemoAttribute) atts[0]).Filename; string file = ((DemoAttribute) atts[0]).Filename;
LoadFile (file); LoadFile (file);
@ -253,12 +239,11 @@ namespace GtkDemo
} }
} }
private void OnRowActivated (object o, RowActivatedArgs args) private void RowActivated (object o, RowActivatedArgs args)
{ {
TreeIter iter; TreeIter iter;
if (treeView.Model.GetIter (out iter, args.Path)) if (treeView.Model.GetIter (out iter, args.Path)) {
{
Type type = (Type) treeView.Model.GetValue (iter, 1); Type type = (Type) treeView.Model.GetValue (iter, 1);
if (type != null) if (type != null)
Activator.CreateInstance (type); Activator.CreateInstance (type);
@ -272,4 +257,3 @@ namespace GtkDemo
} }
} }
} }

View file

@ -1,45 +1,29 @@
//
// TestMenus.cs
//
// Author: Duncan Mak (duncan@ximian.com)
//
// Copyright (C) 2002, Duncan Mak, Ximian Inc.
//
/* Menus /* Menus
* *
* There are several widgets involved in displaying menus. The * There are several widgets involved in displaying menus. The MenuBar
* MenuBar widget is a horizontal menu bar, which normally appears * widget is a horizontal menu bar, which normally appears at the top
* at the top of an application. The Menu widget is the actual menu * of an application. The Menu widget is the actual menu that pops up.
* that pops up. Both MenuBar and Menu are subclasses of * Both MenuBar and Menu are subclasses of MenuShell; a MenuShell
* MenuShell; a MenuShell contains menu items * contains menu items (MenuItem). Each menu item contains text and/or
* (MenuItem). Each menu item contains text and/or images and can * images and can be selected by the user.
* be selected by the user.
* *
* There are several kinds of menu item, including plain MenuItem, * There are several kinds of menu item, including plain MenuItem,
* CheckMenuItem which can be checked/unchecked, RadioMenuItem * CheckMenuItem which can be checked/unchecked, RadioMenuItem which
* which is a check menu item that's in a mutually exclusive group, * is a check menu item that's in a mutually exclusive group,
* SeparatorMenuItem which is a separator bar, TearoffMenuItem * SeparatorMenuItem which is a separator bar, TearoffMenuItem which
* which allows a Menu to be torn off, and ImageMenuItem which * allows a Menu to be torn off, and ImageMenuItem which can place a
* can place a Image or other widget next to the menu text. * Image or other widget next to the menu text.
* *
* A MenuItem can have a submenu, which is simply a Menu to pop * A MenuItem can have a submenu, which is simply a Menu to pop up
* up when the menu item is selected. Typically, all menu items in a menu bar * when the menu item is selected. Typically, all menu items in a menu
* have submenus. * bar have submenus.
* *
* The OptionMenu widget is a button that pops up a Menu when clicked. * UIManager provides a higher-level interface for creating menu bars
* It's used inside dialogs and such. * and menus; while you can construct menus manually, most people
* * don't do that. There's a separate demo for UIManager.
* ItemFactory provides a higher-level interface for creating menu bars
* and menus; while you can construct menus manually, most people don't
* do that. There's a separate demo for ItemFactory.
* *
*/ */
// TODO : window width is not exactly equal
// point on the right side
using System; using System;
using Gtk; using Gtk;
@ -50,101 +34,78 @@ namespace GtkDemo
{ {
public DemoMenus () : base ("Menus") public DemoMenus () : base ("Menus")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete);
AccelGroup accel_group = new AccelGroup (); AccelGroup accel_group = new AccelGroup ();
this.AddAccelGroup (accel_group); AddAccelGroup (accel_group);
VBox box1 = new VBox (false, 0); VBox box1 = new VBox (false, 0);
this.Add (box1); Add (box1);
MenuBar menubar = new MenuBar (); MenuBar menubar = new MenuBar ();
box1.PackStart (menubar, false, false, 0); box1.PackStart (menubar, false, true, 0);
Menu menu = Create_Menu (2, true);
MenuItem menuitem = new MenuItem ("test\nline2"); MenuItem menuitem = new MenuItem ("test\nline2");
menuitem.Submenu = menu; menuitem.Submenu = CreateMenu (2, true);
menubar.Append (menuitem); menubar.Append (menuitem);
MenuItem menuitem1 = new MenuItem ("foo"); MenuItem menuitem1 = new MenuItem ("foo");
menuitem1.Submenu = Create_Menu (3, true); menuitem1.Submenu = CreateMenu (3, true);
menubar.Append (menuitem1); menubar.Append (menuitem1);
menuitem = new MenuItem ("bar"); menuitem = new MenuItem ("bar");
menuitem.Submenu = Create_Menu (4, true); menuitem.Submenu = CreateMenu (4, true);
menuitem.RightJustified = true; menuitem.RightJustified = true;
menubar.Append (menuitem); menubar.Append (menuitem);
menubar = new MenuBar ();
box1.PackStart (menubar, false, true, 0);
VBox box2 = new VBox (false, 10); VBox box2 = new VBox (false, 10);
box2.BorderWidth = 10; box2.BorderWidth = 10;
box1.PackStart (box2, true, true, 0);
box2 = new VBox (false, 10);
box2.BorderWidth = 10;
box1.PackStart (box2, false, true, 0); box1.PackStart (box2, false, true, 0);
Button close_button = new Button ("close"); Button close = new Button ("close");
close_button.Clicked += new EventHandler (Close_Button); close.Clicked += new EventHandler (CloseClicked);
box2.PackStart (close_button, true, true, 0); box2.PackStart (close, true, true, 0);
close_button.CanDefault = true; close.CanDefault = true;
close_button.GrabDefault (); close.GrabDefault ();
this.ShowAll (); ShowAll ();
} }
private Menu Create_Menu (int depth, bool tearoff) private Menu CreateMenu (int depth, bool tearoff)
{ {
if (depth < 1) if (depth < 1)
return null; return null;
Menu menu = new Menu (); Menu menu = new Menu ();
MenuItem menuitem;
string label;
GLib.SList group = new GLib.SList (IntPtr.Zero); GLib.SList group = new GLib.SList (IntPtr.Zero);
if (tearoff) if (tearoff) {
{ TearoffMenuItem menuitem = new TearoffMenuItem ();
menuitem = new TearoffMenuItem ();
menu.Append (menuitem); menu.Append (menuitem);
menuitem.Show ();
} }
for (int i = 0, j = 1; i < 5; i++, j++) for (int i = 0, j = 1; i < 5; i++, j++) {
{ RadioMenuItem menuitem = new RadioMenuItem (group, String.Format ("item {0} - {1}", depth, j));
label = String.Format ("item {0} - {1}", depth, j); group = menuitem.Group;
menuitem = new RadioMenuItem (group, label);
group = ((RadioMenuItem) menuitem).Group;
menuitem = new MenuItem (label);
menu.Append (menuitem);
menu.Append (menuitem);
if (i == 3) if (i == 3)
menuitem.Sensitive = false; menuitem.Sensitive = false;
Menu child = Create_Menu ((depth - 1), true); menuitem.Submenu = CreateMenu ((depth - 1), true);
if (child != null)
menuitem.Submenu = child;
} }
return menu; return menu;
} }
private void Close_Button (object o, EventArgs args) private void CloseClicked (object o, EventArgs args)
{ {
this.Hide (); Destroy ();
this.Destroy ();
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
} }
} }

View file

@ -1,12 +1,3 @@
//
// DemoPanes.cs
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2002, Daniel Kornhauser, Ximian Inc.
//
/* Paned Widgets /* Paned Widgets
* *
* The HPaned and VPaned Widgets divide their content * The HPaned and VPaned Widgets divide their content
@ -22,6 +13,7 @@
using System; using System;
using System.Collections;
using Gtk; using Gtk;
namespace GtkDemo namespace GtkDemo
@ -29,151 +21,119 @@ namespace GtkDemo
[Demo ("Paned Widget", "DemoPanes.cs")] [Demo ("Paned Widget", "DemoPanes.cs")]
public class DemoPanes : Gtk.Window public class DemoPanes : Gtk.Window
{ {
private VPaned vpaned; Hashtable children = new Hashtable ();
private HPaned top;
private Frame left;
private Frame right;
private Frame bottom;
private CheckButton resizeLeft;
private CheckButton shrinkLeft;
private CheckButton resizeRight;
private CheckButton shrinkRight;
private CheckButton resizeTop;
private CheckButton shrinkTop;
private CheckButton resizeBottom;
private CheckButton shrinkBottom;
private Button button;
public DemoPanes () : base ("Panes") public DemoPanes () : base ("Panes")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete);
this.BorderWidth = 0;
VBox vbox = new VBox (false, 0); VBox vbox = new VBox (false, 0);
this.Add (vbox); Add (vbox);
vpaned = new VPaned (); VPaned vpaned = new VPaned ();
vbox.PackStart (vpaned, true, true, 0); vbox.PackStart (vpaned, true, true, 0);
vpaned.BorderWidth = 5; vpaned.BorderWidth = 5;
top = new HPaned (); HPaned hpaned = new HPaned ();
vpaned.Add1 (top); vpaned.Add1 (hpaned);
left = new Frame (); Frame frame = new Frame ();
left.ShadowType = ShadowType.In; frame.ShadowType = ShadowType.In;
left.SetSizeRequest (60, 60); frame.SetSizeRequest (60, 60);
top.Add1 (left); hpaned.Add1 (frame);
button = new Button ("_Hi there");
left.Add (button);
right = new Frame (); Gtk.Button button = new Button ("_Hi there");
right.ShadowType = ShadowType.In; frame.Add (button);
right.SetSizeRequest (80, 60);
top.Add2 (right);
bottom = new Frame (); frame = new Frame ();
bottom.ShadowType = ShadowType.In; frame.ShadowType = ShadowType.In;
bottom.SetSizeRequest (80, 60); frame.SetSizeRequest (80, 60);
vpaned.Add2 (bottom); hpaned.Add2 (frame);
frame = new Frame ();
frame.ShadowType = ShadowType.In;
frame.SetSizeRequest (60, 80);
vpaned.Add2 (frame);
// Now create toggle buttons to control sizing // Now create toggle buttons to control sizing
vbox.PackStart (CreatePaneOptions (hpaned,
"Horizontal",
"Left",
"Right"),
false, false, 0);
Frame frame = new Frame ("Horizonal"); vbox.PackStart (CreatePaneOptions (vpaned,
"Vertical",
"Top",
"Bottom"),
false, false, 0);
ShowAll ();
}
Frame CreatePaneOptions (Paned paned, string frameLabel,
string label1, string label2)
{
Frame frame = new Frame (frameLabel);
frame.BorderWidth = 4; frame.BorderWidth = 4;
vbox.PackStart (frame);
Table table = new Table (3, 2, true); Table table = new Table (3, 2, true);
frame.Add (table); frame.Add (table);
Label label = new Label ("Left"); Label label = new Label (label1);
table.Attach (label, 0, 1, 0, 1); table.Attach (label, 0, 1, 0, 1);
resizeLeft = new CheckButton ("_Resize"); CheckButton check = new CheckButton ("_Resize");
table.Attach (resizeLeft, 0, 1, 1, 2); table.Attach (check, 0, 1, 1, 2);
resizeLeft.Toggled += new EventHandler (LeftCB); check.Toggled += new EventHandler (ToggleResize);
children[check] = paned.Child1;
shrinkLeft = new CheckButton ("_Shrink"); check = new CheckButton ("_Shrink");
table.Attach (shrinkLeft, 0, 1, 2, 3); table.Attach (check, 0, 1, 2, 3);
shrinkLeft.Active = true; check.Active = true;
shrinkLeft.Toggled += new EventHandler (LeftCB); check.Toggled += new EventHandler (ToggleShrink);
children[check] = paned.Child1;
label = new Label ("Right"); label = new Label (label2);
table.Attach (label, 1, 2, 0, 1); table.Attach (label, 1, 2, 0, 1);
resizeRight = new CheckButton ("_Resize"); check = new CheckButton ("_Resize");
table.Attach (resizeRight, 1, 2, 1, 2); table.Attach (check, 1, 2, 1, 2);
resizeRight.Active = true; check.Active = true;
resizeRight.Toggled += new EventHandler (RightCB); check.Toggled += new EventHandler (ToggleResize);
children[check] = paned.Child2;
shrinkRight = new CheckButton ("_Shrink"); check = new CheckButton ("_Shrink");
table.Attach (shrinkRight, 1, 2, 2, 3); table.Attach (check, 1, 2, 2, 3);
shrinkRight.Active = true; check.Active = true;
shrinkRight.Toggled += new EventHandler (RightCB); check.Toggled += new EventHandler (ToggleShrink);
children[check] = paned.Child2;
frame = new Frame ("Vertical"); return frame;
frame.BorderWidth = 4;
vbox.PackStart (frame);
table = new Table (3, 2, true);
frame.Add (table);
label = new Label ("Top");
table.Attach (label, 0, 1, 0, 1);
resizeTop = new CheckButton ("_Resize");
table.Attach (resizeTop, 0, 1, 1, 2);
resizeTop.Toggled += new EventHandler (TopCB);
shrinkTop = new CheckButton ("_Shrink");
table.Attach (shrinkTop, 0, 1, 2, 3);
shrinkTop.Active = true;
shrinkTop.Toggled += new EventHandler (TopCB);
label = new Label ("Bottom");
table.Attach (label, 1, 2, 0, 1);
resizeBottom = new CheckButton ("_Resize");
table.Attach (resizeBottom, 1, 2, 1, 2);
resizeBottom.Active = true;
resizeBottom.Toggled += new EventHandler (BottomCB);
shrinkBottom = new CheckButton ("_Shrink");
table.Attach (shrinkBottom, 1, 2, 2, 3);
shrinkBottom.Active = true;
shrinkBottom.Toggled += new EventHandler (BottomCB);
this.ShowAll ();
} }
private void LeftCB (object o, EventArgs args) private void ToggleResize (object obj, EventArgs args)
{ {
top.Remove (left); ToggleButton toggle = obj as ToggleButton;
top.Pack1 (left, resizeLeft.Active, shrinkLeft.Active); Widget child = children[obj] as Widget;
Paned paned = child.Parent as Paned;
Paned.PanedChild pc = paned[child] as Paned.PanedChild;
pc.Resize = toggle.Active;
} }
private void RightCB (object o, EventArgs args) private void ToggleShrink (object obj, EventArgs args)
{ {
top.Remove (right); ToggleButton toggle = obj as ToggleButton;
top.Pack2 (right, resizeRight.Active, shrinkRight.Active); Widget child = children[obj] as Widget;
Paned paned = child.Parent as Paned;
Paned.PanedChild pc = paned[child] as Paned.PanedChild;
pc.Shrink = toggle.Active;
} }
private void TopCB (object o, EventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
vpaned.Remove (top); Destroy ();
vpaned.Pack1 (top, resizeTop.Active, shrinkTop.Active); return true;
}
private void BottomCB (object o, EventArgs args)
{
vpaned.Remove (bottom);
vpaned.Pack2 (bottom, resizeBottom.Active, shrinkBottom.Active);
}
private void WindowDelete (object o, DeleteEventArgs args)
{
this.Hide ();
this.Destroy ();
} }
} }
} }

View file

@ -1,11 +1,3 @@
// DemoPixbuf.cs: Pixbuf demonstration
//
// Gtk# port of pixbuf demo in gtk-demo app.
//
// Author: Yves Kurz <yves@magnific.ch>
//
// <c> 2003 Yves Kurz
/* Pixbufs /* Pixbufs
* *
* A Pixbuf represents an image, normally in RGB or RGBA format. * A Pixbuf represents an image, normally in RGB or RGBA format.
@ -24,6 +16,7 @@ using Gdk;
using Gtk; using Gtk;
using System; using System;
using System.Runtime.InteropServices; // for Marshal.Copy
namespace GtkDemo namespace GtkDemo
{ {
@ -34,7 +27,7 @@ namespace GtkDemo
const int CycleLen = 60; const int CycleLen = 60;
const string BackgroundName = "background.jpg"; const string BackgroundName = "background.jpg";
string [] ImageNames = { static string[] ImageNames = {
"apple-red.png", "apple-red.png",
"gnome-applets.png", "gnome-applets.png",
"gnome-calendar.png", "gnome-calendar.png",
@ -45,23 +38,26 @@ namespace GtkDemo
"gnu-keys.png" "gnu-keys.png"
}; };
// background image
static Pixbuf background;
static int backWidth, backHeight;
// images
static Pixbuf[] images;
// current frame // current frame
Pixbuf frame; Pixbuf frame;
int frameNum; int frameNum;
// background image
Pixbuf background;
int backWidth, backHeight;
// images
Pixbuf[] images;
// drawing area // drawing area
DrawingArea drawingArea; DrawingArea drawingArea;
// Loads the images for the demo uint timeoutId;
void LoadPixbuf ()
static DemoPixbuf ()
{ {
// Load the images for the demo
background = Gdk.Pixbuf.LoadFromResource (BackgroundName); background = Gdk.Pixbuf.LoadFromResource (BackgroundName);
backWidth = background.Width; backWidth = background.Width;
@ -78,15 +74,20 @@ namespace GtkDemo
void Expose (object o, ExposeEventArgs args) void Expose (object o, ExposeEventArgs args)
{ {
Widget widget = (Widget) o; Widget widget = (Widget) o;
Gdk.Rectangle area = args.Event.Area;
byte[] pixels;
int rowstride;
frame.RenderToDrawableAlpha( rowstride = frame.Rowstride;
widget.GdkWindow, pixels = new byte[(frame.Height - area.Y) * rowstride];
0, 0, Marshal.Copy (frame.Pixels, pixels, rowstride * area.Y + area.X * 3, pixels.Length);
0, 0,
backWidth, backHeight, widget.GdkWindow.DrawRgbImageDithalign (widget.Style.BlackGC,
Gdk.PixbufAlphaMode.Full, 8, area.X, area.Y, area.Width, area.Height,
RgbDither.Normal, Gdk.RgbDither.Normal,
100, 100); pixels, rowstride,
area.X, area.Y);
args.RetVal = true;
} }
// timeout handler to regenerate the frame // timeout handler to regenerate the frame
@ -102,52 +103,38 @@ namespace GtkDemo
double radius = Math.Min (xmid, ymid) / 2; double radius = Math.Min (xmid, ymid) / 2;
for (int i = 0; i < images.Length; i++) { for (int i = 0; i < images.Length; i++) {
double ang = 2 * Math.PI * i / images.Length - f * 2 * double ang = 2 * Math.PI * (double) i / images.Length - f * 2 * Math.PI;
Math.PI;
int iw = images[i].Width; int iw = images[i].Width;
int ih = images[i].Height; int ih = images[i].Height;
double r = radius + (radius / 3) * Math.Sin (f * 2 * double r = radius + (radius / 3) * Math.Sin (f * 2 * Math.PI);
Math.PI);
int xpos = (int) Math.Floor (xmid + r * Math.Cos (ang) - int xpos = (int) Math.Floor (xmid + r * Math.Cos (ang) -
iw / 2 + 0.5); iw / 2.0 + 0.5);
int ypos = (int) Math.Floor (ymid + r * Math.Sin (ang) - int ypos = (int) Math.Floor (ymid + r * Math.Sin (ang) -
ih / 2 + 0.5); ih / 2.0 + 0.5);
double k = (i % 2 == 1) ? Math.Sin (f * 2 * Math.PI) : double k = (i % 2 == 1) ? Math.Sin (f * 2 * Math.PI) :
Math.Cos (f * 2 * Math.PI); Math.Cos (f * 2 * Math.PI);
k = 2 * k * k; k = 2 * k * k;
k = Math.Max (0.25, k); k = Math.Max (0.25, k);
Rectangle r1; /*, r2, dest*/ Rectangle r1, r2, dest;
r1 = new Rectangle (xpos, ypos,(int) (iw * k),
(int) (ih * k));
/* FIXME: Why is that code not working (in the original gtk-demo it works
r1 = new Rectangle (xpos, ypos, (int) (iw * k), (int) (ih * k));
r2 = new Rectangle (0, 0, backWidth, backHeight); r2 = new Rectangle (0, 0, backWidth, backHeight);
dest = new Rectangle (0, 0, 0, 0); dest = Rectangle.Intersect (r1, r2);
r1.Intersect (r2, dest); if (!dest.IsEmpty) {
images[i].Composite (frame, dest.X, dest.Y,
images[i].Composite (frame, dest.x, dest.y, dest.width, dest.Width, dest.Height,
dest.height, xpos, ypos, k, k, xpos, ypos, k, k,
InterpType.Nearest, (int) ((i % 2 == 1) InterpType.Nearest,
? Math.Max (127, Math.Abs (255 * Math.Sin (f * (int) ((i % 2 == 1) ?
2 * Math.PI))) Math.Max (127, Math.Abs (255 * Math.Sin (f * 2 * Math.PI))) :
: Math.Max (127, Math.Abs (255 * Math.Cos (f * Math.Max (127, Math.Abs (255 * Math.Cos (f * 2 * Math.PI)))));
2 * Math.PI))))); }
*/
images[i].Composite (frame, r1.X, r1.Y, r1.Width,
r1.Height, xpos, ypos, k, k,
InterpType.Nearest, (int) ((i % 2 == 1)
? Math.Max (127, Math.Abs (255 * Math.Sin (f *
2 * Math.PI)))
: Math.Max (127, Math.Abs (255 * Math.Cos (f *
2 * Math.PI)))));
} }
drawingArea.QueueDraw (); drawingArea.QueueDraw ();
@ -156,47 +143,34 @@ namespace GtkDemo
return true; return true;
} }
public DemoPixbuf () : base ("Gdk Pixbuf Demo") public DemoPixbuf () : base ("Pixbufs")
{ {
this.DeleteEvent += new DeleteEventHandler (OnWindowDelete); Resizable = false;
SetSizeRequest (backWidth, backHeight);
try frame = new Pixbuf (Colorspace.Rgb, false, 8, backWidth, backHeight);
{
LoadPixbuf ();
} catch (Exception e)
{
using (MessageDialog md = new MessageDialog (this,
DialogFlags.DestroyWithParent,
MessageType.Error,
ButtonsType.Close,
"Error: \n" + e.Message)) {
md.Run ();
md.Hide ();
}
throw;
}
frame = new Pixbuf (Colorspace.Rgb, true, 8, backWidth,
backHeight);
drawingArea = new DrawingArea (); drawingArea = new DrawingArea ();
drawingArea.ExposeEvent += new ExposeEventHandler (Expose); drawingArea.ExposeEvent += new ExposeEventHandler (Expose);
Add (drawingArea); Add (drawingArea);
GLib.Timeout.Add (FrameDelay, new GLib.TimeoutHandler(timeout)); timeoutId = GLib.Timeout.Add (FrameDelay, new GLib.TimeoutHandler(timeout));
this.SetDefaultSize (backWidth, backHeight);
// this.Resizable = false;
ShowAll (); ShowAll ();
} }
void OnWindowDelete (object obj, DeleteEventArgs args) protected override void OnDestroyed ()
{ {
this.Hide (); if (timeoutId != 0) {
this.Destroy (); GLib.Source.Remove (timeoutId);
args.RetVal = true; timeoutId = 0;
}
} }
} }
protected override bool OnDeleteEvent (Gdk.Event evt)
{
Destroy ();
return true;
}
}
}

View file

@ -1,11 +1,3 @@
//
// DemoSizeGroup.cs
//
// Author: Duncan Mak (duncan@ximian.com)
//
// Copyright (C) 2002, Duncan Mak, Ximian Inc.
//
/* Size Groups /* Size Groups
* *
* SizeGroup provides a mechanism for grouping a number of * SizeGroup provides a mechanism for grouping a number of
@ -31,10 +23,14 @@ namespace GtkDemo
{ {
private SizeGroup sizeGroup; private SizeGroup sizeGroup;
public DemoSizeGroup () static string [] colors = { "Red", "Green", "Blue" };
static string [] dashes = { "Solid", "Dashed", "Dotted" };
static string [] ends = { "Square", "Round", "Arrow" };
public DemoSizeGroup () : base ("SizeGroup", null, DialogFlags.DestroyWithParent,
Gtk.Stock.Close, Gtk.ResponseType.Close)
{ {
this.Title = "Size groups"; Resizable = false;
this.Resizable = false;
VBox vbox = new VBox (false, 5); VBox vbox = new VBox (false, 5);
this.VBox.PackStart (vbox, true, true, 0); this.VBox.PackStart (vbox, true, true, 0);
@ -52,10 +48,6 @@ namespace GtkDemo
table.ColumnSpacing = 10; table.ColumnSpacing = 10;
frame.Add (table); frame.Add (table);
string [] colors = {"Red", "Green", "Blue", };
string [] dashes = {"Solid", "Dashed", "Dotted", };
string [] ends = {"Square", "Round", "Arrow", };
AddRow (table, 0, sizeGroup, "_Foreground", colors); AddRow (table, 0, sizeGroup, "_Foreground", colors);
AddRow (table, 1, sizeGroup, "_Background", colors); AddRow (table, 1, sizeGroup, "_Background", colors);
@ -76,17 +68,13 @@ namespace GtkDemo
CheckButton checkButton = new CheckButton ("_Enable grouping"); CheckButton checkButton = new CheckButton ("_Enable grouping");
vbox.PackStart (checkButton, false, false, 0); vbox.PackStart (checkButton, false, false, 0);
checkButton.Active = true; checkButton.Active = true;
checkButton.Toggled += new EventHandler (ButtonToggleCb); checkButton.Toggled += new EventHandler (ToggleGrouping);
Button CloseButton = new Button (Stock.Close); ShowAll ();
this.AddActionWidget (CloseButton, ResponseType.Close);
this.Response += new ResponseHandler (ResponseCallback);
this.ShowAll ();
} }
// Convenience function to create an option menu holding a number of strings // Convenience function to create a combo box holding a number of strings
private ComboBox CreateOptionMenu (string [] strings) private ComboBox CreateComboBox (string [] strings)
{ {
ComboBox combo = ComboBox.NewText (); ComboBox combo = ComboBox.NewText ();
@ -104,29 +92,26 @@ namespace GtkDemo
table.Attach (label, table.Attach (label,
0, 1, row, row + 1, 0, 1, row, row + 1,
AttachOptions.Expand, AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, 0,
0, 0); 0, 0);
ComboBox combo = CreateOptionMenu (options); ComboBox combo = CreateComboBox (options);
label.MnemonicWidget = combo;
sizeGroup.AddWidget (combo); sizeGroup.AddWidget (combo);
table.Attach (combo, table.Attach (combo,
1, 2, row, row + 1, 1, 2, row, row + 1,
AttachOptions.Expand, AttachOptions.Expand, 0, 0,
0, 0); 0, 0);
} }
private void ButtonToggleCb (object o, EventArgs args) private void ToggleGrouping (object o, EventArgs args)
{ {
ToggleGrouping ((ToggleButton) o, sizeGroup); ToggleButton checkButton = (ToggleButton)o;
}
// SizeGroupMode.None is not generally useful, but is useful // SizeGroupMode.None is not generally useful, but is useful
// here to show the effect of SizeGroupMode.Horizontal by // here to show the effect of SizeGroupMode.Horizontal by
// contrast // contrast
private void ToggleGrouping (ToggleButton checkButton, SizeGroup sizeGroup)
{
SizeGroupMode mode; SizeGroupMode mode;
if (checkButton.Active) if (checkButton.Active)
@ -137,13 +122,9 @@ namespace GtkDemo
sizeGroup.Mode = mode; sizeGroup.Mode = mode;
} }
private void ResponseCallback (object obj, ResponseArgs args) protected override void OnResponse (Gtk.ResponseType responseId)
{ {
if ((args.ResponseId) == ResponseType.Close) { Destroy ();
this.Hide ();
this.Destroy ();
} }
} }
}
} }

View file

@ -1,10 +1,3 @@
//
// StockBrowser.cs, port of stock_browser.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@media.mit.edu>
//
// (C) 2003 Ximian, Inc.
/* Stock Item and Icon Browser /* Stock Item and Icon Browser
* *
* This source code for this demo doesn't demonstrate anything * This source code for this demo doesn't demonstrate anything
@ -15,6 +8,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Reflection;
using Gtk; using Gtk;
namespace GtkDemo namespace GtkDemo
@ -22,207 +16,182 @@ namespace GtkDemo
[Demo ("Stock Item and Icon Browser", "DemoStockBrowser.cs")] [Demo ("Stock Item and Icon Browser", "DemoStockBrowser.cs")]
public class DemoStockBrowser : Gtk.Window public class DemoStockBrowser : Gtk.Window
{ {
class StockInfo enum Column {
Id,
Name,
Label,
Accel,
};
Label typeLabel, nameLabel, idLabel, accelLabel;
Image iconImage;
public DemoStockBrowser () : base ("Stock Icons and Items")
{ {
internal string Name; SetDefaultSize (-1, 500);
internal string Label; BorderWidth = 8;
internal string Accel;
internal string ID;
internal Gdk.Pixbuf Icon;
}
// in a real application this would be
// split into its own file
class StockFrame : Gtk.Frame
{
StockInfo info;
Label category;
Label name;
Label id;
Label label;
Image icon;
internal StockFrame () : base ("Selected Item")
{
this.SetSizeRequest (200, -1);
// Icon and Item / Icon Only / ???
category = new Label ("???");
// icon / blank
icon = new Image ("");
// _Add / blank
label = new Label ();
label.UseUnderline = true;
// Gtk.Stock.Cancel
name = new Label ();
// gtk-stock-cancel
id = new Label ();
VBox vbox = new VBox (false, 3);
vbox.PackStart (category, false, true, 0);
vbox.PackStart (icon, false, true, 0);
vbox.PackStart (label, false, true, 0);
vbox.PackStart (name, false, true, 0);
vbox.PackStart (id, false, true, 0);
this.Add (vbox);
this.ShowAll ();
}
internal StockInfo Info
{
get { return info; }
set {
info = value;
name.Text = info.Name;
label.Text = info.Label;
id.Text = info.ID;
icon.Pixbuf = info.Icon;
}
}
}
StockFrame stockFrame;
public DemoStockBrowser () : base ("Stock Item Browser Demo")
{
this.SetDefaultSize (600, 400);
this.DeleteEvent += new DeleteEventHandler (WindowDelete);
this.BorderWidth = 8;
HBox hbox = new HBox (false, 8); HBox hbox = new HBox (false, 8);
this.Add (hbox); Add (hbox);
ScrolledWindow scrolledWindow = new ScrolledWindow (null, null); ScrolledWindow sw = new ScrolledWindow ();
scrolledWindow.SetPolicy (PolicyType.Never, PolicyType.Automatic); sw.SetPolicy (PolicyType.Never, PolicyType.Automatic);
hbox.PackStart (scrolledWindow, true, true, 0); hbox.PackStart (sw, false, false, 0);
TreeView list = new TreeView (); ListStore model = CreateModel ();
list.AppendColumn ("Icon", new CellRendererPixbuf (), "pixbuf", 0);
list.AppendColumn ("Name", new CellRendererText (), "text", 1);
list.AppendColumn ("Label", new CellRendererText (), "text", 2);
list.AppendColumn ("Accel", new CellRendererText (), "text", 3);
list.AppendColumn ("ID", new CellRendererText (), "text", 4);
list.Model = CreateStore ();
list.Selection.Changed += new EventHandler (OnSelectionChanged); TreeView treeview = new TreeView (model);
scrolledWindow.Add (list); sw.Add (treeview);
stockFrame = new StockFrame (); TreeViewColumn column = new TreeViewColumn ();
hbox.PackStart (stockFrame, false, false, 0); column.Title = "Name";
CellRenderer renderer = new CellRendererPixbuf ();
column.PackStart (renderer, false);
column.SetAttributes (renderer, "stock_id", Column.Id);
renderer = new CellRendererText ();
column.PackStart (renderer, true);
column.SetAttributes (renderer, "text", Column.Name);
this.ShowAll (); treeview.AppendColumn (column);
treeview.AppendColumn ("Label", new CellRendererText (), "text", Column.Label);
treeview.AppendColumn ("Accel", new CellRendererText (), "text", Column.Accel);
treeview.AppendColumn ("ID", new CellRendererText (), "text", Column.Id);
Alignment align = new Alignment (0.5f, 0.0f, 0.0f, 0.0f);
hbox.PackEnd (align, false, false, 0);
Frame frame = new Frame ("Selected Item");
align.Add (frame);
VBox vbox = new VBox (false, 8);
vbox.BorderWidth = 8;
frame.Add (vbox);
typeLabel = new Label ();
vbox.PackStart (typeLabel, false, false, 0);
iconImage = new Gtk.Image ();
vbox.PackStart (iconImage, false, false, 0);
accelLabel = new Label ();
vbox.PackStart (accelLabel, false, false, 0);
nameLabel = new Label ();
vbox.PackStart (nameLabel, false, false, 0);
idLabel = new Label ();
vbox.PackStart (idLabel, false, false, 0);
treeview.Selection.Mode = Gtk.SelectionMode.Single;
treeview.Selection.Changed += new EventHandler (SelectionChanged);
ShowAll ();
} }
private ListStore CreateStore () private ListStore CreateModel ()
{ {
// FIXME: tremendous duplication of info ListStore store = new Gtk.ListStore (typeof (string), typeof(string), typeof(string), typeof(string), typeof (string));
// image, name, label, accel, id, StockInfo
ListStore store = new Gtk.ListStore (typeof (Gdk.Pixbuf), typeof(string), typeof(string), typeof(string), typeof (string), typeof (StockInfo));
string[] stock_ids = Gtk.Stock.ListIds (); string[] stockIds = Gtk.Stock.ListIds ();
Array.Sort (stockIds);
foreach (string s in stock_ids) // Use reflection to get the list of C# names
{ Hashtable idToName = new Hashtable ();
foreach (PropertyInfo info in typeof (Gtk.Stock).GetProperties (BindingFlags.Public | BindingFlags.Static)) {
if (info.PropertyType == typeof (string))
idToName[info.GetValue (null, null)] = "Gtk.Stock." + info.Name;
}
foreach (string id in stockIds) {
Gtk.StockItem si; Gtk.StockItem si;
si = Gtk.Stock.Lookup (s); string accel;
if (si.StockId != null) {
Gdk.Pixbuf icon = this.RenderIcon (s, IconSize.Menu, "");
StockInfo info = new StockInfo ();
info.Icon = icon;
info.Name = GetCLSName (si.StockId);
info.Label = si.Label;
info.Accel = GetKeyName (si);
info.ID = si.StockId;
// FIXME: si.Label needs to _AccelAware si = Gtk.Stock.Lookup (id);
store.AppendValues (icon, GetCLSName (si.StockId), si.Label, GetKeyName (si), si.StockId, info); if (si.Keyval != 0)
} accel = Accelerator.Name (si.Keyval, si.Modifier);
else { else
//Console.WriteLine ("StockItem '{0}' could not be found.", s); accel = "";
}
store.AppendValues (id, idToName[id], si.Label, accel);
} }
return store; return store;
} }
// changes 'gtk-stock-close' into 'Gtk.Stock.Close' void SelectionChanged (object o, EventArgs args)
// should use StudlyCaps from gapi2xml.pl instead
string GetCLSName (string stockID)
{
string cls = "";
if (stockID.StartsWith ("gtk-"))
cls = stockID.Substring (4, stockID.Length - 4);
char[] split = cls.ToCharArray ();
bool raiseNext = false;
ArrayList tmp = new ArrayList ();
tmp.Add (char.ToUpper (split[0]));
for (int i = 1; i < split.Length; i ++)
{
if (split[i] == '-') {
raiseNext = true;
continue;
}
if (raiseNext) {
tmp.Add (char.ToUpper (split[i]));
raiseNext = false;
}
else {
tmp.Add (split[i]);
}
}
split = new char[tmp.Count];
int j = 0;
foreach (char c in tmp)
split[j++] = c;
return "Gtk.Stock." + new string (split);
}
// use si.Keyval and si.Modifier
// to produce a reasonable representation
// of the key binding
string GetKeyName (StockItem si)
{
string mod = "";
string key = "";
switch (si.Modifier) {
// seems to be the only one used
case Gdk.ModifierType.ControlMask:
mod = "<Control>";
break;
default:
break;
}
if (si.Keyval > 0)
key = Gdk.Keyval.Name (si.Keyval);
return String.Format ("{0} {1}", mod, key);
}
void OnSelectionChanged (object o, EventArgs args)
{ {
TreeSelection selection = (TreeSelection)o;
TreeIter iter; TreeIter iter;
TreeModel model; TreeModel model;
if (((TreeSelection) o).GetSelected (out model, out iter)) if (selection.GetSelected (out model, out iter)) {
{ string id = (string) model.GetValue (iter, (int)Column.Id);
StockInfo info = (StockInfo) model.GetValue (iter, 5); string name = (string) model.GetValue (iter, (int)Column.Name);
stockFrame.Info = info; string label = (string) model.GetValue (iter, (int)Column.Label);
string accel = (string) model.GetValue (iter, (int)Column.Accel);
IconSize size = GetLargestSize (id);
bool icon = (size != IconSize.Invalid);
if (icon && label != null)
typeLabel.Text = "Icon and Item";
else if (icon)
typeLabel.Text = "Icon Only";
else if (label != null)
typeLabel.Text = "Item Only";
else
typeLabel.Text = "???????";
if (name != null)
nameLabel.Text = name;
else
nameLabel.Text = "";
idLabel.Text = id;
if (label != null)
accelLabel.TextWithMnemonic = label + " " + accel;
else
accelLabel.Text = "";
if (icon)
iconImage.SetFromStock (id, size);
else
iconImage.Pixbuf = null;
} else {
typeLabel.Text = "No selected item";
nameLabel.Text = "";
idLabel.Text = "";
accelLabel.Text = "";
iconImage.Pixbuf = null;
} }
} }
private void WindowDelete (object o, DeleteEventArgs args) // Finds the largest size at which the given image stock id is
// available. This would not be useful for a normal application
private IconSize GetLargestSize (string stockId)
{ {
this.Hide (); IconSet set = IconFactory.LookupDefault (stockId);
this.Destroy (); if (set == null)
args.RetVal = true; return IconSize.Invalid;
}
IconSize[] sizes = set.Sizes;
IconSize bestSize = IconSize.Invalid;
int bestPixels = 0;
foreach (IconSize size in sizes) {
int width, height;
Gtk.Icon.SizeLookup (size, out width, out height);
if (width * height > bestPixels) {
bestSize = size;
bestPixels = width * height;
} }
} }
return bestSize;
}
protected override bool OnDeleteEvent (Gdk.Event evt)
{
Destroy ();
return true;
}
}
}

View file

@ -1,11 +1,4 @@
// /* Text Widget/Multiple Views
// DemoTextView.cs, port of textview.c form gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// (C) 2003 Ximian, Inc.
/* Text Widget
* *
* The Gtk.TextView widget displays a Gtk.TextBuffer. One Gtk.TextBuffer * The Gtk.TextView widget displays a Gtk.TextBuffer. One Gtk.TextBuffer
* can be displayed by multiple Gtk.TextViews. This demo has two views * can be displayed by multiple Gtk.TextViews. This demo has two views
@ -27,34 +20,31 @@ namespace GtkDemo
TextView view1; TextView view1;
TextView view2; TextView view2;
public DemoTextView () : base ("TextView Demo") public DemoTextView () : base ("TextView")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete); SetDefaultSize (450,450);
this.SetDefaultSize (450,450); BorderWidth = 0;
this.BorderWidth = 6;
VPaned vpaned = new VPaned (); VPaned vpaned = new VPaned ();
vpaned.BorderWidth = 5; vpaned.BorderWidth = 5;
this.Add (vpaned); Add (vpaned);
/* For convenience, we just use the autocreated buffer from // For convenience, we just use the autocreated buffer from
* the first text view; you could also create the buffer // the first text view; you could also create the buffer
* by itself with new Gtk.TextBuffer (), then later create // by itself, then later create a view widget.
* a view widget.
*/
view1 = new TextView (); view1 = new TextView ();
TextBuffer buffer = view1.Buffer; TextBuffer buffer = view1.Buffer;
view2 = new TextView (buffer); view2 = new TextView (buffer);
ScrolledWindow scrolledWindow = new ScrolledWindow (); ScrolledWindow sw = new ScrolledWindow ();
scrolledWindow.SetPolicy (PolicyType.Automatic, Gtk.PolicyType.Automatic); sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vpaned.Add1 (scrolledWindow); vpaned.Add1 (sw);
scrolledWindow.Add (view1); sw.Add (view1);
scrolledWindow = new Gtk.ScrolledWindow (); sw = new ScrolledWindow ();
scrolledWindow.SetPolicy (Gtk.PolicyType.Automatic, Gtk.PolicyType.Automatic); sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vpaned.Add2 (scrolledWindow); vpaned.Add2 (sw);
scrolledWindow.Add (view2); sw.Add (view2);
CreateTags (buffer); CreateTags (buffer);
InsertText (buffer); InsertText (buffer);
@ -62,9 +52,7 @@ namespace GtkDemo
AttachWidgets (view1); AttachWidgets (view1);
AttachWidgets (view2); AttachWidgets (view2);
vpaned.ShowAll(); ShowAll ();
this.ShowAll ();
} }
private TextChildAnchor buttonAnchor; private TextChildAnchor buttonAnchor;
@ -75,6 +63,9 @@ namespace GtkDemo
private void AttachWidgets (TextView textView) private void AttachWidgets (TextView textView)
{ {
// This is really different from the C version, but the
// C versions seems a little pointless.
Button button = new Button ("Click Me"); Button button = new Button ("Click Me");
button.Clicked += new EventHandler(EasterEggCB); button.Clicked += new EventHandler(EasterEggCB);
textView.AddChildAtAnchor (button, buttonAnchor); textView.AddChildAtAnchor (button, buttonAnchor);
@ -84,7 +75,6 @@ namespace GtkDemo
combo.AppendText ("Option 1"); combo.AppendText ("Option 1");
combo.AppendText ("Option 2"); combo.AppendText ("Option 2");
combo.AppendText ("Option 3"); combo.AppendText ("Option 3");
combo.Active = 0;
textView.AddChildAtAnchor (combo, menuAnchor); textView.AddChildAtAnchor (combo, menuAnchor);
@ -94,7 +84,7 @@ namespace GtkDemo
textView.AddChildAtAnchor (scale, scaleAnchor); textView.AddChildAtAnchor (scale, scaleAnchor);
scale.ShowAll (); scale.ShowAll ();
Gtk.Image image = new Gtk.Image (Gdk.Pixbuf.LoadFromResource ("floppybuddy.gif")); Gtk.Image image = Gtk.Image.LoadFromResource ("floppybuddy.gif");
textView.AddChildAtAnchor (image, animationAnchor); textView.AddChildAtAnchor (image, animationAnchor);
image.ShowAll (); image.ShowAll ();
@ -103,26 +93,29 @@ namespace GtkDemo
entry.ShowAll (); entry.ShowAll ();
} }
const int gray50_width = 2;
const int gray50_height = 2;
const string gray50_bits = "\x02\x01";
private void CreateTags (TextBuffer buffer) private void CreateTags (TextBuffer buffer)
{ {
/* Create a bunch of tags. Note that it's also possible to // Create a bunch of tags. Note that it's also possible to
* create tags with gtk_text_tag_new() then add them to the // create tags with gtk_text_tag_new() then add them to the
* tag table for the buffer, gtk_text_buffer_create_tag() is // tag table for the buffer, gtk_text_buffer_create_tag() is
* just a convenience function. Also note that you don't have // just a convenience function. Also note that you don't have
* to give tags a name; pass NULL for the name to create an // to give tags a name; pass NULL for the name to create an
* anonymous tag. // anonymous tag.
* //
* In any real app, another useful optimization would be to create // In any real app, another useful optimization would be to create
* a GtkTextTagTable in advance, and reuse the same tag table for // a GtkTextTagTable in advance, and reuse the same tag table for
* all the buffers with the same tag set, instead of creating // all the buffers with the same tag set, instead of creating
* new copies of the same tags for every buffer. // new copies of the same tags for every buffer.
* //
* Tags are assigned default priorities in order of addition to the // Tags are assigned default priorities in order of addition to the
* tag table. That is, tags created later that affect the same text // tag table. That is, tags created later that affect the same text
* property affected by an earlier tag will override the earlier // property affected by an earlier tag will override the earlier
* tag. You can modify tag priorities with // tag. You can modify tag priorities with
* gtk_text_tag_set_priority(). // gtk_text_tag_set_priority().
*/
TextTag tag = new TextTag ("heading"); TextTag tag = new TextTag ("heading");
tag.Weight = Pango.Weight.Bold; tag.Weight = Pango.Weight.Bold;
@ -161,15 +154,11 @@ namespace GtkDemo
tag.Background = "red"; tag.Background = "red";
buffer.TagTable.Add (tag); buffer.TagTable.Add (tag);
int gray50_width = 2;
int gray50_height = 2;
string gray50_bits = new string ((char) 0x02, (char) 0x01);
// The C gtk-demo passes NULL for the drawable param, which isn't // The C gtk-demo passes NULL for the drawable param, which isn't
// multi-head safe, so it seems bad to allow it in the C# API. // multi-head safe, so it seems bad to allow it in the C# API.
// But the Window isn't realized at this point, so we can't get // But the Window isn't realized at this point, so we can't get
// an actual Drawable from it. So we kludge for now. // an actual Drawable from it. So we kludge for now.
Pixmap stipple = Pixmap.CreateBitmapFromData (Gdk.Screen.Default.RootWindow, (string) gray50_bits, gray50_width, gray50_height); Pixmap stipple = Pixmap.CreateBitmapFromData (Gdk.Screen.Default.RootWindow, gray50_bits, gray50_width, gray50_height);
tag = new TextTag ("background_stipple"); tag = new TextTag ("background_stipple");
tag.BackgroundStipple = stipple; tag.BackgroundStipple = stipple;
@ -253,21 +242,18 @@ namespace GtkDemo
private void InsertText (TextBuffer buffer) private void InsertText (TextBuffer buffer)
{ {
// we use resources for portability and convenience
Pixbuf pixbuf = Gdk.Pixbuf.LoadFromResource ("gtk-logo-rgb.gif"); Pixbuf pixbuf = Gdk.Pixbuf.LoadFromResource ("gtk-logo-rgb.gif");
pixbuf.ScaleSimple (32, 32, InterpType.Bilinear); pixbuf = pixbuf.ScaleSimple (32, 32, InterpType.Bilinear);
/* get start of buffer; each insertion will revalidate the // get start of buffer; each insertion will revalidate the
* iterator to point to just after the inserted text. // iterator to point to just after the inserted text.
*/
TextIter insertIter; TextIter insertIter = buffer.StartIter;
insertIter = buffer.GetIterAtOffset (0);
buffer.Insert (ref insertIter, buffer.Insert (ref insertIter,
"The text widget can display text with all kinds of nifty attributes. It also supports multiple views of the same buffer; this demo is showing the same buffer in two places.\n\n"); "The text widget can display text with all kinds of nifty attributes. It also supports multiple views of the same buffer; this demo is showing the same buffer in two places.\n\n");
buffer.InsertWithTagsByName (ref insertIter, "Font styles. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Font styles. ", "heading");
buffer.Insert (ref insertIter, "For example, you can have "); buffer.Insert (ref insertIter, "For example, you can have ");
buffer.InsertWithTagsByName (ref insertIter, "italic", "italic"); buffer.InsertWithTagsByName (ref insertIter, "italic", "italic");
buffer.Insert (ref insertIter, ", "); buffer.Insert (ref insertIter, ", ");
@ -276,106 +262,122 @@ namespace GtkDemo
buffer.InsertWithTagsByName (ref insertIter, "monospace (typewriter)", "monospace"); buffer.InsertWithTagsByName (ref insertIter, "monospace (typewriter)", "monospace");
buffer.Insert (ref insertIter, ", or "); buffer.Insert (ref insertIter, ", or ");
buffer.InsertWithTagsByName (ref insertIter, "big", "big"); buffer.InsertWithTagsByName (ref insertIter, "big", "big");
buffer.Insert (ref insertIter, " text"); buffer.Insert (ref insertIter, " text. ");
buffer.Insert (ref insertIter, buffer.Insert (ref insertIter,
"It's best not to hardcode specific text sizes; you can use relative sizes as with CSS, such as "); "It's best not to hardcode specific text sizes; you can use relative sizes as with CSS, such as ");
buffer.InsertWithTagsByName (ref insertIter, "xx-small", "xx-small"); buffer.InsertWithTagsByName (ref insertIter, "xx-small", "xx-small");
buffer.Insert (ref insertIter, ", or"); buffer.Insert (ref insertIter, " or");
buffer.InsertWithTagsByName (ref insertIter, "x-large", "x-large"); buffer.InsertWithTagsByName (ref insertIter, "x-large", "x-large");
buffer.Insert (ref insertIter, buffer.Insert (ref insertIter,
" to ensure that your program properly adapts if the user changes the default font size.\n\n"); " to ensure that your program properly adapts if the user changes the default font size.\n\n");
buffer.InsertWithTagsByName (ref insertIter, "Colors such as", "heading");
buffer.InsertWithTagsByName (ref insertIter, "Colors. ", "heading");
buffer.Insert (ref insertIter, "Colors such as ");
buffer.InsertWithTagsByName (ref insertIter, "a blue foreground", "blue_foreground"); buffer.InsertWithTagsByName (ref insertIter, "a blue foreground", "blue_foreground");
buffer.Insert (ref insertIter, ", or "); buffer.Insert (ref insertIter, " or ");
buffer.InsertWithTagsByName (ref insertIter, "a red background", "red_background"); buffer.InsertWithTagsByName (ref insertIter, "a red background", "red_background");
buffer.Insert (ref insertIter, " or even "); buffer.Insert (ref insertIter, " or even ");
buffer.InsertWithTagsByName (ref insertIter, "a stippled red background", buffer.InsertWithTagsByName (ref insertIter, "a stippled red background",
"red_background", "red_background",
"background_stipple"); "background_stipple");
buffer.Insert (ref insertIter, ", or ");
buffer.Insert (ref insertIter, " or ");
buffer.InsertWithTagsByName (ref insertIter, buffer.InsertWithTagsByName (ref insertIter,
"a stippled blue foreground on solid red background", "a stippled blue foreground on solid red background",
"blue_foreground", "blue_foreground",
"red_background", "red_background",
"foreground_stipple"); "foreground_stipple");
buffer.Insert (ref insertIter, " (select that to read it) can be used.\n\n"); buffer.Insert (ref insertIter, " (select that to read it) can be used.\n\n");
buffer.InsertWithTagsByName (ref insertIter, "Underline, strikethrough, and rise. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Underline, strikethrough, and rise. ", "heading");
buffer.InsertWithTagsByName (ref insertIter, "Strikethrough", "strikethrough"); buffer.InsertWithTagsByName (ref insertIter, "Strikethrough", "strikethrough");
buffer.Insert (ref insertIter, ", "); buffer.Insert (ref insertIter, ", ");
buffer.InsertWithTagsByName (ref insertIter, "underline", "underline"); buffer.InsertWithTagsByName (ref insertIter, "underline", "underline");
buffer.Insert (ref insertIter, ", "); buffer.Insert (ref insertIter, ", ");
buffer.InsertWithTagsByName (ref insertIter, "double_underline", "double_underline"); buffer.InsertWithTagsByName (ref insertIter, "double underline", "double_underline");
buffer.Insert (ref insertIter, ", "); buffer.Insert (ref insertIter, ", ");
buffer.InsertWithTagsByName (ref insertIter, "superscript", "superscript"); buffer.InsertWithTagsByName (ref insertIter, "superscript", "superscript");
buffer.Insert (ref insertIter, ", and "); buffer.Insert (ref insertIter, ", and ");
buffer.InsertWithTagsByName (ref insertIter, "subscript", "subscript"); buffer.InsertWithTagsByName (ref insertIter, "subscript", "subscript");
buffer.Insert (ref insertIter, " are all supported.\n\n"); buffer.Insert (ref insertIter, " are all supported.\n\n");
buffer.InsertWithTagsByName (ref insertIter, "Images. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Images. ", "heading");
buffer.Insert (ref insertIter, "The buffer can have images in it: "); buffer.Insert (ref insertIter, "The buffer can have images in it: ");
insertIter = buffer.GetIterAtMark (buffer.InsertMark);
buffer.InsertPixbuf (ref insertIter, pixbuf); buffer.InsertPixbuf (ref insertIter, pixbuf);
insertIter = buffer.GetIterAtMark (buffer.InsertMark);
buffer.InsertPixbuf (ref insertIter, pixbuf); buffer.InsertPixbuf (ref insertIter, pixbuf);
insertIter = buffer.GetIterAtMark (buffer.InsertMark);
buffer.InsertPixbuf (ref insertIter, pixbuf); buffer.InsertPixbuf (ref insertIter, pixbuf);
buffer.Insert (ref insertIter, " for example.\n\n"); buffer.Insert (ref insertIter, " for example.\n\n");
buffer.InsertWithTagsByName (ref insertIter, "Spacing. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Spacing. ", "heading");
buffer.InsertWithTagsByName (ref insertIter, "You can adjust the amount of space before each line.\n", "big_gap_before_line", "wide_margins");
buffer.InsertWithTagsByName (ref insertIter, "You can also adjust the amount of space after each line; this line has a whole lot of space after it.\n", "big_gap_after_line", "wide_margins"); buffer.Insert (ref insertIter, "You can adjust the amount of space before each line.\n");
buffer.InsertWithTagsByName (ref insertIter, "You can also adjust the amount of space between wrapped lines; this line has extra space between each wrapped line in the same paragraph. To show off wrapping, some filler text: the quick brown fox jumped over the lazy dog. Blah blah blah blah blah blah blah blah blah.\n", "double_spaced_line", "wide_margins"); buffer.InsertWithTagsByName (ref insertIter, "This line has a whole lot of space before it.\n",
"big_gap_before_line", "wide_margins");
buffer.InsertWithTagsByName (ref insertIter, "You can also adjust the amount of space after each line; this line has a whole lot of space after it.\n",
"big_gap_after_line", "wide_margins");
buffer.InsertWithTagsByName (ref insertIter, "You can also adjust the amount of space between wrapped lines; this line has extra space between each wrapped line in the same paragraph. To show off wrapping, some filler text: the quick brown fox jumped over the lazy dog. Blah blah blah blah blah blah blah blah blah.\n",
"double_spaced_line", "wide_margins");
buffer.Insert (ref insertIter, "Also note that those lines have extra-wide margins.\n\n"); buffer.Insert (ref insertIter, "Also note that those lines have extra-wide margins.\n\n");
buffer.InsertWithTagsByName (ref insertIter, "Editability. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Editability. ", "heading");
buffer.InsertWithTagsByName (ref insertIter, "This line is 'locked down' and can't be edited by the user - just try it! You can't delete this line.\n\n", "not_editable");
buffer.InsertWithTagsByName (ref insertIter, "This line is 'locked down' and can't be edited by the user - just try it! You can't delete this line.\n\n",
"not_editable");
buffer.InsertWithTagsByName (ref insertIter, "Wrapping. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Wrapping. ", "heading");
buffer.Insert (ref insertIter, "This line (and most of the others in this buffer) is word-wrapped, using the proper Unicode algorithm. Word wrap should work in all scripts and languages that GTK+ supports. Let's make this a long paragraph to demonstrate: blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\n\n"); buffer.Insert (ref insertIter, "This line (and most of the others in this buffer) is word-wrapped, using the proper Unicode algorithm. Word wrap should work in all scripts and languages that GTK+ supports. Let's make this a long paragraph to demonstrate: blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\n\n");
buffer.InsertWithTagsByName (ref insertIter, "This line has character-based wrapping, and can wrap between any two character glyphs. Let's make this a long paragraph to demonstrate: blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\n\n", "char_wrap");
buffer.InsertWithTagsByName (ref insertIter, "This line has all wrapping turned off, so it makes the horizontal scrollbar appear.\n\n\n", "no_wrap"); buffer.InsertWithTagsByName (ref insertIter, "This line has character-based wrapping, and can wrap between any two character glyphs. Let's make this a long paragraph to demonstrate: blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\n\n",
"char_wrap");
buffer.InsertWithTagsByName (ref insertIter, "This line has all wrapping turned off, so it makes the horizontal scrollbar appear.\n\n\n",
"no_wrap");
buffer.InsertWithTagsByName (ref insertIter, "Justification. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Justification. ", "heading");
buffer.InsertWithTagsByName (ref insertIter, "\nThis line has center justification.\n", "center"); buffer.InsertWithTagsByName (ref insertIter, "\nThis line has center justification.\n", "center");
buffer.InsertWithTagsByName (ref insertIter, "This line has right justification.\n", "right_justify"); buffer.InsertWithTagsByName (ref insertIter, "This line has right justification.\n", "right_justify");
buffer.InsertWithTagsByName (ref insertIter, "\nThis line has big wide margins. Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.\n", "wide_margins");
buffer.InsertWithTagsByName (ref insertIter, "\nThis line has big wide margins. Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.\n",
"wide_margins");
buffer.InsertWithTagsByName (ref insertIter, "Internationalization. ", "heading"); buffer.InsertWithTagsByName (ref insertIter, "Internationalization. ", "heading");
buffer.Insert (ref insertIter, "You can put all sorts of Unicode text in the buffer.\n\nGerman (Deutsch S\u00fcd) Gr\u00fc\u00df Gott\nGreek (\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac) \u0393\u03b5\u03b9\u03ac \u03c3\u03b1\u03c2\nHebrew \u05e9\u05dc\u05d5\u05dd\nJapanese (\u65e5\u672c\u8a9e)\n\nThe widget properly handles bidirectional text, word wrapping, DOS/UNIX/Unicode paragraph separators, grapheme boundaries, and so on using the Pango internationalization framework.\n"); buffer.Insert (ref insertIter, "You can put all sorts of Unicode text in the buffer.\n\nGerman (Deutsch S\u00fcd) Gr\u00fc\u00df Gott\nGreek (\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac) \u0393\u03b5\u03b9\u03ac \u03c3\u03b1\u03c2\nHebrew \u05e9\u05dc\u05d5\u05dd\nJapanese (\u65e5\u672c\u8a9e)\n\nThe widget properly handles bidirectional text, word wrapping, DOS/UNIX/Unicode paragraph separators, grapheme boundaries, and so on using the Pango internationalization framework.\n");
buffer.Insert (ref insertIter, "Here's a word-wrapped quote in a right-to-left language:\n");
buffer.Insert (ref insertIter, "Here's a word-wrapped quote in a right-to-left language:\n");
buffer.InsertWithTagsByName (ref insertIter, "\u0648\u0642\u062f \u0628\u062f\u0623 \u062b\u0644\u0627\u062b \u0645\u0646 \u0623\u0643\u062b\u0631 \u0627\u0644\u0645\u0624\u0633\u0633\u0627\u062a \u062a\u0642\u062f\u0645\u0627 \u0641\u064a \u0634\u0628\u0643\u0629 \u0627\u0643\u0633\u064a\u0648\u0646 \u0628\u0631\u0627\u0645\u062c\u0647\u0627 \u0643\u0645\u0646\u0638\u0645\u0627\u062a \u0644\u0627 \u062a\u0633\u0639\u0649 \u0644\u0644\u0631\u0628\u062d\u060c \u062b\u0645 \u062a\u062d\u0648\u0644\u062a \u0641\u064a \u0627\u0644\u0633\u0646\u0648\u0627\u062a \u0627\u0644\u062e\u0645\u0633 \u0627\u0644\u0645\u0627\u0636\u064a\u0629 \u0625\u0644\u0649 \u0645\u0624\u0633\u0633\u0627\u062a \u0645\u0627\u0644\u064a\u0629 \u0645\u0646\u0638\u0645\u0629\u060c \u0648\u0628\u0627\u062a\u062a \u062c\u0632\u0621\u0627 \u0645\u0646 \u0627\u0644\u0646\u0638\u0627\u0645 \u0627\u0644\u0645\u0627\u0644\u064a \u0641\u064a \u0628\u0644\u062f\u0627\u0646\u0647\u0627\u060c \u0648\u0644\u0643\u0646\u0647\u0627 \u062a\u062a\u062e\u0635\u0635 \u0641\u064a \u062e\u062f\u0645\u0629 \u0642\u0637\u0627\u0639 \u0627\u0644\u0645\u0634\u0631\u0648\u0639\u0627\u062a \u0627\u0644\u0635\u063a\u064a\u0631\u0629\u002e \u0648\u0623\u062d\u062f \u0623\u0643\u062b\u0631 \u0647\u0630\u0647 \u0627\u0644\u0645\u0624\u0633\u0633\u0627\u062a \u0646\u062c\u0627\u062d\u0627 \u0647\u0648 \u00bb\u0628\u0627\u0646\u0643\u0648\u0633\u0648\u0644\u00ab \u0641\u064a \u0628\u0648\u0644\u064a\u0641\u064a\u0627.\n\n", "rtl_quote"); buffer.InsertWithTagsByName (ref insertIter, "\u0648\u0642\u062f \u0628\u062f\u0623 \u062b\u0644\u0627\u062b \u0645\u0646 \u0623\u0643\u062b\u0631 \u0627\u0644\u0645\u0624\u0633\u0633\u0627\u062a \u062a\u0642\u062f\u0645\u0627 \u0641\u064a \u0634\u0628\u0643\u0629 \u0627\u0643\u0633\u064a\u0648\u0646 \u0628\u0631\u0627\u0645\u062c\u0647\u0627 \u0643\u0645\u0646\u0638\u0645\u0627\u062a \u0644\u0627 \u062a\u0633\u0639\u0649 \u0644\u0644\u0631\u0628\u062d\u060c \u062b\u0645 \u062a\u062d\u0648\u0644\u062a \u0641\u064a \u0627\u0644\u0633\u0646\u0648\u0627\u062a \u0627\u0644\u062e\u0645\u0633 \u0627\u0644\u0645\u0627\u0636\u064a\u0629 \u0625\u0644\u0649 \u0645\u0624\u0633\u0633\u0627\u062a \u0645\u0627\u0644\u064a\u0629 \u0645\u0646\u0638\u0645\u0629\u060c \u0648\u0628\u0627\u062a\u062a \u062c\u0632\u0621\u0627 \u0645\u0646 \u0627\u0644\u0646\u0638\u0627\u0645 \u0627\u0644\u0645\u0627\u0644\u064a \u0641\u064a \u0628\u0644\u062f\u0627\u0646\u0647\u0627\u060c \u0648\u0644\u0643\u0646\u0647\u0627 \u062a\u062a\u062e\u0635\u0635 \u0641\u064a \u062e\u062f\u0645\u0629 \u0642\u0637\u0627\u0639 \u0627\u0644\u0645\u0634\u0631\u0648\u0639\u0627\u062a \u0627\u0644\u0635\u063a\u064a\u0631\u0629\u002e \u0648\u0623\u062d\u062f \u0623\u0643\u062b\u0631 \u0647\u0630\u0647 \u0627\u0644\u0645\u0624\u0633\u0633\u0627\u062a \u0646\u062c\u0627\u062d\u0627 \u0647\u0648 \u00bb\u0628\u0627\u0646\u0643\u0648\u0633\u0648\u0644\u00ab \u0641\u064a \u0628\u0648\u0644\u064a\u0641\u064a\u0627.\n\n", "rtl_quote");
buffer.Insert (ref insertIter, "You can put widgets in the buffer: Here's a button: "); buffer.Insert (ref insertIter, "You can put widgets in the buffer: Here's a button: ");
insertIter = buffer.GetIterAtMark(buffer.InsertMark);
buttonAnchor = buffer.CreateChildAnchor (ref insertIter); buttonAnchor = buffer.CreateChildAnchor (ref insertIter);
buffer.Insert (ref insertIter, " and a menu: ");
buffer.Insert (ref insertIter, "and a menu");
insertIter = buffer.GetIterAtMark(buffer.InsertMark);
menuAnchor = buffer.CreateChildAnchor (ref insertIter); menuAnchor = buffer.CreateChildAnchor (ref insertIter);
buffer.Insert (ref insertIter, " and a scale: ");
buffer.Insert (ref insertIter, "and a scale");
insertIter = buffer.GetIterAtMark(buffer.InsertMark);
scaleAnchor = buffer.CreateChildAnchor (ref insertIter); scaleAnchor = buffer.CreateChildAnchor (ref insertIter);
buffer.Insert (ref insertIter, " and an animation: ");
buffer.Insert (ref insertIter, "and an animation");
insertIter = buffer.GetIterAtMark(buffer.InsertMark);
animationAnchor = buffer.CreateChildAnchor (ref insertIter); animationAnchor = buffer.CreateChildAnchor (ref insertIter);
buffer.Insert (ref insertIter, " finally a text entry: "); buffer.Insert (ref insertIter, " finally a text entry: ");
insertIter = buffer.GetIterAtMark(buffer.InsertMark);
entryAnchor = buffer.CreateChildAnchor (ref insertIter); entryAnchor = buffer.CreateChildAnchor (ref insertIter);
buffer.Insert (ref insertIter, ".\n");
buffer.Insert (ref insertIter, "\n");
buffer.Insert (ref insertIter, "\n\nThis demo doesn't demonstrate all the GtkTextBuffer features; it leaves out, for example: invisible/hidden text (doesn't work in GTK 2, but planned), tab stops, application-drawn areas on the sides of the widget for displaying breakpoints and such..."); buffer.Insert (ref insertIter, "\n\nThis demo doesn't demonstrate all the GtkTextBuffer features; it leaves out, for example: invisible/hidden text (doesn't work in GTK 2, but planned), tab stops, application-drawn areas on the sides of the widget for displaying breakpoints and such...");
buffer.ApplyTag ("word_wrap", buffer.StartIter, buffer.EndIter); buffer.ApplyTag ("word_wrap", buffer.StartIter, buffer.EndIter);
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
private void RecursiveAttach (int depth, TextView view, TextChildAnchor anchor) private void RecursiveAttach (int depth, TextView view, TextChildAnchor anchor)
@ -384,10 +386,12 @@ namespace GtkDemo
return; return;
TextView childView = new TextView (view.Buffer); TextView childView = new TextView (view.Buffer);
/* Event box is to add a black border around each child view */
// Event box is to add a black border around each child view
EventBox eventBox = new EventBox (); EventBox eventBox = new EventBox ();
Gdk.Color blackColor = new Gdk.Color (0x0, 0x0, 0x0); Gdk.Color color = new Gdk.Color ();
eventBox.ModifyBg (StateType.Normal,blackColor); Gdk.Color.Parse ("black", ref color);
eventBox.ModifyBg (StateType.Normal, color);
Alignment align = new Alignment (0.5f, 0.5f, 1.0f, 1.0f); Alignment align = new Alignment (0.5f, 0.5f, 1.0f, 1.0f);
align.BorderWidth = 1; align.BorderWidth = 1;
@ -404,21 +408,21 @@ namespace GtkDemo
{ {
TextIter insertIter; TextIter insertIter;
TextBuffer bufferCB = new TextBuffer (null); TextBuffer buffer = new TextBuffer (null);
insertIter = bufferCB.GetIterAtOffset (0); insertIter = buffer.StartIter;
bufferCB.Insert (ref insertIter, "This buffer is shared by a set of nested text views.\n Nested view:\n"); buffer.Insert (ref insertIter, "This buffer is shared by a set of nested text views.\n Nested view:\n");
TextChildAnchor anchor = bufferCB.CreateChildAnchor (ref insertIter); TextChildAnchor anchor = buffer.CreateChildAnchor (ref insertIter);
bufferCB.Insert (ref insertIter, "\nDon't do this in real applications, please.\n"); buffer.Insert (ref insertIter, "\nDon't do this in real applications, please.\n");
TextView viewCB = new TextView (bufferCB); TextView view = new TextView (buffer);
RecursiveAttach (0, viewCB, anchor); RecursiveAttach (0, view, anchor);
Gtk.Window window = new Gtk.Window (null); Gtk.Window window = new Gtk.Window (Gtk.WindowType.Toplevel);
ScrolledWindow scrolledWindow = new ScrolledWindow (null, null); ScrolledWindow sw = new ScrolledWindow ();
scrolledWindow.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
window.Add (scrolledWindow); window.Add (sw);
scrolledWindow.Add (viewCB); sw.Add (view);
window.SetDefaultSize (300, 400); window.SetDefaultSize (300, 400);
window.ShowAll (); window.ShowAll ();

View file

@ -1,10 +1,3 @@
//
// DemoTreeItem.cs, port of tree_store.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Tree View/Tree Store /* Tree View/Tree Store
* *
* The Gtk.TreeStore is used to store data in tree form, to be * The Gtk.TreeStore is used to store data in tree form, to be
@ -27,20 +20,19 @@ namespace GtkDemo
{ {
private TreeStore store; private TreeStore store;
public DemoTreeStore () : base ("TreeStore Demo") public DemoTreeStore () : base ("Card planning sheet")
{ {
this.DeleteEvent += new DeleteEventHandler (WindowDelete);
VBox vbox = new VBox (false, 8); VBox vbox = new VBox (false, 8);
vbox.BorderWidth = 8; vbox.BorderWidth = 8;
this.Add (vbox); Add (vbox);
vbox.PackStart (new Label ("Jonathan's Holiday Card Planning Sheet"), false, false, 0); vbox.PackStart (new Label ("Jonathan's Holiday Card Planning Sheet"),
false, false, 0);
ScrolledWindow scrolledWindow = new ScrolledWindow (); ScrolledWindow sw = new ScrolledWindow ();
scrolledWindow.ShadowType = ShadowType.EtchedIn; sw.ShadowType = ShadowType.EtchedIn;
scrolledWindow.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
vbox.PackStart (scrolledWindow, true, true, 0); vbox.PackStart (sw, true, true, 0);
// create model // create model
CreateModel (); CreateModel ();
@ -48,128 +40,129 @@ namespace GtkDemo
// create tree view // create tree view
TreeView treeView = new TreeView (store); TreeView treeView = new TreeView (store);
treeView.RulesHint = true; treeView.RulesHint = true;
TreeSelection treeSelection = treeView.Selection; treeView.Selection.Mode = SelectionMode.Multiple;
treeSelection.Mode = SelectionMode.Multiple;
AddColumns (treeView); AddColumns (treeView);
scrolledWindow.Add (treeView);
sw.Add (treeView);
// expand all rows after the treeview widget has been realized // expand all rows after the treeview widget has been realized
for (int i = 0; i < 12; i++) treeView.Realized += ExpandRows;
{
treeView.ExpandRow (new TreePath (i.ToString ()), false); SetDefaultSize (650, 400);
ShowAll ();
} }
this.SetDefaultSize (650, 400); private void ExpandRows (object obj, EventArgs args)
this.ShowAll (); {
TreeView treeView = obj as TreeView;
treeView.ExpandAll ();
} }
ArrayList columns = new ArrayList ();
private void ItemToggled (object sender, ToggledArgs args) private void ItemToggled (object sender, ToggledArgs args)
{ {
CellRendererToggle cellRendererToggle = sender as CellRendererToggle; int column = columns.IndexOf (sender);
int column = (int) cellRendererToggle.PersistentData["column"];
Gtk.TreeIter iter; Gtk.TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) if (store.GetIterFromString (out iter, args.Path)) {
{
bool val = (bool) store.GetValue (iter, column); bool val = (bool) store.GetValue (iter, column);
Console.WriteLine ("toggled {0} with value {1}", args.Path, !val);
store.SetValue (iter, column, !val); store.SetValue (iter, column, !val);
} }
} }
private void AddColumns (TreeView treeView) private void AddColumns (TreeView treeView)
{ {
CellRendererText text;
CellRendererToggle toggle;
// column for holiday names // column for holiday names
CellRendererText rendererText = new CellRendererText (); text = new CellRendererText ();
rendererText.Xalign = 0.0f; text.Xalign = 0.0f;
rendererText.PersistentData ["column"] = Column.HolidayName; columns.Add (text);
TreeViewColumn column = new TreeViewColumn ("Holiday", rendererText, TreeViewColumn column = new TreeViewColumn ("Holiday", text,
"text", Column.HolidayName); "text", Column.HolidayName);
treeView.InsertColumn (column, (int) Column.HolidayName); treeView.InsertColumn (column, (int) Column.HolidayName);
// alex column // alex column
CellRendererToggle rendererToggle = new CellRendererToggle (); toggle = new CellRendererToggle ();
rendererToggle.Xalign = 0.0f; toggle.Xalign = 0.0f;
rendererToggle.PersistentData ["column"] = Column.Alex; columns.Add (toggle);
rendererToggle.Toggled += new ToggledHandler (ItemToggled); toggle.Toggled += new ToggledHandler (ItemToggled);
rendererToggle.Visible = true; column = new TreeViewColumn ("Alex", toggle,
rendererToggle.Activatable = true; "active", (int) Column.Alex,
rendererToggle.Active = true; "visible", (int) Column.Visible,
column = new TreeViewColumn ("Alex", rendererToggle, "active", (int) Column.Alex); "activatable", (int) Column.World);
column.Sizing = TreeViewColumnSizing.Fixed; column.Sizing = TreeViewColumnSizing.Fixed;
column.FixedWidth = 50; column.FixedWidth = 50;
column.Clickable = true; column.Clickable = true;
treeView.InsertColumn (column, (int) Column.Alex); treeView.InsertColumn (column, (int) Column.Alex);
// havoc column // havoc column
rendererToggle = new CellRendererToggle (); toggle = new CellRendererToggle ();
rendererToggle.Xalign = 0.0f; toggle.Xalign = 0.0f;
rendererToggle.PersistentData ["column"] = Column.Havoc; columns.Add (toggle);
rendererToggle.Toggled += new ToggledHandler (ItemToggled); toggle.Toggled += new ToggledHandler (ItemToggled);
column = new TreeViewColumn ("Havoc", rendererToggle, "active", (int) Column.Havoc); column = new TreeViewColumn ("Havoc", toggle,
column.Visible = true; "active", (int) Column.Havoc,
rendererToggle.Activatable = true; "visible", (int) Column.Visible);
rendererToggle.Active = true;
treeView.InsertColumn (column, (int) Column.Havoc); treeView.InsertColumn (column, (int) Column.Havoc);
column.Sizing = TreeViewColumnSizing.Fixed; column.Sizing = TreeViewColumnSizing.Fixed;
column.FixedWidth = 50; column.FixedWidth = 50;
column.Clickable = true; column.Clickable = true;
// tim column // tim column
rendererToggle = new CellRendererToggle (); toggle = new CellRendererToggle ();
rendererToggle.Xalign = 0.0f; toggle.Xalign = 0.0f;
rendererToggle.PersistentData ["column"] = Column.Tim; columns.Add (toggle);
rendererToggle.Toggled += new ToggledHandler (ItemToggled); toggle.Toggled += new ToggledHandler (ItemToggled);
column = new TreeViewColumn ("Tim", rendererToggle, "active", (int) Column.Tim); column = new TreeViewColumn ("Tim", toggle,
column.Visible = true; "active", (int) Column.Tim,
rendererToggle.Activatable = true; "visible", (int) Column.Visible,
rendererToggle.Active = true; "activatable", (int) Column.World);
treeView.InsertColumn (column, (int) Column.Tim); treeView.InsertColumn (column, (int) Column.Tim);
column.Sizing = TreeViewColumnSizing.Fixed; column.Sizing = TreeViewColumnSizing.Fixed;
column.FixedWidth = 50; column.FixedWidth = 50;
column.Clickable = true; column.Clickable = true;
// owen column // owen column
rendererToggle = new CellRendererToggle (); toggle = new CellRendererToggle ();
rendererToggle.Xalign = 0.0f; toggle.Xalign = 0.0f;
rendererToggle.PersistentData ["column"] = Column.Owen; columns.Add (toggle);
rendererToggle.Toggled += new ToggledHandler (ItemToggled); toggle.Toggled += new ToggledHandler (ItemToggled);
column = new TreeViewColumn ("Owen", rendererToggle, "active", (int) Column.Owen); column = new TreeViewColumn ("Owen", toggle,
column.Visible = true; "active", (int) Column.Owen,
rendererToggle.Activatable = true; "visible", (int) Column.Visible);
rendererToggle.Active = true;
treeView.InsertColumn (column, (int) Column.Owen); treeView.InsertColumn (column, (int) Column.Owen);
column.Sizing = TreeViewColumnSizing.Fixed; column.Sizing = TreeViewColumnSizing.Fixed;
column.FixedWidth = 50; column.FixedWidth = 50;
column.Clickable = true; column.Clickable = true;
// dave column // dave column
rendererToggle = new CellRendererToggle (); toggle = new CellRendererToggle ();
rendererToggle.Xalign = 0.0f; toggle.Xalign = 0.0f;
rendererToggle.PersistentData ["column"] = Column.Dave; columns.Add (toggle);
rendererToggle.Toggled += new ToggledHandler (ItemToggled); toggle.Toggled += new ToggledHandler (ItemToggled);
column = new TreeViewColumn ("Dave", rendererToggle, "active", (int) Column.Dave); column = new TreeViewColumn ("Dave", toggle,
column.Visible = true; "active", (int) Column.Dave,
rendererToggle.Activatable = true; "visible", (int) Column.Visible);
rendererToggle.Active = true;
treeView.InsertColumn (column, (int) Column.Dave); treeView.InsertColumn (column, (int) Column.Dave);
column.Sizing = TreeViewColumnSizing.Fixed; column.Sizing = TreeViewColumnSizing.Fixed;
column.FixedWidth = 50; column.FixedWidth = 50;
column.Clickable = true; column.Clickable = true;
} }
private void WindowDelete (object o, DeleteEventArgs args) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
args.RetVal = true;
} }
private void CreateModel () private void CreateModel ()
{ {
// create tree store // create tree store
store = new TreeStore ( store = new TreeStore (typeof (string),
typeof(string),
typeof (bool), typeof (bool),
typeof (bool), typeof (bool),
typeof (bool), typeof (bool),
@ -179,9 +172,7 @@ namespace GtkDemo
typeof (bool)); typeof (bool));
// add data to the tree store // add data to the tree store
foreach (MyTreeItem month in toplevel) {
foreach (MyTreeItem month in toplevel)
{
TreeIter iter = store.AppendValues (month.Label, TreeIter iter = store.AppendValues (month.Label,
false, false,
false, false,
@ -191,16 +182,16 @@ namespace GtkDemo
false, false,
false); false);
foreach (MyTreeItem hollyday in month.Children) foreach (MyTreeItem holiday in month.Children) {
{
store.AppendValues (iter, store.AppendValues (iter,
hollyday.Label, holiday.Label,
hollyday.Alex, holiday.Alex,
hollyday.Havoc, holiday.Havoc,
hollyday.Tim, holiday.Tim,
hollyday.Owen, holiday.Owen,
hollyday.Dave, holiday.Dave,
true); true,
holiday.WorldHoliday);
} }
} }
} }
@ -316,22 +307,12 @@ namespace GtkDemo
public class MyTreeItem public class MyTreeItem
{ {
public string Label; public string Label;
public bool Alex; public bool Alex, Havoc, Tim, Owen, Dave;
public bool Havoc; public bool WorldHoliday; // shared by the European hackers
public bool Tim;
public bool Owen;
public bool Dave;
public bool World_holiday; /* shared by the European hackers */
public MyTreeItem[] Children; public MyTreeItem[] Children;
public MyTreeItem ( public MyTreeItem (string label, bool alex, bool havoc, bool tim,
string label, bool owen, bool dave, bool worldHoliday,
bool alex,
bool havoc,
bool tim,
bool owen,
bool dave,
bool world_holiday,
MyTreeItem[] children) MyTreeItem[] children)
{ {
Label = label; Label = label;
@ -340,11 +321,11 @@ namespace GtkDemo
Tim = tim; Tim = tim;
Owen = owen; Owen = owen;
Dave = dave; Dave = dave;
World_holiday = world_holiday; WorldHoliday = worldHoliday;
Children = children; Children = children;
} }
} }
// columns // columns
public enum Column public enum Column
{ {
@ -354,9 +335,9 @@ namespace GtkDemo
Tim, Tim,
Owen, Owen,
Dave, Dave,
Visible, Visible,
World, World,
Num,
} }
} }
} }

View file

@ -11,7 +11,17 @@ namespace GtkDemo
[Demo ("UIManager", "DemoUIManager.cs")] [Demo ("UIManager", "DemoUIManager.cs")]
public class DemoUIManager : Window public class DemoUIManager : Window
{ {
VBox vbox; enum Color {
Red,
Green,
Blue
};
enum Shape {
Square,
Rectangle,
Oval
};
const string uiInfo = const string uiInfo =
"<ui>" + "<ui>" +
@ -49,98 +59,97 @@ namespace GtkDemo
" </toolbar>" + " </toolbar>" +
"</ui>"; "</ui>";
public DemoUIManager () : base ("Demo UIManager") public DemoUIManager () : base ("UI Manager")
{
this.SetDefaultSize (400, 300);
this.DeleteEvent += new DeleteEventHandler (WindowDelete);
vbox = new VBox (false, 0);
this.Add (vbox);
AddActions ();
Button close = new Button (Stock.Close);
close.Clicked += new EventHandler (OnCloseClicked);
vbox.PackEnd (close, false, true, 0);
vbox.PackEnd (new Label ("test"), true, true, 0);
this.ShowAll ();
}
void AddActions ()
{
ActionEntry[] actions = new ActionEntry[]
{ {
ActionEntry[] entries = new ActionEntry[] {
new ActionEntry ("FileMenu", null, "_File", null, null, null), new ActionEntry ("FileMenu", null, "_File", null, null, null),
new ActionEntry ("PreferencesMenu", null, "_Preferences", null, null, null), new ActionEntry ("PreferencesMenu", null, "_Preferences", null, null, null),
new ActionEntry ("ColorMenu", null, "_Color", null, null, null), new ActionEntry ("ColorMenu", null, "_Color", null, null, null),
new ActionEntry ("ShapeMenu", null, "_Shape", null, null, null), new ActionEntry ("ShapeMenu", null, "_Shape", null, null, null),
new ActionEntry ("HelpMenu", null, "_Help", null, null, null), new ActionEntry ("HelpMenu", null, "_Help", null, null, null),
new ActionEntry ("New", Stock.New, "_New", "<control>N", "Create a new file", new EventHandler (OnActionActivated)), new ActionEntry ("New", Stock.New, "_New", "<control>N", "Create a new file", new EventHandler (ActionActivated)),
new ActionEntry ("Open", Stock.Open, "_Open", "<control>O", "Open a file", new EventHandler (OnActionActivated)), new ActionEntry ("Open", Stock.Open, "_Open", "<control>O", "Open a file", new EventHandler (ActionActivated)),
new ActionEntry ("Save", Stock.Save, "_Save", "<control>S", "Save current file", new EventHandler (OnActionActivated)), new ActionEntry ("Save", Stock.Save, "_Save", "<control>S", "Save current file", new EventHandler (ActionActivated)),
new ActionEntry ("SaveAs", Stock.SaveAs, "Save _As", null, "Save to a file", new EventHandler (OnActionActivated)), new ActionEntry ("SaveAs", Stock.SaveAs, "Save _As", null, "Save to a file", new EventHandler (ActionActivated)),
new ActionEntry ("Quit", Stock.Quit, "_Quit", "<control>Q", "Quit", new EventHandler (OnActionActivated)), new ActionEntry ("Quit", Stock.Quit, "_Quit", "<control>Q", "Quit", new EventHandler (ActionActivated)),
new ActionEntry ("About", null, "_About", "<control>A", "About", new EventHandler (OnActionActivated)), new ActionEntry ("About", null, "_About", "<control>A", "About", new EventHandler (ActionActivated)),
new ActionEntry ("Logo", "demo-gtk-logo", "Gtk#", null, "Gtk#", new EventHandler (OnActionActivated)) new ActionEntry ("Logo", "demo-gtk-logo", null, null, "Gtk#", new EventHandler (ActionActivated))
}; };
ToggleActionEntry[] toggleActions = new ToggleActionEntry[] ToggleActionEntry[] toggleEntries = new ToggleActionEntry[] {
{ new ToggleActionEntry ("Bold", Stock.Bold, "_Bold", "<control>B", "Bold", new EventHandler (ActionActivated), true)
new ToggleActionEntry ("Bold", Stock.Bold, "_Bold", "<control>B", "Bold", new EventHandler (OnActionActivated), false)
}; };
ActionEntry[] colorActions = new ActionEntry[]
{ RadioActionEntry[] colorEntries = new RadioActionEntry[] {
new ActionEntry ("Red", null, "_Red", "<control>R", "Blood", new EventHandler (OnActionActivated)), new RadioActionEntry ("Red", null, "_Red", "<control>R", "Blood", (int)Color.Red),
new ActionEntry ("Green", null, "_Green", "<control>G", "Grass", new EventHandler (OnActionActivated)), new RadioActionEntry ("Green", null, "_Green", "<control>G", "Grass", (int)Color.Green),
new ActionEntry ("Blue", null, "_Blue", "<control>B", "Sky", new EventHandler (OnActionActivated)) new RadioActionEntry ("Blue", null, "_Blue", "<control>B", "Sky", (int)Color.Blue)
}; };
ActionEntry[] shapeActions = new ActionEntry[] RadioActionEntry[] shapeEntries = new RadioActionEntry[] {
{ new RadioActionEntry ("Square", null, "_Square", "<control>S", "Square", (int)Shape.Square),
new ActionEntry ("Square", null, "_Square", "<control>S", "Square", new EventHandler (OnActionActivated)), new RadioActionEntry ("Rectangle", null, "_Rectangle", "<control>R", "Rectangle", (int)Shape.Rectangle),
new ActionEntry ("Rectangle", null, "_Rectangle", "<control>R", "Rectangle", new EventHandler (OnActionActivated)), new RadioActionEntry ("Oval", null, "_Oval", "<control>O", "Egg", (int)Shape.Oval)
new ActionEntry ("Oval", null, "_Oval", "<control>O", "Oval", new EventHandler (OnActionActivated))
}; };
ActionGroup group = new ActionGroup ("group"); ActionGroup actions = new ActionGroup ("group");
group.Add (actions); actions.Add (entries);
group.Add (toggleActions); actions.Add (toggleEntries);
group.Add (colorActions); actions.Add (colorEntries, (int)Color.Red, new ChangedHandler (RadioActionActivated));
group.Add (shapeActions); actions.Add (shapeEntries, (int)Shape.Oval, new ChangedHandler (RadioActionActivated));
UIManager uim = new UIManager (); UIManager uim = new UIManager ();
uim.InsertActionGroup (group, (int) uim.NewMergeId ()); uim.InsertActionGroup (actions, 0);
uim.AddWidget += new AddWidgetHandler (OnAddWidget); AddAccelGroup (uim.AccelGroup);
uim.AddUiFromString (uiInfo); uim.AddUiFromString (uiInfo);
VBox box1 = new VBox (false, 0);
Add (box1);
box1.PackStart (uim.GetWidget ("/MenuBar"), false, false, 0);
Label label = new Label ("Type\n<alt>\nto start");
label.SetSizeRequest (200, 200);
label.SetAlignment (0.5f, 0.5f);
box1.PackStart (label, true, true, 0);
HSeparator separator = new HSeparator ();
box1.PackStart (separator, false, true, 0);
VBox box2 = new VBox (false, 10);
box2.BorderWidth = 10;
box1.PackStart (box2, false, true, 0);
Button button = new Button ("close");
button.Clicked += new EventHandler (CloseClicked);
box2.PackStart (button, true, true, 0);
button.CanDefault = true;
button.GrabDefault ();
ShowAll ();
} }
private void OnActionActivated (object sender, EventArgs a) private void ActionActivated (object sender, EventArgs a)
{ {
Action action = sender as Action; Action action = sender as Action;
Console.WriteLine ("** Message: Action \"{0}\" activated", action.Name); Console.WriteLine ("Action \"{0}\" activated", action.Name);
} }
private void WindowDelete (object o, DeleteEventArgs args) private void RadioActionActivated (object sender, ChangedArgs args)
{ {
this.Hide (); Console.WriteLine ("Radio action \"{0}\" selected", args.Current.Name);
this.Destroy ();
args.RetVal = true;
} }
void OnCloseClicked (object sender, EventArgs a) protected override bool OnDeleteEvent (Gdk.Event evt)
{ {
this.Hide (); Destroy ();
this.Destroy (); return true;
} }
void OnAddWidget (object sender, AddWidgetArgs a) void CloseClicked (object sender, EventArgs a)
{ {
a.Widget.Show (); Destroy ();
vbox.PackStart (a.Widget, false, true, 0);
} }
} }
} }

View file

@ -1,7 +1,10 @@
This port of gtk-demo.c is still INCOMPLETE. If you can contribute to it This is a mostly complete port of gtk-demo to Gtk#; for notes on
don't hesitate to mail your patches to gtk-sharp-list@lists.ximian.com what's missing, see the TODO file.
The original port was done by Daniel Kornhauser (dkor@alum.mit.edu),
with additions/changes/fixes by various other people, as seen in the
main gtk-sharp ChangeLog.
To compile it just type Make For the most part, the various demos should stay as close as possible
to the C version, so that GtkDemo.exe can be compared against gtk-demo
Daniel Kornhauser. to make sure Gtk# is working correctly.

View file

@ -1,20 +1,14 @@
General General
- general C#-ification - gtk-demo passes a widget to each demo that is used to set the
Screen and sometimes Parent of each demo window
- Demo window management is not the same as in gtk-demo
DemoMain DemoMain
- syntax highlighting - syntax highlighting
DemoStockBrowser "Change Display" is missing
- underline _label properly
- use StudlyCaps instead of current horrible hack
- missing stockitems for some reason
- remove duplication in ListStore, and use DataFunc's
DemoHyperText
- link tags are recreated too much and never removed
Future Future
------ ------
IconView - gtk 2.6 IconView - gtk 2.6
RotatedText - pango 1.6 RotatedText - pango 1.6