func initPage(title string, uri string, size_x int, size_y int) { gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle(title) window.Connect("destroy", gtk.MainQuit) vbox := gtk.NewVBox(false, 1) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) swin.SetShadowType(gtk.SHADOW_IN) webview := webkit.NewWebView() webview.LoadUri(uri) swin.Add(webview) vbox.Add(swin) window.Add(vbox) window.SetSizeRequest(size_x, size_y) window.ShowAll() proxy := os.Getenv("HTTP_PROXY") if len(proxy) > 0 { soup_uri := webkit.SoupUri(proxy) webkit.GetDefaultSession().Set("proxy-uri", soup_uri) soup_uri.Free() } gtk.Main() }
// NewBrowser returns a new browser component func NewBrowser(uri string) *Browser { vbox := gtk.NewVBox(false, 1) urlBarEntry := gtk.NewEntry() urlBarEntry.SetText(uri) urlBarEntry.GrabFocus() vbox.PackStart(urlBarEntry, false, false, 0) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) swin.SetShadowType(gtk.SHADOW_IN) webview := webkit.NewWebView() swin.Add(webview) vbox.Add(swin) // urlBarEntry.Connect("activate", func() { // webview.LoadUri(urlBarEntry.GetText()) // }) //return vbox browser := &Browser{ VBox: vbox, WebView: webview, URLEntry: urlBarEntry, Link: "", } browser.connectSignals() urlBarEntry.Emit("activate") return browser }
func main() { gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("GTK Stock Icons") window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) store := gtk.NewListStore(glib.G_TYPE_STRING, glib.G_TYPE_BOOL, gdkpixbuf.GetGdkPixbufType()) treeview := gtk.NewTreeView() swin.Add(treeview) treeview.SetModel(store) treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("name", gtk.NewCellRendererText(), "text", 0)) treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("check", gtk.NewCellRendererToggle(), "active", 1)) treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("icon", gtk.NewCellRendererPixbuf(), "pixbuf", 2)) n := 0 gtk.StockListIDs().ForEach(func(d interface{}, v interface{}) { id := glib.GPtrToString(d) var iter gtk.TreeIter store.Append(&iter) store.Set(&iter, id, (n == 1), gtk.NewImage().RenderIcon(id, gtk.ICON_SIZE_SMALL_TOOLBAR, "").Pixbuf) n = 1 - n }) window.Add(swin) window.SetSizeRequest(400, 200) window.ShowAll() gtk.Main() }
func main() { gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("GTK Icon View") window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) store := gtk.NewListStore(gdkpixbuf.GetType(), glib.G_TYPE_STRING) iconview := gtk.NewIconViewWithModel(store) iconview.SetPixbufColumn(0) iconview.SetTextColumn(1) swin.Add(iconview) gtk.StockListIDs().ForEach(func(d unsafe.Pointer, v interface{}) { id := glib.GPtrToString(d) var iter gtk.TreeIter store.Append(&iter) store.Set(&iter, gtk.NewImage().RenderIcon(id, gtk.ICON_SIZE_SMALL_TOOLBAR, "").GPixbuf, id) }) window.Add(swin) window.SetSizeRequest(500, 200) window.ShowAll() gtk.Main() }
func main() { mc := memcache.New("127.0.0.1:11211") gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("memcachedclient") window.Connect("destroy", gtk.MainQuit) vbox := gtk.NewVBox(false, 1) swin := gtk.NewScrolledWindow(nil, nil) textview := gtk.NewTextView() textview.SetEditable(false) textview.SetCursorVisible(false) textview.ModifyFontEasy("monospace 12") swin.Add(textview) vbox.Add(swin) buffer := textview.GetBuffer() input := gtk.NewEntry() input.SetEditable(true) vbox.PackEnd(input, false, false, 0) tag := buffer.CreateTag("red", map[string]string{"foreground": "#FF0000"}) input.Connect("activate", func() { var iter gtk.TextIter tokens := strings.SplitN(input.GetText(), " ", 3) if len(tokens) == 2 && strings.ToUpper(tokens[0]) == "GET" { if t, err := mc.Get(tokens[1]); err == nil { buffer.GetEndIter(&iter) buffer.Insert(&iter, string(t.Value)+"\n") } else { buffer.InsertWithTag(&iter, err.Error()+"\n", tag) } input.SetText("") } else if len(tokens) == 3 && strings.ToUpper(tokens[0]) == "SET" { if err := mc.Set( &memcache.Item{ Key: tokens[1], Value: []byte(tokens[2]), }); err == nil { buffer.GetEndIter(&iter) buffer.InsertWithTag(&iter, "OK\n", tag) } else { buffer.InsertWithTag(&iter, err.Error()+"\n", tag) } input.SetText("") } }) input.GrabFocus() window.Add(vbox) window.SetSizeRequest(300, 500) window.ShowAll() gtk.Main() }
func main() { gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("webkit") window.Connect("destroy", gtk.MainQuit) vbox := gtk.NewVBox(false, 1) entry := gtk.NewEntry() entry.SetText("http://golang.org/") vbox.PackStart(entry, false, false, 0) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) swin.SetShadowType(gtk.SHADOW_IN) webview := webkit.NewWebView() webview.Connect("load-committed", func() { entry.SetText(webview.GetUri()) }) swin.Add(webview) vbox.Add(swin) entry.Connect("activate", func() { webview.LoadUri(entry.GetText()) }) button := gtk.NewButtonWithLabel("load String") button.Clicked(func() { webview.LoadString("hello Go GTK!", "text/plain", "utf-8", ".") }) vbox.PackStart(button, false, false, 0) button = gtk.NewButtonWithLabel("load HTML String") button.Clicked(func() { webview.LoadHtmlString(HTML_STRING, ".") }) vbox.PackStart(button, false, false, 0) button = gtk.NewButtonWithLabel("Google Maps") button.Clicked(func() { webview.LoadHtmlString(MAP_EMBED, ".") }) vbox.PackStart(button, false, false, 0) window.Add(vbox) window.SetSizeRequest(600, 600) window.ShowAll() proxy := os.Getenv("HTTP_PROXY") if len(proxy) > 0 { soup_uri := webkit.SoupUri(proxy) webkit.GetDefaultSession().Set("proxy-uri", soup_uri) soup_uri.Free() } entry.Emit("activate") gtk.Main() }
func main() { gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("SourceView") window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) swin.SetShadowType(gtk.SHADOW_IN) sourcebuffer := gsv.NewSourceBufferWithLanguage(gsv.SourceLanguageManagerGetDefault().GetLanguage("cpp")) sourceview := gsv.NewSourceViewWithBuffer(sourcebuffer) var start gtk.TextIter sourcebuffer.GetStartIter(&start) sourcebuffer.BeginNotUndoableAction() sourcebuffer.Insert(&start, `#include <iostream> template<class T> struct foo_base { T operator+(T const &rhs) const { T tmp(static_cast<T const &>(*this)); tmp += rhs; return tmp; } }; class foo : public foo_base<foo> { private: int v; public: foo(int v) : v(v) {} foo &operator+=(foo const &rhs){ this->v += rhs.v; return *this; } operator int() { return v; } }; int main(void) { foo a(1), b(2); a += b; std::cout << (int)a << std::endl; } `) sourcebuffer.EndNotUndoableAction() swin.Add(sourceview) window.Add(swin) window.SetSizeRequest(400, 300) window.ShowAll() gtk.Main() }
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 }
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 }
func main() { gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("GTK Folder View") window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) store := gtk.NewTreeStore(gdkpixbuf.GetGdkPixbufType(), glib.G_TYPE_STRING) treeview := gtk.NewTreeView() swin.Add(treeview) treeview.SetModel(store.ToTreeModel()) treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("pixbuf", gtk.NewCellRendererPixbuf(), "pixbuf", 0)) treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("text", gtk.NewCellRendererText(), "text", 1)) for n := 1; n <= 10; n++ { var iter1, iter2, iter3 gtk.TreeIter store.Append(&iter1, nil) store.Set(&iter1, gtk.NewImage().RenderIcon(gtk.STOCK_DIRECTORY, gtk.ICON_SIZE_SMALL_TOOLBAR, "").Pixbuf, "Folder"+strconv.Itoa(n)) store.Append(&iter2, &iter1) store.Set(&iter2, gtk.NewImage().RenderIcon(gtk.STOCK_DIRECTORY, gtk.ICON_SIZE_SMALL_TOOLBAR, "").Pixbuf, "SubFolder"+strconv.Itoa(n)) store.Append(&iter3, &iter2) store.Set(&iter3, gtk.NewImage().RenderIcon(gtk.STOCK_FILE, gtk.ICON_SIZE_SMALL_TOOLBAR, "").Pixbuf, "File"+strconv.Itoa(n)) } treeview.Connect("row_activated", func() { var path *gtk.TreePath var column *gtk.TreeViewColumn treeview.GetCursor(&path, &column) mes := "TreePath is: " + path.String() dialog := gtk.NewMessageDialog( treeview.GetTopLevelAsWindow(), gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, mes) dialog.SetTitle("TreePath") dialog.Response(func() { dialog.Destroy() }) dialog.Run() }) window.Add(swin) window.SetSizeRequest(400, 200) window.ShowAll() gtk.Main() }
func (v *SearchView) Init() { v.store = gtk.NewTreeStore(gtk.TYPE_STRING) v.view = file_tree.NewSearchTree() v.view.ModifyFontEasy("Regular 8") v.model = v.store.ToTreeModel() v.view.SetModel(v.model) //v.view.NewAppendColumn(gtk.TreeViewColumnWithAttributes("", // gtk.CellRendererText(), "text", 0)) v.view.SetHeadersVisible(false) v.view.Connect("cursor-changed", func() { v.Select() }, nil) v.window = gtk.NewScrolledWindow(nil, nil) v.window.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) v.window.Add(v.view) v.window.SetVisible(opt.show_search) }
// StartBrowser launches a web browser with given url and size func StartBrowser(url string, width, height int) { gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("gogp") window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) swin.SetShadowType(gtk.SHADOW_IN) webview := webkit.NewWebView() swin.Add(webview) window.Add(swin) window.SetSizeRequest(width, height) webview.LoadUri(url) window.ShowAll() gtk.Main() }
func guiMain(ch <-chan Accounts) { glib.ThreadInit(nil) gdk.ThreadsInit() gdk.ThreadsEnter() gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetPosition(gtk.WIN_POS_CENTER) window.SetTitle("password") window.Connect("destroy", gtk.MainQuit) entry := gtk.NewEntry() store := gtk.NewListStore(glib.G_TYPE_STRING) treeview := gtk.NewTreeView() treeview.SetModel(store) // treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("icon", gtk.NewCellRendererPixbuf(), "pixbuf", 0)) treeview.AppendColumn(gtk.NewTreeViewColumnWithAttributes("name", gtk.NewCellRendererText(), "text", 0)) go func() { for accounts := range ch { gthread(func() { store.Clear() for _, a := range accounts { var iter gtk.TreeIter store.Append(&iter) store.Set(&iter, 0, a.Name) } }) } }() swin := gtk.NewScrolledWindow(nil, nil) swin.Add(treeview) vbox := gtk.NewVBox(false, 0) vbox.PackStart(entry, false, false, 1) vbox.PackStart(swin, true, true, 0) window.Add(vbox) window.SetSizeRequest(460, 640) window.SetResizable(false) window.ShowAll() }
func main() { gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("µemacs/pp") window.Connect("destroy", gtk.MainQuit) window.Connect("key-press-event", handleKeyPress) SetKeyReturn(kh.GTKKeyPressEvent{gdk.KEY_Return, 0}) swin := gtk.NewScrolledWindow(nil, nil) sourcebuffer := gsv.NewSourceBufferWithLanguage(gsv.SourceLanguageManagerGetDefault().GetLanguage("cpp")) sourceview = gsv.NewSourceViewWithBuffer(sourcebuffer) var start gtk.TextIter sourcebuffer.GetStartIter(&start) sourcebuffer.Insert(&start, `writing stuff, awww yea!`) textview = gtk.NewTextView() textbuffer = textview.GetBuffer() var bufiter gtk.TextIter sourcebuffer.GetStartIter(&bufiter) bufWrapper := ed.GtkTextBufferReadWriter{&sourceview.TextView.Container.Widget, bufiter, &sourcebuffer.TextBuffer} var comiter gtk.TextIter textbuffer.GetStartIter(&comiter) comWrapper := ed.GtkTextBufferReadWriter{&textview.Container.Widget, comiter, textbuffer} microemacs = editor.Editor{"", &bufWrapper, &comWrapper} vbox := gtk.NewVBox(false, 0) vbox.PackStart(swin, true, true, 0) vbox.PackEnd(textview, false, true, 0) swin.Add(sourceview) window.Add(vbox) window.SetSizeRequest(300, 300) window.ShowAll() gtk.Main() }
// Returns true in case of reloading files, and false in case of keeping as is. func inotify_dialog(s map[string]int) bool { if nil == accel_group { accel_group = gtk.NewAccelGroup() } inotify_dlg := gtk.NewDialog() defer inotify_dlg.Destroy() inotify_dlg.SetTitle("Some files have beed modified outside of tabby") inotify_dlg.AddButton("_Reload all", gtk.RESPONSE_ACCEPT) inotify_dlg.AddButton("_Keep all as is", gtk.RESPONSE_CANCEL) w := inotify_dlg.GetWidgetForResponse(int(gtk.RESPONSE_ACCEPT)) inotify_dlg.AddAccelGroup(accel_group) w.AddAccelerator("clicked", accel_group, gdk.KEY_Return, 0, gtk.ACCEL_VISIBLE) inotify_dlg.SetSizeRequest(800, 350) inotify_store := gtk.NewTreeStore(gtk.TYPE_STRING) inotify_view := gtk.NewTreeView() inotify_view.AppendColumn( gtk.NewTreeViewColumnWithAttributes("text", gtk.NewCellRendererText(), "text", 0)) inotify_view.ModifyFontEasy("Regular 8") inotify_model := inotify_store.ToTreeModel() inotify_view.SetModel(inotify_model) inotify_view.SetHeadersVisible(false) var iter gtk.TreeIter for name, _ := range s { inotify_store.Append(&iter, nil) inotify_store.Set(&iter, name) } inotify_view.SetVisible(true) view_window := gtk.NewScrolledWindow(nil, nil) view_window.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) view_window.SetVisible(true) view_window.Add(inotify_view) vbox := inotify_dlg.GetVBox() vbox.Add(view_window) if gtk.RESPONSE_ACCEPT == inotify_dlg.Run() { return true } return false }
func main() { gtk.Init(&os.Args) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("GTK Table") window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) table := gtk.NewTable(5, 5, false) for y := uint(0); y < 5; y++ { for x := uint(0); x < 5; x++ { table.Attach(gtk.NewButtonWithLabel(fmt.Sprintf("%02d:%02d", x, y)), x, x+1, y, y+1, gtk.FILL, gtk.FILL, 5, 5) } } swin.AddWithViewPort(table) window.Add(swin) window.SetDefaultSize(200, 200) window.ShowAll() gtk.Main() }
//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() }
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() }
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() }
func main() { flag.Parse() common.SetDefaultGtkTheme() runtime.GOMAXPROCS(runtime.NumCPU()) rclient = &remoton.Client{Prefix: "/remoton", TLSConfig: &tls.Config{}} sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGABRT, syscall.SIGKILL, syscall.SIGTERM) go func() { <-sigs chatSrv.Terminate() tunnelSrv.Terminate() }() gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetPosition(gtk.WIN_POS_CENTER) window.SetTitle("REMOTON SUPPORT") window.Connect("destroy", func() { gtk.MainQuit() chatSrv.Terminate() tunnelSrv.Terminate() }) window.SetIcon(common.GetIconGdkPixbuf()) appLayout := gtk.NewVBox(false, 1) menu := gtk.NewMenuBar() appLayout.Add(menu) cascademenu := gtk.NewMenuItemWithMnemonic("_Help") menu.Append(cascademenu) submenu := gtk.NewMenu() cascademenu.SetSubmenu(submenu) menuitem := gtk.NewMenuItemWithMnemonic("_About") menuitem.Connect("activate", func() { dialog := common.GtkAboutDialog() dialog.SetProgramName("Support Desktop") dialog.Run() dialog.Destroy() }) submenu.Append(menuitem) hpaned := gtk.NewHPaned() appLayout.Add(hpaned) //--- //CHAT //--- frameChat := gtk.NewFrame("Chat") chatBox := gtk.NewVBox(false, 1) frameChat.Add(chatBox) swinChat := gtk.NewScrolledWindow(nil, nil) chatHistory := gtk.NewTextView() swinChat.Add(chatHistory) chatEntry := gtk.NewEntry() chatEntry.Connect("key-press-event", func(ctx *glib.CallbackContext) { arg := ctx.Args(0) event := *(**gdk.EventKey)(unsafe.Pointer(&arg)) if event.Keyval == gdk.KEY_Return { msgToSend := chatEntry.GetText() chatSrv.Send(msgToSend) chatHistorySend(chatHistory, msgToSend) chatEntry.SetText("") } }) chatSrv.OnRecv(func(msg string) { log.Println(msg) chatHistoryRecv(chatHistory, msg) }) chatBox.Add(chatEntry) chatBox.Add(swinChat) //--- //CONTROL //--- frameControl := gtk.NewFrame("Control") controlBox := gtk.NewVBox(false, 1) frameControl.Add(controlBox) controlBox.Add(gtk.NewLabel("Machine ID")) machineIDEntry := gtk.NewEntry() controlBox.Add(machineIDEntry) controlBox.Add(gtk.NewLabel("Machine AUTH")) machineAuthEntry := gtk.NewEntry() controlBox.Add(machineAuthEntry) controlBox.Add(gtk.NewLabel("Server")) serverEntry := gtk.NewEntry() serverEntry.SetText("localhost:9934") if os.Getenv("REMOTON_SERVER") != "" { serverEntry.SetText(os.Getenv("REMOTON_SERVER")) serverEntry.SetEditable(false) } controlBox.Add(serverEntry) btnCert := gtk.NewFileChooserButton("Cert", gtk.FILE_CHOOSER_ACTION_OPEN) controlBox.Add(btnCert) btn := gtk.NewButtonWithLabel("Connect") started := false btn.Clicked(func() { if *insecure { rclient.TLSConfig.InsecureSkipVerify = true } else { certPool, err := common.GetRootCAFromFile(btnCert.GetFilename()) if err != nil { dialogError(window, err) return } rclient.TLSConfig.RootCAs = certPool } session := &remoton.SessionClient{Client: rclient, ID: machineIDEntry.GetText(), APIURL: "https://" + serverEntry.GetText()} if !started { err := chatSrv.Start(session) if err != nil { dialogError(btn.GetTopLevelAsWindow(), err) return } err = tunnelSrv.Start(session, machineAuthEntry.GetText()) if err != nil { dialogError(btn.GetTopLevelAsWindow(), err) return } btn.SetLabel("Disconnect") started = true } else { chatSrv.Terminate() tunnelSrv.Terminate() btn.SetLabel("Connect") started = false } }) controlBox.Add(btn) hpaned.Pack1(frameControl, false, false) hpaned.Pack2(frameChat, false, false) window.Add(appLayout) window.ShowAll() gtk.Main() }
func guiMain(confglobal string, conflocal string) { var CallID string ch := make(chan string, 100) Config := ReadConfig(confglobal) Configlocal := ReadConfiglocal(conflocal) owner := Configlocal.Main.Owner //prepare config for XSI var xsiConfig xsi.ConfigT xsiConfig.Main.User = Configlocal.Main.Owner xsiConfig.Main.Password = Configlocal.Main.Password xsiConfig.Main.Host = Config.Main.Host xsiConfig.Main.HTTPHost = Config.Main.HTTPHost xsiConfig.Main.HTTPPort = Config.Main.HTTPPort def := xsi.MakeDef(xsiConfig) //start main client go clientMain(ch, Config) //prepare config for OCI var ociConfig ocip.ConfigT ociConfig.Main.User = Configlocal.Main.Owner ociConfig.Main.Password = Configlocal.Main.Password ociConfig.Main.Host = Config.Main.Host ociConfig.Main.OCIPPort = Config.Main.OCIPPort //set unavailable at start app ocip.OCIPsend(ociConfig, "UserCallCenterModifyRequest19", ConcatStr("", "userId=", owner), "agentACDState=Unavailable") //prepare timer timer := time.NewTimer(time.Second) timer.Stop() //init gthreads glib.ThreadInit(nil) gdk.ThreadsInit() gdk.ThreadsEnter() gtk.Init(nil) //names names := make(map[string]string) for iter, target := range Config.Main.TargetID { names[target] = Config.Main.Name[iter] } //icons to pixbuf map pix := make(map[string]*gdkpixbuf.Pixbuf) im_call := gtk.NewImageFromFile("ico/Call-Ringing-48.ico") pix["call"] = im_call.GetPixbuf() im_blank := gtk.NewImageFromFile("ico/Empty-48.ico") pix["blank"] = im_blank.GetPixbuf() im_green := gtk.NewImageFromFile("ico/Green-ball-48.ico") pix["green"] = im_green.GetPixbuf() im_grey := gtk.NewImageFromFile("ico/Grey-ball-48.ico") pix["grey"] = im_grey.GetPixbuf() im_yellow := gtk.NewImageFromFile("ico/Yellow-ball-48.ico") pix["yellow"] = im_yellow.GetPixbuf() window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("Call Center") window.SetIcon(pix["call"]) window.SetPosition(gtk.WIN_POS_CENTER) window.SetSizeRequest(350, 500) window.SetDecorated(false) window.SetResizable(true) window.Connect("destroy", gtk.MainQuit) swin := gtk.NewScrolledWindow(nil, nil) swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) swin.SetShadowType(gtk.SHADOW_IN) //owner owner1 := gtk.NewLabel(names[owner]) owner2 := gtk.NewLabel("") owner3 := gtk.NewImage() //qstatus qlabel1 := gtk.NewLabel("В очереди:") qlabel2 := gtk.NewLabel("") //buttons b_av := gtk.NewButtonWithLabel("Доступен") b_av.SetCanFocus(false) b_av.Connect("clicked", func() { ocip.OCIPsend(ociConfig, "UserCallCenterModifyRequest19", ConcatStr("", "userId=", owner), "agentACDState=Available") }) b_un := gtk.NewButtonWithLabel("Недоступен") b_un.SetCanFocus(false) b_un.Connect("clicked", func() { ocip.OCIPsend(ociConfig, "UserCallCenterModifyRequest19", ConcatStr("", "userId=", owner), "agentACDState=Unavailable") }) b_wr := gtk.NewButtonWithLabel("Дообработка") b_wr.SetCanFocus(false) b_wr.Connect("clicked", func() { ocip.OCIPsend(ociConfig, "UserCallCenterModifyRequest19", ConcatStr("", "userId=", owner), "agentACDState=Wrap-Up") }) //main table table := gtk.NewTable(3, 3, false) table.Attach(owner1, 0, 1, 0, 1, gtk.FILL, gtk.FILL, 1, 1) table.Attach(owner3, 1, 2, 0, 1, gtk.FILL, gtk.FILL, 1, 1) table.Attach(owner2, 2, 3, 0, 1, gtk.FILL, gtk.FILL, 1, 1) table.Attach(b_av, 0, 1, 1, 2, gtk.FILL, gtk.FILL, 1, 1) table.Attach(b_un, 1, 2, 1, 2, gtk.FILL, gtk.FILL, 1, 1) table.Attach(b_wr, 2, 3, 1, 2, gtk.FILL, gtk.FILL, 1, 1) table.Attach(qlabel1, 0, 1, 2, 3, gtk.FILL, gtk.FILL, 1, 1) table.Attach(qlabel2, 1, 2, 2, 3, gtk.FILL, gtk.FILL, 1, 1) //menu buttons btnclose := gtk.NewToolButtonFromStock(gtk.STOCK_STOP) btnclose.SetCanFocus(false) btnclose.OnClicked(gtk.MainQuit) btnhide := gtk.NewToolButtonFromStock(gtk.STOCK_REMOVE) btnhide.SetCanFocus(false) btnhide.OnClicked(window.Iconify) //move window var p2, p1 point var gdkwin *gdk.Window p1.x = -1 p2.y = -1 var x int = 0 var y int = 0 var diffx int = 0 var diffy int = 0 px := &x py := &y movearea := gtk.NewDrawingArea() movearea.Connect("motion-notify-event", func(ctx *glib.CallbackContext) { if gdkwin == nil { gdkwin = movearea.GetWindow() } arg := ctx.Args(0) mev := *(**gdk.EventMotion)(unsafe.Pointer(&arg)) var mt gdk.ModifierType if mev.IsHint != 0 { gdkwin.GetPointer(&p2.x, &p2.y, &mt) } if (gdk.EventMask(mt) & gdk.BUTTON_PRESS_MASK) != 0 { if p1.x != -1 && p1.y != -1 { window.GetPosition(px, py) diffx = p2.x - p1.x diffy = p2.y - p1.y window.Move(x+diffx, y+diffy) } p1.x = p2.x - diffx p1.y = p2.y - diffy } else { p1.x = -1 p2.y = -1 } }) movearea.SetEvents(int(gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.BUTTON_PRESS_MASK)) //resize window var p2r, p1r point var gdkwinr *gdk.Window p1r.x = -1 p2r.y = -1 var xr int = 0 var yr int = 0 var diffxr int = 0 var diffyr int = 0 pxr := &xr pyr := &yr resizearea := gtk.NewDrawingArea() resizearea.SetSizeRequest(10, 10) resizearea.Connect("motion-notify-event", func(ctx *glib.CallbackContext) { if gdkwinr == nil { gdkwinr = resizearea.GetWindow() } argr := ctx.Args(0) mevr := *(**gdk.EventMotion)(unsafe.Pointer(&argr)) var mtr gdk.ModifierType if mevr.IsHint != 0 { gdkwinr.GetPointer(&p2r.x, &p2r.y, &mtr) } if (gdk.EventMask(mtr) & gdk.BUTTON_PRESS_MASK) != 0 { if p1r.x != -1 && p1r.y != -1 { diffxr = p2r.x - p1r.x diffyr = p2r.y - p1r.y window.GetSize(pxr, pyr) window.Resize(xr+diffxr, yr+diffyr) } } p1r = p2r }) resizearea.SetEvents(int(gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.BUTTON_PRESS_MASK)) //menu menutable := gtk.NewTable(1, 8, true) menutable.Attach(movearea, 0, 6, 0, 1, gtk.FILL, gtk.FILL, 0, 0) menutable.Attach(btnhide, 6, 7, 0, 1, gtk.EXPAND, gtk.EXPAND, 0, 0) menutable.Attach(btnclose, 7, 8, 0, 1, gtk.EXPAND, gtk.EXPAND, 0, 0) //agents dlabel1 := make(map[string]*gtk.Label) dlabel2 := make(map[string]*gtk.Image) dlabel3 := make(map[string]*gtk.Image) b_tr := make(map[string]*gtk.Button) var count uint = 0 for _, target := range Config.Main.TargetID { if target != owner { count = count + 1 dlabel1[target] = gtk.NewLabel(names[target]) dlabel2[target] = gtk.NewImage() dlabel3[target] = gtk.NewImage() tmp := gtk.NewButtonWithLabel("Перевод") tmp.SetCanFocus(false) tmptarget := target tmp.Connect("clicked", func() { xsi.XSITransfer(xsiConfig, def, owner, CallID, tmptarget) }) b_tr[target] = tmp } } table_ag := gtk.NewTable(4, count+1, false) var place uint = 0 for _, target := range Config.Main.TargetID { if target != owner { place = place + 1 table_ag.Attach(dlabel1[target], 0, 1, place, place+1, gtk.FILL, gtk.FILL, 1, 1) table_ag.Attach(dlabel3[target], 2, 3, place, place+1, gtk.FILL, gtk.FILL, 1, 1) table_ag.Attach(dlabel2[target], 1, 2, place, place+1, gtk.FILL, gtk.FILL, 1, 1) table_ag.Attach(b_tr[target], 3, 4, place, place+1, gtk.FILL, gtk.FILL, 1, 1) } } //calls table_cl := gtk.NewTable(2, 15, false) dlabel4 := make(map[uint]*gtk.Label) dlabel5 := make(map[uint]*gtk.Label) var i uint for i = 0; i < 15; i++ { dlabel4[i] = gtk.NewLabel("") table_cl.Attach(dlabel4[i], 0, 1, i, i+1, gtk.FILL, gtk.FILL, 1, 1) dlabel5[i] = gtk.NewLabel("") table_cl.Attach(dlabel5[i], 1, 2, i, i+1, gtk.FILL, gtk.FILL, 1, 1) } //tabs notebook := gtk.NewNotebook() notebook.AppendPage(table_ag, gtk.NewLabel("Агенты")) notebook.AppendPage(table_cl, gtk.NewLabel("Звонки")) //add all to window vbox := gtk.NewVBox(false, 1) vbox.Add(menutable) vbox.Add(table) vbox.Add(notebook) vbox.Add(resizearea) swin.AddWithViewPort(vbox) window.Add(swin) window.ShowAll() //main func for update go func() { for { select { case data := <-ch: cinfo := strings.Split(strings.Trim(data, "\n"), ";") //owner if cinfo[0] == owner && cinfo[1] == "state" { if cinfo[4] != "" { CallID = cinfo[5] gdk.ThreadsEnter() owner2.SetLabel(strings.Trim(cinfo[4], "tel:")) gdk.ThreadsLeave() } else { CallID = "" gdk.ThreadsEnter() owner2.SetLabel("") gdk.ThreadsLeave() } if cinfo[3] == "Available" { gdk.ThreadsEnter() owner3.SetFromPixbuf(pix["green"]) gdk.ThreadsLeave() } else if cinfo[3] == "Wrap-Up" { gdk.ThreadsEnter() owner3.SetFromPixbuf(pix["yellow"]) gdk.ThreadsLeave() timer.Reset(time.Second * Config.Main.Wraptime) } else { gdk.ThreadsEnter() owner3.SetFromPixbuf(pix["grey"]) gdk.ThreadsLeave() } } //CC q if cinfo[0] == Config.Main.CCID && cinfo[1] == "state" { if cinfo[6] != "" { gdk.ThreadsEnter() qlabel2.SetLabel(cinfo[6]) gdk.ThreadsLeave() } } //CC calls if cinfo[0] == Config.Main.CCID && cinfo[1] == "calls" { if cinfo[3] != "" { var i, j uint j = 2 for i = 0; i < 15; i++ { if cinfo[j] != "" { date, _ := strconv.Atoi(cinfo[j]) date = date / 1000 j++ Addr := strings.Trim(cinfo[j], "tel:") j++ Time := time.Unix(int64(date), 0) gdk.ThreadsEnter() tmp4 := dlabel4[i] tmp4.SetLabel(Time.Format(time.Stamp)) tmp5 := dlabel5[i] tmp5.SetLabel(Addr) dlabel4[i] = tmp4 dlabel5[i] = tmp5 gdk.ThreadsLeave() } } } } //Targets if cinfo[0] != owner && cinfo[0] != Config.Main.CCID && cinfo[1] == "state" { if cinfo[2] == "On-Hook" { gdk.ThreadsEnter() tmp := dlabel3[cinfo[0]] tmp.SetFromPixbuf(pix["blank"]) dlabel3[cinfo[0]] = tmp gdk.ThreadsLeave() } if cinfo[2] == "Off-Hook" { gdk.ThreadsEnter() tmp := dlabel3[cinfo[0]] tmp.SetFromPixbuf(pix["call"]) dlabel3[cinfo[0]] = tmp gdk.ThreadsLeave() } if cinfo[3] == "Available" { gdk.ThreadsEnter() tmp := dlabel2[cinfo[0]] tmp.SetFromPixbuf(pix["green"]) dlabel2[cinfo[0]] = tmp gdk.ThreadsLeave() } else if cinfo[3] == "Wrap-Up" { gdk.ThreadsEnter() tmp := dlabel2[cinfo[0]] tmp.SetFromPixbuf(pix["yellow"]) dlabel2[cinfo[0]] = tmp gdk.ThreadsLeave() } else { gdk.ThreadsEnter() tmp := dlabel2[cinfo[0]] tmp.SetFromPixbuf(pix["grey"]) dlabel2[cinfo[0]] = tmp gdk.ThreadsLeave() } } //timer for wrap-up case <-timer.C: ocip.OCIPsend(ociConfig, "UserCallCenterModifyRequest19", ConcatStr("", "userId=", owner), "agentACDState=Available") } } }() gtk.Main() }
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() } }
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() }
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() }
func init_tabby() { init_navigation() init_inotify() search_view.Init() source_buf = gtksourceview.NewSourceBuffer() source_buf.Connect("paste-done", paste_done_cb, nil) source_buf.Connect("mark-set", mark_set_cb, nil) source_buf.Connect("modified-changed", buf_changed_cb, nil) init_lang() source_buf.CreateTag("instance", map[string]string{"background": "#FF8080"}) tree_store = gtk.NewTreeStore(glib.G_TYPE_STRING) tree_view = file_tree.NewFileTree() tree_view.ModifyFontEasy("Regular 8") tree_model = tree_store.ToTreeModel() tree_view.SetModel(tree_model) tree_view.SetHeadersVisible(false) tree_view.Connect("cursor-changed", tree_view_select_cb, nil) error_view = gtk.NewTextView() error_view.ModifyFontEasy("Monospace Regular 8") error_view.SetEditable(false) error_buf = error_view.GetBuffer() source_view = gtksourceview.NewSourceViewWithBuffer(source_buf) source_view.ModifyFontEasy("Monospace Regular 10") source_view.SetAutoIndent(true) source_view.SetHighlightCurrentLine(true) source_view.SetShowLineNumbers(true) source_view.SetRightMarginPosition(80) source_view.SetShowRightMargin(true) source_view.SetIndentWidth(2) source_view.SetTabWidth(2) source_view.SetInsertSpacesInsteadOfTabs(opt.space_not_tab) source_view.SetDrawSpaces(gtksourceview.SOURCE_DRAW_SPACES_TAB) source_view.SetSmartHomeEnd(gtksourceview.SOURCE_SMART_HOME_END_ALWAYS) source_view.SetWrapMode(gtk.WRAP_WORD) vbox := gtk.NewVBox(false, 0) inner_hpaned := gtk.NewHPaned() view_vpaned := gtk.NewVPaned() outer_hpaned := gtk.NewHPaned() outer_hpaned.Add1(inner_hpaned) inner_hpaned.Add2(view_vpaned) menubar := gtk.NewMenuBar() vbox.PackStart(menubar, false, false, 0) vbox.PackStart(outer_hpaned, true, true, 0) file_item := gtk.NewMenuItemWithMnemonic("_File") menubar.Append(file_item) file_submenu := gtk.NewMenu() file_item.SetSubmenu(file_submenu) accel_group := gtk.NewAccelGroup() new_item := gtk.NewMenuItemWithMnemonic("_New") file_submenu.Append(new_item) new_item.Connect("activate", new_cb, nil) new_item.AddAccelerator("activate", accel_group, gdk.KEY_n, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) open_item := gtk.NewMenuItemWithMnemonic("_Open") file_submenu.Append(open_item) open_item.Connect("activate", open_cb, nil) open_item.AddAccelerator("activate", accel_group, gdk.KEY_o, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) open_rec_item := gtk.NewMenuItemWithMnemonic("Open _Recursively") file_submenu.Append(open_rec_item) open_rec_item.Connect("activate", open_rec_cb, nil) save_item := gtk.NewMenuItemWithMnemonic("_Save") file_submenu.Append(save_item) save_item.Connect("activate", save_cb, nil) save_item.AddAccelerator("activate", accel_group, gdk.KEY_s, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) save_as_item := gtk.NewMenuItemWithMnemonic("Save _as") file_submenu.Append(save_as_item) save_as_item.Connect("activate", save_as_cb, nil) close_item := gtk.NewMenuItemWithMnemonic("_Close") file_submenu.Append(close_item) close_item.Connect("activate", close_cb, nil) close_item.AddAccelerator("activate", accel_group, gdk.KEY_w, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) exit_item := gtk.NewMenuItemWithMnemonic("E_xit") file_submenu.Append(exit_item) exit_item.Connect("activate", exit_cb, nil) navigation_item := gtk.NewMenuItemWithMnemonic("_Navigation") menubar.Append(navigation_item) navigation_submenu := gtk.NewMenu() navigation_item.SetSubmenu(navigation_submenu) prev_instance_item := gtk.NewMenuItemWithMnemonic("_Previous Instance") navigation_submenu.Append(prev_instance_item) prev_instance_item.Connect("activate", prev_instance_cb, nil) prev_instance_item.AddAccelerator("activate", accel_group, gdk.KEY_F2, 0, gtk.ACCEL_VISIBLE) next_instance_item := gtk.NewMenuItemWithMnemonic("_Next Instance") navigation_submenu.Append(next_instance_item) next_instance_item.Connect("activate", next_instance_cb, nil) next_instance_item.AddAccelerator("activate", accel_group, gdk.KEY_F3, 0, gtk.ACCEL_VISIBLE) prev_result_item := gtk.NewMenuItemWithMnemonic("Prev search result") navigation_submenu.Append(prev_result_item) prev_result_item.Connect("activate", func() { search_view.PrevResult() }, nil) prev_result_item.AddAccelerator("activate", accel_group, gdk.KEY_F4, 0, gtk.ACCEL_VISIBLE) next_result_item := gtk.NewMenuItemWithMnemonic("Next search result") navigation_submenu.Append(next_result_item) next_result_item.Connect("activate", func() { search_view.NextResult() }, nil) next_result_item.AddAccelerator("activate", accel_group, gdk.KEY_F5, 0, gtk.ACCEL_VISIBLE) find_item := gtk.NewMenuItemWithMnemonic("_Find") navigation_submenu.Append(find_item) find_item.Connect("activate", find_cb, nil) find_item.AddAccelerator("activate", accel_group, gdk.KEY_f, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) find_file_item := gtk.NewMenuItemWithMnemonic("_Find file") navigation_submenu.Append(find_file_item) find_file_item.Connect("activate", find_file_cb, nil) find_file_item.AddAccelerator("activate", accel_group, gdk.KEY_d, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) fnr_item := gtk.NewMenuItemWithMnemonic("Find and Replace") navigation_submenu.Append(fnr_item) fnr_item.Connect("activate", fnr_cb, nil) fnr_item.AddAccelerator("activate", accel_group, gdk.KEY_r, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) prev_file_item := gtk.NewMenuItemWithMnemonic("Prev File") navigation_submenu.Append(prev_file_item) prev_file_item.Connect("activate", prev_file_cb, nil) prev_file_item.AddAccelerator("activate", accel_group, gdk.KEY_F7, 0, gtk.ACCEL_VISIBLE) next_file_item := gtk.NewMenuItemWithMnemonic("Next File") navigation_submenu.Append(next_file_item) next_file_item.Connect("activate", next_file_cb, nil) next_file_item.AddAccelerator("activate", accel_group, gdk.KEY_F8, 0, gtk.ACCEL_VISIBLE) tools_item := gtk.NewMenuItemWithMnemonic("_Tools") menubar.Append(tools_item) tools_submenu := gtk.NewMenu() tools_item.SetSubmenu(tools_submenu) gofmt_item := gtk.NewMenuItemWithMnemonic("_Gofmt") tools_submenu.Append(gofmt_item) gofmt_item.Connect("activate", gofmt_cb, nil) gofmt_item.AddAccelerator("activate", accel_group, gdk.KEY_F9, 0, gtk.ACCEL_VISIBLE) gofmtAll_item := gtk.NewMenuItemWithMnemonic("Gofmt _All") tools_submenu.Append(gofmtAll_item) gofmtAll_item.Connect("activate", gofmt_all, nil) gofmtAll_item.AddAccelerator("activate", accel_group, gdk.KEY_F9, gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE) options_item := gtk.NewMenuItemWithMnemonic("_Options") menubar.Append(options_item) options_submenu := gtk.NewMenu() options_item.SetSubmenu(options_submenu) search_chkitem := gtk.NewCheckMenuItemWithMnemonic("Show _Searchview") options_submenu.Append(search_chkitem) search_chkitem.SetActive(opt.show_search) search_chkitem.Connect("toggled", func() { search_chk_cb(search_chkitem.GetActive()) }, nil) error_chkitem := gtk.NewCheckMenuItemWithMnemonic("Show _Errorview") options_submenu.Append(error_chkitem) error_chkitem.SetActive(opt.show_error) error_chkitem.Connect("toggled", func() { error_chk_cb(error_chkitem.GetActive()) }, nil) notab_chkitem := gtk.NewCheckMenuItemWithMnemonic("Spaces for _Tabs") options_submenu.Append(notab_chkitem) notab_chkitem.SetActive(opt.space_not_tab) notab_chkitem.Connect("toggled", func() { notab_chk_cb(notab_chkitem.GetActive()) }, nil) font_item := gtk.NewMenuItemWithMnemonic("_Font") options_submenu.Append(font_item) font_item.Connect("activate", font_cb, nil) tabsize_item := gtk.NewMenuItemWithMnemonic("_Tab size") options_submenu.Append(tabsize_item) tabsize_submenu := gtk.NewMenu() tabsize_item.SetSubmenu(tabsize_submenu) const tabsize_cnt = 8 tabsize_chk := make([]*gtk.CheckMenuItem, tabsize_cnt) for y := 0; y < tabsize_cnt; y++ { tabsize_chk[y] = gtk.NewCheckMenuItemWithMnemonic(strconv.Itoa(y + 1)) tabsize_submenu.Append(tabsize_chk[y]) cur_ind := y tabsize_chk[y].Connect("activate", func() { if false == tabsize_chk[cur_ind].GetActive() { active_cnt := 0 for j := 0; j < tabsize_cnt; j++ { if tabsize_chk[j].GetActive() { active_cnt++ } } if 0 == active_cnt { tabsize_chk[cur_ind].SetActive(true) } return } for j := 0; j < tabsize_cnt; j++ { if j != cur_ind { tabsize_chk[j].SetActive(false) } } options_set_tabsize(cur_ind + 1) }, nil) } tree_window := gtk.NewScrolledWindow(nil, nil) tree_window.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) inner_hpaned.Add1(tree_window) tree_window.Add(tree_view) outer_hpaned.Add2(search_view.window) text_window := gtk.NewScrolledWindow(nil, nil) text_window.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) view_vpaned.Add1(text_window) text_window.Add(source_view) error_window = gtk.NewScrolledWindow(nil, nil) error_window.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) view_vpaned.Add2(error_window) error_window.Add(error_view) inner_hpaned.Connect("size_request", func() { ohp_cb(outer_hpaned.GetPosition()) }, nil) view_vpaned.Connect("size_request", func() { ihp_cb(inner_hpaned.GetPosition()) }, nil) source_view.Connect("size_request", func() { vvp_cb(view_vpaned.GetPosition()) }, nil) outer_hpaned.SetPosition(opt.ohp_position) inner_hpaned.SetPosition(opt.ihp_position) view_vpaned.SetPosition(opt.vvp_position) main_window = gtk.NewWindow(gtk.WINDOW_TOPLEVEL) main_window.AddAccelGroup(accel_group) main_window.SetSizeRequest(400, 200) //minimum size main_window.Resize(opt.window_width, opt.window_height) main_window.Move(opt.window_x, opt.window_y) main_window.Connect("destroy", exit_cb, "") main_window.Connect("configure-event", window_event_cb, "") main_window.Add(vbox) // init_tabby blocks for some reason when is called after ShowAll. init_vars() main_window.ShowAll() error_window.SetVisible(opt.show_error) // Cannot be called before ShowAll. This is also not clear. file_switch_to(file_stack_pop()) stack_prev(&file_stack_max) if "" == cur_file { new_cb() } source_view.GrabFocus() }
func main() { gtk.Init(&os.Args) gdk.ThreadsInit() 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"}) button := gtk.NewButtonWithLabel("Update Timeline") button.SetTooltipMarkup("update <b>public timeline</b>") button.Clicked(func() { 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"]} gdk.ThreadsEnter() button.SetSensitive(false) gdk.ThreadsLeave() go func() { ts, err := twitterstream.Open(client, cred, "https://stream.twitter.com/1/statuses/filter.json", url.Values{"track": {"picplz,instagr"}}) if err != nil { println(err.Error()) return } for ts.Err() == nil { t := tweet{} if err := ts.UnmarshalNext(&t); err != nil { fmt.Println("error reading tweet: ", err) continue } var iter gtk.TextIter pixbufbytes, resp := readURL(t.User.ProfileImageUrl) gdk.ThreadsEnter() buffer.GetStartIter(&iter) if resp != nil { buffer.InsertPixbuf(&iter, bytes2pixbuf(pixbufbytes, resp.Header.Get("Content-Type"))) } gdk.ThreadsLeave() gdk.ThreadsEnter() buffer.Insert(&iter, " ") buffer.InsertWithTag(&iter, t.User.ScreenName, tag) buffer.Insert(&iter, ":"+t.Text+"\n") gtk.MainIterationDo(false) gdk.ThreadsLeave() } }() }) vbox.PackEnd(button, false, false, 0) window.Add(vbox) window.SetSizeRequest(800, 500) window.ShowAll() gdk.ThreadsEnter() gtk.Main() gdk.ThreadsLeave() }
func main() { flag.Parse() runtime.GOMAXPROCS(runtime.NumCPU()) common.SetDefaultGtkTheme() machinePassword = uuid.New()[:4] clremoton = newClient(&remoton.Client{Prefix: "/remoton", TLSConfig: &tls.Config{}}) sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGABRT, syscall.SIGKILL, syscall.SIGTERM) go func() { <-sigs clremoton.Terminate() }() gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetPosition(gtk.WIN_POS_CENTER) window.SetTitle("REMOTON CLIENT") window.Connect("destroy", func(ctx *glib.CallbackContext) { gtk.MainQuit() clremoton.Terminate() }, "quit") window.SetIcon(common.GetIconGdkPixbuf()) appLayout := gtk.NewVBox(false, 1) menu := gtk.NewMenuBar() appLayout.Add(menu) cascademenu := gtk.NewMenuItemWithMnemonic("_Help") menu.Append(cascademenu) submenu := gtk.NewMenu() cascademenu.SetSubmenu(submenu) menuitem := gtk.NewMenuItemWithMnemonic("_About") menuitem.Connect("activate", func() { dialog := common.GtkAboutDialog() dialog.SetProgramName("Client Desktop") dialog.SetComments("Share your desktop secure") dialog.Run() dialog.Destroy() }) submenu.Append(menuitem) hpaned := gtk.NewHPaned() appLayout.Add(hpaned) statusbar := gtk.NewStatusbar() contextID := statusbar.GetContextId("remoton-desktop-client") //--- //CONTROL //--- frameControl := gtk.NewFrame("Controls") controlBox := gtk.NewVBox(false, 1) frameControl.Add(controlBox) controlBox.Add(gtk.NewLabel("MACHINE ID")) machineIDEntry := gtk.NewEntry() machineIDEntry.SetEditable(false) controlBox.Add(machineIDEntry) machineAuthEntry := gtk.NewEntry() machineAuthEntry.SetEditable(false) controlBox.Add(machineAuthEntry) controlBox.Add(gtk.NewLabel("Server")) serverEntry := gtk.NewEntry() serverEntry.SetText("127.0.0.1:9934") if os.Getenv("REMOTON_SERVER") != "" { serverEntry.SetText(os.Getenv("REMOTON_SERVER")) serverEntry.SetEditable(false) } controlBox.Add(serverEntry) controlBox.Add(gtk.NewLabel("Auth Server")) authServerEntry := gtk.NewEntry() authServerEntry.SetText("public") controlBox.Add(authServerEntry) var getCertFilename func() string localCert := filepath.Join(filepath.Dir(os.Args[0]), "cert.pem") if _, err := os.Stat(localCert); err == nil || os.IsExist(err) { controlBox.Add(gtk.NewLabel("Cert local")) getCertFilename = func() string { return localCert } } else if os.Getenv("REMOTON_CERT_FILE") != "" { controlBox.Add(gtk.NewLabel("Cert enviroment")) getCertFilename = func() string { return os.Getenv("REMOTON_CERT_FILE") } } else { btnCert := gtk.NewFileChooserButton("Cert", gtk.FILE_CHOOSER_ACTION_OPEN) getCertFilename = btnCert.GetFilename controlBox.Add(btnCert) } btnSrv := gtk.NewButtonWithLabel("Start") clremoton.VNC.OnConnection(func(addr net.Addr) { statusbar.Push(contextID, "Someone connected") log.Println("New connection from:" + addr.String()) }) btnSrv.Clicked(func() { if *insecure { clremoton.SetInsecure() } else { certPool, err := common.GetRootCAFromFile(getCertFilename()) if err != nil { dialogError(window, err) return } clremoton.SetCertPool(certPool) } if !clremoton.Started() { log.Println("starting remoton") machinePassword = uuid.New()[:4] err := clremoton.Start(serverEntry.GetText(), authServerEntry.GetText(), machinePassword) if err != nil { dialogError(btnSrv.GetTopLevelAsWindow(), err) statusbar.Push(contextID, "Failed") } else { btnSrv.SetLabel("Stop") machineIDEntry.SetText(clremoton.MachineID()) machineAuthEntry.SetText(machinePassword) statusbar.Push(contextID, "Connected") } } else { clremoton.Stop() btnSrv.SetLabel("Start") machineIDEntry.SetText("") machineAuthEntry.SetText("") statusbar.Push(contextID, "Stopped") } }) controlBox.Add(btnSrv) //--- // CHAT //--- frameChat := gtk.NewFrame("Chat") chatBox := gtk.NewVBox(false, 1) frameChat.Add(chatBox) swinChat := gtk.NewScrolledWindow(nil, nil) chatHistory := gtk.NewTextView() clremoton.Chat.OnRecv(func(msg string) { chatHistoryRecv(chatHistory, msg) }) swinChat.Add(chatHistory) chatEntry := gtk.NewEntry() chatEntry.Connect("key-press-event", func(ctx *glib.CallbackContext) { arg := ctx.Args(0) event := *(**gdk.EventKey)(unsafe.Pointer(&arg)) if event.Keyval == gdk.KEY_Return { msgToSend := chatEntry.GetText() clremoton.Chat.Send(msgToSend) chatHistorySend(chatHistory, msgToSend) chatEntry.SetText("") } }) chatBox.Add(chatEntry) chatBox.Add(swinChat) hpaned.Pack1(frameControl, false, false) hpaned.Pack2(frameChat, false, true) appLayout.Add(statusbar) window.Add(appLayout) window.ShowAll() gtk.Main() }
func main() { gtk.Init(&os.Args) gdk.ThreadsInit() 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"}) button := gtk.NewButtonWithLabel("Update Timeline") button.SetTooltipMarkup("update <b>public timeline</b>") button.Clicked(func() { go func() { gdk.ThreadsEnter() button.SetSensitive(false) gdk.ThreadsLeave() r, err := http.Get("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=go_nuts") if err == nil { var b []byte if r.ContentLength == -1 { b, err = ioutil.ReadAll(r.Body) } else { b = make([]byte, r.ContentLength) _, err = io.ReadFull(r.Body, b) } if err != nil { fmt.Println(err) return } var j interface{} err = json.NewDecoder(bytes.NewBuffer(b)).Decode(&j) if err != nil { fmt.Println(err) return } arr := j.([]interface{}) for i := 0; i < len(arr); i++ { data := arr[i].(map[string]interface{}) icon := data["user"].(map[string]interface{})["profile_image_url"].(string) var iter gtk.TextIter pixbufbytes, resp := readURL(icon) gdk.ThreadsEnter() buffer.GetEndIter(&iter) if resp != nil { buffer.InsertPixbuf(&iter, bytes2pixbuf(pixbufbytes, resp.Header.Get("Content-Type"))) } gdk.ThreadsLeave() name := data["user"].(map[string]interface{})["screen_name"].(string) text := data["text"].(string) gdk.ThreadsEnter() buffer.Insert(&iter, " ") buffer.InsertWithTag(&iter, name, tag) buffer.Insert(&iter, ":"+text+"\n") gtk.MainIterationDo(false) gdk.ThreadsLeave() } } else { fmt.Println(err) } button.SetSensitive(true) }() }) vbox.PackEnd(button, false, false, 0) window.Add(vbox) window.SetSizeRequest(800, 500) window.ShowAll() gdk.ThreadsEnter() gtk.Main() gdk.ThreadsLeave() }
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() }