Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

2.7 KB
Raw Blame
import { AppSettings, WindowProps } from 'common/types'
import {
  BrowserWindow,
  Menu,
  screen,
  type ContextMenuParams,
  type MenuItemConstructorOptions
} from 'electron'
import { mainPreloadPath } from './constants/paths'
import { configStore } from './constants/key_value_stores'

let mainWindow: BrowserWindow | null = null

export const getMainWindow = () => {
  if (mainWindow) return mainWindow
  return BrowserWindow.getAllWindows().at(0)
}

let windowProps: WindowProps | null = null

export const isFrameless = () => {
  return windowProps?.frame === false || windowProps?.titleBarStyle === 'hidden'
}

export const buildTextContextMenuTemplate = (
  params: Pick<ContextMenuParams, 'isEditable' | 'selectionText'>
): MenuItemConstructorOptions[] => {
  if (params.isEditable) {
    return [
      { role: 'cut' },
      { role: 'copy' },
      { role: 'paste' },
      { type: 'separator' },
      { role: 'selectAll' }
    ]
  }

  if (params.selectionText.trim().length > 0) {
    return [{ role: 'copy' }, { role: 'selectAll' }]
  }

  return []
}

// creates the mainWindow based on the configuration
export const createMainWindow = () => {
  windowProps = {
    height: 690,
    width: 1200,
    x: 0,
    y: 0,
    maximized: false
  } as WindowProps

  if (configStore.has('window-props')) {
    windowProps = configStore.get('window-props', windowProps)
  } else {
    // make sure initial screen size is not bigger than the available screen space
    const screenInfo = screen.getPrimaryDisplay()

    if (screenInfo?.workAreaSize?.height < windowProps.height) {
      windowProps.height = screenInfo.workAreaSize.height * 0.8
    }

    if (screenInfo?.workAreaSize?.width < windowProps.width) {
      windowProps.width = screenInfo.workAreaSize.width * 0.8
    }
  }
  // Set up frameless window if enabled in settings
  const settings = configStore.get('settings', <AppSettings>{})
  if (settings?.framelessWindow) {
    // use native overlay controls where supported
    if (['darwin', 'win32'].includes(process.platform)) {
      windowProps.titleBarStyle = 'hidden'
      windowProps.titleBarOverlay = true
    } else {
      windowProps.frame = false
    }
  }

  // Create the browser window.
  mainWindow = new BrowserWindow({
    ...windowProps,
    minHeight: 345,
    minWidth: 600,
    show: false,

    webPreferences: {
      webviewTag: true,
      contextIsolation: true,
      nodeIntegration: true,
      // sandbox: false,
      preload: mainPreloadPath
    }
  })

  mainWindow.webContents.on('context-menu', (_event, params) => {
    const template = buildTextContextMenuTemplate(params)
    if (template.length === 0) return
    Menu.buildFromTemplate(template).popup({ window: mainWindow ?? undefined })
  })

  return mainWindow
}