Esempio n. 1
0
func CreateFont(size int, driver gxui.Driver) gxui.Font {
	font, err := driver.CreateFont(gxfont.Monospace, size)
	if err != nil {
		panic(err)
	}
	return font
}
Esempio n. 2
0
func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)

	label := theme.CreateLabel()
	label.SetText("This is a progress bar:")

	progressBar := theme.CreateProgressBar()
	progressBar.SetDesiredSize(math.Size{W: 400, H: 20})
	progressBar.SetTarget(100)

	layout := theme.CreateLinearLayout()
	layout.AddChild(label)
	layout.AddChild(progressBar)
	layout.SetHorizontalAlignment(gxui.AlignCenter)

	window := theme.CreateWindow(800, 600, "Progress bar")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(layout)
	window.OnClose(driver.Terminate)

	progress := 0
	pause := time.Millisecond * 500
	var timer *time.Timer
	timer = time.AfterFunc(pause, func() {
		driver.Call(func() {
			progress = (progress + 3) % progressBar.Target()
			progressBar.SetProgress(progress)
			timer.Reset(pause)
		})
	})
}
Esempio n. 3
0
File: main.go Progetto: ww24/goss
func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)
	img := theme.CreateImage()

	// mx := source.Bounds().Max
	// fmt.Println(mx)

	window := theme.CreateWindow(500, 500, "Screenshot")
	size := window.Viewport().SizePixels()
	fmt.Println(size)
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(img)

	go func() {
		for {
			source, err := goss.Capture()
			if err != nil {
				fmt.Fprintln(os.Stderr, "Failed to capture screenshot.")
				os.Exit(1)
			}

			rgba := image.NewRGBA(source.Bounds())
			draw.Draw(rgba, source.Bounds(), source, image.ZP, draw.Src)
			texture := driver.CreateTexture(rgba, 1)
			img.SetTexture(texture)
		}
	}()

	window.OnClose(driver.Terminate)
}
func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)

	window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))

	image := theme.CreateImage()

	ticker := time.NewTicker(time.Millisecond * 15)
	pendulum := &mathematicalPendulum{}
	pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}

	go func() {
		for _ = range ticker.C {
			canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
			canvas.Clear(gxui.White)

			draw(pendulum, canvas, 0, 0)
			draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)

			canvas.Complete()
			driver.Call(func() {
				image.SetCanvas(canvas)
			})
		}
	}()

	window.AddChild(image)

	window.OnClose(ticker.Stop)
	window.OnClose(driver.Terminate)
}
Esempio n. 5
0
File: main.go Progetto: gbember/gt
//画行走路线
func drawWalkPath(window gxui.Window, theme gxui.Theme, driver gxui.Driver, x1, y1, x2, y2 int64) {
	ps, isWalk := nm.FindPath(nmastar, x1, y1, x2, y2)
	if !isWalk {
		return
	}
	canvas := driver.CreateCanvas(math.Size{W: int(nmj.Width), H: int(nmj.Heigth)})

	var polys []gxui.PolygonVertex
	for i := 0; i < len(ps); i++ {

		polys = append(polys,
			gxui.PolygonVertex{
				Position: math.Point{
					int(ps[i].X),
					int(ps[i].Y),
				}})
	}
	canvas.DrawLines(polys, gxui.CreatePen(2, gxui.Green))

	canvas.Complete()
	image := theme.CreateImage()
	image.SetCanvas(canvas)
	window.AddChild(image)

}
Esempio n. 6
0
func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)

	window := theme.CreateWindow(800, 600, "Hi")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))

	fontData, err := ioutil.ReadFile(sysFont("幼圆")) //this font comes from windows
	if err != nil {
		log.Fatalf("error reading font: %v", err)
	}
	font, err := driver.CreateFont(fontData, 50)
	if err != nil {
		panic(err)
	}
	label := theme.CreateLabel()
	label.SetFont(font)
	label.SetColor(gxui.Red50)
	label.SetText("支持一下中文")

	button := theme.CreateButton()
	button.SetText("点我一下")

	window.AddChild(label)
	window.AddChild(button)

	window.OnClose(driver.Terminate)

}
Esempio n. 7
0
func appMain(driver gxui.Driver) {
	file := "./img/block.bmp"
	f, err := os.Open(file)
	if err != nil {
		fmt.Printf("Failed to open image '%s': %v\n", file, err)
		os.Exit(1)
	}

	source, _, err := image.Decode(f)
	if err != nil {
		fmt.Printf("Failed to read image '%s': %v\n", file, err)
		os.Exit(1)
	}

	theme := flags.CreateTheme(driver)
	img := theme.CreateImage()

	//mx := source.Bounds().Max
	window := theme.CreateWindow(1000, 1000, "Tetris")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(img)

	rgba := image.NewRGBA(source.Bounds())
	draw.Draw(rgba, source.Bounds(), source, image.ZP, draw.Src)
	texture := driver.CreateTexture(rgba, 1)
	img.SetTexture(texture)

	window.OnClose(driver.Terminate)
}
Esempio n. 8
0
func route(driver gxui.Driver, src_id, dest_id int32, src, dest Point3) (canvas gxui.Canvas) {
	defer func() {
		canvas.Complete()
	}()
	canvas = driver.CreateCanvas(math.Size{W: 800, H: 600})
	t0 := time.Now()
	// Phase 1. Use Dijkstra to find shortest path on Triangles
	path := dijkstra.Run(src_id)

	// Phase 2.  construct path indices
	// Check if this path include src & dest
	path_triangle := [][3]int32{triangles[dest_id]}
	prev_id := dest_id
	for {
		cur_id, ok := path[prev_id]
		if !ok {
			return canvas
		}
		path_triangle = append([][3]int32{triangles[cur_id]}, path_triangle...)
		if cur_id == src_id {
			break
		}
		prev_id = cur_id
	}

	// Phase 3. use Navmesh to construct line
	start, end := &Point3{X: src.X, Y: src.Y}, &Point3{X: dest.X, Y: dest.Y}
	nm := NavMesh{}
	trilist := TriangleList{vertices, path_triangle}
	r, _ := nm.Route(trilist, start, end)
	log.Println("navmesh time:", time.Now().Sub(t0))

	var poly []gxui.PolygonVertex
	poly = append(poly,
		gxui.PolygonVertex{
			Position: math.Point{
				int(SCALE_FACTOR * start.X),
				int(SCALE_FACTOR * start.Y),
			}})

	for k := range r.Line {
		poly = append(poly,
			gxui.PolygonVertex{
				Position: math.Point{
					int(SCALE_FACTOR * r.Line[k].X),
					int(SCALE_FACTOR * r.Line[k].Y),
				}})
	}
	poly = append(poly,
		gxui.PolygonVertex{
			Position: math.Point{
				int(SCALE_FACTOR * end.X),
				int(SCALE_FACTOR * end.Y),
			}})

	canvas.DrawLines(poly, gxui.CreatePen(2, gxui.Green))
	return
}
Esempio n. 9
0
File: theme.go Progetto: langxj/gxui
func CreateTheme(driver gxui.Driver) gxui.Theme {
	defaultFont, err := driver.CreateFont(gxfont.Default, 12)
	if err == nil {
		defaultFont.LoadGlyphs(32, 126)
	} else {
		fmt.Printf("Warning: Failed to load default font - %v\n", err)
	}

	defaultMonospaceFont, err := driver.CreateFont(gxfont.Monospace, 12)
	if err == nil {
		defaultFont.LoadGlyphs(32, 126)
	} else {
		fmt.Printf("Warning: Failed to load default monospace font - %v\n", err)
	}

	scrollBarRailDefaultBg := gxui.Black
	scrollBarRailDefaultBg.A = 0.7

	scrollBarRailOverBg := gxui.Gray20
	scrollBarRailOverBg.A = 0.7

	neonBlue := gxui.ColorFromHex(0xFF5C8CFF)
	focus := gxui.ColorFromHex(0xA0C4D6FF)

	return &basic.Theme{
		DriverInfo:               driver,
		DefaultFontInfo:          defaultFont,
		DefaultMonospaceFontInfo: defaultMonospaceFont,
		WindowBackground:         gxui.Black,

		//                                   fontColor    brushColor   penColor
		BubbleOverlayStyle:        basic.CreateStyle(gxui.Gray80, gxui.Gray20, gxui.Gray40, 1.0),
		ButtonDefaultStyle:        basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray20, 1.0),
		ButtonOverStyle:           basic.CreateStyle(gxui.Gray90, gxui.Gray15, gxui.Gray50, 1.0),
		ButtonPressedStyle:        basic.CreateStyle(gxui.Gray20, gxui.Gray70, gxui.Gray30, 1.0),
		CodeSuggestionListStyle:   basic.CreateStyle(gxui.Gray80, gxui.Gray20, gxui.Gray10, 1.0),
		DropDownListDefaultStyle:  basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray20, 1.0),
		DropDownListOverStyle:     basic.CreateStyle(gxui.Gray80, gxui.Gray15, gxui.Gray50, 1.0),
		FocusedStyle:              basic.CreateStyle(gxui.Gray80, gxui.Transparent, focus, 1.0),
		HighlightStyle:            basic.CreateStyle(gxui.Gray80, gxui.Transparent, neonBlue, 2.0),
		LabelStyle:                basic.CreateStyle(gxui.Gray80, gxui.Transparent, gxui.Transparent, 0.0),
		PanelBackgroundStyle:      basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray15, 1.0),
		ScrollBarBarDefaultStyle:  basic.CreateStyle(gxui.Gray80, gxui.Gray30, gxui.Gray40, 1.0),
		ScrollBarBarOverStyle:     basic.CreateStyle(gxui.Gray80, gxui.Gray50, gxui.Gray60, 1.0),
		ScrollBarRailDefaultStyle: basic.CreateStyle(gxui.Gray80, scrollBarRailDefaultBg, gxui.Transparent, 1.0),
		ScrollBarRailOverStyle:    basic.CreateStyle(gxui.Gray80, scrollBarRailOverBg, gxui.Gray20, 1.0),
		SplitterBarDefaultStyle:   basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray10, 1.0),
		SplitterBarOverStyle:      basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray50, 1.0),
		TabActiveHighlightStyle:   basic.CreateStyle(gxui.Gray90, neonBlue, neonBlue, 0.0),
		TabDefaultStyle:           basic.CreateStyle(gxui.Gray80, gxui.Gray30, gxui.Gray40, 1.0),
		TabOverStyle:              basic.CreateStyle(gxui.Gray90, gxui.Gray30, gxui.Gray50, 1.0),
		TabPressedStyle:           basic.CreateStyle(gxui.Gray20, gxui.Gray70, gxui.Gray30, 1.0),
		TextBoxDefaultStyle:       basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray20, 1.0),
		TextBoxOverStyle:          basic.CreateStyle(gxui.Gray80, gxui.Gray10, gxui.Gray50, 1.0),
	}
}
Esempio n. 10
0
func appMain(driver gxui.Driver) {
	theme = light.CreateTheme(driver)
	window = theme.CreateWindow(800, 600, "Snake")

	playGround = field.Create(800, 600, 20, 20)
	sn = snake.Create(math.Point{X: 380, Y: 200}, math.Point{X: 380, Y: 280}, 20)

	drawScene(driver)
	fmt.Println(sn.Direction())

	window.OnKeyUp(func(event gxui.KeyboardEvent) {
		dir := sn.Direction()
		key := event.Key

		switch {
		case key == gxui.KeyRight && dir == snake.Top:
			sn.TurnRight()
		case key == gxui.KeyRight && dir == snake.Bottom:
			sn.TurnLeft()
		case key == gxui.KeyLeft && dir == snake.Top:
			sn.TurnLeft()
		case key == gxui.KeyLeft && dir == snake.Bottom:
			sn.TurnRight()
		case key == gxui.KeyUp && dir == snake.Left:
			sn.TurnRight()
		case key == gxui.KeyUp && dir == snake.Right:
			sn.TurnLeft()
		case key == gxui.KeyDown && dir == snake.Left:
			sn.TurnLeft()
		case key == gxui.KeyDown && dir == snake.Right:
			sn.TurnRight()

		}
	})

	ticker := time.NewTicker(time.Millisecond * 200)

	go func() {
		for _ = range ticker.C {
			driver.Call(func() {
				(&sn).Move()
				drawScene(driver)
			})
		}
	}()

	window.OnClose(func() {
		driver.Terminate()
		ticker.Stop()
	})

}
Esempio n. 11
0
func drawScene(driver gxui.Driver) {
	window.RemoveAll()

	canvas = driver.CreateCanvas(math.Size{W: 800, H: 600})

	sn.Draw(canvas)
	playGround.Draw(canvas)

	canvas.Complete()
	image := theme.CreateImage()
	image.SetCanvas(canvas)
	window.AddChild(image)
}
Esempio n. 12
0
File: main.go Progetto: gbember/gt
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)
	width := int(nmj.Width)
	height := int(nmj.Heigth)

	window := theme.CreateWindow(width, height, "navmesh")
	canvas := driver.CreateCanvas(math.Size{W: width, H: height})

	ps := nmj.Points

	// mouse
	isStart := true
	x1, y1, x2, y2 := int64(0), int64(0), int64(0), int64(0)

	window.OnMouseDown(func(me gxui.MouseEvent) {
		if nm.IsWalkOfPoint(navmesh.Point{X: int64(me.Point.X), Y: int64(me.Point.Y)}) {
			if isStart {
				x1 = int64(me.Point.X)
				y1 = int64(me.Point.Y)
			} else {
				x2 = int64(me.Point.X)
				y2 = int64(me.Point.Y)
			}
			if !isStart {
				drawWalkPath(window, theme, driver, x1, y1, x2, y2)
			}
			isStart = !isStart
		}
	})

	// draw mesh
	for i := 0; i < len(ps); i++ {
		polys := make([]gxui.PolygonVertex, 0, len(ps[i]))
		for j := 0; j < len(ps[i]); j++ {
			polys = append(polys, gxui.PolygonVertex{
				Position: math.Point{
					int(ps[i][j].X),
					int(ps[i][j].Y),
				}})
		}
		//		canvas.DrawPolygon(polys, gxui.CreatePen(2, gxui.Gray80), gxui.CreateBrush(gxui.Gray40))
		canvas.DrawPolygon(polys, gxui.CreatePen(2, gxui.Red), gxui.CreateBrush(gxui.Yellow))
	}

	canvas.Complete()
	image := theme.CreateImage()
	image.SetCanvas(canvas)
	window.AddChild(image)
	window.OnClose(driver.Terminate)
}
Esempio n. 13
0
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	// ┌───────┐║┌───────┐
	// │       │║│       │
	// │   A   │║│   B   │
	// │       │║│       │
	// └───────┘║└───────┘
	// ═══════════════════
	// ┌───────┐║┌───────┐
	// │       │║│       │
	// │   C   │║│   D   │
	// │       │║│       │
	// └───────┘║└───────┘

	ftData, err := ioutil.ReadFile("static/font/simhei.ttf")
	if err != nil {
		log.Println(err)
	}
	ft, err := driver.CreateFont(ftData, 20)
	if err != nil {
		log.Println(err)
	}
	menu := theme.CreateLinearLayout()
	menu.SetDirection(gxui.LeftToRight)
	logo_label := theme.CreateLabel()
	logo_label.SetColor(gxui.White)
	logo_label.SetFont(ft)
	logo_label.SetText("百度盘")
	logo_label.SetSize(math.Size{300, 200})
	menu.AddChild(logo_label)

	splitterCD := theme.CreateSplitterLayout()
	splitterCD.SetOrientation(gxui.Horizontal)
	splitterCD.AddChild(panelHolder("C", theme))
	splitterCD.AddChild(panelHolder("D", theme))

	vSplitter := theme.CreateSplitterLayout()
	vSplitter.SetOrientation(gxui.Vertical)
	vSplitter.AddChild(menu)
	vSplitter.AddChild(splitterCD)

	window := theme.CreateWindow(800, 600, "百度盘")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(vSplitter)
	window.OnClose(driver.Terminate)
}
Esempio n. 14
0
File: window.go Progetto: 4ydx/gxui
func (w *Window) Init(outer WindowOuter, driver gxui.Driver, width, height int, title string) {
	w.Attachable.Init(outer)
	w.BackgroundBorderPainter.Init(outer)
	w.Container.Init(outer)
	w.Paddable.Init(outer)
	w.PaintChildren.Init(outer)
	w.outer = outer
	w.driver = driver

	w.onClose = gxui.CreateEvent(func() {})
	w.onResize = gxui.CreateEvent(func() {})
	w.onMouseMove = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onMouseEnter = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onMouseExit = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onMouseDown = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onMouseUp = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onMouseScroll = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onKeyDown = gxui.CreateEvent(func(gxui.KeyboardEvent) {})
	w.onKeyUp = gxui.CreateEvent(func(gxui.KeyboardEvent) {})
	w.onKeyRepeat = gxui.CreateEvent(func(gxui.KeyboardEvent) {})
	w.onKeyStroke = gxui.CreateEvent(func(gxui.KeyStrokeEvent) {})

	w.onClick = gxui.CreateEvent(func(gxui.MouseEvent) {})
	w.onDoubleClick = gxui.CreateEvent(func(gxui.MouseEvent) {})

	w.focusController = gxui.CreateFocusController(outer)
	w.mouseController = gxui.CreateMouseController(outer, w.focusController)
	w.keyboardController = gxui.CreateKeyboardController(outer)

	w.onResize.Listen(func() {
		w.outer.LayoutChildren()
		w.Draw()
	})

	w.SetBorderPen(gxui.TransparentPen)

	w.setViewport(driver.CreateWindowedViewport(width, height, title))

	// Window starts shown
	w.Attach()

	// Interface compliance test
	_ = gxui.Window(w)
}
Esempio n. 15
0
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	canvas := driver.CreateCanvas(math.Size{W: 500, H: 300})

	layout := theme.CreateLinearLayout()
	layout.SetSizeMode(gxui.Fill)
	layout.SetDirection(gxui.TopToBottom)

	buttonsLayout := theme.CreateLinearLayout()
	buttonsLayout.SetSizeMode(gxui.Fill)
	buttonsLayout.SetDirection(gxui.LeftToRight)

	button := func(name string, action func()) gxui.Button {
		b := theme.CreateButton()
		b.SetText(name)
		b.OnClick(func(gxui.MouseEvent) { action() })
		return b
	}

	okayButton := button("Okay", func() { log.Println("Okay") })
	buttonsLayout.AddChild(okayButton)
	cancelButton := button("Cancel", func() { log.Println("Cancel") })
	buttonsLayout.AddChild(cancelButton)

	drawPlot(canvas)
	canvas.Complete()

	image := theme.CreateImage()
	image.SetCanvas(canvas)

	window := theme.CreateWindow(800, 600, "bview")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
	layout.AddChild(buttonsLayout)
	layout.AddChild(image)
	window.AddChild(layout)
	window.OnClose(driver.Terminate)
	window.SetPadding(math.Spacing{L: 10, T: 10, R: 10, B: 10})

	window.OnResize(func() { log.Println(layout.Children().String()) })

}
Esempio n. 16
0
File: main.go Progetto: langxj/gxui
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)
	window := theme.CreateWindow(800, 600, "Polygon")
	window.SetScale(flags.DefaultScaleFactor)

	canvas := driver.CreateCanvas(math.Size{W: 1000, H: 1000})
	drawStar(canvas, math.Point{X: 100, Y: 100}, 50, 0.2, 6)
	drawStar(canvas, math.Point{X: 650, Y: 170}, 70, 0.5, 7)
	drawStar(canvas, math.Point{X: 40, Y: 300}, 20, 0, 5)
	drawStar(canvas, math.Point{X: 410, Y: 320}, 25, 0.9, 5)
	drawStar(canvas, math.Point{X: 220, Y: 520}, 45, 0, 6)

	drawMoon(canvas, math.Point{X: 400, Y: 300}, 200)
	canvas.Complete()

	image := theme.CreateImage()
	image.SetCanvas(canvas)
	window.AddChild(image)

	window.OnClose(driver.Terminate)
}
Esempio n. 17
0
func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)

	canvas := driver.CreateCanvas(math.Size{W: 800, H: 600})

	for i := 0; i < 800; i++ {
		var fy = maths.Sin(float64(i) * (maths.Pi / 180))
		y := (int(fy*100) + 240)
		plot(canvas, i, y)
	}

	canvas.Complete()

	image := theme.CreateImage()
	image.SetCanvas(canvas)

	window := theme.CreateWindow(800, 600, "")
	window.AddChild(image)
	window.OnClose(driver.Terminate)

}
Esempio n. 18
0
func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)
	window := theme.CreateWindow(800, 600, "Polygon")

	container := theme.CreateLinearLayout()

	//	texture := driver.CreateTexture(getImage(cacheDir, tweet.User.ProfileImageURL), 96)
	f, err := os.Open("data/icont19.png")
	if err != nil {
		log.Fatalln(err)
	}
	defer f.Close()
	im, _, err := image.Decode(f)
	if err != nil {
		log.Fatalln(err)
	}

	for i := 0; i < 100; i++ {
		pict := theme.CreateImage()
		texture := driver.CreateTexture(im, 96)
		texture.SetFlipY(true)
		pict.SetTexture(texture)
		pict.SetExplicitSize(math.Size{32, 32})
		pict.SetMargin(math.CreateSpacing(4))
		container.AddChild(pict)
	}

	label := theme.CreateLabel()
	label.SetText("hogehogehoge")
	label.SetMargin(math.CreateSpacing(200))
	container.AddChild(label)

	window.OnClose(driver.Terminate)

	window.AddChild(container)

	gxui.EventLoop(driver)
}
Esempio n. 19
0
func appMain(driver gxui.Driver) {

	d = driver
	source := image.Image(newMandelbrot())

	theme := flags.CreateTheme(driver)

	mx := source.Bounds().Max

	img = theme.CreateImage()

	window = theme.CreateWindow(mx.X, mx.Y, "Image viewer")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(img)

	rgba := image.NewRGBA(source.Bounds())
	draw.Draw(rgba, source.Bounds(), source, image.ZP, draw.Src)
	texture = driver.CreateTexture(rgba, 1)
	img.SetTexture(texture)

	window.OnClick(windowOnClickHandler)
	window.OnClose(driver.Terminate)
}
Esempio n. 20
0
File: main.go Progetto: liulnn/gxui
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	font, err := driver.CreateFont(gxfont.Default, 75)
	if err != nil {
		panic(err)
	}

	window := theme.CreateWindow(380, 100, "Hi")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))

	label := theme.CreateLabel()
	label.SetFont(font)
	label.SetText("Hello world")

	window.AddChild(label)

	ticker := time.NewTicker(time.Millisecond * 30)
	go func() {
		phase := float32(0)
		for _ = range ticker.C {
			c := gxui.Color{
				R: 0.75 + 0.25*math.Cosf((phase+0.000)*math.TwoPi),
				G: 0.75 + 0.25*math.Cosf((phase+0.333)*math.TwoPi),
				B: 0.75 + 0.25*math.Cosf((phase+0.666)*math.TwoPi),
				A: 0.50 + 0.50*math.Cosf(phase*10),
			}
			phase += 0.01
			driver.Call(func() {
				label.SetColor(c)
			})
		}
	}()

	window.OnClose(ticker.Stop)
	window.OnClose(driver.Terminate)
}
Esempio n. 21
0
File: main.go Progetto: langxj/gxui
func appMain(driver gxui.Driver) {
	args := flag.Args()
	if len(args) != 1 {
		fmt.Print("usage: image_viewer image-path\n")
		os.Exit(1)
	}

	file := args[0]
	f, err := os.Open(file)
	if err != nil {
		fmt.Printf("Failed to open image '%s': %v\n", file, err)
		os.Exit(1)
	}

	source, _, err := image.Decode(f)
	if err != nil {
		fmt.Printf("Failed to read image '%s': %v\n", file, err)
		os.Exit(1)
	}

	theme := flags.CreateTheme(driver)
	img := theme.CreateImage()

	mx := source.Bounds().Max
	window := theme.CreateWindow(mx.X, mx.Y, "Image viewer")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(img)

	// Copy the image to a RGBA format before handing to a gxui.Texture
	rgba := image.NewRGBA(source.Bounds())
	draw.Draw(rgba, source.Bounds(), source, image.ZP, draw.Src)
	texture := driver.CreateTexture(rgba, 1)
	img.SetTexture(texture)

	window.OnClose(driver.Terminate)
}
Esempio n. 22
0
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	font, err := driver.CreateFont(gxfont.Default, 75)
	if err != nil {
		panic(err)
	}

	window := theme.CreateWindow(800, 480, "Привет")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
	window.SetBorderPen(gxui.Pen{Width: 5, Color: gxui.Yellow})

	f, err := os.Open("wallpaper.jpg")
	if err != nil {
		fmt.Printf("Failed to open image %v\n", err)
		os.Exit(1)
	}

	source, _, err := image.Decode(f)
	if err != nil {
		fmt.Printf("Failed to open image %v\n", err)
		os.Exit(2)
	}

	wallpaper := theme.CreateImage()
	window.AddChild(wallpaper)

	// Copy the image to a RGBA format before handing to a gxui.Texture
	rgba := image.NewRGBA(source.Bounds())
	draw.Draw(rgba, source.Bounds(), source, image.ZP, draw.Src)
	texture := driver.CreateTexture(rgba, 1)
	wallpaper.SetTexture(texture)

	layout := theme.CreateLinearLayout()
	layout.SetDirection(gxui.TopToBottom)
	window.AddChild(layout)

	label := theme.CreateLabel()
	label.SetFont(font)
	label.SetText("Здравствуй мир")
	label.OnMouseMove(func(e gxui.MouseEvent) {
		fmt.Printf("X=%d; Y=%d\n", e.Point.X, e.Point.Y)
	})
	layout.AddChild(label)

	lTimer := theme.CreateLabel()
	lTimer.SetFont(font)
	lTimer.SetColor(gxui.Green30)
	layout.AddChild(lTimer)

	button := theme.CreateButton()
	button.SetText("Exit")
	button.SetPadding(math.Spacing{20, 10, 20, 10})
	button.SetMargin(math.Spacing{20, 10, 20, 10})
	button.OnClick(func(e gxui.MouseEvent) {
		window.Close()
	})
	layout.AddChild(button)

	ticker := time.NewTicker(time.Millisecond * 30)
	go func() {
		phase := float32(0)
		for _ = range ticker.C {
			c := gxui.Color{
				R: 0.75 + 0.25*math.Cosf((phase+0.000)*math.TwoPi),
				G: 0.75 + 0.25*math.Cosf((phase+0.333)*math.TwoPi),
				B: 0.75 + 0.25*math.Cosf((phase+0.666)*math.TwoPi),
				A: 0.50 + 0.50*math.Cosf(phase*10),
			}
			phase += 0.01
			driver.Call(func() {
				label.SetColor(c)
			})
		}
	}()

	ticker2 := time.NewTicker(time.Millisecond * 100)
	go func() {
		for t := range ticker.C {
			driver.Call(func() {
				lTimer.SetText(t.Format(time.Stamp))
			})
		}
	}()

	window.OnClose(ticker.Stop)
	window.OnClose(ticker2.Stop)
	window.OnClose(driver.Terminate)
}
Esempio n. 23
0
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	font, err := driver.CreateFont(gxfont.Default, H1_FONT_SIZE)
	catch(err)

	window := theme.CreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, APP_TITLE)
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.White))
	window.SetScale(flags.DefaultScaleFactor)
	window.SetPadding(math.Spacing{L: 10, R: 10, T: 10, B: 10})

	layout := theme.CreateLinearLayout()
	layout.SetSizeMode(gxui.Fill)
	layout.SetHorizontalAlignment(gxui.AlignCenter)
	layout.HorizontalAlignment().AlignCenter()

	fullscreenButton := theme.CreateButton()
	fullscreenButton.SetText("Make Fullscreen")
	fullscreenButton.OnClick(func(ev gxui.MouseEvent) {
		fullscreen := !window.Fullscreen()
		window.SetFullscreen(fullscreen)

		if fullscreen {
			fullscreenButton.SetText("Make Windowed")
		} else {
			fullscreenButton.SetText("Make Fullscreen")
		}
	})

	h1Title := theme.CreateLabel()
	h1Title.SetFont(font)
	h1Title.SetColor(gxui.Color{R: 0, G: 0, B: 0, A: 1})

	KinopoiskLabel := theme.CreateLabel()
	KinopoiskLabel.SetFont(font)
	KinopoiskLabel.SetColor(gxui.Color{R: 0, G: 0, B: 0, A: 1})

	ImdbLabel := theme.CreateLabel()
	ImdbLabel.SetFont(font)
	ImdbLabel.SetColor(gxui.Color{R: 0, G: 0, B: 0, A: 1})

	// https://github.com/google/gxui/blob/master/samples/image_viewer/main.go
	img := theme.CreateImage()

	getFilmButton := theme.CreateButton()
	getFilmButton.SetText("Get Film!")
	getFilmButton.OnClick(func(ev gxui.MouseEvent) {
		getFilm(driver, h1Title, KinopoiskLabel, ImdbLabel, img)
	})

	getFilm(driver, h1Title, KinopoiskLabel, ImdbLabel, img)

	layout.AddChild(fullscreenButton)
	layout.AddChild(h1Title)
	layout.AddChild(KinopoiskLabel)
	layout.AddChild(ImdbLabel)
	layout.AddChild(getFilmButton)
	layout.AddChild(img)
	window.AddChild(layout)

	window.OnClose(driver.Terminate)
}
Esempio n. 24
0
func MainWindow(driver gxui.Driver) {
	theme = dark.CreateTheme(driver)

	fontData, err := ioutil.ReadFile("./fonts/Microsoft Yahei.ttf")
	if err != nil {
		log.Fatalf("error reading font: %v", err)
	}
	font, err := driver.CreateFont(fontData, 20)
	if err != nil {
		panic(err)
	}
	theme.SetDefaultFont(font)

	headLayout := theme.CreateLinearLayout()
	headLayout.SetSizeMode(gxui.Fill)
	headLayout.SetHorizontalAlignment(gxui.AlignCenter)
	headLayout.SetDirection(gxui.TopToBottom)
	headLayout.SetSize(math.Size{W: 100, H: 50})

	label := theme.CreateLabel()
	label.SetMargin(math.CreateSpacing(10))
	label.SetText("豆瓣FM红心歌单下载")

	headLayout.AddChild(label)

	bodyLayout := theme.CreateLinearLayout()
	bodyLayout.SetSizeMode(gxui.Fill)
	bodyLayout.SetHorizontalAlignment(gxui.AlignCenter)
	bodyLayout.SetSize(math.Size{W: 100, H: 400})
	bodyLayout.SetDirection(gxui.TopToBottom)
	// bodyLayout.SetMargin(math.Spacing{T: 50})

	userHint := theme.CreateLabel()
	userHint.SetMargin(math.CreateSpacing(10))
	userHint.SetText("用户名")
	bodyLayout.AddChild(userHint)
	usernameField := theme.CreateTextBox()
	bodyLayout.AddChild(usernameField)

	passHint := theme.CreateLabel()
	passHint.SetMargin(math.CreateSpacing(10))
	passHint.SetText("密码")
	bodyLayout.AddChild(passHint)
	passwordField := theme.CreateTextBox()
	bodyLayout.AddChild(passwordField)

	footLayout := theme.CreateLinearLayout()
	footLayout.SetSizeMode(gxui.Fill)
	footLayout.SetHorizontalAlignment(gxui.AlignCenter)
	footLayout.SetDirection(gxui.TopToBottom)
	// footLayout.SetMargin(math.Spacing{T: 450})

	button := theme.CreateButton()
	button.SetText("登录并下载")
	button.OnClick(func(gxui.MouseEvent) {
		user := usernameField.Text()
		password := passwordField.Text()
		if user == "" || password == "" {
			return
		}
		label.SetText(user + "&" + password)
	})
	footLayout.AddChild(button)

	window := theme.CreateWindow(600, 800, "豆瓣FM下载器")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.White))

	window.AddChild(headLayout)
	window.AddChild(bodyLayout)
	window.AddChild(footLayout)

	window.OnClose(driver.Terminate)
	window.SetPadding(math.Spacing{L: 10, T: 10, R: 10, B: 10})
}
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)

	layout := theme.CreateLinearLayout()
	layout.SetSizeMode(gxui.Fill)

	addLabel := func(text string) {
		label := theme.CreateLabel()
		label.SetText(text)
		layout.AddChild(label)
	}

	addLabel("1. Fetch certificates from websites")
	addLabel("Insert IP or domain name here and press 'Fetch' button")

	urlTextBox := theme.CreateTextBox()
	urlTextBox.SetDesiredWidth(300)

	fetchButton := theme.CreateButton()
	fetchButton.SetText("Fetch")
	fetchButton.SetVisible(false)

	{
		lineLayout := theme.CreateLinearLayout()
		lineLayout.SetDirection(gxui.LeftToRight)
		lineLayout.AddChild(urlTextBox)
		lineLayout.AddChild(fetchButton)
		layout.AddChild(lineLayout)
	}

	statusLabel := theme.CreateLabel()
	statusLabel.SetMultiline(true)
	statusLabel.SetText("")
	layout.AddChild(statusLabel)

	certListAdapter := gxui.CreateDefaultAdapter()
	certList := theme.CreateList()
	certList.SetAdapter(certListAdapter)

	removeButton := theme.CreateButton()
	removeButton.SetText("Remove")

	{
		lineLayout := theme.CreateLinearLayout()
		lineLayout.SetDirection(gxui.LeftToRight)
		lineLayout.AddChild(certList)
		lineLayout.AddChild(removeButton)
		layout.AddChild(lineLayout)
	}

	addLabel("2. Select programmer serial port")

	portListAdapter := gxui.CreateDefaultAdapter()
	portList := theme.CreateList()
	portList.SetAdapter(portListAdapter)

	refreshButton := theme.CreateButton()
	refreshButton.SetText("Refresh List")

	{
		lineLayout := theme.CreateLinearLayout()
		lineLayout.SetDirection(gxui.LeftToRight)
		lineLayout.AddChild(portList)
		lineLayout.AddChild(refreshButton)
		layout.AddChild(lineLayout)
	}

	addLabel("3. Upload certificate to WiFi module")

	uploadButton := theme.CreateButton()
	uploadButton.SetText("Upload certificates")
	layout.AddChild(uploadButton)

	progressStatus := theme.CreateLabel()
	layout.AddChild(progressStatus)

	progressBar := theme.CreateProgressBar()
	size := math.MaxSize
	size.H = 20
	progressBar.SetDesiredSize(size)
	layout.AddChild(progressBar)

	// Business logic

	portSelected := false
	updateUploadButton := func() {
		visible := portSelected && certListAdapter.Count() > 0
		uploadButton.SetVisible(visible)
	}
	updateUploadButton()

	updateDownloadedCerts := func() {
		certListAdapter.SetItems(downloadedCerts)
		updateUploadButton()
	}

	downloadCert := func() {
		if uploading {
			return
		}
		url := urlTextBox.Text()
		if strings.Index(url, ":") == -1 {
			url += ":443"
		}
		data, err := certificates.EntryForAddress(url)
		if err != nil {
			log.Println("Error downloading certificate. " + err.Error())
			statusLabel.SetText("Error downloading certificate. " + err.Error())
			return
		} else {
			statusLabel.SetText("Download successful")
		}
		cert := &Cert{
			Label: url,
			Data:  data,
		}
		downloadedCerts = append(downloadedCerts, cert)
		urlTextBox.SetText("")
		updateDownloadedCerts()
	}

	urlTextBox.OnTextChanged(func([]gxui.TextBoxEdit) {
		isEmpty := (urlTextBox.Text() == "")
		fetchButton.SetVisible(!isEmpty)
	})
	urlTextBox.OnKeyPress(func(event gxui.KeyboardEvent) {
		char := event.Key
		if char == gxui.KeyEnter || char == gxui.KeyKpEnter {
			isEmpty := (urlTextBox.Text() == "")
			if !isEmpty {
				downloadCert()
			}
		}
	})

	fetchButton.OnClick(func(gxui.MouseEvent) {
		downloadCert()
	})

	removeButton.OnClick(func(gxui.MouseEvent) {
		if uploading {
			return
		}
		selected := certList.Selected()
		i := certList.Adapter().ItemIndex(selected)
		downloadedCerts = append(downloadedCerts[:i], downloadedCerts[i+1:]...)
		updateDownloadedCerts()
		removeButton.SetVisible(false)
	})
	certList.OnSelectionChanged(func(gxui.AdapterItem) {
		removeButton.SetVisible(true)
	})
	removeButton.SetVisible(false)

	refreshPortList := func() {
		if uploading {
			return
		}
		if list, err := serial.GetPortsList(); err != nil {
			log.Println("Error fetching serial ports" + err.Error())
		} else {
			portListAdapter.SetItems(list)
		}
	}
	refreshPortList()

	refreshButton.OnClick(func(gxui.MouseEvent) {
		refreshPortList()
		portSelected = false
		updateUploadButton()
	})
	portList.OnSelectionChanged(func(gxui.AdapterItem) {
		portSelected = true
		updateUploadButton()
	})

	updateProgress := func(msg string, percent int) {
		time.Sleep(time.Second)
		driver.CallSync(func() {
			if percent == -1 {
				progressStatus.SetColor(gxui.Red)
				progressBar.SetVisible(false)
			} else if percent == 100 {
				progressStatus.SetColor(gxui.Green)
				progressBar.SetVisible(false)
			} else {
				progressStatus.SetColor(gxui.White)
				progressBar.SetProgress(percent)
				progressBar.SetVisible(true)
			}
			progressStatus.SetText(msg)
		})
	}
	progressBar.SetVisible(false)

	uploadButton.OnClick(func(gxui.MouseEvent) {
		if uploading {
			return
		}
		port := portList.Selected().(string)
		uploading = true
		go uploadCertificates(port, driver, updateProgress)
		log.Println(port)
	})

	updateDownloadedCerts()

	window := theme.CreateWindow(800, 600, "Linear layout")
	window.SetTitle("WINC1500 SSL Certificate updater")
	window.SetScale(flags.DefaultScaleFactor)
	window.AddChild(layout)
	window.OnClose(driver.Terminate)
	window.SetPadding(math.Spacing{L: 10, T: 10, R: 10, B: 10})
	window.Relayout()
}
Esempio n. 26
0
func getFilm(driver gxui.Driver, h1Title gxui.Label, KinopoiskLabel gxui.Label, ImdbLabel gxui.Label, img gxui.Image) {
	m := Movies{}

	// TODO: cache file in memory
	xmlFile, _ := ioutil.ReadFile(XML_PATH)
	err := xml.Unmarshal(xmlFile, &m)
	catch(err)

	rand := rand.Intn(len(m.FilmsList))
	random_movie := m.FilmsList[rand]

	search_movie_title := ""
	if random_movie.En != "" {
		search_movie_title += random_movie.En + " "
	}
	if random_movie.Ru != "" {
		search_movie_title += random_movie.Ru + " "
	}
	if random_movie.Year != "" {
		search_movie_title += random_movie.Year + " "
	}
	search_movie_title += EN_SEARCH_PREFIX

	if search_movie_title != "" {
		resp, err := http.Get(GOOGLE_IMAGES_URL + url.QueryEscape(search_movie_title))
		catch(err)

		if resp.StatusCode == 200 {
			defer resp.Body.Close()
			jsonData, err := ioutil.ReadAll(resp.Body)
			catch(err)

			var jsonMap JsonMap

			err = json.Unmarshal([]byte(jsonData), &jsonMap)
			catch(err)

			ImageUrl := filterFromBlockedResources(jsonMap)
			f, err := http.Get(ImageUrl)
			catch(err)
			source, _, err := image.Decode(f.Body)
			catch(err)
			rgba := image.NewRGBA(source.Bounds())
			draw.Draw(rgba, source.Bounds(), source, image.ZP, draw.Src)
			texture := driver.CreateTexture(rgba, 1)
			img.SetTexture(texture)
		}

		title := ""
		if random_movie.Ru != "" {
			title += random_movie.Ru + " | "
		}
		if random_movie.En != "" {
			title += random_movie.En + " | "
		}
		if random_movie.Year != "" {
			title += random_movie.Year
		}

		if title[len(title)-2:] == "| " {
			title = title[:len(title)-2]
		}
		h1Title.SetText(title)
		//p.TitleForSearch = strings.Replace(title, " | ", " ", -1) // TODO: TitleForSearch == search_movie_title ? replace it!

		KinopoiskLabel.SetText(random_movie.Kinopoisk)
		ImdbLabel.SetText(random_movie.Imdb)
	} else {
		h1Title.SetText("Movie [" + strconv.Itoa(rand) + "] - not found!")
	}
}
Esempio n. 27
0
func appMain(driver gxui.Driver) {
	theme := flags.CreateTheme(driver)
	window := theme.CreateWindow(800, 600, "navmesh")
	canvas := driver.CreateCanvas(math.Size{W: 800, H: 600})

	// mouse
	isStart := true
	var src_id, dest_id int32 // source & dest triangle id
	var src, dest Point3
	window.OnMouseDown(func(me gxui.MouseEvent) {
		pt := Point3{X: float32(me.Point.X) / SCALE_FACTOR, Y: float32(me.Point.Y) / SCALE_FACTOR}
		id := getTriangleId(pt)
		if isStart {
			src_id = id
			src = pt
		} else {
			dest_id = id
			dest = pt
		}
		if !isStart {
			if src_id != -1 && dest_id != -1 {
				canvas := route(driver, src_id, dest_id, src, dest)
				image := theme.CreateImage()
				image.SetCanvas(canvas)
				window.AddChild(image)
			}
		}
		isStart = !isStart
	})

	// draw mesh
	for k := 0; k < len(triangles); k++ {
		poly := []gxui.PolygonVertex{
			gxui.PolygonVertex{
				Position: math.Point{
					int(SCALE_FACTOR * vertices[triangles[k][0]].X),
					int(SCALE_FACTOR * vertices[triangles[k][0]].Y),
				}},

			gxui.PolygonVertex{
				Position: math.Point{
					int(SCALE_FACTOR * vertices[triangles[k][1]].X),
					int(SCALE_FACTOR * vertices[triangles[k][1]].Y),
				}},

			gxui.PolygonVertex{
				Position: math.Point{
					int(SCALE_FACTOR * vertices[triangles[k][2]].X),
					int(SCALE_FACTOR * vertices[triangles[k][2]].Y),
				}},
		}
		canvas.DrawPolygon(poly, gxui.CreatePen(3, gxui.Gray80), gxui.CreateBrush(gxui.Gray40))
		//canvas.DrawPolygon(poly, gxui.CreatePen(2, gxui.Red), gxui.CreateBrush(gxui.Yellow))
	}

	canvas.Complete()
	image := theme.CreateImage()
	image.SetCanvas(canvas)
	window.AddChild(image)
	window.OnClose(driver.Terminate)
}