示例#1
0
func TestWebView_RunJavaScript_exception(t *testing.T) {
	webView := NewWebView()
	defer webView.Destroy()

	wantErr := errors.New("An exception was raised in JavaScript")
	webView.Connect("load-changed", func(_ *glib.Object, loadEvent LoadEvent) {
		switch loadEvent {
		case LoadFinished:
			webView.RunJavaScript(`throw new Error("foo")`, func(result *gojs.Value, err error) {
				if result != nil {
					ctx := webView.JavaScriptGlobalContext()
					t.Errorf("want result == nil, got %q", ctx.ToStringOrDie(result))
				}
				if !reflect.DeepEqual(wantErr, err) {
					t.Errorf("want error %q, got %q", wantErr, err)
				}
				gtk.MainQuit()
			})
		}
	})

	glib.IdleAdd(func() bool {
		webView.LoadHTML(`<p></p>`, "")
		return false
	})

	gtk.Main()
}
示例#2
0
func TestWebView_RunJavaScript(t *testing.T) {
	webView := NewWebView()
	defer webView.Destroy()

	wantResultString := "abc"
	webView.Connect("load-changed", func(_ *glib.Object, loadEvent LoadEvent) {
		switch loadEvent {
		case LoadFinished:
			webView.RunJavaScript(`document.getElementById("foo").innerHTML`, func(result *gojs.Value, err error) {
				if err != nil {
					t.Errorf("RunJavaScript error: %s", err)
				}
				resultString := webView.JavaScriptGlobalContext().ToStringOrDie(result)
				if wantResultString != resultString {
					t.Errorf("want result string %q, got %q", wantResultString, resultString)
				}
				gtk.MainQuit()
			})
		}
	})

	glib.IdleAdd(func() bool {
		webView.LoadHTML(`<p id=foo>abc</p>`, "")
		return false
	})

	gtk.Main()
}
示例#3
0
func TestWebView_GetSnapshot(t *testing.T) {
	webView := NewWebView()
	defer webView.Destroy()

	webView.Connect("load-changed", func(_ *glib.Object, loadEvent LoadEvent) {
		switch loadEvent {
		case LoadFinished:
			webView.GetSnapshot(func(img *image.RGBA, err error) {
				if err != nil {
					t.Errorf("GetSnapshot error: %q", err)
				}
				if img.Pix == nil {
					t.Error("!img.Pix")
				}
				if img.Stride == 0 || img.Rect.Max.X == 0 || img.Rect.Max.Y == 0 {
					t.Error("!img.Stride or !img.Rect.Max.X or !img.Rect.Max.Y")
				}
				gtk.MainQuit()
			})
		}
	})

	glib.IdleAdd(func() bool {
		webView.LoadHTML(`<p id=foo>abc</p>`, "")
		return false
	})

	gtk.Main()
}
示例#4
0
func TestWebView_URI(t *testing.T) {
	setup()
	defer teardown()

	mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {})

	wantURI := server.URL + "/"
	var gotURI string
	webView.Connect("notify::uri", func() {
		glib.IdleAdd(func() bool {
			gotURI = webView.URI()
			if gotURI != "" {
				gtk.MainQuit()
			}
			return false
		})
	})

	glib.IdleAdd(func() bool {
		webView.LoadURI(server.URL)
		return false
	})

	gtk.Main()

	if wantURI != gotURI {
		t.Errorf("want URI %q, got %q", wantURI, gotURI)
	}
}
示例#5
0
func (ui *Ui) init() {
	win, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	win.SetTitle("GNOMEConnect")
	win.SetDefaultSize(800, 600)
	win.Connect("destroy", func() {
		gtk.MainQuit()
		ui.Quit <- true
	})
	ui.win = win

	hbox, _ := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 0)
	win.Add(hbox)

	scroller := ui.initDevicesList()
	hbox.PackStart(scroller, false, true, 0)

	sep, _ := gtk.SeparatorNew(gtk.ORIENTATION_HORIZONTAL)
	hbox.PackStart(sep, false, true, 0)

	box := ui.initDeviceView()
	hbox.PackEnd(box, true, true, 0)

	titlebar := ui.initTitlebar()
	win.SetTitlebar(titlebar)

	win.ShowAll()
	ui.selectDevice(nil)
}
示例#6
0
func TestWebView_LoadHTML(t *testing.T) {
	webView := NewWebView()
	defer webView.Destroy()

	loadOk := false
	webView.Connect("load-failed", func() {
		t.Errorf("load failed")
	})
	webView.Connect("load-changed", func(_ *glib.Object, loadEvent LoadEvent) {
		switch loadEvent {
		case LoadFinished:
			loadOk = true
			gtk.MainQuit()
		}
	})

	glib.IdleAdd(func() bool {
		webView.LoadHTML("<p>hello</p>", "")
		return false
	})

	gtk.Main()

	if !loadOk {
		t.Error("!loadOk")
	}
}
示例#7
0
func TestWebView_LoadURI_load_failed(t *testing.T) {
	webView := NewWebView()
	defer webView.Destroy()

	loadFailed := false
	loadFinished := false
	webView.Connect("load-failed", func() {
		loadFailed = true
	})
	webView.Connect("load-changed", func(_ *glib.Object, loadEvent LoadEvent) {
		switch loadEvent {
		case LoadFinished:
			loadFinished = true
			gtk.MainQuit()
		}
	})

	glib.IdleAdd(func() bool {
		// Load a bad URL to trigger load failure.
		webView.LoadURI("http://127.0.0.1:99999")
		return false
	})

	gtk.Main()

	if !loadFailed {
		t.Error("!loadFailed")
	}
	if !loadFinished {
		t.Error("!loadFinished")
	}
}
示例#8
0
文件: menubar.go 项目: hsk81/btcgui
func createFileMenu() *gtk.MenuItem {
	menu, err := gtk.MenuItemNewWithMnemonic("_File")
	if err != nil {
		log.Fatal(err)
	}

	dropdown, err := gtk.MenuNew()
	if err != nil {
		log.Fatal(err)
	}

	menu.SetSubmenu(dropdown)

	mitem, err := gtk.MenuItemNewWithMnemonic("E_xit")
	if err != nil {
		log.Fatal(err)
	}
	mitem.Connect("activate", func() {
		gtk.MainQuit()
	})

	dropdown.Append(mitem)

	return menu
}
示例#9
0
文件: simple.go 项目: alimy/gotk3
func main() {
	// Initialize GTK without parsing any command line arguments.
	gtk.Init(nil)

	// Create a new toplevel window, set its title, and connect it to the
	// "destroy" signal to exit the GTK main loop when it is destroyed.
	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle("Simple Example")
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	// Create a new label widget to show in the window.
	l, err := gtk.LabelNew("Hello, gotk3!")
	if err != nil {
		log.Fatal("Unable to create label:", err)
	}

	// Add the label to the window.
	win.Add(l)

	// Set the default window size.
	win.SetDefaultSize(800, 600)

	// Recursively show all widgets contained in this window.
	win.ShowAll()

	// Begin executing the GTK main loop.  This blocks until
	// gtk.MainQuit() is run.
	gtk.Main()
}
示例#10
0
文件: selfplug.go 项目: runjak/gotk3
func main() {
	// Initialize GTK without parsing any command line arguments.
	gtk.Init(nil)

	// Create a new toplevel window, set its title, and connect it to the
	// "destroy" signal to exit the GTK main loop when it is destroyed.
	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle("Simple Example")
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	// Create a new socket:
	s, err := gtkx.SocketNew()
	if err != nil {
		log.Fatal("Unable to create socket:", err)
	}

	//Adding the socket to the window:
	win.Add(s)

	// Getting the socketId:
	sId := s.GetId()
	fmt.Printf("Our socket: %v\n", sId)

	//Building a Plug for our Socket:
	p, err := gtkx.PlugNew(sId)
	if err != nil {
		log.Fatal("Unable to create plug:", err)
	}

	//Building a Button for our Plug:
	b, err := gtk.ButtonNewWithLabel("Click me .)")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}

	//Click events for the Button:
	b.Connect("clicked", func() {
		fmt.Printf("Yeah, such clicks!\n")
	})

	//Adding the Button to the Plug:
	p.Add(b)
	//Displaying the Plug:
	p.ShowAll()

	// Set the default window size.
	win.SetDefaultSize(800, 600)

	// Recursively show all widgets contained in this window.
	win.ShowAll()

	// Begin executing the GTK main loop.  This blocks until
	// gtk.MainQuit() is run.
	gtk.Main()
}
示例#11
0
func TestWebView_Title(t *testing.T) {
	webView := NewWebView()
	defer webView.Destroy()

	wantTitle := "foo"
	var gotTitle string
	webView.Connect("notify::title", func() {
		glib.IdleAdd(func() bool {
			gotTitle = webView.Title()
			if gotTitle != "" {
				gtk.MainQuit()
			}
			return false
		})
	})

	glib.IdleAdd(func() bool {
		webView.LoadHTML("<html><head><title>"+wantTitle+"</title></head><body></body></html>", "")
		return false
	})

	gtk.Main()

	if wantTitle != gotTitle {
		t.Errorf("want title %q, got %q", wantTitle, gotTitle)
	}
}
示例#12
0
文件: pages.go 项目: jrick/xombrero2
// NewPageManager creates and initializes a page manager.
func NewPageManager(session []PageDescription) *PageManager {
	nb, _ := gtk.NotebookNew()
	nb.SetCanFocus(false)
	nb.SetShowBorder(false)
	p := &PageManager{
		Notebook: nb,
		htmls:    map[uintptr]*HTMLPage{},
	}

	if session == nil {
		session = []PageDescription{BlankPage}
	}
	for _, page := range session {
		p.OpenPage(page)
	}

	actions := NewActionMenu()
	actions.newTab.Connect("activate", func() {
		n := p.OpenPage(BlankPage)
		p.FocusPageN(n)
	})
	actions.quit.Connect("activate", func() {
		gtk.MainQuit()
	})

	nb.SetActionWidget(actions, gtk.PACK_END)
	actions.Show()

	return p
}
示例#13
0
文件: xterm.go 项目: runjak/gotk3
func main() {
	/*
	   We set an environment variable so that we don't get bothered by xterm accessibility warnings
	   like "** (xterm:16917): WARNING **: Couldn't connect to accessibility bus: Failed to connect to socket /tmp/dbus-QznzMfGEXB: Connection refused"
	   See http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15154
	*/
	os.Setenv("NO_AT_BRIDGE", "1")

	// Initialize GTK without parsing any command line arguments.
	gtk.Init(nil)

	// Create a new toplevel window, set its title, and connect it to the
	// "destroy" signal to exit the GTK main loop when it is destroyed.
	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle("Simple Example")
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	// Create a new socket:
	s, err := gtkx.SocketNew()
	if err != nil {
		log.Fatal("Unable to create socket:", err)
	}

	//Adding the socket to the window:
	win.Add(s)

	// Getting the socketId:
	sId := s.GetId()
	fmt.Printf("Our socket: %v\n", sId)

	// Embedding something in the socket:
	xterm := exec.Command("xterm", "-into", gtkx.WindowIdToString(sId))

	go func() {
		xterm.Run()
	}()

	// Set the default window size.
	win.SetDefaultSize(800, 600)

	// Recursively show all widgets contained in this window.
	win.ShowAll()

	// Begin executing the GTK main loop.  This blocks until
	// gtk.MainQuit() is run.
	gtk.Main()
}
示例#14
0
文件: textview.go 项目: alimy/gotk3
func setup_window(title string) *gtk.Window {
	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle(title)
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})
	win.SetDefaultSize(800, 600)
	win.SetPosition(gtk.WIN_POS_CENTER)
	return win
}
示例#15
0
文件: goroutines.go 项目: alimy/gotk3
func main() {
	gtk.Init(nil)

	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	win.Add(windowWidget())

	// Native GTK is not thread safe, and thus, gotk3's GTK bindings may not
	// be used from other goroutines.  Instead, glib.IdleAdd() must be used
	// to add a function to run in the GTK main loop when it is in an idle
	// state.
	//
	// Two examples of using glib.IdleAdd() are shown below.  The first runs
	// a user created function, LabelSetTextIdle, and passes it two
	// arguments for a label and the text to set it with.  The second calls
	// (*gtk.Label).SetText directly, passing in only the text as an
	// argument.
	//
	// If the function passed to glib.IdleAdd() returns one argument, and
	// that argument is a bool, this return value will be used in the same
	// manner as a native g_idle_add() call.  If this return value is false,
	// the function will be removed from executing in the GTK main loop's
	// idle state.  If the return value is true, the function will continue
	// to execute when the GTK main loop is in this state.
	go func() {
		for {
			time.Sleep(time.Second)
			s := fmt.Sprintf("Set a label %d time(s)!", nSets)
			_, err := glib.IdleAdd(LabelSetTextIdle, topLabel, s)
			if err != nil {
				log.Fatal("IdleAdd() failed:", err)
			}
			nSets++
			s = fmt.Sprintf("Set a label %d time(s)!", nSets)
			_, err = glib.IdleAdd(bottomLabel.SetText, s)
			if err != nil {
				log.Fatal("IdleAdd() failed:", err)
			}
			nSets++
		}
	}()

	win.ShowAll()
	gtk.Main()
}
示例#16
0
func main() {
	gtk.Init(nil)

	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	win.Add(windowWidget())
	win.ShowAll()

	gtk.Main()
}
示例#17
0
// RunGUI initializes GTK, creates the toplevel window and all child widgets,
// opens the pages for the default session, and runs the Glib main event loop.
// This function blocks until the toplevel window is destroyed and the event
// loop exits.
func RunGUI() {
	gtk.Init(nil)

	window, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})
	window.SetDefaultGeometry(defaultWinWidth, defaultWinHeight)
	window.Show()

	wc := wk2.DefaultWebContext()
	wc.SetProcessModel(wk2.ProcessModelMultipleSecondaryProcesses)

	session := []PageDescription{HomePage}
	pm := NewPageManager(session)
	window.Add(pm)
	pm.Show()

	gtk.Main()
}
示例#18
0
// Displays image in a new Gtk window
// This function blocks until the window is closed
func displayImage(img image.Image) error {
	// Copy img into a new gdk.Pixbuf
	pixbuf, err := imageToPixbuf(img)
	if err != nil {
		return errors.New("Failed to create a pixbuf for image")
	}
	// Initialize GtkWindow
	gtk.Init(nil)
	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		return errors.New("Failed to create new window")
	}
	win.Connect("destroy", func() { gtk.MainQuit() })
	// Create GtkImage widget from pixbuf
	gimg, err := gtk.ImageNewFromPixbuf(pixbuf)
	if err != nil {
		return errors.New("Failed to load image into window")
	}
	win.Add(gimg)
	win.ShowAll()
	gtk.Main()
	return nil
}
示例#19
0
func TestWebView_LoadURI(t *testing.T) {
	setup()
	defer teardown()

	responseOk := false
	mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
		w.Write([]byte("abc"))
		responseOk = true
	})

	loadFinished := false
	webView.Connect("load-failed", func() {
		t.Errorf("load failed")
	})
	webView.Connect("load-changed", func(_ *glib.Object, loadEvent LoadEvent) {
		switch loadEvent {
		case LoadFinished:
			loadFinished = true
			gtk.MainQuit()
		}
	})

	glib.IdleAdd(func() bool {
		webView.LoadURI(server.URL)
		return false
	})

	gtk.Main()

	if !responseOk {
		t.Error("!responseOk")
	}
	if !loadFinished {
		t.Error("!loadFinished")
	}
}
示例#20
0
文件: gui.go 项目: fiddenmar/netlabs
func main() {
	gtk.Init(nil)

	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle("UDP client v0.0.1")
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	var c client.Client
	answers := make(chan string)

	grid, err := gtk.GridNew()
	if err != nil {
		log.Fatal("Unable to create grid:", err)
	}

	messageHistory, err := gtk.TextViewNew()
	if err != nil {
		log.Fatal("Unable to create TextView:", err)
	}
	grid.Attach(messageHistory, 0, 0, 4, 1)

	messageEntry, err := gtk.EntryNew()
	if err != nil {
		log.Fatal("Unable to create entry:", err)
	}
	grid.Attach(messageEntry, 0, 1, 1, 1)

	privateEntry, err := gtk.EntryNew()
	if err != nil {
		log.Fatal("Unable to create entry:", err)
	}
	grid.Attach(privateEntry, 1, 1, 1, 1)

	sendButton, err := gtk.ButtonNewWithLabel("Send")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}
	sendButton.Connect("clicked", func(btn *gtk.Button) {
		lbl, _ := btn.GetLabel()
		if lbl != "Send" {
			return
		}
		log.Print(lbl)
		msg, _ := messageEntry.GetText()
		log.Print(msg)
		c.Message(msg)
	})
	grid.Attach(sendButton, 0, 2, 1, 1)

	privateButton, err := gtk.ButtonNewWithLabel("Private")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}
	privateButton.Connect("clicked", func(btn *gtk.Button) {
		lbl, _ := btn.GetLabel()
		if lbl != "Private" {
			return
		}
		log.Print(lbl)
		private, _ := privateEntry.GetText()
		log.Print(private)
		if private != "" {
			msg, _ := messageEntry.GetText()
			log.Print(msg)
			c.Private(private, msg)
		}
	})
	grid.Attach(privateButton, 1, 2, 1, 1)

	listButton, err := gtk.ButtonNewWithLabel("List")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}
	listButton.Connect("clicked", func(btn *gtk.Button) {
		lbl, _ := btn.GetLabel()
		if lbl != "List" {
			return
		}
		log.Print(lbl)
		c.List()
		log.Print(lbl)
	})
	grid.Attach(listButton, 2, 1, 1, 1)

	leaveButton, err := gtk.ButtonNewWithLabel("Leave")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}
	leaveButton.Connect("clicked", func(btn *gtk.Button) {
		lbl, _ := btn.GetLabel()
		if lbl != "Leave" {
			return
		}
		log.Print(lbl)
		c.Leave()
		os.Exit(0)
	})
	grid.Attach(leaveButton, 3, 1, 1, 1)
	win.Add(grid)
	// Set the default window size.
	win.SetDefaultSize(400, 600)

	// Recursively show all widgets contained in this window.
	win.ShowAll()

	port, _ := strconv.Atoi(os.Args[3])
	c.Init(os.Args[1], os.Args[2], port, answers)
	go printMessages(messageHistory, answers)
	go c.Answer()
	c.Register()
	gtk.Main()
}
示例#21
0
文件: window.go 项目: hsk81/btcgui
// CreateWindow creates the toplevel window for the GUI.
func CreateWindow() (*gtk.Window, error) {
	var err error
	mainWindow, err = gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		return nil, err
	}
	mainWindow.SetTitle("btcgui")
	mainWindow.Connect("destroy", func() {
		gtk.MainQuit()
	})

	grid, err := gtk.GridNew()
	if err != nil {
		return nil, err
	}
	grid.SetOrientation(gtk.ORIENTATION_VERTICAL)

	grid.Add(createMenuBar())

	notebook, err := gtk.NotebookNew()
	if err != nil {
		return nil, err
	}
	notebook.SetHExpand(true)
	notebook.SetVExpand(true)
	grid.Add(notebook)

	l, err := gtk.LabelNew("Overview")
	if err != nil {
		return nil, err
	}
	notebook.AppendPage(createOverview(), l)

	l, err = gtk.LabelNew("Send Coins")
	if err != nil {
		return nil, err
	}
	notebook.AppendPage(createSendCoins(), l)

	l, err = gtk.LabelNew("Receive Coins")
	if err != nil {
		return nil, err
	}
	notebook.AppendPage(createRecvCoins(), l)

	l, err = gtk.LabelNew("Transactions")
	if err != nil {
		log.Fatal(err)
	}
	notebook.AppendPage(createTransactions(), l)

	// TODO(jrick): Add back when address book is implemented.
	/*
		l, err = gtk.LabelNew("Address Book")
		if err != nil {
			log.Fatal(err)
		}
		notebook.AppendPage(createAddrBook(), l)
	*/

	grid.Add(createStatusbar())

	mainWindow.Add(grid)

	mainWindow.SetDefaultGeometry(800, 600)

	return mainWindow, nil
}
示例#22
0
文件: grid.go 项目: alimy/gotk3
func main() {
	gtk.Init(nil)

	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle("Grid Example")
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	// Create a new grid widget to arrange child widgets
	grid, err := gtk.GridNew()
	if err != nil {
		log.Fatal("Unable to create grid:", err)
	}

	// gtk.Grid embeds an Orientable struct to simulate the GtkOrientable
	// GInterface.  Set the orientation from the default horizontal to
	// vertical.
	grid.SetOrientation(gtk.ORIENTATION_VERTICAL)

	// Create some widgets to put in the grid.
	lab, err := gtk.LabelNew("Just a label")
	if err != nil {
		log.Fatal("Unable to create label:", err)
	}

	btn, err := gtk.ButtonNewWithLabel("Button with label")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}

	entry, err := gtk.EntryNew()
	if err != nil {
		log.Fatal("Unable to create entry:", err)
	}

	spnBtn, err := gtk.SpinButtonNewWithRange(0.0, 1.0, 0.001)
	if err != nil {
		log.Fatal("Unable to create spin button:", err)
	}

	nb, err := gtk.NotebookNew()
	if err != nil {
		log.Fatal("Unable to create notebook:", err)
	}

	// Calling (*gtk.Container).Add() with a gtk.Grid will add widgets next
	// to each other, in the order they were added, to the right side of the
	// last added widget when the grid is in a horizontal orientation, and
	// at the bottom of the last added widget if the grid is in a vertial
	// orientation.  Using a grid in this manner works similar to a gtk.Box,
	// but unlike gtk.Box, a gtk.Grid will respect its child widget's expand
	// and margin properties.
	grid.Add(btn)
	grid.Add(lab)
	grid.Add(entry)
	grid.Add(spnBtn)

	// Widgets may also be added by calling (*gtk.Grid).Attach() to specify
	// where to place the widget in the grid, and optionally how many rows
	// and columns to span over.
	//
	// Additional rows and columns are automatically added to the grid as
	// necessary when new widgets are added with (*gtk.Container).Add(), or,
	// as shown in this case, using (*gtk.Grid).Attach().
	//
	// In this case, a notebook is added beside the widgets inserted above.
	// The notebook widget is inserted with a left position of 1, a top
	// position of 1 (starting at the same vertical position as the button),
	// a width of 1 column, and a height of 2 rows (spanning down to the
	// same vertical position as the entry).
	//
	// This example also demonstrates how not every area of the grid must
	// contain a widget.  In particular, the area to the right of the label
	// and the right of spin button have contain no widgets.
	grid.Attach(nb, 1, 1, 1, 2)
	nb.SetHExpand(true)
	nb.SetVExpand(true)

	// Add a child widget and tab label to the notebook so it renders.
	nbChild, err := gtk.LabelNew("Notebook content")
	if err != nil {
		log.Fatal("Unable to create button:", err)
	}
	nbTab, err := gtk.LabelNew("Tab label")
	if err != nil {
		log.Fatal("Unable to create label:", err)
	}
	nb.AppendPage(nbChild, nbTab)

	// Add the grid to the window, and show all widgets.
	win.Add(grid)
	win.ShowAll()

	gtk.Main()
}
示例#23
0
func (app *Application) Run() {

	gtk.Init(nil)

	app.active_dicts = make(map[string]bool)

	builder, err := gtk.BuilderNew()
	if err != nil {
		log.Fatal(err)
	}
	builder.AddFromFile("dictsearch.glade")
	w, err := builder.GetObject("win")
	if err != nil {
		log.Fatal(err)
	}

	app.win = w.(*gtk.Window)
	app.win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	// Box, containing list of dictionary chaeckbuttons
	dict_list_box, err := builder.GetObject("dict_list_box")
	if err != nil {
		log.Fatal(err)
	}
	app.dict_list = dict_list_box.(*gtk.Box)

	// Search Entry
	s_e, err := builder.GetObject("search_entry")
	if err != nil {
		log.Fatal(err)
	}
	app.search_entry = s_e.(*gtk.Entry)
	app.search_entry.Connect("activate", func() {
		text, err := app.search_entry.GetText()
		if err != nil {
			log.Fatal(err)
		}
		go app.Search(text, app.ch, app.done_flag)
	})

	// Search Button
	s_b, err := builder.GetObject("search_button")
	if err != nil {
		log.Fatal(err)
	}
	app.search_button = s_b.(*gtk.Button)
	app.search_button.Connect("clicked", func() {
		text, err := app.search_entry.GetText()
		if err != nil {
			log.Fatal(err)
		}
		go app.Search(text, app.ch, app.done_flag)
	})

	// Text View
	tv, err := builder.GetObject("textview")
	if err != nil {
		log.Fatal(err)
	}
	app.text_view = tv.(*gtk.TextView)
	app.text_view.SetEditable(false)
	app.text_view.SetWrapMode(gtk.WRAP_WORD)

	// Adding dictionary checkbuttons
	for i, dic := range app.GetDictList(dict_path) {
		dict_button, err := gtk.CheckButtonNew()
		if err != nil {
			log.Fatal(err)
		}
		label := dic
		dict_button.SetLabel(label)
		name := fmt.Sprintf("checkbutton%d", i)
		dict_button.SetName(name)
		dict_button.SetFocusOnClick(false)
		dict_button.Connect("toggled", func() {
			if dict_button.GetActive() {
				app.active_dicts[label] = true
			} else {
				delete(app.active_dicts, label)
			}
		})
		app.dict_list.Add(dict_button)
	}

	// StatusBar
	stb, err := builder.GetObject("statusbar")
	if err != nil {
		log.Fatal(err)
	}
	app.status_bar = stb.(*gtk.Statusbar)

	app.search_entry.GrabFocus()

	app.win.ShowAll()
	gtk.Main()

}
示例#24
0
func main() {
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr)
		fmt.Fprintf(os.Stderr, "webkit-eval-js evaluates a JavaScript expression in the context of a web page\n")
		fmt.Fprintf(os.Stderr, "running in a headless instance of the WebKit browser.\n\n")
		fmt.Fprintf(os.Stderr, "Usage:\n\n")
		fmt.Fprintf(os.Stderr, "\twebkit-eval-js url script-file\n\n")
		fmt.Fprintf(os.Stderr, "url is the web page to execute the script in, and script-file is a local file\n")
		fmt.Fprintf(os.Stderr, "with the JavaScript you want to evaluate. The result is printed to stdout as JSON.\n\n")
		fmt.Fprintln(os.Stderr)
		fmt.Fprintf(os.Stderr, "Example usage:\n\n")
		fmt.Fprintf(os.Stderr, "\tTo return the value of `document.title` on https://google.com:\n")
		fmt.Fprintf(os.Stderr, "\t    $ echo document.title | webkit-eval-js https://google.com /dev/stdin\n")
		fmt.Fprintf(os.Stderr, "\tPrints:\n")
		fmt.Fprintf(os.Stderr, "\t    \"Google\"\n\n")
		fmt.Fprintf(os.Stderr, "Notes:\n\n")
		fmt.Fprintf(os.Stderr, "\tBecause a headless WebKit instance is used, your $DISPLAY must be set. Use\n")
		fmt.Fprintf(os.Stderr, "\tXvfb if you are running on a machine without an existing X server. See\n")
		fmt.Fprintf(os.Stderr, "\thttps://sourcegraph.com/github.com/sourcegraph/go-webkit2/readme for more info.\n")
		fmt.Fprintln(os.Stderr)
		os.Exit(1)
	}
	flag.Parse()

	if flag.NArg() != 2 {
		flag.Usage()
		os.Exit(1)
	}

	log := log.New(os.Stderr, "", 0)

	pageURL := flag.Arg(0)
	scriptFile := flag.Arg(1)

	if _, err := url.Parse(pageURL); err != nil {
		log.Fatalf("Failed to parse URL %q: %s", pageURL, err)
	}

	script, err := ioutil.ReadFile(scriptFile)
	if err != nil {
		log.Fatalf("Failed to open script file %q: %s", scriptFile, err)
	}

	runtime.LockOSThread()
	gtk.Init(nil)

	webView := webkit2.NewWebView()
	defer webView.Destroy()

	webView.Connect("load-failed", func() {
		fmt.Println("Load failed.")
	})
	webView.Connect("load-changed", func(_ *glib.Object, loadEvent webkit2.LoadEvent) {
		switch loadEvent {
		case webkit2.LoadFinished:
			webView.RunJavaScript(string(script), func(val *gojs.Value, err error) {
				if err != nil {
					log.Fatalf("JavaScript error: %s", err)
				} else {
					json, err := val.JSON()
					if err != nil {
						log.Fatal("JavaScript serialization error: %s", err)
					}
					fmt.Println(string(json))
				}
				gtk.MainQuit()
			})
		}
	})

	glib.IdleAdd(func() bool {
		webView.LoadURI(pageURL)
		return false
	})

	gtk.Main()
}
示例#25
0
func createNewWalletDialog() (*gtk.Dialog, error) {
	dialog, err := gtk.DialogNew()
	if err != nil {
		return nil, err
	}
	dialog.SetTitle("New wallet")

	dialog.AddButton("_OK", gtk.RESPONSE_OK)

	dialog.SetDefaultGeometry(500, 100)

	grid, err := gtk.GridNew()
	if err != nil {
		return nil, err
	}
	grid.SetHExpand(true)
	grid.SetVExpand(true)

	b, err := dialog.GetContentArea()
	if err != nil {
		return nil, err
	}
	b.Add(grid)

	// Because the label will wrap and the final minimum heights
	// and widths will be absurdly large, first give a size request and
	// show the grid (allocating space for the requested size).  This will
	// make text wrapping labels size nicely inside the grid.
	grid.SetSizeRequest(500, 100)
	grid.Show()

	l, err := gtk.LabelNew("")
	if err != nil {
		return nil, err
	}
	l.SetLineWrap(true)
	l.SetMarkup(newWalletMessage)
	l.SetAlignment(0, 0)
	grid.Attach(l, 0, 0, 2, 1)

	b.SetHExpand(true)
	b.SetVExpand(true)

	l, err = gtk.LabelNew("Enter passphrase:")
	if err != nil {
		return nil, err
	}
	l.SetAlignment(1.0, 0.5)
	grid.Attach(l, 0, 1, 1, 1)

	passphrase, err := gtk.EntryNew()
	if err != nil {
		return nil, err
	}
	passphrase.SetVisibility(false)
	passphrase.SetHExpand(true)
	passphrase.Connect("activate", func() {
		dialog.Emit("response", gtk.RESPONSE_OK, nil)
	})
	grid.Attach(passphrase, 1, 1, 1, 1)

	l, err = gtk.LabelNew("Confirm passphrase:")
	if err != nil {
		return nil, err
	}
	l.SetAlignment(1.0, 0.5)
	grid.Attach(l, 0, 2, 1, 1)

	repeated, err := gtk.EntryNew()
	if err != nil {
		return nil, err
	}
	repeated.SetVisibility(false)
	repeated.SetVAlign(gtk.ALIGN_START)
	repeated.Connect("activate", func() {
		dialog.Emit("response", gtk.RESPONSE_OK, nil)
	})
	grid.Attach(repeated, 1, 2, 1, 1)

	showEntryText, err := gtk.CheckButtonNewWithLabel("Show passphrase")
	if err != nil {
		return nil, err
	}
	showEntryText.Connect("toggled", func() {
		active := showEntryText.GetActive()
		passphrase.SetVisibility(active)
		repeated.SetVisibility(active)
	})
	grid.Attach(showEntryText, 1, 3, 2, 1)

	dialog.SetTransientFor(mainWindow)
	dialog.SetPosition(gtk.WIN_POS_CENTER_ON_PARENT)
	dialog.ShowAll()

	dialog.Connect("response", func(_ *glib.Object, rt gtk.ResponseType) {
		switch rt {
		case gtk.RESPONSE_OK:
			pStr, err := passphrase.GetText()
			if err != nil {
				log.Print(err)
				return
			}
			rStr, err := repeated.GetText()
			if err != nil {
				log.Print(err)
				return
			}
			if len(pStr) == 0 {
				mDialog := gtk.MessageDialogNew(dialog, 0,
					gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
					"A passphrase must be entered to create a wallet.")
				mDialog.SetTitle("Wallet creation failed")
				mDialog.Run()
				mDialog.Destroy()
				return
			}
			if pStr == rStr {
				go func() {
					triggers.newWallet <- &NewWalletParams{
						passphrase: pStr,
					}

					if err := <-triggerReplies.walletCreationErr; err != nil {
						glib.IdleAdd(func() {
							mDialog := gtk.MessageDialogNew(dialog, 0,
								gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
								err.Error())
							mDialog.SetTitle("Wallet creation failed")
							mDialog.Run()
							mDialog.Destroy()
						})
					} else {
						glib.IdleAdd(func() {
							dialog.Destroy()
						})
					}
				}()
			} else {
				msg := "The supplied passphrases do not match."
				mDialog := gtk.MessageDialogNew(dialog, 0,
					gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, msg)
				mDialog.SetTitle("Wallet creation failed")
				mDialog.Run()
				mDialog.Destroy()
			}
		case gtk.RESPONSE_CANCEL:
			dialog.Destroy()
		}
	})

	dialog.Connect("delete-event", func() {
		mDialog := gtk.MessageDialogNew(mainWindow, 0,
			gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
			"btcgui cannot be used without a wallet and will now close.")
		mDialog.Show()
		mDialog.Run()
		mDialog.Destroy()
		gtk.MainQuit()
	})

	return dialog, nil
}