WiFiSetupPage never showed networks and could not be exited once entered. Several compounding bugs were responsible across network.go and page.go. Primary bugs fixed: - WiFiSetupPage.Init() never assigned p.wifiDevice after FindDevices(), so startScan() always hit the nil guard and exited without launching a scan goroutine. No networks ever appeared in the list. A value copy of the Wi-Fi device is now taken from m.Devices immediately after FindDevices() returns, with an explicit error if no adapter is found. - CheckInternetConnection() called FindDevices() on every tick, rebuilding m.Devices every 2 seconds. This caused [NET-030] log spam, invalidated any pointers held into the slice, and meant checkState()'s fresh Manager instances (which have an empty Devices slice) would never detect internet after Fix 2 was applied. CheckInternetConnection() now calls FindDevices() only when m.Devices is empty (fresh Manager), and does a cheaper per-device State property refresh when devices are already known (long-lived Manager). This satisfies both callers correctly. - Connect() called WaitForInternet(30s, 5s) synchronously before returning, blocking the main UI thread for up to 35 seconds. It also returned an error if internet wasn't stable in time, even though AddAndActivateConnection had succeeded, causing the page to show "Failed to initiate connection" while NM was still negotiating in the background. WaitForInternet removed from Connect(); the page's existing checkConnectionStatusLoop and handleConnectionStatusUpdate already handle post-connection state tracking. Additional bugs fixed: - startScan() launched a new StartScan goroutine on every R-press without signalling the previous one to stop. Concurrent goroutines raced on resultsChan and accumulated indefinitely. stopScan is now closed and replaced before each scan, and checkConnectionStatusLoop is restarted with the new channel. - Connect() always generated a new UUID and called AddAndActivateConnection without checking for an existing profile. Repeated connection attempts (e.g. wrong password then correct) accumulated duplicate stale profiles in NetworkManager. Existing profiles matching the SSID are now deleted via Settings.Connection.Delete before creating a new one. - m.Devices was read and written concurrently from StartScan and CheckInternetConnection goroutines without synchronisation. A sync.RWMutex is added to Manager; state refreshes take a write lock, StartScan device lookup takes a read lock. - Connect() checked wifiDevice.State using the caller's value copy taken at Init() time, which never updated. The current state is now read from m.Devices under lock at the point of connection. - auth-alg: "open" was unconditionally set in the 802-11-wireless-security settings block. This field is only meaningful for WPA/WPA2-Personal and should be omitted for SAE (WPA3) and EAP variants. It is now only set when KeyMgmt is "wpa-psk".
499 lines
13 KiB
Go
499 lines
13 KiB
Go
package application
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/go-gl/gl/v3.3-core/gl"
|
|
"github.com/veandco/go-sdl2/sdl"
|
|
"github.com/veandco/go-sdl2/ttf"
|
|
"gorm.io/gorm"
|
|
"rhemawavetech.com/rhemawave/internal/db"
|
|
"rhemawavetech.com/rhemawave/internal/download"
|
|
"rhemawavetech.com/rhemawave/internal/fontManager"
|
|
"rhemawavetech.com/rhemawave/internal/graphics"
|
|
"rhemawavetech.com/rhemawave/internal/keybinds"
|
|
"rhemawavetech.com/rhemawave/internal/license"
|
|
"rhemawavetech.com/rhemawave/internal/logger"
|
|
"rhemawavetech.com/rhemawave/internal/mixer"
|
|
"rhemawavetech.com/rhemawave/internal/network"
|
|
"rhemawavetech.com/rhemawave/internal/page"
|
|
"rhemawavetech.com/rhemawave/internal/shaderManager"
|
|
"rhemawavetech.com/rhemawave/internal/sync"
|
|
)
|
|
|
|
const (
|
|
targetFPS = 60.0
|
|
openGLMajorVersion = 3
|
|
openGLMinorVersion = 3
|
|
// volumeStepSize = 16
|
|
// apiURL = "https://portal.rhemawavetech.com/api/v1"
|
|
)
|
|
|
|
type State int
|
|
|
|
const (
|
|
FIRST_RUN State = iota
|
|
NEEDS_INTERNET
|
|
NEEDS_LICENSE_KEY
|
|
NEEDS_EMAIL_ADDRESS
|
|
DOWNLOADING_ASSETS
|
|
READY
|
|
)
|
|
|
|
type Application struct {
|
|
Window *sdl.Window
|
|
License *license.Response
|
|
pageStack []page.Page
|
|
pendingAction func()
|
|
running bool
|
|
DB *gorm.DB
|
|
Config atomic.Pointer[db.AppConfig]
|
|
PageRouter *page.Router
|
|
state State
|
|
}
|
|
|
|
var lastNetworkCheckTime time.Time
|
|
var networkIsUp bool
|
|
|
|
// ----------------------------------------------------------------------------
|
|
// Main Entry Point
|
|
// ----------------------------------------------------------------------------
|
|
|
|
func Run() {
|
|
var err error
|
|
var homeDir string
|
|
var dataDir string
|
|
var DB *gorm.DB
|
|
var initialConfig db.AppConfig
|
|
var result *gorm.DB
|
|
|
|
networkIsUp = false
|
|
|
|
logger.Info("Starting Application")
|
|
|
|
homeDir, err = os.UserHomeDir()
|
|
if err != nil {
|
|
logger.Error("unable to fetch user $HOME directory: %v", err)
|
|
return
|
|
}
|
|
|
|
dataDir = filepath.Join(homeDir, ".local", "share", "rhemawave")
|
|
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
|
logger.Error("unable to create data directory %s %v", dataDir, err)
|
|
return
|
|
}
|
|
|
|
testFile := filepath.Join(dataDir, ".access_test")
|
|
f, err := os.Create(testFile)
|
|
if err != nil {
|
|
logger.Error("data %s is not writeable: %v", dataDir, err)
|
|
return
|
|
}
|
|
f.Close()
|
|
os.Remove(testFile)
|
|
|
|
logger.AddFile(filepath.Join(dataDir, "log.txt"))
|
|
logger.SetLevel = logger.LevelDebug
|
|
|
|
DB, err = db.Connect(filepath.Join(dataDir, "database.sqlite"))
|
|
if err != nil {
|
|
logger.Error("application failed to connect to the database: %v", err)
|
|
return
|
|
}
|
|
|
|
if err = db.Migrate(DB); err != nil {
|
|
logger.Error("application failed to perform database migrations: %v", err)
|
|
return
|
|
}
|
|
|
|
// Populate the initial Config cache OR create defaults
|
|
firstRun := false
|
|
result = DB.First(&initialConfig)
|
|
if result.Error != nil {
|
|
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
logger.Info("First run detected: Creating default configuration...")
|
|
firstRun = true
|
|
initialConfig = db.AppConfig{
|
|
DataDir: dataDir,
|
|
AssetsDir: dataDir,
|
|
SystemLevel: "BASIC",
|
|
SelectedAudioDevice: "default",
|
|
InitialFontSize: 128,
|
|
StandardFontSize: 32,
|
|
LinePattern: "fibonacci",
|
|
AudioEnabled: true,
|
|
SavedVolume: 1.0,
|
|
}
|
|
if err := DB.Create(&initialConfig).Error; err != nil {
|
|
logger.Error("failed to insert default config into database: %v", err)
|
|
return
|
|
}
|
|
} else {
|
|
logger.Error("error querying database for initial config: %v", result.Error)
|
|
return
|
|
}
|
|
}
|
|
|
|
logger.AddDatabase(DB)
|
|
|
|
app := &Application{
|
|
DB: DB,
|
|
}
|
|
|
|
if firstRun {
|
|
app.state = FIRST_RUN
|
|
}
|
|
|
|
app.refreshCache()
|
|
|
|
w, h := app.initializeSDLAndOpenGL()
|
|
defer app.cleanup()
|
|
|
|
app.initializeManagers()
|
|
app.initializeAudio()
|
|
// Create a buffered channel so log writes don't slow down downloads.
|
|
downloadProgressChan := make(chan download.DownloadStatus, 1000)
|
|
|
|
app.PageRouter = page.NewRouter(page.PageCtx{
|
|
CfgPtr: app.Config.Load(),
|
|
DbPtr: app.DB,
|
|
W: w,
|
|
H: h,
|
|
MessageChannel: downloadProgressChan,
|
|
RefreshConfig: app.refreshCache,
|
|
})
|
|
|
|
// Sync the proclamations from the API to the Database
|
|
sync.SyncProclamations(DB)
|
|
sync.SyncCategories(DB)
|
|
sync.SyncFrequencies(DB)
|
|
audioFileNames := []string{
|
|
"OriginalAudio.wav",
|
|
"174Hz.wav",
|
|
"396Hz.wav",
|
|
"417Hz.wav",
|
|
"432Hz.wav",
|
|
"639Hz.wav",
|
|
"741Hz.wav",
|
|
"852Hz.wav",
|
|
"963Hz.wav",
|
|
"1111Hz.wav",
|
|
"14Hz_Binaural.wav",
|
|
"40Hz_Binaural.wav",
|
|
"AlphaWaves.wav",
|
|
"PinealGland.wav",
|
|
}
|
|
|
|
go download.DownloadAudioFiles(app.PageRouter.Context.MessageChannel, audioFileNames, filepath.Join(app.PageRouter.Context.CfgPtr.AssetsDir, "audio"))
|
|
|
|
app.runEventLoop()
|
|
}
|
|
|
|
// checkState keeps watch of the application state and sets pages
|
|
// accordingly. This function runs once per
|
|
func (app *Application) checkState() {
|
|
// app.state is READY so do nothing.
|
|
if app.state == READY {
|
|
return
|
|
}
|
|
|
|
// Check if there is an internet connection, and if not, force the WiFi page
|
|
if !networkIsUp {
|
|
if lastNetworkCheckTime.IsZero() || time.Since(lastNetworkCheckTime) >= time.Second {
|
|
networkManager, err := network.New()
|
|
if err != nil {
|
|
logger.Error("error obtaining a network manager %v", err)
|
|
return
|
|
}
|
|
lastNetworkCheckTime = time.Now()
|
|
status, err := networkManager.CheckInternetConnection()
|
|
if err != nil {
|
|
logger.Error("error checking for internet connection %v", err)
|
|
return
|
|
}
|
|
if status.StatusCode != network.StatusWifiConnectedInternetUp &&
|
|
status.StatusCode != network.StatusEthernetConnectedInternetUp {
|
|
if app.state != NEEDS_INTERNET {
|
|
app.PageRouter.NavigateTo(page.WIFI)
|
|
app.state = NEEDS_INTERNET
|
|
}
|
|
return
|
|
}
|
|
networkIsUp = true // internet confirmed, don't check again
|
|
} else {
|
|
return // throttled, and we don't yet know if network is up — can't proceed
|
|
}
|
|
}
|
|
|
|
// Then check for an email address
|
|
if app.Config.Load().EmailAddress == "" {
|
|
if app.state != NEEDS_EMAIL_ADDRESS {
|
|
app.PageRouter.NavigateTo(page.EMAIL_ADDRESS)
|
|
app.state = NEEDS_EMAIL_ADDRESS
|
|
}
|
|
return
|
|
}
|
|
|
|
// Then check for a license key
|
|
if app.Config.Load().LicenseKey == "" {
|
|
if app.state != NEEDS_LICENSE_KEY {
|
|
app.PageRouter.NavigateTo(page.LICENSE_KEY)
|
|
app.state = NEEDS_LICENSE_KEY
|
|
}
|
|
return
|
|
}
|
|
|
|
app.state = READY
|
|
app.PageRouter.NavigateTo(page.HOME)
|
|
}
|
|
|
|
func (app *Application) refreshCache() {
|
|
var freshConfig db.AppConfig
|
|
if result := app.DB.First(&freshConfig); result.Error != nil {
|
|
logger.Error("failed to fetch configuration from the database: %v", result.Error)
|
|
}
|
|
app.Config.Store(&freshConfig)
|
|
}
|
|
|
|
func (app *Application) initializeSDLAndOpenGL() (W, H int32) {
|
|
logger.Info("Initializing SDL")
|
|
if err := sdl.Init(sdl.INIT_VIDEO | sdl.INIT_AUDIO); err != nil {
|
|
logger.Fatal("SDL init failed: %v", err)
|
|
}
|
|
|
|
logger.Info("Initializing TTF")
|
|
if err := ttf.Init(); err != nil {
|
|
logger.Fatal("TTF init failed: %v", err)
|
|
}
|
|
|
|
sdl.GLSetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, openGLMajorVersion)
|
|
sdl.GLSetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, openGLMinorVersion)
|
|
sdl.GLSetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE)
|
|
sdl.ShowCursor(sdl.DISABLE)
|
|
sdl.SetRelativeMouseMode(true)
|
|
|
|
logger.Info("Querying display mode")
|
|
displayMode, err := sdl.GetDisplayMode(0, 0)
|
|
if err != nil {
|
|
logger.Fatal("Display mode query failed: %v", err)
|
|
}
|
|
if displayMode.W == 0 || displayMode.H == 0 {
|
|
logger.Fatal("Invalid display dimensions: %dx%d", displayMode.W, displayMode.H)
|
|
}
|
|
logger.Info("Display: %dx%d @ %dHz", displayMode.W, displayMode.H, displayMode.RefreshRate)
|
|
|
|
logger.Info("Creating window")
|
|
window, err := sdl.CreateWindow(
|
|
"Rhema Wave",
|
|
sdl.WINDOWPOS_UNDEFINED,
|
|
sdl.WINDOWPOS_UNDEFINED,
|
|
displayMode.W,
|
|
displayMode.H,
|
|
sdl.WINDOW_OPENGL|sdl.WINDOW_FULLSCREEN_DESKTOP|sdl.WINDOW_SHOWN,
|
|
)
|
|
if err != nil {
|
|
logger.Fatal("Window creation failed: %v", err)
|
|
}
|
|
app.Window = window
|
|
|
|
logger.Info("Creating OpenGL context")
|
|
if _, err := app.Window.GLCreateContext(); err != nil {
|
|
logger.Fatal("OpenGL context creation failed: %v", err)
|
|
}
|
|
|
|
logger.Info("Initializing go-gl")
|
|
if err := gl.InitWithProcAddrFunc(sdl.GLGetProcAddress); err != nil {
|
|
logger.Fatal("go-gl initialization failed: %v", err)
|
|
}
|
|
|
|
logger.Info("OpenGL version: %s", gl.GoStr(gl.GetString(gl.VERSION)))
|
|
logger.Info("OpenGL renderer: %s", gl.GoStr(gl.GetString(gl.RENDERER)))
|
|
|
|
if err := sdl.GLSetSwapInterval(1); err != nil {
|
|
logger.Warning("Failed to enable vsync: %v", err)
|
|
}
|
|
|
|
w, h := app.Window.GLGetDrawableSize()
|
|
logger.Info("Drawable size: %dx%d", w, h)
|
|
|
|
logger.Info("Initializing virtual framebuffer (%dx%d -> %dx%d)",
|
|
graphics.VirtualWidth, graphics.VirtualHeight, w, h)
|
|
if err := graphics.InitVirtualFramebuffer(w, h); err != nil {
|
|
logger.Fatal("Virtual framebuffer init failed: %v", err)
|
|
}
|
|
|
|
app.initKeybinds()
|
|
logger.Info("SDL and OpenGL initialization complete")
|
|
return graphics.VirtualWidth, graphics.VirtualHeight
|
|
}
|
|
|
|
func (app *Application) initializeManagers() {
|
|
logger.Info("Initializing ShaderManager")
|
|
shaderDir := filepath.Join(app.Config.Load().AssetsDir, "shaders")
|
|
logger.Info("Loading shaders from %s", shaderDir)
|
|
if err := shaderManager.InitShaderManager(shaderDir); err != nil {
|
|
logger.Fatal("ShaderManager initialization failed: %v", err)
|
|
}
|
|
|
|
logger.Info("Initializing FontManager")
|
|
if err := fontManager.InitFontManager(app.Config.Load()); err != nil {
|
|
logger.Fatal("FontManager initialization failed: %v", err)
|
|
}
|
|
}
|
|
|
|
func (app *Application) initializeAudio() {
|
|
logger.Info("Initializing audio")
|
|
|
|
if err := mixer.Init(app.Config.Load(), app.refreshCache); err != nil {
|
|
logger.Error("Unable to initialize audio device '%s': %v", app.Config.Load().SelectedAudioDevice, err)
|
|
logger.Error("Audio will be unavailable until a device is configured")
|
|
} else {
|
|
logger.Info("Audio initialized with device: '%s'", app.Config.Load().SelectedAudioDevice)
|
|
}
|
|
}
|
|
|
|
func (app *Application) cleanup() {
|
|
logger.Info("Cleaning up")
|
|
|
|
if app.PageRouter != nil && app.PageRouter.ActivePage != nil {
|
|
app.PageRouter.ActivePage.Destroy()
|
|
}
|
|
|
|
graphics.DestroyVirtualFramebuffer()
|
|
|
|
if app.Window != nil {
|
|
app.Window.Destroy()
|
|
}
|
|
|
|
ttf.Quit()
|
|
sdl.Quit()
|
|
logger.Info("Cleanup complete")
|
|
logger.Close()
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------
|
|
// Event Loop
|
|
// ----------------------------------------------------------------------------
|
|
|
|
func (app *Application) runEventLoop() {
|
|
if app.PageRouter == nil || app.PageRouter.ActivePage == nil {
|
|
logger.Fatal("No initial page loaded, Router is empty")
|
|
}
|
|
const frameDelay = time.Second / targetFPS
|
|
app.running = true
|
|
lastTime := time.Now()
|
|
logger.Info("Entering event loop")
|
|
|
|
for app.running {
|
|
frameStart := time.Now()
|
|
|
|
app.checkState()
|
|
app.handleEvents()
|
|
if !app.running {
|
|
break
|
|
}
|
|
|
|
deltaTime := float32(time.Since(lastTime).Seconds())
|
|
lastTime = time.Now()
|
|
|
|
app.updateCurrentPage(deltaTime)
|
|
app.renderFrame()
|
|
|
|
frameTime := time.Since(frameStart)
|
|
if frameTime < frameDelay {
|
|
time.Sleep(frameDelay - frameTime)
|
|
}
|
|
}
|
|
|
|
logger.Info("Event loop exited")
|
|
}
|
|
|
|
func (app *Application) handleEvents() {
|
|
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
|
|
switch e := event.(type) {
|
|
case *sdl.QuitEvent:
|
|
app.running = false
|
|
return
|
|
|
|
case *sdl.KeyboardEvent:
|
|
if e.Type == sdl.KEYDOWN && e.Repeat == 0 {
|
|
isCtrlPressed := (e.Keysym.Mod&sdl.KMOD_CTRL) != 0 || (e.Keysym.Mod&sdl.KMOD_GUI) != 0
|
|
if e.Keysym.Sym == sdl.K_c && isCtrlPressed {
|
|
continue
|
|
}
|
|
keybinds.PerformAction(e)
|
|
}
|
|
}
|
|
|
|
if currentPage := app.PageRouter.ActivePage; currentPage != nil {
|
|
if err := currentPage.HandleEvent(&event); err != nil {
|
|
logger.Error("Page event handler error: %v", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (app *Application) updateCurrentPage(deltaTime float32) {
|
|
if currentPage := app.PageRouter.ActivePage; currentPage != nil {
|
|
currentPage.Update(deltaTime)
|
|
}
|
|
}
|
|
|
|
func (app *Application) renderFrame() {
|
|
graphics.BeginVirtualRender()
|
|
gl.ClearColor(0.0, 0.0, 0.0, 1.0)
|
|
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
|
|
|
|
if currentPage := app.PageRouter.ActivePage; currentPage != nil {
|
|
currentPage.Render()
|
|
}
|
|
|
|
graphics.BlitToScreen()
|
|
app.Window.GLSwap()
|
|
}
|
|
|
|
// ----------------------------------------------------------------------------
|
|
// Keybind Registration
|
|
// ----------------------------------------------------------------------------
|
|
|
|
func (app *Application) initKeybinds() {
|
|
keybinds.Register(sdl.K_F3, sdl.KMOD_NONE, func() {
|
|
if app.state != READY {
|
|
return
|
|
}
|
|
app.PageRouter.NavigateTo(page.SETTINGS)
|
|
})
|
|
|
|
keybinds.Register(sdl.K_F2, sdl.KMOD_NONE, func() {
|
|
if app.state != READY {
|
|
return
|
|
}
|
|
app.PageRouter.NavigateTo(page.SCROLLER)
|
|
})
|
|
|
|
keybinds.Register(sdl.K_F1, sdl.KMOD_NONE, func() {
|
|
if app.state != READY {
|
|
return
|
|
}
|
|
app.PageRouter.NavigateTo(page.HOME)
|
|
|
|
})
|
|
|
|
keybinds.Register(sdl.K_q, sdl.KMOD_RCTRL, func() {
|
|
app.Stop()
|
|
})
|
|
}
|
|
|
|
func (app *Application) Stop() {
|
|
app.running = false
|
|
}
|
|
|
|
func (app *Application) Quit() {
|
|
logger.Info("User has quit the application")
|
|
app.running = false
|
|
}
|