Skip to content

Commit

Permalink
Save and load state in desktop
Browse files Browse the repository at this point in the history
  • Loading branch information
pipe01 committed Dec 17, 2024
1 parent 2cabb5c commit 9607023
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
3 changes: 2 additions & 1 deletion frontend/desktop/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
__debug_bin*
imgui.ini
spiflash.bin
.vscode
.vscode
state.bin
21 changes: 19 additions & 2 deletions frontend/desktop/emulator/emulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package emulator
#cgo LDFLAGS: -L.. -linfiniemu -lm -lstdc++
#include <setjmp.h>
#include <string.h>
#define ENABLE_RUNLOG 1
Expand Down Expand Up @@ -472,9 +473,9 @@ func (e *Emulator) RunIterations(iterations uint64, iterations_per_us uint64) in
return fault
}

func (e *Emulator) Stop() {
func (e *Emulator) Stop() RunMode {
if !e.isRunning.CompareAndSwap(true, false) {
return
return e.currentRunMode
}

e.perfLoopCancel()
Expand All @@ -491,6 +492,8 @@ func (e *Emulator) Stop() {
}

time.Sleep(100 * time.Millisecond) // TODO: Properly wait for loop or scheduler to stop

return e.currentRunMode
}

func (e *Emulator) InstructionsPerSecond() uint64 {
Expand Down Expand Up @@ -720,6 +723,20 @@ func (e *Emulator) CloseRunlog() {
C.runlog_free(e.runlog)
}

func (e *Emulator) SaveState() []byte {
var size C.size_t
state := C.pinetime_save_state(e.pt, &size)

return C.GoBytes(unsafe.Pointer(state), C.int(size))
}

func (e *Emulator) LoadState(state []byte) bool {
cstate := C.CBytes(state)
defer C.free(cstate)

return bool(C.pinetime_load_state(e.pt, (*C.uchar)(cstate), C.size_t(len(state))))
}

func ConvertImage(raw []byte) *image.RGBA {
img := image.NewRGBA(image.Rect(0, 0, DisplayWidth, DisplayHeight))

Expand Down
14 changes: 14 additions & 0 deletions frontend/desktop/gui/gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ func RunGUI(e *emulator.Emulator, analyzeHeap, runGDB, noScheduler bool) error {
}

imgui.LabelText(strconv.FormatUint(e.InstructionsPerSecond(), 10), "Instructions per second")
imgui.LabelText(fmt.Sprintf("%d%%", int(100*float64(e.InstructionsPerSecond())/float64(emulator.BaseFrequencyHZ))), "Effective speed")

imgui.BeginDisabled(runGDB)
{
Expand All @@ -408,6 +409,19 @@ func RunGUI(e *emulator.Emulator, analyzeHeap, runGDB, noScheduler bool) error {
if imgui.Button("Heap") {
e.FindFreeHeapBlocks()
}
imgui.SameLine()
if imgui.Button("Save") {
os.WriteFile("state.bin", e.SaveState(), 0777)
}
imgui.SameLine()
if imgui.Button("Load") {
state, err := os.ReadFile("state.bin")
if err == nil {
runMode := e.Stop()
e.LoadState(state)
e.Start(runMode)
}
}
}
imgui.End()

Expand Down

0 comments on commit 9607023

Please sign in to comment.