Beispiel #1
0
func accountWindow() {
	// window settings
	window_account := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window_account.SetPosition(gtk.WIN_POS_CENTER)
	window_account.SetTitle("Add Account")

	// main container
	container_main := gtk.NewVBox(false, 10)
	container_user := gtk.NewHBox(false, 0)
	container_pass := gtk.NewHBox(false, 0)
	container_buttons := gtk.NewHBox(false, 5)
	container_main.SetBorderWidth(10)

	// username
	user_label := gtk.NewLabel("Username")
	user_entry := gtk.NewEntry()

	// password
	pass_label := gtk.NewLabel("Password")
	pass_entry := gtk.NewEntry()
	pass_entry.SetVisibility(false)

	// login and cancel buttons
	button_login := gtk.NewButtonWithLabel("Add")
	button_cancel := gtk.NewButtonWithLabel("Cancel")

	// login
	button_login.Clicked(func() {
		username := user_entry.GetText()
		password := pass_entry.GetText()
		profile, err := CreateProfile(username, password)
		if err == nil && profile != nil {
			println("[*] Login successful")
			window_account.Destroy()
		}
	})

	// cancel
	button_cancel.Clicked(func() {
		window_account.Destroy()
	})

	// add elements to containers
	container_buttons.Add(button_login)
	container_buttons.Add(button_cancel)
	container_user.PackStart(user_label, false, false, 20)
	container_user.PackEnd(user_entry, true, true, 1)
	container_pass.PackStart(pass_label, false, false, 20)
	container_pass.PackEnd(pass_entry, true, true, 1)
	container_main.PackStart(container_user, false, false, 1)
	container_main.PackStart(container_pass, false, false, 1)
	container_main.PackStart(container_buttons, false, false, 1)

	window_account.Add(container_main)
	window_account.SetSizeRequest(350, 150)
	window_account.SetResizable(false)
	window_account.ShowAll()
}
Beispiel #2
0
// Frame - Calculation
// This frame contains radix(16,10,8) and result labels
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
func (this *UI) init_Calc() {
	// In this function, the designated frame is Calc_Frame
	_Frame := this.Calc_Frame
	if _Frame == nil {
		panic("UI::init_Calc() : nil Frame received")
	}

	// (inner) Box of Calculation
	fm_calc_box := gtk.NewHBox(false, 1)
	if fm_calc_box == nil {
		panic("UI::init_Calc() : HBox allocation Failed")
	}

	_Frame.Add(fm_calc_box)

	// Box for Radix Buttons.
	box_rdx := gtk.NewVBox(false, 1)
	if box_rdx == nil {
		panic("UI::init_Calc() : VBox allocation Failed")
	}

	btn_hex := button("Hex") // [Hex] : Hexadecimal
	btn_dec := button("Dec") // [Dec] : Decimal
	btn_oct := button("Oct") // [Oct] : Octal
	box_rdx.Add(btn_hex)
	box_rdx.Add(btn_dec)
	box_rdx.Add(btn_oct)

	// Insert radix buttons into the map
	this.Btn_map["Hex"] = btn_hex
	this.Btn_map["Dec"] = btn_dec
	this.Btn_map["Oct"] = btn_oct

	// Box for Result Labels
	box_labels := gtk.NewVBox(false, 1)
	if box_labels == nil {
		panic("UI::init_Calc() : VBox allocation Failed")
	}

	// Place previous result
	box_labels.Add(this.Lbl_prev)

	// Place left and right operand
	box_LnR := gtk.NewHBox(false, 3)
	if box_LnR == nil {
		panic("UI::init_Calc() : HBox allocation Failed")
	}
	box_LnR.Add(this.Lbl_lhs)
	box_LnR.Add(this.Lbl_rhs)
	box_labels.Add(box_LnR)

	// Add both Boxes (Radix & Result) to frame box
	fm_calc_box.Add(box_rdx)
	fm_calc_box.Add(box_labels)

	fmt.Println("UI::init_Calc() done.")
}
Beispiel #3
0
func (g *GUI) mkSidebar() *gtk.ScrolledWindow {
	sbVBox := gtk.NewVBox(false, 0)

	sbVBox.PackStart(labelCustomFont("Tools", "Sans Bold 14"), false, false, 3)

	g.showbiomes = gtk.NewCheckButtonWithLabel("Show Biomes")
	g.showbiomes.SetActive(true)
	g.showbiomes.Connect("toggled", g.showbiomesToggled)
	sbVBox.PackStart(g.showbiomes, false, false, 3)

	g.fixSnowIce = gtk.NewCheckButtonWithLabel("Fix Snow/Ice")
	g.fixSnowIce.SetTooltipText("Add Snow/Ice for Taiga/Ice Plains. Remove Snow/Ice for other biomes.")
	g.fixSnowIce.Connect("toggled", g.fixSnowIceToggled)
	sbVBox.PackStart(g.fixSnowIce, false, false, 3)

	fill := gtk.NewRadioButtonWithLabel(nil, "Fill")
	fill.SetActive(true)
	fill.Connect("toggled", g.mkUpdateToolFx(fill, NewFillTool()))

	draw := gtk.NewRadioButtonWithLabel(fill.GetGroup(), "Draw")
	drawRadius := gtk.NewSpinButtonWithRange(1, 20, 1)
	drawHBox := gtk.NewHBox(false, 0)
	drawHBox.PackStart(draw, true, true, 0)
	drawHBox.PackStart(gtk.NewLabel("Radius:"), false, false, 3)
	drawHBox.PackEnd(drawRadius, false, false, 3)
	draw.Connect("toggled", g.mkUpdateToolFx(draw, NewDrawTool(func() int { return drawRadius.GetValueAsInt() })))

	sbVBox.PackStart(fill, false, false, 3)
	sbVBox.PackStart(drawHBox, false, false, 3)

	sbVBox.PackStart(gtk.NewHSeparator(), false, false, 3)
	bioHeaderHBox := gtk.NewHBox(false, 0)
	bioHeaderHBox.PackStart(labelCustomFont("Biomes", "Sans Bold 14"), true, false, 0)
	editBiomesBtn := gtk.NewButton()
	editBiomesBtn.Add(gtk.NewImageFromStock(gtk.STOCK_EDIT, gtk.ICON_SIZE_SMALL_TOOLBAR))
	editBiomesBtn.Connect("clicked", g.biomeEditor)
	editBiomesBtn.SetTooltipText("Configure Biomes")
	bioHeaderHBox.PackStart(editBiomesBtn, false, false, 0)
	sbVBox.PackStart(bioHeaderHBox, false, false, 3)

	g.bioVBoxWrap = gtk.NewVBox(false, 0)
	g.bioVBox = gtk.NewVBox(false, 0)
	g.bioVBoxWrap.PackStart(g.bioVBox, false, false, 0)
	sbVBox.PackStart(g.bioVBoxWrap, false, false, 3)
	g.updateBiomeInfo()

	scrolled := gtk.NewScrolledWindow(nil, nil)
	scrolled.SetPolicy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
	scrolled.AddWithViewPort(sbVBox)
	return scrolled
}
Beispiel #4
0
func main() {
	gtk.Init(&os.Args)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("GTK Notebook")
	window.Connect("destroy", gtk.MainQuit)

	notebook := gtk.NewNotebook()
	for n := 1; n <= 10; n++ {
		page := gtk.NewFrame("demo" + strconv.Itoa(n))
		notebook.AppendPage(page, gtk.NewLabel("demo"+strconv.Itoa(n)))

		vbox := gtk.NewHBox(false, 1)

		prev := gtk.NewButtonWithLabel("go prev")
		prev.Clicked(func() {
			notebook.PrevPage()
		})
		vbox.Add(prev)

		next := gtk.NewButtonWithLabel("go next")
		next.Clicked(func() {
			notebook.NextPage()
		})
		vbox.Add(next)

		page.Add(vbox)
	}

	window.Add(notebook)
	window.SetSizeRequest(400, 200)
	window.ShowAll()

	gtk.Main()
}
Beispiel #5
0
func (g *GUI) Init() {
	g.biomes = ReadDefaultBiomes()

	g.window = gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	g.window.SetTitle("biomed")

	g.accel = gtk.NewAccelGroup()
	g.window.AddAccelGroup(g.accel)

	menubar := g.mkMenuBar()
	vbox := gtk.NewVBox(false, 0)
	vbox.PackStart(menubar, false, false, 0)

	hbox := gtk.NewHBox(false, 0)

	g.mapw = NewMapWidget(GUICallbacks{g.reportError, g.updateInfo, g.setBusy}, MkBiomeLookup(g.biomes))
	hbox.PackStart(g.mapw.DArea(), true, true, 3)

	sidebar := g.mkSidebar()
	hbox.PackEnd(sidebar, false, false, 3)

	vbox.PackStart(hbox, true, true, 0)

	g.statusbar = gtk.NewStatusbar()
	g.statusContext = g.statusbar.GetContextId("mapinfo")
	vbox.PackEnd(g.statusbar, false, false, 0)

	g.window.Add(vbox)
	g.window.SetDefaultSize(800, 600)

	g.window.Connect("destroy", g.exitApp)

	g.setTool(NewFillTool())
}
Beispiel #6
0
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
}
Beispiel #7
0
func main() {
	gtk.Init(&os.Args)

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("Arrow Buttons")
	window.Connect("destroy", gtk.MainQuit)

	box := gtk.NewHBox(false, 0)
	box.Show()
	window.Add(box)

	up := createArrowButton(gtk.ARROW_UP, gtk.SHADOW_IN)
	down := createArrowButton(gtk.ARROW_DOWN, gtk.SHADOW_OUT)
	left := createArrowButton(gtk.ARROW_LEFT, gtk.SHADOW_ETCHED_IN)
	right := createArrowButton(gtk.ARROW_RIGHT, gtk.SHADOW_ETCHED_OUT)

	box.PackStart(up, false, false, 3)
	box.PackStart(down, false, false, 3)
	box.PackStart(left, false, false, 3)
	box.PackStart(right, false, false, 3)

	up.Clicked(func() { println("↑") })
	down.Clicked(func() { println("↓") })
	left.Clicked(func() { println("←") })
	right.Clicked(func() { println("→") })

	window.Show()
	gtk.Main()
}
Beispiel #8
0
func CreateActivatableDemo(vbox *gtk.VBox) {
	action_entry := gtk.NewAction("ActionEntry",
		"Button attached to Action", "", gtk.STOCK_INFO)
	action_entry.Connect("activate", func() {
		fmt.Println("Action clicked")
	})
	frame1 := gtk.NewFrame("GtkActivatable interface demonstration")
	frame1.SetBorderWidth(5)
	hbox2 := gtk.NewHBox(false, 5)
	hbox2.SetSizeRequest(400, 50)
	hbox2.SetBorderWidth(5)
	button1 := gtk.NewButton()
	button1.SetSizeRequest(250, 0)
	button1.SetRelatedAction(action_entry)
	hbox2.PackStart(button1, false, false, 0)
	hbox2.PackStart(gtk.NewVSeparator(), false, false, 0)
	button2 := gtk.NewButtonWithLabel("Hide Action")
	button2.SetSizeRequest(150, 0)
	button2.Connect("clicked", func() {
		action_entry.SetVisible(false)
		fmt.Println("Hide Action")
	})
	hbox2.PackStart(button2, false, false, 0)
	button3 := gtk.NewButtonWithLabel("Unhide Action")
	button3.SetSizeRequest(150, 0)
	button3.Connect("clicked", func() {
		action_entry.SetVisible(true)
		fmt.Println("Show Action")
	})
	hbox2.PackStart(button3, false, false, 0)
	frame1.Add(hbox2)
	vbox.PackStart(frame1, false, true, 0)
}
Beispiel #9
0
func newBiomeList() *biomeList {
	bl := &biomeList{
		HBox:     gtk.NewHBox(false, 0),
		treeview: gtk.NewTreeView(),
		lStore:   gtk.NewListStore(glib.G_TYPE_STRING, glib.G_TYPE_STRING, glib.G_TYPE_STRING, glib.G_TYPE_STRING),
		addBtn:   gtk.NewButton(),
		delBtn:   gtk.NewButton(),
		upBtn:    gtk.NewButton(),
		downBtn:  gtk.NewButton(),
	}

	scroll := gtk.NewScrolledWindow(nil, nil)
	scroll.SetPolicy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
	scroll.Add(bl.treeview)
	bl.PackStart(scroll, true, true, 3)

	bl.treeview.SetModel(bl.lStore)
	bl.treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("Color", gtk.NewCellRendererText(), "background", 0))
	bl.treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("ID", gtk.NewCellRendererText(), "text", 1))
	bl.treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("Snowline", gtk.NewCellRendererText(), "text", 2))
	bl.treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("Name", gtk.NewCellRendererText(), "text", 3))

	bl.treeview.GetSelection().SetMode(gtk.SELECTION_SINGLE)
	bl.treeview.Connect("cursor-changed", bl.onCursorChanged)

	vbox := gtk.NewVBox(false, 0)

	bl.addBtn.Add(gtk.NewImageFromStock(gtk.STOCK_ADD, gtk.ICON_SIZE_SMALL_TOOLBAR))
	bl.delBtn.Add(gtk.NewImageFromStock(gtk.STOCK_DELETE, gtk.ICON_SIZE_SMALL_TOOLBAR))
	bl.upBtn.Add(gtk.NewImageFromStock(gtk.STOCK_GO_UP, gtk.ICON_SIZE_SMALL_TOOLBAR))
	bl.downBtn.Add(gtk.NewImageFromStock(gtk.STOCK_GO_DOWN, gtk.ICON_SIZE_SMALL_TOOLBAR))

	bl.addBtn.Connect("clicked", bl.onAdd)
	bl.delBtn.Connect("clicked", bl.onDel)
	bl.upBtn.Connect("clicked", bl.onUp)
	bl.downBtn.Connect("clicked", bl.onDown)

	bl.delBtn.SetSensitive(false)
	bl.upBtn.SetSensitive(false)
	bl.downBtn.SetSensitive(false)

	vbox.PackStart(bl.addBtn, false, false, 3)
	vbox.PackStart(bl.delBtn, false, false, 3)
	vbox.PackStart(bl.upBtn, false, false, 3)
	vbox.PackStart(bl.downBtn, false, false, 3)

	bl.PackStart(vbox, false, false, 0)

	return bl
}
Beispiel #10
0
func (g *Gui) buildList(vbox *gtk.VBox) {
	frame := gtk.NewFrame("Device List")
	framebox := gtk.NewVBox(false, 1)
	frame.Add(framebox)
	vbox.Add(frame)
	g.Status = gtk.NewStatusbar()
	vbox.PackStart(g.Status, false, false, 0)
	g.Store = gtk.NewListStore(glib.G_TYPE_STRING, glib.G_TYPE_STRING)
	treeview := gtk.NewTreeView()
	framebox.Add(treeview)
	treeview.SetModel(g.Store)
	treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("Device", gtk.NewCellRendererText(), "text", 0))
	treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("Name", gtk.NewCellRendererText(), "text", 1))
	treeview.GetSelection().SetMode(gtk.SELECTION_SINGLE)
	controls := gtk.NewHBox(true, 0)
	g.Start = gtk.NewButtonWithLabel("Start Sync")
	g.Start.Clicked(func() {
		var iter gtk.TreeIter
		var device glib.GValue
		selection := treeview.GetSelection()
		if selection.CountSelectedRows() > 0 {
			selection.GetSelected(&iter)
			g.Store.GetValue(&iter, 0, &device)
			MainGui.notify("Start Writing On: " + device.GetString())
			doWrite(device.GetString())
		} else {
			MainGui.notify("No Active Selection")
		}
	})
	controls.Add(g.Start)
	g.Recheck = gtk.NewButtonWithLabel("Rescan")
	g.Recheck.Clicked(func() {
		devices := SearchValid()
		MainGui.Store.Clear()
		for _, x := range devices {
			MainGui.appendItem("/dev/hidraw"+strconv.FormatUint(x.SeqNum(), 10), x.SysAttrValue("product"))
		}
		MainGui.notify("Scanning Done")
	})
	controls.Add(g.Recheck)
	framebox.PackStart(controls, false, false, 0)
}
Beispiel #11
0
func newBiomeEditFrame() *biomeEditFrame {
	frm := &biomeEditFrame{
		Frame:         gtk.NewFrame("Edit Biome"),
		applyBtn:      gtk.NewButtonWithLabel("Apply"),
		idInput:       gtk.NewEntry(),
		snowLineInput: gtk.NewEntry(),
		nameInput:     gtk.NewEntry(),
		colorInput:    gtk.NewColorButton(),
	}

	frm.idInput.SetSizeRequest(40, -1)
	frm.snowLineInput.SetSizeRequest(40, -1)

	frm.idInput.Connect("changed", frm.unlockApply)
	frm.nameInput.Connect("changed", frm.unlockApply)
	frm.snowLineInput.Connect("changed", frm.unlockApply)
	frm.applyBtn.SetSensitive(false)

	vbox := gtk.NewVBox(false, 0)
	hbox := gtk.NewHBox(false, 0)

	frm.idInput.SetTooltipText("The data value of the Biome [0-255]")
	frm.snowLineInput.SetTooltipText(fmt.Sprintf("Height (Y coordinate) at which snowfall starts (-1 or %d for no snowfall, 0 for always snowy)", mcmap.ChunkSizeY))

	hbox.PackStart(gtk.NewLabel("Color:"), false, false, 0)
	hbox.PackStart(frm.colorInput, false, false, 3)
	hbox.PackStart(gtk.NewLabel("ID:"), false, false, 0)
	hbox.PackStart(frm.idInput, false, false, 3)
	hbox.PackStart(gtk.NewLabel("Snowline:"), false, false, 0)
	hbox.PackStart(frm.snowLineInput, false, false, 3)
	hbox.PackStart(gtk.NewLabel("Name:"), false, false, 0)
	hbox.PackStart(frm.nameInput, true, true, 3)

	vbox.PackStart(hbox, false, false, 0)
	vbox.PackStart(frm.applyBtn, false, false, 3)
	frm.Add(vbox)

	frm.applyBtn.Connect("clicked", frm.doApply)

	return frm
}
Beispiel #12
0
func (g *GUI) updateBiomeInfo() {
	vbox := gtk.NewVBox(false, 0)
	var grp *glib.SList

	for _, biome := range g.biomes {
		biohbox := gtk.NewHBox(false, 0)
		cbox := colorBox(gdk.NewColor(biome.Color))
		cbox.SetSizeRequest(20, 20)
		biohbox.PackStart(cbox, false, false, 3)
		rbutton := gtk.NewRadioButtonWithLabel(grp, biome.Name)
		grp = rbutton.GetGroup()
		rbutton.Connect("toggled", g.mkUpdateBiomeFx(rbutton, biome.ID))
		biohbox.PackEnd(rbutton, true, true, 3)
		vbox.PackStart(biohbox, false, false, 3)
	}

	g.bioVBoxWrap.Remove(g.bioVBox)
	g.bioVBoxWrap.PackStart(vbox, false, false, 3)
	vbox.ShowAll()
	g.bioVBox = vbox

	g.mapw.updateBioLookup(MkBiomeLookup(g.biomes))
}
Beispiel #13
0
func NewBiomeInfoEditor(biomes []BiomeInfo) *BiomeInfoEditor {
	ed := &BiomeInfoEditor{
		Dialog:  gtk.NewDialog(),
		biolist: newBiomeList(),
	}

	ed.SetModal(true)

	vbox := ed.GetVBox()

	btnHBox := gtk.NewHBox(true, 0)

	resetBtn := gtk.NewButtonWithLabel("Reset to defaults")
	resetBtn.Connect("clicked", ed.reset)
	loadBtn := gtk.NewButtonWithLabel("Load from file ...")
	loadBtn.Connect("clicked", ed.load)
	saveBtn := gtk.NewButtonWithLabel("Save to file ...")
	saveBtn.Connect("clicked", ed.save)

	btnHBox.PackStart(resetBtn, true, true, 3)
	btnHBox.PackStart(loadBtn, true, true, 3)
	btnHBox.PackStart(saveBtn, true, true, 3)
	vbox.PackStart(btnHBox, false, false, 3)

	ed.biolist.SetBiomes(biomes)
	vbox.PackStart(ed.biolist, true, true, 3)

	editFrame := newBiomeEditFrame()
	connectBiomeListEditFrame(ed.biolist, editFrame)
	vbox.PackStart(editFrame, false, false, 3)

	ed.AddButton("Cancel", gtk.RESPONSE_CANCEL)
	ed.AddButton("OK", gtk.RESPONSE_OK)
	ed.ShowAll()
	return ed
}
Beispiel #14
0
func main() {
	runtime.LockOSThread()
	gtk.Init(&os.Args)
	gdk.ThreadsInit()

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("DMS GUI")
	window.Connect("destroy", gtk.MainQuit)

	vbox := gtk.NewVBox(false, 0)
	window.Add(vbox)

	hbox := gtk.NewHBox(false, 0)
	vbox.PackStart(hbox, false, true, 0)

	hbox.PackStart(gtk.NewLabel("Shared directory: "), false, true, 0)

	dialog := gtk.NewFileChooserDialog(
		"Select directory to share", window, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
		gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
		gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)

	button := gtk.NewFileChooserButtonWithDialog(dialog)
	hbox.Add(button)

	logView := gtk.NewTextView()
	logView.SetEditable(false)
	logView.ModifyFontEasy("monospace")
	logView.SetWrapMode(gtk.WRAP_WORD_CHAR)
	logViewScroller := gtk.NewScrolledWindow(nil, nil)
	logViewScroller.Add(logView)
	logViewScroller.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
	vbox.PackEnd(logViewScroller, true, true, 0)

	getPath := func() string {
		return button.GetFilename()
	}

	window.ShowAll()
	if dialog.Run() != gtk.RESPONSE_ACCEPT {
		return
	}
	go func() {
		dmsServer := dms.Server{
			RootObjectPath: getPath(),
		}
		if err := dmsServer.Serve(); err != nil {
			log.Fatalln(err)
		}
		defer dmsServer.Close()
		runtime.LockOSThread()
		gdk.ThreadsEnter()
		button.Connect("selection-changed", func() {
			dmsServer.RootObjectPath = getPath()
		})
		gdk.ThreadsLeave()
		runtime.UnlockOSThread()
		dmsServer.Serve()
	}()
	gtk.Main()
	runtime.UnlockOSThread()
}
Beispiel #15
0
func win_start() {
	defer catch() // Panic Handler
	// Initiate GTK
	gtk.Init(&os.Args)

	// Window Setup
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

	// Create the Main Window
	// Set title & size
	win := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	win.SetTitle("0x_Calc")

	// on Exit -> Quit the program
	win.Connect("destroy", gtk.MainQuit)

	box_win := gtk.NewVBox(Homogeneous, Default_Spacing)

	// Menu Bar
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

	/*
			// Vertical Box for menu
			box_menu := gtk.NewVBox(false, 1)
			// MenuBar - menu
			mb_menu := gtk.NewMenuBar()
			box_menu.PackStart(mb_menu, false, false, 0)

			// Menu Items

			// [File]
			mi_file := gtk.NewMenuItemWithMnemonic("_File2")
			mb_menu.Append(mi_file)
			// Submenu for [File]
			subm_file := gtk.NewMenu()
			mi_file.SetSubmenu(subm_file)

			mi_exit := gtk.NewMenuItemWithMnemonic("_Exit2")
			mb_menu.Append(mi_exit)

			mi_exit.Connect("activate", func() {
				gtk.MainQuit()
			})

		// Add the menubox
		win.Add(box_menu)
	*/

	// Frame - Calculation
	// This frame contains radix(16,10,8) and result labels
	// ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ====
	fm_calc := gtk.NewFrame("Calculation")
	// (inner) Box of Calculation
	fm_calc_box := gtk.NewHBox(false, 1)
	fm_calc.Add(fm_calc_box)

	// Box for Radix Buttons.
	box_rdx := gtk.NewVBox(false, 1)
	btn_hex := button("Hex")                 // [Hex] : Hexadecimal
	btn_dec := gtk.NewButtonWithLabel("Dec") // [Dec] : Decimal
	btn_oct := gtk.NewButtonWithLabel("Oct") // [Oct] : Octal
	box_rdx.Add(btn_hex)
	box_rdx.Add(btn_dec)
	box_rdx.Add(btn_oct)

	// Box for Result Labels
	box_labels := gtk.NewVBox(false, 1)
	lbl_prev := gtk.NewLabel("Previous Result") // Previous Calculation
	lbl_late := gtk.NewLabel("Current Result")  // Latest Calculaltion
	box_labels.Add(lbl_prev)
	box_labels.Add(lbl_late)

	// Add both Boxes (Radix & Result) to frame box
	fm_calc_box.Add(box_rdx)
	fm_calc_box.Add(box_labels)

	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

	// Frame - Numbers
	// This frame contains number buttons for calculation
	//  	Hexadecimal	: 0 ~ 9, A ~ F
	//  	Decimal   	: 0 ~ 9
	//  	Octal     	: 0 ~ 7
	// ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ====
	fm_nums := gtk.NewFrame("Numbers")
	// (inner) Box of Numbers
	fm_nums_box := gtk.NewVBox(false, 1)
	fm_nums.Add(fm_nums_box)

	// Table Initialization
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
	tbl_nums := gtk.NewTable(5, 4, false)

	// Jagged slice of buttons
	// nums := [][]*gtk.Button{}

	// Button for Number
	num := [17]*gtk.Button{
		// 0~7 : Oct
		button("0"), button("1"), button("2"), button("3"),
		button("4"), button("5"), button("6"), button("7"),
		// 0~9 : Dec
		button("8"), button("9"),
		// 0~F : Hex
		button("A"), button("B"), button("C"),
		button("D"), button("E"), button("F"),
	}

	// Place buttons into the table
	tbl_nums.Attach(num[0], 0, 1, 3, 4, gtk.FILL, gtk.FILL, 1, 1) // 0
	tbl_nums.Attach(num[1], 0, 1, 2, 3, gtk.FILL, gtk.FILL, 1, 1) // 1
	tbl_nums.Attach(num[2], 1, 2, 2, 3, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[3], 2, 3, 2, 3, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[4], 0, 1, 1, 2, gtk.FILL, gtk.FILL, 1, 1) // 4
	tbl_nums.Attach(num[5], 1, 2, 1, 2, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[6], 2, 3, 1, 2, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[7], 0, 1, 0, 1, gtk.FILL, gtk.FILL, 1, 1) // 7
	tbl_nums.Attach(num[8], 1, 2, 0, 1, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[9], 2, 3, 0, 1, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[10], 3, 4, 2, 3, gtk.FILL, gtk.FILL, 1, 1) // A
	tbl_nums.Attach(num[11], 4, 5, 2, 3, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[12], 3, 4, 1, 2, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[13], 4, 5, 1, 2, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[14], 3, 4, 0, 1, gtk.FILL, gtk.FILL, 1, 1)
	tbl_nums.Attach(num[15], 4, 5, 0, 1, gtk.FILL, gtk.FILL, 1, 1) // F

	// Add the table to box
	fm_nums_box.Add(tbl_nums)
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

	// Frame - Operations
	// This frame contains operations.
	//  	ADD, SUB, MUL, DIV, MOD
	//  	AND, OR, XOR, NOT
	//  	LSHFT, RSHFT
	// ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ====
	fm_oper := gtk.NewFrame("Operations")
	// (inner) Box of Operations
	fm_oper_box := gtk.NewVBox(false, 1)
	fm_oper.Add(fm_oper_box)

	tbl_opers := gtk.NewTable(5, 3, false)

	// Operation Buttons
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
	// Button for Number
	// 'oper' is Jagged slice of buttons
	oper := [][]*gtk.Button{}
	// slice of Arithmetic
	oper_arit := []*gtk.Button{
		button("ADD"), button("SUB"), button("MUL"), button("DIV"),
		button("MOD")}
	// slice of Bitwise
	oper_bit := []*gtk.Button{
		button("AND"), button("OR"), button("XOR"), button("NOT")}
	// slice of Bit Shift
	oper_shft := []*gtk.Button{
		button("LSHIFT"), button("RSHIFT")}

	// Compose the jagged slice
	oper = append(oper, oper_arit)
	oper = append(oper, oper_bit)
	oper = append(oper, oper_shft)

	// Iterate jagged slice and place them into the table
	for r, btn_slice := range oper {
		// r : row
		// btn_slice : slice of buttons
		for c, btn := range btn_slice {
			// c : column
			// btn == btn_slice[c] == oper[row][col]
			// Place the button to table
			tbl_opers.Attach(btn, uint(c), uint(c)+1, uint(r), uint(r)+1,
				gtk.FILL, gtk.FILL, 1, 1)
		}
	}

	fm_oper_box.Add(tbl_opers)

	// Place buttons into the table
	// tbl_opers.Attach(oper[0], 0, 1, 3, 4, gtk.FILL, gtk.FILL, 5, 1) // 0

	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

	// Frame Positionings
	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
	vpan1 := gtk.NewVPaned()
	vpan1.Pack1(fm_calc, No_Resize, No_Shrink)

	hpan1 := gtk.NewHPaned()
	hpan1.Pack1(fm_nums, No_Resize, No_Shrink)
	hpan1.Pack2(fm_oper, No_Resize, No_Shrink)

	vpan1.Pack2(hpan1, No_Resize, No_Shrink)

	box_win.Add(vpan1)

	// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
	fmt.Println("UI Over?")
	win.Add(box_win)
	win.SetSizeRequest(UI_Width, UI_Height)
	win.ShowAll()

	// Start the UI
	gtk.Main()
}
Beispiel #16
0
func main() {
	gtk.Init(nil)

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("GoMADScan")
	window.SetIconName("GoMADScan-info")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		// fmt.Println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "")

	//--------------------------------------------------------
	// 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("")
	framebox1 := gtk.NewVBox(false, 1)
	frame1.Add(framebox1)

	frame2 := gtk.NewFrame("Column index for search (0: all columns)")
	framebox2 := gtk.NewVBox(false, 1)
	frame2.Add(framebox2)

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

	//--------------------------------------------------------
	// GtkImage
	//--------------------------------------------------------
	dir := os.Getenv("GOPATH")
	if dir == "" {
		dir = filepath.Join(os.Getenv("HOME"), "/go")
	}
	imagefile := filepath.Join(dir, "/src/github.com/carushi/GoMADScan/image/logo.png")
	label := gtk.NewLabel("Go-based Modification associated database scanner")
	label.ModifyFontEasy("DejaVu Serif 15")
	framebox1.PackStart(label, false, true, 0)
	image := gtk.NewImageFromFile(imagefile)
	framebox1.Add(image)

	//--------------------------------------------------------
	// Data input and output filename
	//--------------------------------------------------------
	arg := arguments{
		0,
		filepath.Join(dir, "/src/github.com/carushi/GoMADScan/data/Sample_modification_site"),
		filepath.Join(dir, "/src/github.com/carushi/GoMADScan/data/Ras_gene_synonym.txt"),
		filepath.Join(dir, "/src/github.com/carushi/GoMADScan/data/output.txt"),
		false,
		true,
		"\t"}

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

	//--------------------------------------------------------
	// InputArea
	//--------------------------------------------------------
	ientry := gtk.NewEntry()
	ientry.SetText(arg.inputPath)
	inputs := gtk.NewHBox(false, 1)
	button := gtk.NewButtonWithLabel("Choose input file")
	button.Clicked(func() {
		//--------------------------------------------------------
		// GtkFileChooserDialog
		//--------------------------------------------------------
		filechooserdialog := gtk.NewFileChooserDialog(
			"Choose File...",
			button.GetTopLevelAsWindow(),
			gtk.FILE_CHOOSER_ACTION_OPEN,
			gtk.STOCK_OK,
			gtk.RESPONSE_ACCEPT)
		filter := gtk.NewFileFilter()
		filter.AddPattern("*")
		filechooserdialog.AddFilter(filter)
		filechooserdialog.Response(func() {
			arg.inputPath = filechooserdialog.GetFilename()
			ientry.SetText(arg.inputPath)
			filechooserdialog.Destroy()
		})
		filechooserdialog.Run()
	})
	inputs.Add(button)
	inputs.Add(ientry)
	framebox2.PackStart(inputs, false, false, 0)

	fentry := gtk.NewEntry()
	fentry.SetText(arg.filterPath)
	inputs = gtk.NewHBox(false, 1)
	button = gtk.NewButtonWithLabel("Choose keyword file")
	button.Clicked(func() {
		//--------------------------------------------------------
		// GtkFileChooserDialog
		//--------------------------------------------------------
		filechooserdialog := gtk.NewFileChooserDialog(
			"Choose File...",
			button.GetTopLevelAsWindow(),
			gtk.FILE_CHOOSER_ACTION_OPEN,
			gtk.STOCK_OK,
			gtk.RESPONSE_ACCEPT)
		filter := gtk.NewFileFilter()
		filter.AddPattern("*")
		filechooserdialog.AddFilter(filter)
		filechooserdialog.Response(func() {
			arg.filterPath = filechooserdialog.GetFilename()
			fentry.SetText(arg.filterPath)
			filechooserdialog.Destroy()
		})
		filechooserdialog.Run()
	})
	inputs.Add(button)
	inputs.Add(fentry)
	framebox2.PackStart(inputs, false, false, 0)

	oentry := gtk.NewEntry()
	oentry.SetText(arg.outputPath)
	inputs = gtk.NewHBox(false, 1)
	button = gtk.NewButtonWithLabel("Choose output file")
	button.Clicked(func() {
		//--------------------------------------------------------
		// GtkFileChooserDialog
		//--------------------------------------------------------
		filechooserdialog := gtk.NewFileChooserDialog(
			"Choose File...",
			button.GetTopLevelAsWindow(),
			gtk.FILE_CHOOSER_ACTION_OPEN,
			gtk.STOCK_OK,
			gtk.RESPONSE_ACCEPT)
		filter := gtk.NewFileFilter()
		filter.AddPattern("*")
		filechooserdialog.AddFilter(filter)
		filechooserdialog.Response(func() {
			arg.outputPath = filechooserdialog.GetFilename()
			oentry.SetText(arg.outputPath)
			filechooserdialog.Destroy()
		})
		filechooserdialog.Run()
	})
	inputs.Add(button)
	inputs.Add(oentry)
	framebox2.PackStart(inputs, false, false, 0)

	buttons := gtk.NewHBox(false, 1)

	//--------------------------------------------------------
	// GtkCheckButton
	//--------------------------------------------------------
	checkbutton := gtk.NewCheckButtonWithLabel("Case-insensitive (lower/upper)")
	checkbutton.Connect("toggled", func() {
		if checkbutton.GetActive() {
			arg.ignoreCase = true
		} else {
			arg.ignoreCase = false
		}
	})
	buttons.Add(checkbutton)

	checkMatchButton := gtk.NewCheckButtonWithLabel("Partial matching / Perfect matching")
	checkMatchButton.Connect("toggled", func() {
		if checkMatchButton.GetActive() {
			arg.perfectMatch = false
		} else {
			arg.perfectMatch = true
		}
	})
	buttons.Add(checkMatchButton)

	combobox := gtk.NewComboBoxText()
	for _, delim := range delimName {
		combobox.AppendText(delim)
	}
	combobox.SetActive(0)
	combobox.Connect("changed", func() {
		fmt.Println("value:", combobox.GetActiveText())
		arg.delim = combobox.GetActiveText()
	})
	buttons.Add(combobox)

	//--------------------------------------------------------
	// 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
	var end gtk.TextIter
	buffer := textview.GetBuffer()
	swin.Add(textview)

	//--------------------------------------------------------
	// Run button
	//--------------------------------------------------------
	runbutton := gtk.NewButtonWithLabel("Run")
	runbutton.Clicked(func() {
		arg.inputPath = ientry.GetText()
		arg.filterPath = fentry.GetText()
		arg.outputPath = oentry.GetText()
		num, err := getKeysearchWords(arg)
		buffer.GetStartIter(&end)
		if err != nil {
			log.Println(err)
			buffer.Insert(&end, err.Error()+"\n")
		} else {
			buffer.Insert(&end, "GoMADScan found "+strconv.Itoa(num)+
				" modification sites.\nThe result is written into "+arg.outputPath+".\n")
		}
	})
	buttons.Add(runbutton)
	framebox2.PackStart(buttons, false, false, 0)

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

	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	framebox2.Add(swin)

	// buffer.Connect("changed", func() {
	//  // fmt.Println("changed")
	// })

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

	var menuitem *gtk.MenuItem
	menuitem = gtk.NewMenuItemWithMnemonic("_Exit")
	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)

	menuitem = gtk.NewMenuItemWithMnemonic("_About")
	menuitem.Connect("activate", func() {
		dialog := gtk.NewAboutDialog()
		dialog.SetName("GoMADScan")
		dialog.SetProgramName("GoMADScan")
		dialog.SetAuthors(authors())
		dialog.SetLicense("LGPL v3")
		dialog.SetWrapLicense(true)
		dialog.Run()
		dialog.Destroy()
	})
	submenu.Append(menuitem)

	//--------------------------------------------------------
	// GtkStatusbar
	//--------------------------------------------------------
	statusbar := gtk.NewStatusbar()
	context_id := statusbar.GetContextId("GoMADScan v0")
	statusbar.Push(context_id, "Simple search GUI")

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

	//--------------------------------------------------------
	// Event
	//--------------------------------------------------------
	window.Add(vbox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}
Beispiel #17
0
func main() {
	var autoupdating bool = false
	var autoticker *time.Ticker
	var entries [][]*gtk.Entry = make([][]*gtk.Entry, entitylimit)
	for i := 0; i < entitylimit; i++ {
		entries[i] = make([]*gtk.Entry, entityfields)
	}
	var entities []*physics.Entity = initentities(entries)

	// Initialize gtk
	gtk.Init(nil)

	// WINDOW
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("Gravity Visualization")

	// Connect top window closing to gtk main loop closing
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		gtk.MainQuit()
	})

	// TOP VERTICAL BOX
	topvbox := gtk.NewVBox(false, 1)

	// NOTEBOOK FOR TABS
	notebook := gtk.NewNotebook()

	// DRAWING AREA VERTICAL BOX
	davbox := gtk.NewVBox(false, 1)

	// DRAWING AREA
	drawingarea = gtk.NewDrawingArea()
	drawingarea.SetSizeRequest(width, height)
	drawingarea.ModifyBG(gtk.STATE_NORMAL, gdk.NewColor("white"))
	drawingarea.Connect("expose_event", func() {
		drawentities(entities)
	})
	davbox.PackStart(drawingarea, true, true, 0)

	// TICK SPEED SLIDER
	ticksliderhbox := gtk.NewHBox(false, 1)

	ticksliderlabel := gtk.NewLabel("Time between ticks (ms)")
	ticksliderhbox.Add(ticksliderlabel)

	tickslider := gtk.NewHScaleWithRange(1, 1000, 100)
	// Default value of 10 ms
	tickslider.SetValue(10)
	ticksliderhbox.Add(tickslider)
	davbox.Add(ticksliderhbox)

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

	// RESET MENU ITEM
	resetbutton := gtk.NewButtonWithLabel("Reset")
	resetbutton.Clicked(func() {
		entities = initentities(entries)
		drawingarea.QueueDraw()
	})
	buttons.Add(resetbutton)

	// TICK MENU ITEM
	tickbutton := gtk.NewButtonWithLabel("Tick")
	tickbutton.Clicked(func() {
		updateentities(entities)
	})
	buttons.Add(tickbutton)

	// AUTOUPDATE MENU ITEM
	autotickbutton := gtk.NewToggleButtonWithLabel("AutoUpdate")
	autotickbutton.Clicked(func() {
		// Stop the previous ticker if it exists
		if autoticker != nil {
			autoticker.Stop()
		}

		if autoupdating {
			// Toggle autoupdating state
			autoupdating = false
		} else {
			// Start the ticker
			autoticker = time.NewTicker(time.Duration(tickslider.GetValue()) * time.Millisecond)

			// Spawn a goroutine that will run update entities every tick
			go func() {
				for _ = range autoticker.C {
					updateentities(entities)
				}
			}()

			// Toggle autoupdating state
			autoupdating = true
		}
	})
	buttons.Add(autotickbutton)
	davbox.Add(buttons)

	notebook.AppendPage(davbox, gtk.NewLabel("Simulation"))

	// INITIALIZE PANEL
	entitiesvbox := gtk.NewVBox(false, 1)

	// INITIALIZE LABELS FOR TABLE
	titles := gtk.NewHBox(false, 1)
	titles.Add(gtk.NewLabel("Mass"))
	titles.Add(gtk.NewLabel("X-Pos"))
	titles.Add(gtk.NewLabel("Y-Pos"))
	titles.Add(gtk.NewLabel("X-Vel"))
	titles.Add(gtk.NewLabel("Y-Vel"))
	titles.Add(gtk.NewLabel("X-Acc"))
	titles.Add(gtk.NewLabel("Y-Acc"))
	entitiesvbox.Add(titles)

	// INITIALIZE ENTRIES IN ROWS FOR TABLE
	for row := 0; row < entitylimit; row++ {
		rowbox := gtk.NewHBox(false, 1)
		for col := 0; col < entityfields; col++ {
			textfield := gtk.NewEntry()
			// Hold reference to text field in entries 2d array
			entries[row][col] = textfield
			rowbox.Add(textfield)
		}
		entitiesvbox.Add(rowbox)
	}

	// CLEAR ENTITIES BUTTON
	clearentitiesbutton := gtk.NewButtonWithLabel("Clear Entries")
	clearentitiesbutton.Clicked(func() {
		for row := 0; row < entitylimit; row++ {
			for col := 0; col < entityfields; col++ {
				entries[row][col].SetText("")
			}
		}
	})
	entitiesvbox.Add(clearentitiesbutton)

	// Limit the size of the entitiesvbox and add to notebook
	entitiesvbox.SetSizeRequest(width, height)
	notebook.AppendPage(entitiesvbox, gtk.NewLabel("Entities"))

	// FINISH PACKING COMPONENTS
	topvbox.PackStart(notebook, false, false, 0)

	// FINISH PACKING WINDOW
	window.Add(topvbox)

	// Show the GUI
	window.ShowAll()

	// Grab the drawable and initialize graphics context now that they are initialized
	drawable = drawingarea.GetWindow().GetDrawable()
	blackgc = gdk.NewGC(drawable)
	redgc = gdk.NewGC(drawable)
	redgc.SetRgbFgColor(gdk.NewColorRGB(255, 0, 0))
	bluegc = gdk.NewGC(drawable)
	bluegc.SetRgbFgColor(gdk.NewColorRGB(0, 0, 255))

	gtk.Main()
}
Beispiel #18
0
func main() {
	gtk.Init(&os.Args)
	display = gtk.NewEntry()
	display.SetAlignment(1.0)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("Simple Go Calculator")
	window.Connect("destroy", Quit)

	// Vertical box containing all components
	vbox := gtk.NewVBox(false, 1)

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

	// Add calculator display to vertical box
	display.SetCanFocus(false) // disable focus on calcuator display
	vbox.Add(display)

	// Menu items
	filemenu := gtk.NewMenuItemWithMnemonic("_File")
	menubar.Append(filemenu)
	filesubmenu := gtk.NewMenu()
	filemenu.SetSubmenu(filesubmenu)

	aboutmenuitem := gtk.NewMenuItemWithMnemonic("_About")
	aboutmenuitem.Connect("activate", func() {
		messagedialog := gtk.NewMessageDialog(
			window.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			"Simple Go Calculator")
		messagedialog.Response(func() {})
		messagedialog.Run()
		messagedialog.Destroy()
	},
		nil)
	filesubmenu.Append(aboutmenuitem)

	resetmenuitem := gtk.NewMenuItemWithMnemonic("_Reset")
	resetmenuitem.Connect("activate", func() { Reset(); display.SetText("0") })
	filesubmenu.Append(resetmenuitem)

	exitmenuitem := gtk.NewMenuItemWithMnemonic("E_xit")
	exitmenuitem.Connect("activate", Quit)
	filesubmenu.Append(exitmenuitem)

	// Vertical box containing all buttons
	buttons := gtk.NewVBox(false, 5)

	bmap := map[string]*gtk.Button{}

	for i := 0; i < 4; i++ {
		hbox := gtk.NewHBox(false, 5) // a horizontal box for each 4 buttons
		for j := 0; j < 4; j++ {
			b := gtk.NewButtonWithLabel(string(nums[i*4+j]))
			b.Clicked(Input(b)) //add click event
			hbox.Add(b)
			bmap[string(nums[i*4+j])] = b
		}
		buttons.Add(hbox) // add horizonatal box to vertical buttons' box
	}

	vbox.Add(buttons)

	window.Connect("key-press-event", func(ctx *glib.CallbackContext) bool {
		arg := ctx.Args(0)
		kev := *(**gdk.EventKey)(unsafe.Pointer(&arg))
		c := (string(uint8(kev.Keyval % 0xff)))
		if kev.Keyval == gdk.KEY_Return {
			c = "="
			return true
		}
		if b, ok := bmap[c]; ok {
			Input(b)()
			b.GrabFocus()
		} else if kev.Keyval == gdk.KEY_Delete {
			Reset()
			display.SetText("0")
			return true
		}
		return false
	})

	window.Add(vbox)
	window.SetSizeRequest(250, 250)
	window.ShowAll()
	gtk.Main()
}
Beispiel #19
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) {
		gtk.MainQuit()
	}, "")

	vbox := gtk.NewVBox(false, 0)

	toolbar := gtk.NewToolbar()
	toolbar.SetStyle(gtk.TOOLBAR_ICONS)
	vbox.PackStart(toolbar, false, false, 5)

	btnnew := gtk.NewToolButtonFromStock(gtk.STOCK_NEW)
	btnclose := gtk.NewToolButtonFromStock(gtk.STOCK_CLOSE)
	separator := gtk.NewSeparatorToolItem()
	btncustom := gtk.NewToolButton(nil, "Custom")
	btnmenu := gtk.NewMenuToolButtonFromStock("gtk.STOCK_CLOSE")
	btnmenu.SetArrowTooltipText("This is a tool tip")

	btnnew.OnClicked(onToolButtonClicked)
	btnclose.OnClicked(onToolButtonClicked)
	btncustom.OnClicked(onToolButtonClicked)

	toolmenu := gtk.NewMenu()
	menuitem := gtk.NewMenuItemWithMnemonic("8")
	menuitem.Show()
	toolmenu.Append(menuitem)
	menuitem = gtk.NewMenuItemWithMnemonic("16")
	menuitem.Show()
	toolmenu.Append(menuitem)
	menuitem = gtk.NewMenuItemWithMnemonic("32")
	menuitem.Show()
	toolmenu.Append(menuitem)
	btnmenu.SetMenu(toolmenu)

	toolbar.Insert(btnnew, -1)
	toolbar.Insert(btnclose, -1)
	toolbar.Insert(separator, -1)
	toolbar.Insert(btncustom, -1)
	toolbar.Insert(btnmenu, -1)

	hbox := gtk.NewHBox(false, 0)
	vbox.PackStart(hbox, true, true, 0)

	toolbar2 := gtk.NewToolbar()
	toolbar2.SetOrientation(gtk.ORIENTATION_VERTICAL)
	hbox.PackStart(toolbar2, false, false, 5)
	btnhelp := gtk.NewToolButtonFromStock(gtk.STOCK_HELP)
	btnhelp.OnClicked(onToolButtonClicked)
	toolbar2.Insert(btnhelp, -1)

	btntoggle := gtk.NewToggleToolButton()
	btntoggle2 := gtk.NewToggleToolButtonFromStock(gtk.STOCK_ITALIC)
	toolbar2.Insert(btntoggle, -1)
	toolbar2.Insert(btntoggle2, -1)

	for i := 0; i < toolbar.GetNItems(); i++ {
		gti := toolbar.GetNthItem(i)
		switch gti.(type) {
		case *gtk.ToolButton:
			fmt.Printf("toolbar[%d] is a *gtk.ToolButton\n", i)
			w := gti.(*gtk.ToolButton).GetIconWidget()
			gti.(*gtk.ToolButton).SetIconWidget(w)
		case *gtk.ToggleToolButton:
			fmt.Printf("toolbar[%d] is a *gtk.ToggleToolButton\n", i)
			gti.(*gtk.ToggleToolButton).SetActive(true)
		case *gtk.SeparatorToolItem:
			fmt.Printf("toolbar[%d] is a *gtk.SeparatorToolItem\n", i)
		default:
			fmt.Printf("toolbar: Item is of unknown type\n")
		}
	}

	for i := 0; i < toolbar2.GetNItems(); i++ {
		gti := toolbar2.GetNthItem(i)
		switch gti.(type) {
		case *gtk.ToolButton:
			fmt.Printf("toolbar2[%d] is a *gtk.ToolButton\n", i)
		case *gtk.ToggleToolButton:
			fmt.Printf("toolbar2[%d] is a *gtk.ToggleToolButton\n", i)
			gti.(*gtk.ToggleToolButton).SetActive(true)
		case *gtk.SeparatorToolItem:
			fmt.Printf("toolbar2[%d] is a *gtk.SeparatorToolItem\n", i)
		default:
			fmt.Printf("toolbar2: Item is of unknown type\n")
		}
	}

	window.Add(vbox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}
Beispiel #20
0
func main() {
	gtk.Init(&os.Args)

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("GoTalk")
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})
	vbox := gtk.NewVBox(false, 1)
	scrolledwin := gtk.NewScrolledWindow(nil, nil)
	textview := gtk.NewTextView()
	textview.SetEditable(false)
	textview.SetCursorVisible(false)
	scrolledwin.Add(textview)
	vbox.Add(scrolledwin)

	buffer := textview.GetBuffer()

	entry := gtk.NewEntry()
	vbox.PackEnd(entry, false, false, 0)

	window.Add(vbox)
	window.SetSizeRequest(300, 400)
	window.ShowAll()

	dialog := gtk.NewDialog()
	dialog.SetTitle(window.GetTitle())
	sgroup := gtk.NewSizeGroup(gtk.SIZE_GROUP_HORIZONTAL)

	hbox := gtk.NewHBox(false, 1)
	dialog.GetVBox().Add(hbox)
	label := gtk.NewLabel("username:"******"password:"******"talk.google.com:443", username_, password_)
	if err != nil {
		log.Fatal(err)
	}

	entry.Connect("activate", func() {
		text := entry.GetText()
		tokens := strings.SplitN(text, " ", 2)
		if len(tokens) == 2 {
			func() {
				defer recover()
				talk.Send(xmpp.Chat{Remote: tokens[0], Type: "chat", Text: tokens[1]})
				entry.SetText("")
			}()
		}
	})

	go func() {
		for {
			func() {
				defer recover()
				chat, err := talk.Recv()
				if err != nil {
					log.Fatal(err)
				}

				var iter gtk.TextIter
				buffer.GetStartIter(&iter)
				if msg, ok := chat.(xmpp.Chat); ok {
					buffer.Insert(&iter, msg.Remote+": "+msg.Text+"\n")
				}
			}()
		}
	}()

	gtk.Main()
}
Beispiel #21
0
func main() {
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("Lab 1")
	window.Connect("destroy",
		func(ctx *glib.CallbackContext) {
			gtk.MainQuit()
		},
		"Window destroyed")

	all_boxes := gtk.NewVBox(false, 0)
	base_conversion_box := gtk.NewHBox(false, 0)

	left_label_vbox := gtk.NewVBox(false, 5)
	number_entry_label := gtk.NewLabel("Input:")
	output_number_label := gtk.NewLabel("Output:")
	left_label_vbox.PackStart(number_entry_label, true, true, 0)
	left_label_vbox.PackStart(output_number_label, true, true, 0)

	left_input_vbox := gtk.NewVBox(false, 5)
	number_entry := gtk.NewEntry()
	output_number := gtk.NewEntry()
	left_input_vbox.PackStart(number_entry, true, true, 0)
	left_input_vbox.PackStart(output_number, true, true, 0)

	middle_label_vbox := gtk.NewVBox(false, 5)
	base_entry_label := gtk.NewLabel("Input base:")
	output_number_base10_label := gtk.NewLabel("Output (base 10):")
	middle_label_vbox.PackStart(base_entry_label, true, true, 0)
	middle_label_vbox.PackStart(output_number_base10_label, true, true, 0)

	middle_input_vbox := gtk.NewVBox(false, 5)
	base_entry := gtk.NewEntry()
	output_number_base10 := gtk.NewEntry()
	middle_input_vbox.PackStart(base_entry, true, true, 0)
	middle_input_vbox.PackStart(output_number_base10, true, true, 0)

	right_box := gtk.NewVBox(false, 5)
	output_base_box := gtk.NewHBox(false, 5)
	base_output_entry_label := gtk.NewLabel("Output base:")
	base_output_entry := gtk.NewEntry()
	base_output_entry.SetWidthChars(4)
	output_base_box.PackStart(base_output_entry_label, true, true, 0)
	output_base_box.PackStart(base_output_entry, true, true, 0)
	calculate_button := gtk.NewButtonWithLabel("Calculate")
	right_box.PackStart(output_base_box, true, true, 0)
	right_box.PackStart(calculate_button, true, true, 0)

	base_conversion_box.PackStart(left_label_vbox, true, true, 5)
	base_conversion_box.PackStart(left_input_vbox, true, true, 5)
	base_conversion_box.PackStart(middle_label_vbox, true, true, 5)
	base_conversion_box.PackStart(middle_input_vbox, true, true, 5)
	base_conversion_box.PackStart(right_box, true, true, 5)

	calculate_button.Clicked(func() {
		starting_number := number_entry.GetText()
		starting_base := base_entry.GetText()
		integer := string_to_int(starting_number, starting_base)
		output_number_base10.SetText(strconv.Itoa(integer))
		converted_number := int_to_string(integer, char_to_int(base_output_entry.GetText()))
		output_number.SetText(converted_number)
	})

	string_conversion_box := gtk.NewHBox(false, 5)
	input_label := gtk.NewLabel("Input string:")
	input_string := gtk.NewEntry()
	caps_label := gtk.NewLabel("Captial:")
	all_caps := gtk.NewEntry()
	lower_label := gtk.NewLabel("Lower case:")
	all_lower := gtk.NewEntry()
	convert_button := gtk.NewButtonWithLabel("Convert")
	string_conversion_box.PackStart(input_label, true, true, 0)
	string_conversion_box.PackStart(input_string, true, true, 0)
	string_conversion_box.PackStart(caps_label, true, true, 0)
	string_conversion_box.PackStart(all_caps, true, true, 0)
	string_conversion_box.PackStart(lower_label, true, true, 0)
	string_conversion_box.PackStart(all_lower, true, true, 0)
	string_conversion_box.PackStart(convert_button, true, true, 0)

	convert_button.Clicked(func() {
		string_to_convert := input_string.GetText()
		all_caps.SetText(caps(string_to_convert))
		all_lower.SetText(lowers(string_to_convert))
	})

	all_boxes.PackStart(base_conversion_box, true, true, 0)
	all_boxes.PackStart(gtk.NewHSeparator(), true, true, 10)
	all_boxes.PackStart(string_conversion_box, true, true, 0)
	window.Add(all_boxes)
	window.ShowAll()
	gtk.Main()
}
Beispiel #22
0
func main() {
	b, err := ioutil.ReadFile("settings.json")
	if err != nil {
		fmt.Println(`"settings.json" not found: `, err)
		return
	}
	var config map[string]string
	err = json.Unmarshal(b, &config)
	if err != nil {
		fmt.Println(`can't read "settings.json": `, err)
		return
	}
	client := &oauth.Client{Credentials: oauth.Credentials{config["ClientToken"], config["ClientSecret"]}}
	cred := &oauth.Credentials{config["AccessToken"], config["AccessSecret"]}

	runtime.LockOSThread()
	gtk.Init(&os.Args)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("Twitter!")
	window.Connect("destroy", gtk.MainQuit)

	vbox := gtk.NewVBox(false, 1)

	scrolledwin := gtk.NewScrolledWindow(nil, nil)
	textview := gtk.NewTextView()
	textview.SetEditable(false)
	textview.SetCursorVisible(false)
	scrolledwin.Add(textview)
	vbox.Add(scrolledwin)

	buffer := textview.GetBuffer()
	tag := buffer.CreateTag("blue", map[string]string{"foreground": "#0000FF", "weight": "700"})

	hbox := gtk.NewHBox(false, 1)
	vbox.PackEnd(hbox, false, true, 5)

	label := gtk.NewLabel("Tweet")
	hbox.PackStart(label, false, false, 5)
	text := gtk.NewEntry()
	hbox.PackEnd(text, true, true, 5)

	text.Connect("activate", func() {
		t := text.GetText()
		text.SetText("")
		post(client, cred, t)
	})

	window.Add(vbox)
	window.SetSizeRequest(800, 500)
	window.ShowAll()

	var mutex sync.Mutex

	go func() {
		show(client, cred, func(t *tweet) {
			mutex.Lock()
			display(t, buffer, tag)
			mutex.Unlock()
		})

		stream(client, cred, func(t *tweet) {
			mutex.Lock()
			display(t, buffer, tag)
			var start, end gtk.TextIter
			buffer.GetIterAtLine(&start, buffer.GetLineCount()-2)
			buffer.GetEndIter(&end)
			buffer.Delete(&start, &end)
			mutex.Unlock()
		})
	}()

	for alive {
		mutex.Lock()
		alive = gtk.MainIterationDo(false)
		mutex.Unlock()
	}
}
Beispiel #23
0
func main() {
	var menuitem *gtk.MenuItem
	gtk.Init(nil)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle("GoBox a0.1")
	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("Dossier et Paramètres")
	framebox1 := gtk.NewVBox(false, 1)
	frame1.Add(framebox1)

	frame2 := gtk.NewFrame("Fonctions")
	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, "../../mattn/go-gtk/data/go-gtk-logo.png")
	  imagefile := path.Join(dir, "./go-gtk-logo.png")
	  println(dir)*/

	label := gtk.NewLabel("GoBox a0.1")
	label.ModifyFontEasy("DejaVu Serif 15")
	framebox1.PackStart(label, false, true, 0)

	//--------------------------------------------------------
	// GtkEntry
	//--------------------------------------------------------
	champIp := gtk.NewEntry()
	champIp.SetText("10.0.0.1")
	framebox1.Add(champIp)

	champPort := gtk.NewEntry()
	champPort.SetText("80")
	framebox1.Add(champPort)

	folder := "./"

	/*image := gtk.NewImageFromFile(imagefile)
	  framebox1.Add(image)*/
	buttons := gtk.NewHBox(false, 1)
	//--------------------------------------------------------
	// GtkButton
	//--------------------------------------------------------
	button := gtk.NewButtonWithLabel("Choisir le dossier")
	button.Clicked(func() {
		//--------------------------------------------------------
		// GtkFileChooserDialog
		//--------------------------------------------------------
		filechooserdialog := gtk.NewFileChooserDialog(
			"Sélectionnez le dossier ...",
			button.GetTopLevelAsWindow(),
			gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
			gtk.STOCK_OK,
			gtk.RESPONSE_ACCEPT)
		/*filter := gtk.NewFileFilter()
		  filter.AddPattern("*.go")
		  filechooserdialog.AddFilter(filter)*/
		filechooserdialog.Response(func() {
			println(filechooserdialog.GetFilename())
			folder = filechooserdialog.GetFilename() + "/"
			filechooserdialog.Destroy()
		})
		filechooserdialog.Run()
	})
	buttons.Add(button)

	//--------------------------------------------------------
	// GtkToggleButton
	//--------------------------------------------------------
	togglebutton := gtk.NewToggleButtonWithLabel("Lancer la synchronisation")
	togglebutton.Connect("toggled", func() {
		if togglebutton.GetActive() {
			togglebutton.SetLabel("Synchronisation ON")
			//Appel fonction synchro avec paramètres
			println(folder, champIp.GetText(), champPort.GetText())
			sync(folder, champIp.GetText(), champPort.GetText())
		} else {
			togglebutton.SetLabel("Synchronisation OFF")
		}
	})
	buttons.Add(togglebutton)

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

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

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

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

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

	auteurs := gtk.NewEntry()
	auteurs.SetText("Application crée en MCS par Olivier CANO et Adrien CHAPELET")

	menuitem = gtk.NewMenuItemWithMnemonic("À_ propos")
	menuitem.Connect("activate", func() {
		messagedialog := gtk.NewMessageDialog(
			button.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			auteurs.GetText())
		messagedialog.Response(func() {
			messagedialog.Destroy()
		})
		messagedialog.Run()
	})
	submenu.Append(menuitem)

	//--------------------------------------------------------
	// GtkStatusbar
	//--------------------------------------------------------
	statusbar := gtk.NewStatusbar()
	context_id := statusbar.GetContextId("go-gtk")
	statusbar.Push(context_id, "En attente de synchronisation")

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

	//--------------------------------------------------------
	// Event
	//--------------------------------------------------------
	window.Add(vbox)
	window.SetSizeRequest(500, 300)
	window.ShowAll()
	gtk.Main()
}
Beispiel #24
0
func main() {
	gtk.Init(&os.Args)
	display = gtk.NewEntry()
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetTitle("Simple Go Calculator")
	window.Connect("destroy", Quit, nil)

	// Vertical box containing all components
	vbox := gtk.NewVBox(false, 1)

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

	// Add calculator display to vertical box
	display.SetCanFocus(false) // disable focus on calcuator display
	display.SetText("0")
	display.SetAlignment(1.0) //align text to right
	vbox.Add(display)

	// Menu items
	filemenu := gtk.NewMenuItemWithMnemonic("_File")
	menubar.Append(filemenu)
	filesubmenu := gtk.NewMenu()
	filemenu.SetSubmenu(filesubmenu)

	aboutmenuitem := gtk.NewMenuItemWithMnemonic("_About")
	aboutmenuitem.Connect("activate", func() {
		messagedialog := gtk.NewMessageDialog(
			window.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			"Simple Go Calculator")
		messagedialog.Response(func() {}, nil)
		messagedialog.Run()
		messagedialog.Destroy()
	},
		nil)
	filesubmenu.Append(aboutmenuitem)

	resetmenuitem := gtk.NewMenuItemWithMnemonic("_Reset")
	resetmenuitem.Connect("activate", func() { Reset(); display.SetText("0") }, nil)
	filesubmenu.Append(resetmenuitem)

	exitmenuitem := gtk.NewMenuItemWithMnemonic("E_xit")
	exitmenuitem.Connect("activate", Quit, nil)
	filesubmenu.Append(exitmenuitem)

	// Vertical box containing all buttons
	buttons := gtk.NewVBox(false, 5)

	for i := 0; i < 4; i++ {
		hbox := gtk.NewHBox(false, 5) // a horizontal box for each 4 buttons
		for j := 0; j < 4; j++ {
			b := gtk.NewButtonWithLabel(string(nums[i*4+j]))
			b.Clicked(Input(b), nil) //add click event
			hbox.Add(b)
		}
		buttons.Add(hbox) // add horizonatal box to vertical buttons' box
	}

	vbox.Add(buttons)

	window.Add(vbox)
	window.SetSizeRequest(250, 250)
	window.ShowAll()
	gtk.Main()
}
Beispiel #25
0
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()
}
Beispiel #26
0
//InitializeGUI es la funcion que inicializa y ejecuta todo el entorno gráfico de la aplicacion
func (p *Gui) InitializeGUI(errorstr string, file *os.File) {
	gtk.Init(nil)

	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.Maximize()
	window.SetTitle("Go-SIC ASM/SIM!")
	window.SetIconName("gtk-dialog-info")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		fmt.Println("got destroy!", ctx.Data().(string))
		gtk.MainQuit()
	}, "foo")

	//--------------------------------------------------------
	//	GTK statusbar
	//--------------------------------------------------------
	statusbar := gtk.NewStatusbar()
	context_id := statusbar.GetContextId("hola")
	//--------------------------------------------------------
	// 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("Código Fuente/Archivo intermedio/TABSIM")
	framebox1 := gtk.NewVBox(false, 1)
	frame1.Add(framebox1)
	frame1.SetSizeRequest(300, 300)

	frame2 := gtk.NewFrame("Debug/Código Objeto")
	framebox2 := gtk.NewVBox(false, 1)
	frame2.Add(framebox2)

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

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

	label := gtk.NewLabel("Ensamblador SIC SIC/XE")
	label.ModifyFontEasy("DejaVu Serif 15")
	framebox1.PackStart(label, false, true, 0)
	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	swin := gtk.NewScrolledWindow(nil, nil)

	swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	swin.SetShadowType(gtk.SHADOW_IN)
	textview := gtk.NewTextView()

	textview.ModifyFontEasy("Sans 10")
	var start, end gtk.TextIter
	buffer := textview.GetBuffer()
	buffer.GetStartIter(&start)
	swin.Add(textview)
	ventanasPrincipales.Add(swin)
	//framebox1.Add(swin)
	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	swin4 := gtk.NewScrolledWindow(nil, nil)

	swin4.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	swin4.SetShadowType(gtk.SHADOW_IN)
	textview4 := gtk.NewTextView()

	textview4.ModifyFontEasy("Sans 10")
	var start4, end4 gtk.TextIter
	buffer4 := textview4.GetBuffer()
	buffer4.GetStartIter(&start4)
	swin4.Add(textview4)
	ventanasPrincipales.Add(swin4)
	//framebox1.Add(swin)
	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	swin5 := gtk.NewScrolledWindow(nil, nil)

	swin5.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	swin5.SetShadowType(gtk.SHADOW_IN)
	textview5 := gtk.NewTextView()

	textview5.ModifyFontEasy("Sans 10")
	var start5, end5 gtk.TextIter
	buffer5 := textview5.GetBuffer()
	buffer5.GetStartIter(&start5)
	swin5.Add(textview5)
	ventanasPrincipales.Add(swin5)
	framebox1.PackStart(ventanasPrincipales, true, true, 1)
	//framebox1.Add(swin)
	//--------------------------------------------------------
	// GtkHBox
	//--------------------------------------------------------
	ventanas := gtk.NewHBox(false, 1)
	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	swin2 := gtk.NewScrolledWindow(nil, nil)

	swin2.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	swin2.SetShadowType(gtk.SHADOW_IN)
	textview2 := gtk.NewTextView()
	textview2.SetEditable(false)
	var start2, end2 gtk.TextIter
	buffer2 := textview2.GetBuffer()
	buffer2.GetStartIter(&start2)
	swin2.Add(textview2)
	//framebox2.Add(swin2)
	ventanas.Add(swin2)
	//--------------------------------------------------------
	// GtkTextView
	//--------------------------------------------------------
	swin3 := gtk.NewScrolledWindow(nil, nil)

	swin3.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	swin3.SetShadowType(gtk.SHADOW_IN)
	textview3 := gtk.NewTextView()
	textview3.SetEditable(false)
	var start3, end3 gtk.TextIter
	buffer3 := textview3.GetBuffer()
	buffer3.GetStartIter(&start3)
	swin3.Add(textview3)
	//framebox2.Add(swin2)
	ventanas.Add(swin3)
	framebox2.PackStart(ventanas, true, true, 1)

	//--------------------------------------------------------
	// GtkEntry
	//--------------------------------------------------------
	entry := gtk.NewEntry()
	entry.SetText("Para comenzar, favor de escoger un archivo del directorio....")
	//entry.SetSensitive(false)
	entry.SetEditable(false)
	framebox2.Add(entry)

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

	//--------------------------------------------------------
	// GtkButton //**OPEN FILE****//
	//--------------------------------------------------------
	button := gtk.NewButtonWithLabel("Elegir archivo...")
	var filename string
	var isXE bool
	button.Clicked(func() {
		fmt.Println("button clicked:", button.GetLabel())
		messagedialog := gtk.NewMessageDialog(
			button.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			"Escoja un archivo .*s o *.x de su directorio")
		messagedialog.Response(func() {
			fmt.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("*.s")
			filter.AddPattern("*.x")
			filechooserdialog.AddFilter(filter)
			filechooserdialog.Response(func() {
				/*aqui va el dialogo */
				filename = filechooserdialog.GetFilename()
				var extension = filepath.Ext(filename)
				if extension == ".x" {
					isXE = true
				} else {
					isXE = false
				}
				fmt.Println(filechooserdialog.GetFilename())
				statusbar.Push(context_id, filename)
				dat, err := ioutil.ReadFile(filechooserdialog.GetFilename())
				if err == nil {
					buffer.GetStartIter(&start)
					buffer.GetEndIter(&end)
					buffer.Delete(&start, &end)

					buffer.Insert(&start, string(dat))
					entry.SetText("Ahora haz click en el boton '¡Analizar!'")
					//fmt.Print(string(dat))
				}
				filechooserdialog.Destroy()
			})
			filechooserdialog.Run()
			messagedialog.Destroy()
		})
		messagedialog.Run()
	})
	buttons.Add(button)
	//--------------------------------------------------------
	// GtkButton
	//--------------------------------------------------------
	button2 := gtk.NewButtonWithLabel("Ensamblar!")
	button2.Clicked(func() {
		fmt.Println("button clicked:", button2.GetLabel())
		messagedialog2 := gtk.NewMessageDialog(
			button.GetTopLevelAsWindow(),
			gtk.DIALOG_MODAL,
			gtk.MESSAGE_INFO,
			gtk.BUTTONS_OK,
			"Analisis lexico y sintactico presiona OK para continuar...")
		messagedialog2.Response(func() {
			fmt.Println(filename)
			statusbar.Push(context_id, filename)
			file, err := os.Open(filename)
			if err != nil {
				log.Fatalf("Error al cargar el archivo: %s", err.Error())
			} else {
				//*********************************************************
				util.GetTabSim().Allocate()
				if isXE == false {
					fmt.Println("IS SIC")
					errorstr = parser.New().Parse(file, true, false)
					file, err = os.Open(filename)

					util.GetAssembler().CreateOpCodeTable()
					errorstr = parser.New().Parse(file, false, false)
					file.Close()
					//util.GetAssembler().PrintCode()
					util.GetAssembler().FormatCodeToHEX()
					buffer2.GetStartIter(&start2)
					buffer2.GetEndIter(&end2)
					buffer2.Delete(&start2, &end2)
					if len(errorstr) > 0 {
						buffer2.Insert(&start2, string(errorstr+util.GetTabSim().Errores))

						strArray := strings.Split(filename, ".s")
						f, err := os.OpenFile(strArray[0]+".ts", os.O_WRONLY|os.O_CREATE, 0600)
						if err != nil {
							panic(err)
						}
						defer f.Close()
						if _, err = f.WriteString(errorstr); err != nil {
							panic(err)
						}
					} else {
						buffer2.Insert(&start2, "Correcto!"+util.GetTabSim().Errores)
					}
					///*******************************************************
					///*******************************************************
					tabsimlines := util.GetTabSim().ReturnTable()
					buffer5.GetStartIter(&start5)
					buffer5.GetEndIter(&end5)
					buffer5.Delete(&start5, &end5)
					if len(tabsimlines) > 0 {
						buffer5.Insert(&start5, string(tabsimlines))
					}
					///*******************************************************
					///*******************************************************
					util.GetTabSim().DecToHex()
					objectCode := util.GetAssembler().ObjCode()
					var obj string
					for i := 0; i < len(objectCode); i++ {

						if len(objectCode[i]) > 10 {

							obj += objectCode[i]
						}
						if i == len(objectCode)-1 {
							obj += objectCode[i]
						}
					}
					buffer3.GetStartIter(&start3)
					buffer3.GetEndIter(&end3)
					buffer3.Delete(&start3, &end3)
					if len(obj) > 0 {
						buffer3.Insert(&start3, string(obj))
					}
					f2 := newFile(strings.Split(filename, ".s")[0], ".os")
					if _, err = f2.WriteString(obj); err != nil {
						panic(err)
					}
					///*******************************************************
					///*******************************************************
					var todostr string
					lines, err := readLines(filename)
					if err == nil {
						addrsstr := util.GetTabSim().GetProgPcStr()
						//fmt.Println(addrsstr)
						for i := 0; i < len(lines); i++ {
							if addrsstr[i+1] == "" {
								addrsstr[i+1] = addrsstr[i]
								todostr += addrsstr[i] + "\t" + lines[i] + "\n"
							} else {
								todostr += addrsstr[i] + "\t" + lines[i] + "\t" + util.GetTabSim().Progobjstr[i] + "\n"
							}
						}
						//util.GetTabSim().PrintProgpc()
						//fmt.Print(todostr)
						addrsstr = nil
					}
					buffer4.GetStartIter(&start4)
					buffer4.GetEndIter(&end4)
					buffer4.Delete(&start4, &end4)
					if len(obj) > 0 {
						buffer4.Insert(&start4, string(todostr))
					}
				} else {
					fmt.Println("IS SIC XE")
					errorstr = parser.New().Parse(file, true, true)
					file, err = os.Open(filename)

					util.GetAssembler().CreateOpCodeTable()
					parser.New().Parse(file, false, true)
					file.Close()
					//util.GetAssembler().PrintCode()
					//util.GetAssembler().FormatCodeToHEX()
					buffer2.GetStartIter(&start2)
					buffer2.GetEndIter(&end2)
					buffer2.Delete(&start2, &end2)
					if len(errorstr) > 0 {
						buffer2.Insert(&start2, string(errorstr+util.GetTabSim().Errores))

						strArray := strings.Split(filename, ".x")
						f, err := os.OpenFile(strArray[0]+".tx", os.O_WRONLY|os.O_CREATE, 0600)
						if err != nil {
							panic(err)
						}
						defer f.Close()
						if _, err = f.WriteString(errorstr); err != nil {
							panic(err)
						}
					} else {
						buffer2.Insert(&start2, "Correcto!"+util.GetTabSim().Errores)
					}
					///*******************************************************
					///*******************************************************
					tabsimlines := util.GetTabSim().ReturnTable()
					buffer5.GetStartIter(&start5)
					buffer5.GetEndIter(&end5)
					buffer5.Delete(&start5, &end5)
					if len(tabsimlines) > 0 {
						buffer5.Insert(&start5, string(tabsimlines))
					}
					///*******************************************************
					///*******************************************************

					objectCode := util.GetAssembler().ObjCodeXE()
					util.GetTabSim().PcToHex()
					var obj string
					for i := 0; i < len(objectCode); i++ {

						if len(objectCode[i]) > 10 {

							obj += objectCode[i]
						}
						if i == len(objectCode)-1 {
							obj += objectCode[i]
						}
					}
					buffer3.GetStartIter(&start3)
					buffer3.GetEndIter(&end3)
					buffer3.Delete(&start3, &end3)
					if len(obj) > 0 {
						buffer3.Insert(&start3, string(obj))
					}
					f2 := newFile(strings.Split(filename, ".x")[0], ".ox")
					if _, err = f2.WriteString(obj); err != nil {
						panic(err)
					}
					///*******************************************************
					///*******************************************************
					var todostr string
					lines, err := readLines(filename)
					if err == nil {
						addrsstr := util.GetTabSim().GetProgPcStr()
						//fmt.Println(addrsstr)
						for i := 0; i < len(lines); i++ {
							if addrsstr[i+1] == "" {
								addrsstr[i+1] = addrsstr[i]
								todostr += addrsstr[i] + "\t" + lines[i] + "\tError" + "\n"
							} else {
								todostr += addrsstr[i] + "\t" + lines[i] + "\t \t"
								if i != 0 && i < len(lines)-1 {
									todostr += util.GetAssembler().Hexcode[i-1] + "\n"
								} else {
									todostr += "\n"
								}
							}
						}
						//util.GetTabSim().PrintProgpc()
						//fmt.Print(todostr)
						addrsstr = nil
					}
					buffer4.GetStartIter(&start4)
					buffer4.GetEndIter(&end4)
					buffer4.Delete(&start4, &end4)
					if len(obj) > 0 {
						buffer4.Insert(&start4, string(todostr))
					}
				}
			}
			entry.SetText("En la ventana debug se encuentran los errores lexicos y sintacticos del programa")
			fmt.Println("Dialog OK!")

			messagedialog2.Destroy()
		})
		messagedialog2.Run()
	})
	buttons.Add(button2)
	framebox2.PackStart(buttons, false, false, 0)

	/////////////////////////////////////////////

	button3 := gtk.NewButtonWithLabel("Cargador...")
	button3.Clicked(func() {
		strArray2 := strings.Split(filename, ".s")
		f2, err := os.OpenFile(strArray2[0]+".o", os.O_WRONLY|os.O_CREATE, 0600)
		var obj string
		objectCode := util.GetAssembler().ObjCode()
		for i := 0; i < len(objectCode); i++ {

			if len(objectCode[i]) > 10 {

				obj += objectCode[i]
			}
			if i == len(objectCode)-1 {
				obj += objectCode[i]
			}
		}
		if _, err = f2.WriteString(obj); err != nil {
			panic(err)
		}
		//nombre := strings.Split(strArray2[0], "work")

		cmd := exec.Command("script.sh", strArray2[0]+".o")

		err = cmd.Start()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Waiting for command to finish...")
		//err = cmd.Wait()
		log.Printf("Command finished with error: %v", err)
	})

	buttons.Add(button3)

	////////////////////////////

	buttons = gtk.NewHBox(false, 1)

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

	var menuitem2 *gtk.MenuItem
	menuitem2 = gtk.NewMenuItemWithMnemonic("G_uardar")
	menuitem2.Connect("activate", func() {
		strArray := strings.Split(filename, ".s")
		if len(strArray) <= 1 {
			strArray = strings.Split(filename, ".x")
		}
		if len(strArray) > 1 && len(filename) > 0 {
			statusbar.Push(context_id, filename)
			var s string
			buffer.GetStartIter(&start)
			buffer.GetEndIter(&end)
			s = buffer.GetText(&start, &end, true)
			fmt.Println(filename)
			err := ioutil.WriteFile(filename, []byte(s), 0644)
			if err != nil {
				panic(err)
			}
		} else {

			filechooserdialog := gtk.NewFileChooserDialog(
				"Choose File...",
				button.GetTopLevelAsWindow(),
				gtk.FILE_CHOOSER_ACTION_SAVE,
				gtk.STOCK_OK,
				gtk.RESPONSE_ACCEPT)
			filter := gtk.NewFileFilter()
			///***ALLOWS SIC AND SIC-XE EXTENSION***///
			filter.AddPattern("*.s")
			filter.AddPattern("*.x")
			filechooserdialog.AddFilter(filter)
			filechooserdialog.Response(func() {
				/*aqui va el dialogo */
				statusbar.Push(context_id, filename)
				filename = filechooserdialog.GetFilename()
				if len(filename) > 0 {
					fmt.Println(filechooserdialog.GetFilename())
					var s string
					buffer.GetStartIter(&start)
					buffer.GetEndIter(&end)
					s = buffer.GetText(&start, &end, true)

					err := ioutil.WriteFile(filename, []byte(s), 0644)
					if err != nil {
						panic(err)
					}
					entry.SetText("Haz click en el boton analizar")
				}
				filechooserdialog.Destroy()
			})
			filechooserdialog.Run()

		}
	})
	submenu.Append(menuitem2)

	var menuitem *gtk.MenuItem
	menuitem = gtk.NewMenuItemWithMnemonic("S_alir")
	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() {
		textview.SetSensitive(!checkmenuitem.GetActive())
		textview2.SetSensitive(!checkmenuitem.GetActive())
	})
	submenu.Append(checkmenuitem)

	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-SIC sim!")
		dialog.SetProgramName("Go-SIC sim")
		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.Push(context_id, "No hay archivo seleccionado")

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

	//--------------------------------------------------------
	// Event
	//--------------------------------------------------------
	window.Add(vbox)
	window.SetSizeRequest(600, 600)
	window.ShowAll()
	gtk.Main()
}
Beispiel #27
0
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()
}
Beispiel #28
0
func menu_bar(vbox *gtk.VBox) {
	menubar := gtk.NewMenuBar()
	vbox.PackStart(menubar, false, false, 0)

	buttons := gtk.NewAlignment(0, 0, 0, 0)
	checkbox := gtk.NewAlignment(1, 0, 0, 0)
	newPlayerGameButton := gtk.NewButtonWithLabel("Player vs Player")
	newIaGameButton := gtk.NewButtonWithLabel("Player vs AI")
	info = gtk.NewLabel("Hint: Not yet")
	threeCheckBox := gtk.NewCheckButtonWithLabel("Three and three")
	endCheckBox := gtk.NewCheckButtonWithLabel("Unbreakable end")
	hintCheckBox := gtk.NewCheckButtonWithLabel("Hint")
	hbox := gtk.NewHBox(false, 1)
	hbox0 := gtk.NewHBox(false, 1)
	hbox1 := gtk.NewHBox(false, 1)
	hbox0.Add(newPlayerGameButton)
	hbox0.Add(newIaGameButton)
	hbox1.Add(hintCheckBox)
	hbox1.Add(threeCheckBox)
	hbox1.Add(endCheckBox)
	buttons.Add(hbox0)
	checkbox.Add(hbox1)
	hbox.Add(buttons)
	hbox.Add(info)
	hbox.Add(checkbox)
	vbox.PackStart(hbox, false, true, 0)

	cascademenu := gtk.NewMenuItemWithMnemonic("_Game")
	menubar.Append(cascademenu)
	submenu := gtk.NewMenu()
	cascademenu.SetSubmenu(submenu)
	playermenuitem := gtk.NewMenuItemWithMnemonic("_Player Vs Player")
	playermenuitem.Connect("activate", func() {
		gc.SetRgbFgColor(gdk.NewColor("grey"))
		pixmap.GetDrawable().DrawRectangle(gc, true, 0, 0, -1, -1)
		game = Gomoku{make([]int, 361), true, game.endgameTake, game.doubleThree, 1, [2]int{10, 10}, 0}
		player = 1
		countTake = 0
		iamode = false
		display_init_grid(gc, pixmap)
		drawingarea.Hide()
		drawingarea.Show()
		stopGame = false
		stopClick = false
		context_id := statusbar.GetContextId("go-gtk")
		statusbar.Push(context_id, "(not so) Proudly propulsed by the inglorious Gomoku Project, with love, and Golang!")
	})
	submenu.Append(playermenuitem)
	newPlayerGameButton.Clicked(func() {
		playermenuitem.Activate()
	})
	iamenuitem := gtk.NewMenuItemWithMnemonic("_Player Vs AI")
	iamenuitem.Connect("activate", func() {
		gc.SetRgbFgColor(gdk.NewColor("grey"))
		pixmap.GetDrawable().DrawRectangle(gc, true, 0, 0, -1, -1)
		game = Gomoku{make([]int, 361), true, game.endgameTake, game.doubleThree, 1, [2]int{10, 10}, 0}
		player = 1
		countTake = 0
		iamode = true
		display_init_grid(gc, pixmap)
		drawingarea.Hide()
		drawingarea.Show()
		stopGame = false
		stopClick = false
		context_id := statusbar.GetContextId("go-gtk")
		statusbar.Push(context_id, "(not so) Proudly propulsed by the inglorious Gomoku Project, with love, and Golang!")
	})
	submenu.Append(iamenuitem)
	newIaGameButton.Clicked(func() {
		iamenuitem.Activate()
	})
	menuitem = gtk.NewMenuItemWithMnemonic("E_xit")
	menuitem.Connect("activate", func() {
		gtk.MainQuit()
	})
	submenu.Append(menuitem)

	threeCheckBox.Connect("toggled", func() {
		if game.doubleThree == false {
			game.doubleThree = true
		} else {
			game.doubleThree = false
		}
	})

	endCheckBox.Connect("toggled", func() {
		if game.endgameTake == false {
			game.endgameTake = true
		} else {
			game.endgameTake = false
		}
	})

	hintCheckBox.Connect("toggled", func() {
		if hint == false {
			hint = true
			calcHint <- true
		} else {
			hint = false
		}
	})

}