示例#1
0
func main() {

	gtk.Init(&os.Args)
	window := gtk.Window(gtk.GTK_WINDOW_TOPLEVEL)

	window.Connect("delete-event", func() {
		println("Delete-event occured\n")
	})

	window.Connect("destroy", func() { gtk.MainQuit() })

	button := gtk.ButtonWithLabel("Hello, World")

	button.Clicked(func() {
		println("Hello, World\n")
	})

	button.Clicked(func() {
		gtk.MainQuit()
	})

	window.Add(button)
	window.ShowAll()
	gtk.Main()
}
示例#2
0
文件: main.go 项目: vsannikov/mgc
func main() {

	FreeConsole()

	gtk.Init(nil)

	screenHeight := gdk.ScreenHeight()
	screenWidth := gdk.ScreenWidth()

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("mgc")
	window.SetIconName("gtk-about")
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})

	vbox := gtk.NewVBox(false, 0)

	menubar := gtk.NewMenuBar()
	vbox.PackStart(menubar, false, false, 0)

	menu := gtk.NewMenuItemWithMnemonic("_File")
	menubar.Append(menu)
	submenu := gtk.NewMenu()
	menu.SetSubmenu(submenu)

	menuitem := gtk.NewMenuItemWithMnemonic("E_xit")
	menuitem.Connect("activate", func() {
		gtk.MainQuit()
	})
	submenu.Append(menuitem)

	hpaned := gtk.NewHPaned()

	leftFrame := gtk.NewFrame("")
	rightFrame := gtk.NewFrame("")

	leftLabel := gtk.NewLabel("Left")
	rightLabel := gtk.NewLabel("Right")

	leftFrame.Add(leftLabel)
	rightFrame.Add(rightLabel)

	hpaned.Pack1(leftFrame, true, false)
	hpaned.Pack2(rightFrame, true, false)
	vbox.Add(hpaned)

	window.Add(vbox)

	window.SetSizeRequest(screenWidth/4*3, screenHeight/4*3)
	window.ShowAll()

	gtk.Main()
}
示例#3
0
func main() {
	gtk.Init(&os.Args)

	glib.SetApplicationName("go-gtk-statusicon-example")

	mi := gtk.NewMenuItemWithLabel("Popup!")
	mi.Connect("activate", func() {
		gtk.MainQuit()
	})
	nm := gtk.NewMenu()
	nm.Append(mi)
	nm.ShowAll()

	si := gtk.NewStatusIconFromStock(gtk.STOCK_FILE)
	si.SetTitle("StatusIcon Example")
	si.SetTooltipMarkup("StatusIcon Example")
	si.Connect("popup-menu", func(cbx *glib.CallbackContext) {
		nm.Popup(nil, nil, gtk.StatusIconPositionMenu, si, uint(cbx.Args(0)), uint(cbx.Args(1)))
	})

	println(`
Can you see statusicon in systray?
If you don't see it and if you use 'unity', try following.

# gsettings set com.canonical.Unity.Panel systray-whitelist \
  "$(gsettings get com.canonical.Unity.Panel systray-whitelist \|
  sed -e "s/]$/, 'go-gtk-statusicon-example']/")"
`)

	gtk.Main()
}
示例#4
0
文件: dmxd.go 项目: uvgroovy/dmx
func CreateGuiController() *GuiController {
	guiController := &GuiController{}
	guiController.buttons = make([]*gtk.Button, 0)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("GTK Go!")
	window.SetIconName("gtk-dialog-info")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		fmt.Println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")

	buttonsBox := gtk.NewHBox(false, 1)

	black := gdk.NewColorRGB(0, 0, 0)

	for i := 0; i < 8; i++ {
		button := gtk.NewButtonWithLabel(fmt.Sprint(i))

		button.ModifyBG(gtk.STATE_NORMAL, black)
		guiController.buttons = append(guiController.buttons, button)
		buttonsBox.Add(button)
	}

	window.Add(buttonsBox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()

	return guiController
}
示例#5
0
func main() {
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("Hello GTK+Go world!")
	window.SetIconName("gtk-dialog-info")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		gtk.MainQuit()
	}, "foo")
	vbox := gtk.NewVBox(false, 1)
	button := gtk.NewButtonWithLabel("Hello world!")
	button.SetTooltipMarkup("Say Hello World to everybody!")
	button.Clicked(func() {
		messagedialog := gtk.NewMessageDialog(
			button.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			"Hello!")
		messagedialog.Response(func() {
			messagedialog.Destroy()
		})
		messagedialog.Run()
	})
	vbox.PackStart(button, false, false, 0)
	window.Add(vbox)
	window.SetSizeRequest(300, 50)
	window.ShowAll()
	gtk.Main()
}
示例#6
0
文件: webkit.go 项目: zackb/code
func initWebView() *webkit.WebView {
	gtk.Init(nil)
	webview := webkit.NewWebView()
	webview.Connect("load-error", func() {
		fmt.Printf("Load Error: %s\n", webview.GetUri())
	})
	webview.Connect("onload-event", func() {
		fmt.Printf("Onload Event: %s\n", webview.GetUri())
	})
	webview.Connect("resource-load-finished", func(wv interface{}) {
		fmt.Printf("Resource Load Finished: %v\n", wv)
	})
	webview.Connect("load-committed", func() {
		//entry.SetText(webview.GetUri())
		fmt.Printf("Load Committed: %s\n", webview.GetUri())
	})
	webview.Connect("load-finished", func() {
		//entry.SetText(webview.GetUri())
		fmt.Printf("Load Finished: %s\n", webview.GetUri())
		//time.Sleep(time.Second)
		title := webview.GetTitle()
		webview.ExecuteScript("document.title=document.documentElement.innerHTML")
		str := webview.GetTitle()
		webview.ExecuteScript("document.title=" + title)
		fmt.Printf("Html: %s\n", str)
		gtk.MainQuit()
	})

	webview.LoadHtmlString(HTML_STRING, ".")
	gtk.Main()
	return webview
}
func main() {
	gtk.Init(nil)
	window := gtk.Window(gtk.GTK_WINDOW_TOPLEVEL)
	window.SetTitle("Click me")
	label := gtk.Label("There have been no clicks yet")
	var clicks int
	button := gtk.ButtonWithLabel("click me")
	button.Clicked(func() {
		clicks++
		if clicks == 1 {
			label.SetLabel("Button clicked 1 time")
		} else {
			label.SetLabel(fmt.Sprintf("Button clicked %d times",
				clicks))
		}
	})
	vbox := gtk.VBox(false, 1)
	vbox.Add(label)
	vbox.Add(button)
	window.Add(vbox)
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})
	window.ShowAll()
	gtk.Main()
}
示例#8
0
// KeyboardHandler handle events from keyboard
func KeyboardHandler(event chan *keyhandler.KeyPressEvent, window *gtk.Window,
	repl *gtk.Entry, URLEntry *gtk.Entry, notebook *gtk.Notebook) {
	for {
		kpe := <-event
		log.Printf("[DEBUG] KeyPressEvent : %v", kpe)
		gdk.ThreadsEnter()
		switch kpe.KeyVal {
		case gdk.KEY_Escape:
			repl.SetVisible(false)
			break
		case gdk.KEY_colon:
			if !repl.IsFocus() && !URLEntry.IsFocus() {
				repl.SetVisible(true)
				repl.GrabFocus()
				repl.SetText(":")
				repl.SetPosition(1)
			}
			break
		case gdk.KEY_Return:
			if repl.IsFocus() {
				text := repl.GetText()
				log.Printf("Repl text : %s", text)
				if len(text) > 0 {
					command.Run(text, window, "")
				}
				repl.SetText("")
			}
			break
		// case gdk.KEY_w:
		// 	if kpe.GetModifier() == keyhandler.CTRL {
		// 		log.Printf("[DEBUG] nb : %d", notebook.GetNPages())
		// 		notebook.RemovePage(notebook.GetCurrentPage())
		// 		log.Printf("[DEBUG] nb : %d", notebook.GetNPages())
		// 	}
		// 	break
		case gdk.KEY_t:
			if kpe.GetModifier() == keyhandler.CTRL {
				log.Printf("[DEBUG] New tab")
				log.Printf("[DEBUG] nb : %d", notebook.GetNPages())
				log.Printf("[DEBUG] current : %d",
					notebook.GetCurrentPage())
				tab := ui.NewBrowser("")
				page := gtk.NewFrame("")
				//fmt.Sprintf("%d", notebook.GetNPages()+1))
				notebook.AppendPage(page, gtk.NewLabel("New tab"))
				page.Add(tab.VBox)
				log.Printf("[DEBUG] nb : %d", notebook.GetNPages())
				notebook.ShowAll()
			}
			break
		case gdk.KEY_q:
			if kpe.GetModifier() == keyhandler.CTRL {
				gtk.MainQuit()
			}
			break
		}
		gdk.ThreadsLeave()
	}
}
示例#9
0
func exit_cb() {
	// Are-you-sure-you-want-to-exit-because-file-is-unsaved logic will be here.
	session_save()
	if nil != listener {
		listener.Close()
	}
	gtk.MainQuit()
}
示例#10
0
文件: action.go 项目: hauke96/go-gtk
func main() {
	gtk.Init(nil)
	window := CreateWindow()
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		fmt.Println("destroy pending...")
		gtk.MainQuit()
	}, "foo")
	window.ShowAll()
	gtk.Main()
}
示例#11
0
func (w *GhMainWindow) buildMenuBar() *gtk.GtkMenuBar {
	menubar := gtk.MenuBar()

	fileMenuItem := gtk.MenuItemWithMnemonic("_File")
	menubar.Append(fileMenuItem)

	fileMenu := gtk.Menu()
	fileMenuItem.SetSubmenu(fileMenu)

	syncMenuItem := gtk.MenuItemWithMnemonic("_Sync")
	syncMenuItem.Connect("activate", func() {
		w.openSyncWindow()
	})
	fileMenu.Append(syncMenuItem)

	separatorMenuItem := gtk.SeparatorMenuItem()
	fileMenu.Append(separatorMenuItem)

	quitMenuItem := gtk.MenuItemWithMnemonic("_Quit")
	quitMenuItem.Connect("activate", func() {
		gtk.MainQuit()
	})
	fileMenu.Append(quitMenuItem)

	viewMenuItem := gtk.MenuItemWithMnemonic("_View")
	menubar.Append(viewMenuItem)

	viewMenu := gtk.Menu()
	viewMenuItem.SetSubmenu(viewMenu)

	queuedHighlightsMenuItem := gtk.MenuItemWithMnemonic("Queued _Highlights")
	queuedHighlightsMenuItem.Connect("activate", func() {
		w.openQueuedHighlightsWindow()
	})
	viewMenu.Append(queuedHighlightsMenuItem)

	helpMenuItem := gtk.MenuItemWithMnemonic("_Help")
	menubar.Append(helpMenuItem)

	helpMenu := gtk.Menu()
	helpMenuItem.SetSubmenu(helpMenu)

	aboutMenuItem := gtk.MenuItemWithMnemonic("About")
	aboutMenuItem.Connect("activate", func() {
		aboutDialog := AboutDialog()
		dialog := aboutDialog.GtkAboutDialog
		dialog.Run()
		dialog.Destroy()
	})
	helpMenu.Append(aboutMenuItem)

	return menubar
}
示例#12
0
func (window *GhAuthWindow) bindKeys() {
	window.Connect("key-press-event", func(ctx *glib.CallbackContext) {
		arg := ctx.Args(0)
		keyEvent := *(**gdk.EventKey)(unsafe.Pointer(&arg))
		if int(keyEvent.State) == int(gdk.GDK_CONTROL_MASK) {
			if keyEvent.Keyval == gdk.GDK_KEY_w {
				window.Destroy()
			} else if keyEvent.Keyval == gdk.GDK_KEY_q {
				gtk.MainQuit()
			}
		}
	})
}
示例#13
0
文件: threads.go 项目: hauke96/go-gtk
func main() {
	runtime.GOMAXPROCS(10)
	glib.ThreadInit(nil)
	gdk.ThreadsInit()
	gdk.ThreadsEnter()
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.Connect("destroy", gtk.MainQuit)

	vbox := gtk.NewVBox(false, 1)

	label1 := gtk.NewLabel("")
	vbox.Add(label1)
	label2 := gtk.NewLabel("")
	vbox.Add(label2)

	window.Add(vbox)

	window.SetSizeRequest(100, 100)
	window.ShowAll()
	time.Sleep(1000 * 1000 * 100)
	go (func() {
		for i := 0; i < 300000; i++ {
			gdk.ThreadsEnter()
			label1.SetLabel(strconv.Itoa(i))
			gdk.ThreadsLeave()
		}
		gtk.MainQuit()
	})()
	go (func() {
		for i := 300000; i >= 0; i-- {
			gdk.ThreadsEnter()
			label2.SetLabel(strconv.Itoa(i))
			gdk.ThreadsLeave()
		}
		gtk.MainQuit()
	})()
	gtk.Main()
}
示例#14
0
func (g *Gui) buildGUI() {
	g.MainWindow = gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	g.MainWindow.SetPosition(gtk.WIN_POS_CENTER)
	g.MainWindow.SetTitle("Gunnify")
	g.MainWindow.SetIconName("gtk-dialog-info")
	g.MainWindow.Connect("destroy", func(ctx *glib.CallbackContext) {
		println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")
	g.MainWindow.SetSizeRequest(600, 300)
	vbox := gtk.NewVBox(false, 0)
	g.buildList(vbox)
	g.MainWindow.Add(vbox)
}
示例#15
0
func main() {
	gtk.Init(&os.Args)

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetSizeRequest(150, 50)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		gtk.MainQuit()
	}, nil)

	label := gtk.NewLabel("hello world")
	window.Add(label)

	window.ShowAll()
	gtk.Main()
}
示例#16
0
func main() {
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("GTK Go!")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		fmt.Println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")

	//--------------------------------------------------------
	// GtkHBox
	//--------------------------------------------------------
	fixed := gtk.NewFixed()

	//--------------------------------------------------------
	// GtkSpinButton
	//--------------------------------------------------------
	spinbutton1 := gtk.NewSpinButtonWithRange(1.0, 10.0, 1.0)
	spinbutton1.SetDigits(3)
	spinbutton1.Spin(gtk.SPIN_STEP_FORWARD, 7.0)
	fixed.Put(spinbutton1, 40, 50)

	spinbutton1.OnValueChanged(func() {
		val := spinbutton1.GetValueAsInt()
		fval := spinbutton1.GetValue()
		fmt.Println("SpinButton changed, new value: " + strconv.Itoa(val) + " | " + strconv.FormatFloat(fval, 'f', 2, 64))
		min, max := spinbutton1.GetRange()
		fmt.Println("Range: " + strconv.FormatFloat(min, 'f', 2, 64) + " " + strconv.FormatFloat(max, 'f', 2, 64))
		fmt.Println("Digits: " + strconv.Itoa(int(spinbutton1.GetDigits())))
	})

	adjustment := gtk.NewAdjustment(2.0, 1.0, 8.0, 2.0, 0.0, 0.0)
	spinbutton2 := gtk.NewSpinButton(adjustment, 1.0, 1)
	spinbutton2.SetRange(0.0, 20.0)
	spinbutton2.SetValue(18.0)
	spinbutton2.SetIncrements(2.0, 4.0)
	fixed.Put(spinbutton2, 150, 50)

	//--------------------------------------------------------
	// Event
	//--------------------------------------------------------
	window.Add(fixed)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}
示例#17
0
func (window *GhAuthWindow) build() {
	window.bindKeys()
	window.SetModal(true)
	window.SetTitle("Readmill Authentication")
	window.Connect("destroy", func() {
		config := models.Config()

		if config.AccessToken == "" {
			gtk.MainQuit()
		}
	})

	scrolledWindow := gtk.ScrolledWindow(nil, nil)
	scrolledWindow.SetPolicy(gtk.GTK_POLICY_AUTOMATIC, gtk.GTK_POLICY_AUTOMATIC)
	scrolledWindow.SetShadowType(gtk.GTK_SHADOW_IN)

	webview := webkit.WebView()
	webview.Connect("load-committed", func() {
		uri := webview.GetUri()
		matched, _ := regexp.MatchString(`^`+constants.READMILL_REDIRECT_URI+`/\?code=`, uri)

		if matched {
			webview.StopLoading()
			codeRegex, _ := regexp.Compile(`\?code=([^&]*)`)
			result := codeRegex.FindStringSubmatch(uri)
			code := result[1]
			token := readmilloauth.GetToken(constants.READMILL_CLIENT_ID, constants.READMILL_CLIENT_SECRET, constants.READMILL_REDIRECT_URI, code)
			userId := readmilloauth.GetUserId(token)

			config := models.Config()
			config.AccessToken = token
			config.UserId = userId
			config.Write()

			window.Destroy()
		}
	})
	scrolledWindow.Add(webview)

	authorizeUri := readmilloauth.AuthorizeUri(constants.READMILL_CLIENT_ID, constants.READMILL_REDIRECT_URI)
	webview.LoadUri(authorizeUri)

	window.Add(scrolledWindow)
	window.SetSizeRequest(500, 650)
}
示例#18
0
// ShortTime creates a GTK fullscreen window for the shorttime clients.
// No username/password required, only click 'start' button to log in
func ShortTime(client string, minutes int) (user string) {
	// Inital window configuration
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	defer window.Destroy()
	window.Fullscreen()
	window.SetKeepAbove(true)
	window.SetTitle("Mycel Login")

	// Build GUI
	frame := gtk.NewFrame("Logg deg på " + client)
	frame.SetLabelAlign(0.5, 0.5)
	var imageLoader *gdkpixbuf.Loader
	imageLoader, _ = gdkpixbuf.NewLoaderWithMimeType("image/png")
	imageLoader.Write(logo_png())
	imageLoader.Close()
	logo := gtk.NewImageFromPixbuf(imageLoader.GetPixbuf())
	info := gtk.NewLabel("")
	info.SetMarkup("<span foreground='red'>Dette er en korttidsmaskin\nMaks " +
		strconv.Itoa(minutes) + " minutter!</span>")
	button := gtk.NewButtonWithLabel("\nStart\n")

	vbox := gtk.NewVBox(false, 20)
	vbox.SetBorderWidth(20)
	vbox.Add(logo)
	vbox.Add(info)
	vbox.Add(button)

	frame.Add(vbox)

	center := gtk.NewAlignment(0.5, 0.5, 0, 0)
	center.Add(frame)
	window.Add(center)

	// Connect GUI event signals to function callbacks
	button.Connect("clicked", func() {
		gtk.MainQuit()
	})
	window.Connect("delete-event", func() bool {
		return true
	})

	window.ShowAll()
	gtk.Main()
	return "Anonym"
}
示例#19
0
文件: number.go 项目: leif/go-gtk
func main() {
	gtk.Init(&os.Args)

	dialog := gtk.Dialog()
	dialog.SetTitle("number input")

	vbox := dialog.GetVBox()

	label := gtk.Label("Numnber:")
	vbox.Add(label)

	input := gtk.Entry()
	input.SetEditable(true)
	vbox.Add(input)

	input.Connect("insert-text", func(ctx *glib.CallbackContext) {
		a := (*[2000]uint8)(unsafe.Pointer(ctx.Args(0)))
		p := (*int)(unsafe.Pointer(ctx.Args(2)))
		i := 0
		for a[i] != 0 {
			i++
		}
		s := string(a[0:i])
		if s == "." {
			if *p == 0 {
				input.StopEmission("insert-text")
			}
		} else {
			_, err := strconv.ParseFloat(s, 64)
			if err != nil {
				input.StopEmission("insert-text")
			}
		}
	})

	button := gtk.ButtonWithLabel("OK")
	button.Connect("clicked", func() {
		println(input.GetText())
		gtk.MainQuit()
	})
	vbox.Add(button)

	dialog.ShowAll()
	gtk.Main()
}
示例#20
0
func main() {
	gtk.Init(&os.Args)

	mi := gtk.MenuItemWithLabel("Popup!")
	mi.Connect("activate", func() {
		gtk.MainQuit()
	})
	nm := gtk.Menu()
	nm.Append(mi)
	nm.ShowAll()

	si := gtk.StatusIconFromStock(gtk.GTK_STOCK_FILE)
	si.Connect("popup-menu", func(cbx *glib.CallbackContext) {
		nm.Popup(nil, nil, gtk.GtkStatusIconPositionMenu, si, uint(cbx.Args(0)), uint(cbx.Args(1)))
	})

	gtk.Main()
}
示例#21
0
// Init acts as a constructor for the Status window struct
func (v *Status) Init(client, user string, minutes int) {

	// Initialize variables
	v.client = client
	v.user = user
	v.minutes = minutes
	v.warned = false
	v.window = gtk.NewWindow(gtk.WINDOW_TOPLEVEL)

	// Inital Window configuration
	v.window.SetKeepAbove(true)
	v.window.SetTitle(client)
	v.window.SetTypeHint(gdk.WINDOW_TYPE_HINT_MENU)
	v.window.SetSizeRequest(200, 180)
	v.window.SetResizable(false)

	// Build GUI
	userLabel := gtk.NewLabel(user)
	v.timeLabel = gtk.NewLabel("")
	v.timeLabel.SetMarkup("<span size='xx-large'>" + strconv.Itoa(v.minutes) + " min igjen</span>")
	button := gtk.NewButtonWithLabel("Logg ut")

	vbox := gtk.NewVBox(false, 20)
	vbox.SetBorderWidth(5)
	vbox.Add(userLabel)
	vbox.Add(v.timeLabel)
	vbox.Add(button)
	v.window.Add(vbox)

	// Connect GUI event signals to function callbacks
	v.window.Connect("delete-event", func() bool {
		// Don't allow user to quit by closing the window
		return true
	})
	button.Connect("clicked", func() {
		gtk.MainQuit()
	})

	return
}
示例#22
0
func createMenu() *gtk.MenuBar {
	menubar := gtk.NewMenuBar()
	vpaned := gtk.NewVPaned()

	//--------------------------------------------------------
	// GtkMenuItem
	//--------------------------------------------------------
	cascademenu := gtk.NewMenuItemWithMnemonic("_File")
	menubar.Append(cascademenu)
	submenu := gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	var menuitem *gtk.MenuItem
	menuitem = gtk.NewMenuItemWithMnemonic("E_xit")
	menuitem.Connect("activate", func() {
		gtk.MainQuit()
	})
	submenu.Append(menuitem)

	cascademenu = gtk.NewMenuItemWithMnemonic("_View")
	menubar.Append(cascademenu)
	submenu = gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	checkmenuitem := gtk.NewCheckMenuItemWithMnemonic("_Disable")
	checkmenuitem.Connect("activate", func() {
		vpaned.SetSensitive(!checkmenuitem.GetActive())
	})
	submenu.Append(checkmenuitem)

	cascademenu = gtk.NewMenuItemWithMnemonic("_Help")
	menubar.Append(cascademenu)
	submenu = gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	return menubar
}
示例#23
0
文件: demo.go 项目: JessonChan/go-gtk
func main() {
	var menuitem *gtk.MenuItem
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("GTK Go!")
	window.SetIconName("gtk-dialog-info")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")

	//--------------------------------------------------------
	// GtkVBox
	//--------------------------------------------------------
	vbox := gtk.NewVBox(false, 1)

	//--------------------------------------------------------
	// GtkMenuBar
	//--------------------------------------------------------
	menubar := gtk.NewMenuBar()
	vbox.PackStart(menubar, false, false, 0)

	//--------------------------------------------------------
	// GtkVPaned
	//--------------------------------------------------------
	vpaned := gtk.NewVPaned()
	vbox.Add(vpaned)

	//--------------------------------------------------------
	// GtkFrame
	//--------------------------------------------------------
	frame1 := gtk.NewFrame("Demo")
	framebox1 := gtk.NewVBox(false, 1)
	frame1.Add(framebox1)

	frame2 := gtk.NewFrame("Demo")
	framebox2 := gtk.NewVBox(false, 1)
	frame2.Add(framebox2)

	vpaned.Pack1(frame1, false, false)
	vpaned.Pack2(frame2, false, false)

	//--------------------------------------------------------
	// GtkImage
	//--------------------------------------------------------
	dir, _ := path.Split(os.Args[0])
	imagefile := path.Join(dir, "../../data/go-gtk-logo.png")

	label := gtk.NewLabel("Go Binding for GTK")
	label.ModifyFontEasy("DejaVu Serif 15")
	framebox1.PackStart(label, false, true, 0)

	//--------------------------------------------------------
	// GtkEntry
	//--------------------------------------------------------
	entry := gtk.NewEntry()
	entry.SetText("Hello world")
	framebox1.Add(entry)

	image := gtk.NewImageFromFile(imagefile)
	framebox1.Add(image)

	//--------------------------------------------------------
	// GtkScale
	//--------------------------------------------------------
	scale := gtk.NewHScaleWithRange(0, 100, 1)
	scale.Connect("value-changed", func() {
		println("scale:", int(scale.GetValue()))
	})
	framebox2.Add(scale)

	//--------------------------------------------------------
	// GtkHBox
	//--------------------------------------------------------
	buttons := gtk.NewHBox(false, 1)

	//--------------------------------------------------------
	// GtkButton
	//--------------------------------------------------------
	button := gtk.NewButtonWithLabel("Button with label")
	button.Clicked(func() {
		println("button clicked:", button.GetLabel())
		messagedialog := gtk.NewMessageDialog(
			button.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			entry.GetText())
		messagedialog.Response(func() {
			println("Dialog OK!")

			//--------------------------------------------------------
			// GtkFileChooserDialog
			//--------------------------------------------------------
			filechooserdialog := gtk.NewFileChooserDialog(
				"Choose File...",
				button.GetTopLevelAsWindow(),
				gtk.FILE_CHOOSER_ACTION_OPEN,
				gtk.STOCK_OK,
				gtk.RESPONSE_ACCEPT)
			filter := gtk.NewFileFilter()
			filter.AddPattern("*.go")
			filechooserdialog.AddFilter(filter)
			filechooserdialog.Response(func() {
				println(filechooserdialog.GetFilename())
				filechooserdialog.Destroy()
			})
			filechooserdialog.Run()
			messagedialog.Destroy()
		})
		messagedialog.Run()
	})
	buttons.Add(button)

	//--------------------------------------------------------
	// GtkFontButton
	//--------------------------------------------------------
	fontbutton := gtk.NewFontButton()
	fontbutton.Connect("font-set", func() {
		println("title:", fontbutton.GetTitle())
		println("fontname:", fontbutton.GetFontName())
		println("use_size:", fontbutton.GetUseSize())
		println("show_size:", fontbutton.GetShowSize())
	})
	buttons.Add(fontbutton)
	framebox2.PackStart(buttons, false, false, 0)

	buttons = gtk.NewHBox(false, 1)

	//--------------------------------------------------------
	// GtkToggleButton
	//--------------------------------------------------------
	togglebutton := gtk.NewToggleButtonWithLabel("ToggleButton with label")
	togglebutton.Connect("toggled", func() {
		if togglebutton.GetActive() {
			togglebutton.SetLabel("ToggleButton ON!")
		} else {
			togglebutton.SetLabel("ToggleButton OFF!")
		}
	})
	buttons.Add(togglebutton)

	//--------------------------------------------------------
	// GtkCheckButton
	//--------------------------------------------------------
	checkbutton := gtk.NewCheckButtonWithLabel("CheckButton with label")
	checkbutton.Connect("toggled", func() {
		if checkbutton.GetActive() {
			checkbutton.SetLabel("CheckButton CHECKED!")
		} else {
			checkbutton.SetLabel("CheckButton UNCHECKED!")
		}
	})
	buttons.Add(checkbutton)

	//--------------------------------------------------------
	// GtkRadioButton
	//--------------------------------------------------------
	buttonbox := gtk.NewVBox(false, 1)
	radiofirst := gtk.NewRadioButtonWithLabel(nil, "Radio1")
	buttonbox.Add(radiofirst)
	buttonbox.Add(gtk.NewRadioButtonWithLabel(radiofirst.GetGroup(), "Radio2"))
	buttonbox.Add(gtk.NewRadioButtonWithLabel(radiofirst.GetGroup(), "Radio3"))
	buttons.Add(buttonbox)
	//radiobutton.SetMode(false);
	radiofirst.SetActive(true)

	framebox2.PackStart(buttons, false, false, 0)

	//--------------------------------------------------------
	// GtkVSeparator
	//--------------------------------------------------------
	vsep := gtk.NewVSeparator()
	framebox2.PackStart(vsep, false, false, 0)

	//--------------------------------------------------------
	// GtkComboBoxEntry
	//--------------------------------------------------------
	combos := gtk.NewHBox(false, 1)
	comboboxentry := gtk.NewComboBoxEntryNewText()
	comboboxentry.AppendText("Monkey")
	comboboxentry.AppendText("Tiger")
	comboboxentry.AppendText("Elephant")
	comboboxentry.Connect("changed", func() {
		println("value:", comboboxentry.GetActiveText())
	})
	combos.Add(comboboxentry)

	//--------------------------------------------------------
	// GtkComboBox
	//--------------------------------------------------------
	combobox := gtk.NewComboBoxNewText()
	combobox.AppendText("Peach")
	combobox.AppendText("Banana")
	combobox.AppendText("Apple")
	combobox.SetActive(1)
	combobox.Connect("changed", func() {
		println("value:", combobox.GetActiveText())
	})
	combos.Add(combobox)

	framebox2.PackStart(combos, false, false, 0)

	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	swin := gtk.NewScrolledWindow(nil, nil)
	swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	swin.SetShadowType(gtk.SHADOW_IN)
	textview := gtk.NewTextView()
	var start, end gtk.TextIter
	buffer := textview.GetBuffer()
	buffer.GetStartIter(&start)
	buffer.Insert(&start, "Hello ")
	buffer.GetEndIter(&end)
	buffer.Insert(&end, "World!")
	tag := buffer.CreateTag("bold", map[string]string{
		"background": "#FF0000", "weight": "700"})
	buffer.GetStartIter(&start)
	buffer.GetEndIter(&end)
	buffer.ApplyTag(tag, &start, &end)
	swin.Add(textview)
	framebox2.Add(swin)

	buffer.Connect("changed", func() {
		println("changed")
	})

	//--------------------------------------------------------
	// GtkMenuItem
	//--------------------------------------------------------
	cascademenu := gtk.NewMenuItemWithMnemonic("_File")
	menubar.Append(cascademenu)
	submenu := gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	menuitem = gtk.NewMenuItemWithMnemonic("E_xit")
	menuitem.Connect("activate", func() {
		gtk.MainQuit()
	})
	submenu.Append(menuitem)

	cascademenu = gtk.NewMenuItemWithMnemonic("_View")
	menubar.Append(cascademenu)
	submenu = gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	checkmenuitem := gtk.NewCheckMenuItemWithMnemonic("_Disable")
	checkmenuitem.Connect("activate", func() {
		vpaned.SetSensitive(!checkmenuitem.GetActive())
	})
	submenu.Append(checkmenuitem)

	menuitem = gtk.NewMenuItemWithMnemonic("_Font")
	menuitem.Connect("activate", func() {
		fsd := gtk.NewFontSelectionDialog("Font")
		fsd.SetFontName(fontbutton.GetFontName())
		fsd.Response(func() {
			println(fsd.GetFontName())
			fontbutton.SetFontName(fsd.GetFontName())
			fsd.Destroy()
		})
		fsd.SetTransientFor(window)
		fsd.Run()
	})
	submenu.Append(menuitem)

	cascademenu = gtk.NewMenuItemWithMnemonic("_Help")
	menubar.Append(cascademenu)
	submenu = gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	menuitem = gtk.NewMenuItemWithMnemonic("_About")
	menuitem.Connect("activate", func() {
		dialog := gtk.NewAboutDialog()
		dialog.SetName("Go-Gtk Demo!")
		dialog.SetProgramName("demo")
		dialog.SetAuthors(authors())
		dir, _ := path.Split(os.Args[0])
		imagefile := path.Join(dir, "../../data/mattn-logo.png")
		pixbuf, _ := gdkpixbuf.NewFromFile(imagefile)
		dialog.SetLogo(pixbuf)
		dialog.SetLicense("The library is available under the same terms and conditions as the Go, the BSD style license, and the LGPL (Lesser GNU Public License). The idea is that if you can use Go (and Gtk) in a project, you should also be able to use go-gtk.")
		dialog.SetWrapLicense(true)
		dialog.Run()
		dialog.Destroy()
	})
	submenu.Append(menuitem)

	//--------------------------------------------------------
	// GtkStatusbar
	//--------------------------------------------------------
	statusbar := gtk.NewStatusbar()
	context_id := statusbar.GetContextId("go-gtk")
	statusbar.Push(context_id, "GTK binding for Go!")

	framebox2.PackStart(statusbar, false, false, 0)

	//--------------------------------------------------------
	// Event
	//--------------------------------------------------------
	window.Add(vbox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}
示例#24
0
文件: main.go 项目: bit4bit/remoton
func main() {
	flag.Parse()

	common.SetDefaultGtkTheme()

	runtime.GOMAXPROCS(runtime.NumCPU())

	rclient = &remoton.Client{Prefix: "/remoton", TLSConfig: &tls.Config{}}
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGABRT, syscall.SIGKILL, syscall.SIGTERM)
	go func() {
		<-sigs
		chatSrv.Terminate()
		tunnelSrv.Terminate()
	}()
	gtk.Init(nil)

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("REMOTON SUPPORT")
	window.Connect("destroy", func() {
		gtk.MainQuit()
		chatSrv.Terminate()
		tunnelSrv.Terminate()
	})
	window.SetIcon(common.GetIconGdkPixbuf())

	appLayout := gtk.NewVBox(false, 1)
	menu := gtk.NewMenuBar()
	appLayout.Add(menu)

	cascademenu := gtk.NewMenuItemWithMnemonic("_Help")
	menu.Append(cascademenu)
	submenu := gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)

	menuitem := gtk.NewMenuItemWithMnemonic("_About")
	menuitem.Connect("activate", func() {
		dialog := common.GtkAboutDialog()
		dialog.SetProgramName("Support Desktop")
		dialog.Run()
		dialog.Destroy()
	})
	submenu.Append(menuitem)

	hpaned := gtk.NewHPaned()
	appLayout.Add(hpaned)

	//---
	//CHAT
	//---
	frameChat := gtk.NewFrame("Chat")
	chatBox := gtk.NewVBox(false, 1)
	frameChat.Add(chatBox)

	swinChat := gtk.NewScrolledWindow(nil, nil)
	chatHistory := gtk.NewTextView()

	swinChat.Add(chatHistory)

	chatEntry := gtk.NewEntry()
	chatEntry.Connect("key-press-event", func(ctx *glib.CallbackContext) {
		arg := ctx.Args(0)
		event := *(**gdk.EventKey)(unsafe.Pointer(&arg))
		if event.Keyval == gdk.KEY_Return {
			msgToSend := chatEntry.GetText()
			chatSrv.Send(msgToSend)
			chatHistorySend(chatHistory, msgToSend)
			chatEntry.SetText("")
		}

	})
	chatSrv.OnRecv(func(msg string) {
		log.Println(msg)
		chatHistoryRecv(chatHistory, msg)
	})
	chatBox.Add(chatEntry)
	chatBox.Add(swinChat)

	//---
	//CONTROL
	//---
	frameControl := gtk.NewFrame("Control")
	controlBox := gtk.NewVBox(false, 1)
	frameControl.Add(controlBox)

	controlBox.Add(gtk.NewLabel("Machine ID"))
	machineIDEntry := gtk.NewEntry()
	controlBox.Add(machineIDEntry)

	controlBox.Add(gtk.NewLabel("Machine AUTH"))
	machineAuthEntry := gtk.NewEntry()
	controlBox.Add(machineAuthEntry)

	controlBox.Add(gtk.NewLabel("Server"))
	serverEntry := gtk.NewEntry()
	serverEntry.SetText("localhost:9934")
	if os.Getenv("REMOTON_SERVER") != "" {
		serverEntry.SetText(os.Getenv("REMOTON_SERVER"))
		serverEntry.SetEditable(false)
	}
	controlBox.Add(serverEntry)

	btnCert := gtk.NewFileChooserButton("Cert", gtk.FILE_CHOOSER_ACTION_OPEN)
	controlBox.Add(btnCert)
	btn := gtk.NewButtonWithLabel("Connect")
	started := false
	btn.Clicked(func() {
		if *insecure {
			rclient.TLSConfig.InsecureSkipVerify = true
		} else {
			certPool, err := common.GetRootCAFromFile(btnCert.GetFilename())
			if err != nil {
				dialogError(window, err)
				return
			}
			rclient.TLSConfig.RootCAs = certPool
		}

		session := &remoton.SessionClient{Client: rclient,
			ID:     machineIDEntry.GetText(),
			APIURL: "https://" + serverEntry.GetText()}

		if !started {
			err := chatSrv.Start(session)
			if err != nil {
				dialogError(btn.GetTopLevelAsWindow(), err)
				return
			}

			err = tunnelSrv.Start(session, machineAuthEntry.GetText())

			if err != nil {
				dialogError(btn.GetTopLevelAsWindow(), err)
				return
			}

			btn.SetLabel("Disconnect")
			started = true
		} else {
			chatSrv.Terminate()
			tunnelSrv.Terminate()
			btn.SetLabel("Connect")
			started = false
		}

	})
	controlBox.Add(btn)

	hpaned.Pack1(frameControl, false, false)
	hpaned.Pack2(frameChat, false, false)
	window.Add(appLayout)
	window.ShowAll()
	gtk.Main()

}
示例#25
0
文件: hasmail.go 项目: jonhoo/hasmail
// main reads the config file, connects to each IMAP server in a separate thread
// and watches the notify channel for messages telling it to update the status
// icon.
func main() {
	conf, err := goconf.ReadConfigFile(os.Getenv("HOME") + "/.hasmailrc")
	if err != nil {
		fmt.Println("Failed to load configuration file, exiting...\n", err)
		return
	}

	// This channel will be used to tell us if we should exit the program
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)

	// GTK engage!
	gtk.Init(&os.Args)
	glib.SetApplicationName("hasmail")
	defer gtk.MainQuit()

	// Set up the tray icon
	si := gtk.NewStatusIconFromStock(gtk.STOCK_DISCONNECT)
	si.SetTitle("hasmail")
	si.SetTooltipMarkup("Not connected")

	// Set up the tray icon right click menu
	mi := gtk.NewMenuItemWithLabel("Quit")
	mi.Connect("activate", func() {
		quit <- syscall.SIGINT
	})
	nm := gtk.NewMenu()
	nm.Append(mi)
	nm.ShowAll()
	si.Connect("popup-menu", func(cbx *glib.CallbackContext) {
		nm.Popup(nil, nil, gtk.StatusIconPositionMenu, si, uint(cbx.Args(0)), uint32(cbx.Args(1)))
	})

	/* If the user clicks the tray icon, here's what happens:
	 *   - if only a single account has new emails, and a click command has been
	 *     specified for that account, execute it
	 *   - if the user has specified a default click handler, execute that
	 *   - otherwise, do nothing
	 */
	si.Connect("activate", func(cbx *glib.CallbackContext) {
		command, geterr := conf.GetString("default", "click")
		nonZero := 0
		nonZeroAccount := ""

		for account, unseenList := range parts.Unseen {
			if len(unseenList) > 0 {
				nonZero++
				nonZeroAccount = account
			}
		}

		// Can't just use HasOption here because that also checks "default" section,
		// even though Get* doesn't...
		if nonZero == 1 {
			acommand, ageterr := conf.GetString(nonZeroAccount, "click")
			if ageterr == nil {
				command = acommand
				geterr = ageterr
			}
		}

		if geterr == nil {
			fmt.Printf("Executing user command: %s\n", command)
			shell := os.Getenv("SHELL")
			if shell == "" {
				shell = "/bin/sh"
			}

			sh := exec.Command(shell, "-c", command)
			sh.Env = os.Environ()
			err = sh.Start()
			if err != nil {
				fmt.Printf("Failed to run command '%s' on click\n", command)
				fmt.Println(err)
			}
		} else {
			fmt.Println("No action defined for click\n", geterr)
		}
	})

	go gtk.Main()

	// Connect to all accounts
	sections := conf.GetSections()
	notify := make(chan bool, len(sections))
	for _, account := range sections {
		// default isn't really an account
		if account == "default" {
			continue
		}

		initConnection(notify, conf, account)
	}

	// Let the user know that we've now initiated all the connections
	si.SetFromStock(gtk.STOCK_CONNECT)
	si.SetTooltipText("Connecting")

	// Keep updating the status icon (or quit if the user wants us to)
	for {
		select {
		case <-quit:
			return
		case <-notify:
			totUnseen := 0
			s := ""
			for account, e := range parts.Errs {
				if e == 0 {
					continue
				}

				s += account + ": "

				switch e {
				case 1:
					s += "Connection failed!"
				case 2:
					s += "IDLE not supported!"
				case 3:
					s += "No login credentials given!"
				case 4:
					s += "Login failed!"
				case 5:
					s += "Connection dropped!"
				}

				s += "\n"
			}

			for account, unseenList := range parts.Unseen {
				if parts.Errs[account] != 0 {
					continue
				}

				numUnseen := len(unseenList)

				if numUnseen >= 0 {
					totUnseen += numUnseen
				}
				s += account + ": "

				switch numUnseen {
				case 0:
					s += "No new messages"
				case 1:
					s += "One new message"
				default:
					s += fmt.Sprintf("%d new messages", numUnseen)
				}

				s += "\n"
			}

			// get rid of trailing newline
			s = strings.TrimRight(s, "\n")
			si.SetTooltipText(s)

			// http://developer.gnome.org/gtk3/3.0/gtk3-Stock-Items.html
			switch totUnseen {
			case 0:
				si.SetFromStock(gtk.STOCK_NEW)
			case 1:
				si.SetFromStock(gtk.STOCK_DND)
			default:
				si.SetFromStock(gtk.STOCK_DND_MULTIPLE)
			}
		}
	}
}
示例#26
0
文件: gui.go 项目: abiosoft/gocalc
// End the program
func Quit() {
	gtk.MainQuit()
}
示例#27
0
文件: app.go 项目: kisom/socialgopher
func mainWindow() {
	gtk.Init(&os.Args)

	// window settings
	window_main := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window_main.SetPosition(gtk.WIN_POS_CENTER)
	window_main.SetTitle("Social Gopher")
	window_main.Connect("destroy", func() {
		println("[!] Quit application")
		gtk.MainQuit()
	})

	// images
	image_profile := loadImageAsset("profile")
	image_stream := loadImageAsset("stream")
	image_mentions := loadImageAsset("mentions")
	image_interactions := loadImageAsset("interactions")
	image_stars := loadImageAsset("stars")
	image_messages := loadImageAsset("messages")
	image_settings := loadImageAsset("settings")

	// containers
	container_main := gtk.NewHBox(false, 1)
	container_left := gtk.NewVBox(false, 1)
	container_right := gtk.NewVBox(false, 5)
	container_compose := gtk.NewHBox(false, 5)
	container_profile := gtk.NewHBox(false, 5)
	container_profile.Add(image_profile)
	container_left.SetBorderWidth(5)
	container_right.SetBorderWidth(5)

	// toolbar
	button_stream := gtk.NewToolButton(image_stream, "My Stream")
	button_mentions := gtk.NewToolButton(image_mentions, "Mentions")
	button_interactions := gtk.NewToolButton(image_interactions, "Interactions")
	button_stars := gtk.NewToolButton(image_stars, "Stars")
	button_messages := gtk.NewToolButton(image_messages, "Messages")
	button_settings := gtk.NewToolButton(image_settings, "Settings")
	button_separator := gtk.NewSeparatorToolItem()
	toolbar := gtk.NewToolbar()
	toolbar.SetOrientation(gtk.ORIENTATION_VERTICAL)
	toolbar.Insert(button_stream, -1)
	toolbar.Insert(button_mentions, -1)
	toolbar.Insert(button_interactions, -1)
	toolbar.Insert(button_stars, -1)
	toolbar.Insert(button_messages, -1)
	toolbar.Insert(button_separator, -1)
	toolbar.Insert(button_settings, -1)

	// stream list
	list_swin := gtk.NewScrolledWindow(nil, nil)
	list_swin.SetPolicy(-1, 1)
	list_swin.SetShadowType(2)
	list_textView := gtk.NewTextView()
	list_textView.SetEditable(false)
	list_textView.SetCursorVisible(false)
	list_textView.SetWrapMode(2)
	list_swin.Add(list_textView)
	list_buffer := list_textView.GetBuffer()

	// compose message
	compose := gtk.NewTextView()
	compose.SetEditable(true)
	compose.SetWrapMode(2)
	compose_swin := gtk.NewScrolledWindow(nil, nil)
	compose_swin.SetPolicy(1, 1)
	compose_swin.SetShadowType(1)
	compose_swin.Add(compose)
	compose_counter := gtk.NewLabel("256")
	compose_buffer := compose.GetBuffer()

	compose_buffer.Connect("changed", func() {
		chars_left := 256 - compose_buffer.GetCharCount()
		compose_counter.SetText(strconv.Itoa(chars_left))
	})

	// post button and counter
	button_post := gtk.NewButtonWithLabel("Post")
	container_post := gtk.NewVBox(false, 1)
	container_post.Add(compose_counter)
	container_post.Add(button_post)

	// button functions
	button_stream.OnClicked(func() {
		list_buffer.SetText("My Stream")
	})
	button_mentions.OnClicked(func() {
		list_buffer.SetText("Mentions")
	})
	button_interactions.OnClicked(func() {
		list_buffer.SetText("Interactions")
	})
	button_stars.OnClicked(func() {
		list_buffer.SetText("Stars")
	})
	button_messages.OnClicked(func() {
		list_buffer.SetText("Messages")
	})
	button_settings.OnClicked(func() {
		accountWindow()
	})
	button_post.Clicked(func() {
		compose_buffer.SetText("")
	})

	// add elements to containers
	container_left.PackStart(container_profile, false, true, 1)
	container_left.PackEnd(toolbar, true, true, 1)
	container_right.PackStart(list_swin, true, true, 1)
	container_right.PackEnd(container_compose, false, false, 1)
	container_compose.PackStart(compose_swin, true, true, 1)
	container_compose.PackEnd(container_post, false, true, 1)
	container_main.PackStart(container_left, false, true, 1)
	container_main.PackEnd(container_right, true, true, 1)

	window_main.Add(container_main)
	window_main.SetSizeRequest(500, 600)
	window_main.ShowAll()

	gtk.Main()
}
示例#28
0
func Init(title string) {
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle(title)
	window.SetIconName("gtk-dialog-info")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		fmt.Println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")

	//--------------------------------------------------------
	// GtkVBox
	//--------------------------------------------------------
	vbox := gtk.NewVBox(false, 1)

	//--------------------------------------------------------
	// GtkMenuBar
	//--------------------------------------------------------
	menubar := gtk.NewMenuBar()
	vbox.PackStart(menubar, false, false, 0)

	//--------------------------------------------------------
	// GtkDrawable
	//--------------------------------------------------------

	drawingarea := gtk.NewDrawingArea()
	//var gdkwin *gdk.Window
	var pixmap *gdk.Pixmap
	var gc *gdk.GC
	drawingarea.Connect("configure-event", func() {
		println("Configuring drawingArea!")
		if pixmap != nil {
			pixmap.Unref()
		}
		allocation := drawingarea.GetAllocation()
		pixmap = gdk.NewPixmap(drawingarea.GetWindow().GetDrawable(), allocation.Width, allocation.Height, 24)
		gc = gdk.NewGC(pixmap.GetDrawable())
		gc.SetRgbFgColor(gdk.NewColor("white"))
		pixmap.GetDrawable().DrawRectangle(gc, true, 0, 0, -1, -1)
		gc.SetRgbFgColor(gdk.NewColor("black"))
		gc.SetRgbBgColor(gdk.NewColor("white"))
		pixmap.GetDrawable().DrawRectangle(gc, false, 0, 0, 10, 10)
	})

	drawingarea.Connect("expose-event", func() {
		println("Exposing DrawingArea!")
		if pixmap != nil {
			drawingarea.GetWindow().GetDrawable().DrawDrawable(gc, pixmap.GetDrawable(), 0, 0, 0, 0, -1, -1)
		}
	})

	vbox.Add(drawingarea)

	//--------------------------------------------------------
	// GtkScale
	//--------------------------------------------------------
	scale := gtk.NewHScaleWithRange(0, 100, 1)
	scale.Connect("value-changed", func() {
		//fmt.Println("scale:", int(scale.GetValue()))
	})
	vbox.Add(scale)

	window.Add(vbox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}
示例#29
0
func Init(size uint) {
	var (
		files          *gtk.GtkHBox
		examples_cnt   int
		newfile_flag   bool
		cs_desc_normal *_Ctype_char
		cs_desc_bold   *_Ctype_char
	)

	s = new(solver.Solver)
	s.Size = size

	if s.Size == 9 {
		cs_desc_normal = C.CString("Sans 14")
		cs_desc_bold = C.CString("Sans Bold 14")
	} else {
		cs_desc_normal = C.CString("Sans 16")
		cs_desc_bold = C.CString("Sans Bold 16")
	}
	desc_normal = C.pango_font_description_from_string(cs_desc_normal)
	desc_bold = C.pango_font_description_from_string(cs_desc_bold)
	C.free_string(cs_desc_normal)
	C.free_string(cs_desc_bold)

	gtk.Init(&os.Args)

	window := gtk.Window(gtk.GTK_WINDOW_TOPLEVEL)
	window.SetResizable(false)
	window.SetTitle("Sudoku solver")
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})
	window.Connect("key-press-event", func(ctx *glib.CallbackContext) {
		arg := ctx.Args(0)
		kev := *(**gdk.EventKey)(unsafe.Pointer(&arg))
		r, st := rune(kev.Keyval), gdk.GdkModifierType(kev.State)
		if st&gdk.GDK_CONTROL_MASK != 0 {
			if r == 122 || r == 90 { // Ctrl-Z
				m := cs_pop()
				clear()
				for i := uint(0); i < s.Size; i++ {
					for j := uint(0); j < s.Size; j++ {
						v := int(m[i][j])
						if v != 0 {
							entries[i][j].SetText(strconv.Itoa(v))
						}
					}
				}
			}
		}
	})

	vbox := gtk.VBox(false, 10)

	table := gtk.Table(3, s.Size/3, false)
	bg := [2]*gdk.GdkColor{gdk.Color("white"), gdk.Color("#e9f2ea")}
	for y := uint(0); y < 3; y++ {
		for x := uint(0); x < s.Size/3; x++ {
			subtable := gtk.Table(s.Size/3, 3, false)
			for sy := uint(0); sy < s.Size/3; sy++ {
				for sx := uint(0); sx < 3; sx++ {
					w := gtk.Entry()
					w.SetWidthChars(1)
					w.SetMaxLength(1)
					if s.Size == 9 {
						w.SetSizeRequest(23, 25)
					} else {
						w.SetSizeRequest(25, 27)
					}
					w.Connect("key-press-event", func(ctx *glib.CallbackContext) bool {
						data := ctx.Data().([]uint)
						y, x := data[0], data[1]
						arg := ctx.Args(0)
						kev := *(**gdk.EventKey)(unsafe.Pointer(&arg))
						r := rune(kev.Keyval)
						switch r & 0xFF {
						case 81:
							if x != 0 || y != 0 {
								if x == 0 {
									x = s.Size - 1
									y--
								} else {
									x--
								}
							}
						case 82:
							if y != 0 {
								y--
							}
						case 83:
							if x != s.Size-1 || y != s.Size-1 {
								if x == s.Size-1 {
									x = 0
									y++
								} else {
									x++
								}
							}
						case 84:
							if y != s.Size-1 {
								y++
							}
						}
						if y != data[0] || x != data[1] {
							entries[y][x].GrabFocus()
						}
						if unicode.IsOneOf([]*unicode.RangeTable{unicode.L, unicode.Z}, r) {
							return true
						}
						return false
					}, []uint{(s.Size/3)*y + sy, 3*x + sx})
					w.Connect("grab-focus", func(ctx *glib.CallbackContext) {
						data := ctx.Data().([]uint)
						y, x := data[0], data[1]
						for k := 0; k < 2; k++ {
							for i := uint(0); i < s.Size; i++ {
								modify_base(unsafe.Pointer(entries[i][prev_x].Widget), bg[k])
							}
							for j := uint(0); j < s.Size; j++ {
								modify_base(unsafe.Pointer(entries[prev_y][j].Widget), bg[k])
							}
							prev_y, prev_x = y, x
						}
					}, []uint{(s.Size/3)*y + sy, 3*x + sx})
					subtable.Attach(w, sx, sx+1, sy, sy+1, gtk.GTK_FILL, gtk.GTK_FILL, 0, 0)
					entries[(s.Size/3)*y+sy][3*x+sx] = w
					modify_font((s.Size/3)*y+sy, 3*x+sx, desc_bold)
				}
			}
			table.Attach(subtable, x, x+1, y, y+1, gtk.GTK_FILL, gtk.GTK_FILL, 3, 3)
		}
	}

	solve_btn := gtk.ButtonWithLabel("Solve")
	solve_btn.Clicked(func() {
		var m1, m2 [9][9]uint

		for i := uint(0); i < s.Size; i++ {
			for j := uint(0); j < s.Size; j++ {
				v, _ := strconv.Atoi(entries[i][j].GetText())
				m1[i][j] = uint(v)
			}
		}
		if !check_field(&m1) {
			return
		}
		cs_push(m1)
		s.Load(m1)
		s.Solve()
		if s.Finals != s.Size*s.Size {
			// let's try some tough algorithms :)
			s.ToughSolve()
		}
		for i := uint(0); i < s.Size; i++ {
			for j := uint(0); j < s.Size; j++ {
				v := int(s.Get(i, j))
				m2[i][j] = uint(v)
				if v != 0 {
					entries[i][j].SetText(strconv.Itoa(v))
				} else {
					var c_string [9]string
					// get list of candidates
					c_uint, l := s.GetCandidates(i, j)
					for k := uint(0); k < l; k++ {
						c_string[k] = strconv.Itoa(int(c_uint[k]))
					}
					// make a tooltip with them
					entries[i][j].SetTooltipText(strings.Join(c_string[:l], " "))
				}
			}
		}
		// check for differences
		for i := uint(0); i < s.Size; i++ {
			for j := uint(0); j < s.Size; j++ {
				if m1[i][j] == m2[i][j] {
					modify_font(i, j, desc_bold)
				} else {
					modify_font(i, j, desc_normal)
				}
			}
		}
	})
	clear_btn := gtk.ButtonWithLabel("Clear")
	clear_btn.Clicked(func() {
		m := [9][9]uint{}
		for i := uint(0); i < s.Size; i++ {
			for j := uint(0); j < s.Size; j++ {
				m[i][j] = s.Get(i, j)
			}
		}
		cs_push(m)
		clear()
	})

	examples = gtk.ComboBoxText()
	// scan `examples` folder
	sz := strconv.Itoa(int(s.Size))
	dir, err := os.Open("examples/" + sz + "x" + sz)
	if err == nil {
		names, err := dir.Readdirnames(0)
		if err == nil {
			for _, v := range names {
				examples.AppendText(v)
				examples_cnt++
			}
		}
		dir.Close()
	}
	examples.Connect("changed", func() {
		sz := strconv.Itoa(int(s.Size))
		load_sudoku("examples/" + sz + "x" + sz + "/" + examples.GetActiveText())
	})

	newfile := gtk.Entry()
	newfile.Connect("activate", func() {
		filename := newfile.GetText()
		if filename != "" {
			sz := strconv.Itoa(int(s.Size))
			f, err := os.Create("examples/" + sz + "x" + sz + "/" + filename)
			if err == nil {
				for i := uint(0); i < s.Size; i++ {
					for j := uint(0); j < s.Size; j++ {
						v := []byte(entries[i][j].GetText())
						if len(v) == 0 || v[0] < 49 || v[0] > byte(48+s.Size) {
							v = []byte{' '}
						}
						f.Write(v)
						if (j+1)%3 == 0 && j+1 != s.Size {
							f.WriteString("*")
						}
					}
					f.WriteString("\n")
					if (i+1)%(s.Size/3) == 0 && i+1 != s.Size {
						if s.Size == 9 {
							f.WriteString("***********\n")
						} else {
							f.WriteString("*******\n")
						}
					}
				}
				f.Close()
			}
			examples.AppendText(filename)
			examples.SetActive(examples_cnt)
			examples_cnt++
		}
		files.ShowAll()
		newfile.SetText("")
		newfile.Hide()
	})

	icon := gtk.Image()
	icon.SetFromStock(gtk.GTK_STOCK_SAVE_AS, gtk.GTK_ICON_SIZE_BUTTON)
	export := gtk.Button()
	export.SetImage(icon)
	export.Clicked(func() {
		if !newfile_flag {
			files.Add(newfile)
			newfile_flag = true
		}
		files.ShowAll()
		examples.Hide()
		export.Hide()
		newfile.GrabFocus()
	})

	files = gtk.HBox(false, 0)
	files.Add(export)
	files.Add(examples)

	buttons := gtk.HBox(true, 5)
	buttons.Add(solve_btn)
	buttons.Add(clear_btn)

	vbox.Add(table)
	vbox.Add(files)
	vbox.Add(buttons)

	window.Add(vbox)
	window.ShowAll()
}
示例#30
0
func main() {
	var prueba int

	var Actual Juego

	Actual.Init()

	var heuristica int

	heuristica = 1

	var r1 [4]int
	var r2 [8]int

	Actual.fila1 = Actual.fila1Objetivo
	Actual.fila2 = Actual.fila2Objetivo

	r1 = Actual.fila1Objetivo
	r2 = Actual.fila2Objetivo

	//fmt.Println(r1,r2)

	prueba = 100
	//var menuitem *gtk.GtkMenuItem
	gtk.Init(nil)
	window := gtk.Window(gtk.GTK_WINDOW_TOPLEVEL)
	window.SetPosition(gtk.GTK_WIN_POS_CENTER)
	window.SetTitle(" A star")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		println("got destory!\n", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")

	vbox := gtk.HBox(false, 14)

	//menubar:=gtk.MenuBar()
	//vbox.PackStart(menubar,false,false,0)

	vpaned := gtk.VPaned()
	vbox.Add(vpaned)

	frame := gtk.Frame("Profundiad")
	framebox := gtk.HBox(false, 14)

	framebox1 := gtk.VBox(true, 0)
	frame1 := gtk.Frame("Rompecabezas ")

	frame.Add(framebox)
	frame1.Add(framebox1)

	drawingarea := gtk.DrawingArea()

	vpaned.Add(frame)
	vpaned.Add(frame1)

	button := gtk.ButtonWithLabel("Resolver")
	button2 := gtk.ButtonWithLabel("Desordenar")
	button3 := gtk.ButtonWithLabel(" Nivel de Desorden")

	//TxtPasos:=gtk.Entry()

	frameHu := gtk.VBox(true, 2)

	lheuristica := gtk.Label("Heuristica")
	comboBox := gtk.ComboBoxEntryNewText()
	comboBox.AppendText("Piezas Desordenadas")
	comboBox.AppendText("Distancia entre Piezas")

	comboBox.Connect("changed", func() {
		if strings.EqualFold(comboBox.GetActiveText(), "Piezas Desordenadas") {
			heuristica = 2
		} else {
			heuristica = 1
		}
	})

	frameHu.Add(lheuristica)
	frameHu.Add(comboBox)

	entry := gtk.Entry()

	framebox.Add(entry)

	framebox.Add(button)
	framebox.Add(frameHu)

	framebox.Add(button2)
	framebox.Add(button3)

	//framebox1.Add(TxtPasos)
	//var gdkwin *gdk.GdkWindow
	var pixmap *gdk.GdkPixmap
	var gc *gdk.GdkGC

	drawingarea.Connect("configure-event", func() {
		if pixmap != nil {
			pixmap.Unref()
		}
		var allocation gtk.GtkAllocation
		drawingarea.GetAllocation(&allocation)
		pixmap = gdk.Pixmap(drawingarea.GetWindow().GetDrawable(), allocation.Width, allocation.Height, 24)
		gc = gdk.GC(pixmap.GetDrawable())
		gc.SetRgbFgColor(gdk.Color("white"))
		pixmap.GetDrawable().DrawRectangle(gc, true, 0, 0, -1, -1)
		gc.SetRgbFgColor(gdk.Color("blue"))
		gc.SetRgbBgColor(gdk.Color("white"))
		pixmap.GetDrawable().DrawArc(gc, false, 100, 100, 200, 200, 0, 30000)
		pixmap.GetDrawable().DrawArc(gc, false, 150, 150, 100, 100, 0, 30000)

		pixmap.GetDrawable().DrawLine(gc, 200, 100, 200, 300)
		pixmap.GetDrawable().DrawLine(gc, 100, 200, 300, 200)

		pixmap.GetDrawable().DrawLine(gc, 130, 130, 165, 165)
		pixmap.GetDrawable().DrawLine(gc, 235, 235, 270, 270)

		pixmap.GetDrawable().DrawLine(gc, 271, 129, 235, 165)
		pixmap.GetDrawable().DrawLine(gc, 165, 235, 129, 271)

		pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 200, 200, strconv.Itoa(prueba))

		pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 100, 200, strconv.Itoa(prueba))

		pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 100, 300, strconv.Itoa(prueba))
		pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 200, 300, strconv.Itoa(prueba))

	})

	drawingarea.Connect("expose-event", func() {
		if pixmap != nil {
			drawingarea.GetWindow().GetDrawable().DrawDrawable(gc, pixmap.GetDrawable(), 0, 0, 0, 0, -1, -1)
			gc.SetRgbFgColor(gdk.Color("white"))
			pixmap.GetDrawable().DrawRectangle(gc, true, 0, 0, -1, -1)
			gc.SetRgbFgColor(gdk.Color("blue"))
			gc.SetRgbBgColor(gdk.Color("white"))
			pixmap.GetDrawable().DrawArc(gc, false, 100, 100, 200, 200, 0, 30000)
			pixmap.GetDrawable().DrawArc(gc, false, 150, 150, 100, 100, 0, 30000)

			pixmap.GetDrawable().DrawLine(gc, 200, 100, 200, 300)
			pixmap.GetDrawable().DrawLine(gc, 100, 200, 300, 200)

			pixmap.GetDrawable().DrawLine(gc, 130, 130, 165, 165)
			pixmap.GetDrawable().DrawLine(gc, 235, 235, 270, 270)

			pixmap.GetDrawable().DrawLine(gc, 271, 129, 235, 165)
			pixmap.GetDrawable().DrawLine(gc, 165, 235, 129, 271)

			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 210, 190, strconv.Itoa(r1[0]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 210, 140, strconv.Itoa(r2[0]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 260, 190, strconv.Itoa(r2[1]))

			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 210, 230, strconv.Itoa(r1[1]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 260, 230, strconv.Itoa(r2[2]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 210, 280, strconv.Itoa(r2[3]))

			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 170, 230, strconv.Itoa(r1[2]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 170, 280, strconv.Itoa(r2[4]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 120, 230, strconv.Itoa(r2[5]))

			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 170, 190, strconv.Itoa(r1[3]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 120, 190, strconv.Itoa(r2[6]))
			pixmap.GetDrawable().DrawString(gdk.FontsetLoad("-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"), gc, 170, 140, strconv.Itoa(r2[7]))

			drawingarea.GetWindow().Invalidate(nil, false)
		}
	})

	button.Clicked(func() {
		//prueba=prueba+1
		vdeep := entry.GetText()

		fo, err := os.Create("Pasos")
		if err != nil {
			panic(err)
		}
		defer fo.Close()

		Actual.tipoHeuristica = heuristica
		Actual.HeuristicaJuego()

		deep, err := strconv.Atoi(vdeep)
		if err == nil {
			fmt.Println("", deep)
			b, camino := AStar(Actual, deep)
			if b {

				for i := 0; i < len(camino); i++ {

					r1 = camino[i].fila1
					r2 = camino[i].fila2

					var Valores string
					Valores = "["

					for j := 0; j < len(r1); j++ {
						Valores = Valores + " " + strconv.Itoa(r1[j])
					}
					Valores = Valores + "]["

					for j := 0; j < len(r2); j++ {
						Valores = Valores + " " + strconv.Itoa(r2[j])
					}
					Valores = Valores + "] " + strconv.Itoa(camino[i].heuristica) + "\n"

					if _, err := fo.WriteString(Valores); err != nil {
						panic(err)
					}

				}

			} else {
				fmt.Println("No encontro la solución")
			}
		}
	})

	button2.Clicked(func() {

		Actual.Init()
		Actual.tipoHeuristica = heuristica
		Actual.HeuristicaJuego()

		r1 = Actual.fila1
		r2 = Actual.fila2

		//prueba=prueba+1
		//fmt.Println("->",prueba)
	})

	button3.Clicked(func() {

		Actual.fila1 = r1
		Actual.fila2 = r2

		Actual.Init2()
		Actual.tipoHeuristica = heuristica
		Actual.HeuristicaJuego()

		r1 = Actual.fila1
		r2 = Actual.fila2
	})

	drawingarea.SetEvents(int(gdk.GDK_POINTER_MOTION_MASK | gdk.GDK_POINTER_MOTION_HINT_MASK | gdk.GDK_BUTTON_PRESS_MASK))
	framebox1.Add(drawingarea)

	window.Add(vbox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}