Skip to content

Commit

Permalink
Revert "preload + invoke for electron (keybase#22017)" (keybase#22248)
Browse files Browse the repository at this point in the history
This reverts commit 190ec6b.
  • Loading branch information
chrisnojima authored Jan 28, 2020
1 parent 2dcbf63 commit 809f784
Show file tree
Hide file tree
Showing 42 changed files with 364 additions and 355 deletions.
7 changes: 3 additions & 4 deletions shared/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ module.exports = {
},
},
globals: {
KB: 'readonly',
requestAnimationFrame: 'readonly',
cancelAnimationFrame: 'readonly',
require: 'readonly',
__DEV__: false,
__STORYBOOK__: false,
__STORYSHOT__: false,
cancelAnimationFrame: 'readonly',
requestAnimationFrame: 'readonly',
require: 'readonly',
},
reportUnusedDisableDirectives: true,
plugins: ['promise', 'react', 'filenames', 'import', 'react-hooks'],
Expand Down
33 changes: 15 additions & 18 deletions shared/actions/fs/platform-specific.desktop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,17 @@ import * as Saga from '../../util/saga'
import * as RPCTypes from '../../constants/types/rpc-gen'
import * as Types from '../../constants/types/fs'
import * as Constants from '../../constants/fs'
import * as Electron from 'electron'
import * as SafeElectron from '../../util/safe-electron.desktop'
import * as Tabs from '../../constants/tabs'
import fs from 'fs'
import {TypedState, TypedActions} from '../../util/container'
import {fileUIName, isWindows, isLinux} from '../../constants/platform'
import logger from '../../logger'
import {spawn, execFile, exec} from 'child_process'
import path from 'path'
import {makeRetriableErrorHandler, makeUnretriableErrorHandler} from './shared'
import * as RouteTreeGen from '../route-tree-gen'

const {path} = KB
const {sep} = path
const {env} = KB.process

type pathType = 'file' | 'directory'

// pathToURL takes path and converts to (file://) url.
Expand Down Expand Up @@ -51,7 +48,7 @@ const openInDefaultDirectory = (openPath: string): Promise<void> => {
const url = pathToURL(resolvedPath)
logger.info('Open URL (directory):', url)

Electron.remote.shell
SafeElectron.getShell()
.openExternal(url, {activate: true})
.then(() => {
logger.info('Opened directory:', openPath)
Expand Down Expand Up @@ -90,7 +87,7 @@ const _openPathInSystemFileManagerPromise = (openPath: string, isFolder: boolean
new Promise((resolve, reject) => {
if (isFolder) {
if (isWindows) {
if (Electron.remote.shell.openItem(openPath)) {
if (SafeElectron.getShell().openItem(openPath)) {
resolve()
} else {
reject(new Error('unable to open item'))
Expand All @@ -99,7 +96,7 @@ const _openPathInSystemFileManagerPromise = (openPath: string, isFolder: boolean
openInDefaultDirectory(openPath).then(resolve, reject)
}
} else {
Electron.remote.shell.showItemInFolder(openPath)
SafeElectron.getShell().showItemInFolder(openPath)
resolve()
}
})
Expand All @@ -118,7 +115,7 @@ const _rebaseKbfsPathToMountLocation = (kbfsPath: Types.Path, mountLocation: str
mountLocation,
Types.getPathElements(kbfsPath)
.slice(1)
.join(sep)
.join(path.sep)
)

const openPathInSystemFileManager = (state: TypedState, action: FsGen.OpenPathInSystemFileManagerPayload) =>
Expand Down Expand Up @@ -243,7 +240,7 @@ const driverEnableFuse = async (action: FsGen.DriverEnablePayload) => {

const uninstallKBFSConfirm = async () => {
const action = await new Promise<TypedActions | false>(resolve =>
Electron.remote.dialog
SafeElectron.getDialog()
.showMessageBox({
buttons: ['Remove & Restart', 'Cancel'],
detail: `Are you sure you want to remove Keybase from ${fileUIName} and restart the app?`,
Expand All @@ -259,8 +256,8 @@ const uninstallKBFSConfirm = async () => {
const uninstallKBFS = () =>
RPCTypes.installUninstallKBFSRpcPromise().then(() => {
// Restart since we had to uninstall KBFS and it's needed by the service (for chat)
Electron.remote.app.relaunch()
Electron.remote.app.exit(0)
SafeElectron.getApp().relaunch()
SafeElectron.getApp().exit(0)
})

// @ts-ignore
Expand All @@ -270,7 +267,7 @@ const uninstallDokanConfirm = async (state: TypedState) => {
}
if (!state.fs.sfmi.driverStatus.dokanUninstallExecPath) {
const action = await new Promise<TypedActions>(resolve =>
Electron.remote.dialog
SafeElectron.getDialog()
.showMessageBox({
buttons: ['Got it'],
detail:
Expand Down Expand Up @@ -300,7 +297,7 @@ const uninstallDokan = (state: TypedState) => {
}

const openSecurityPreferences = () => {
Electron.remote.shell
SafeElectron.getShell()
.openExternal('x-apple.systempreferences:com.apple.preference.security?General', {activate: true})
.then(() => {
logger.info('Opened Security Preferences')
Expand All @@ -314,15 +311,15 @@ const openSecurityPreferences = () => {
const installCachedDokan = (action: FsGen.DriverEnablePayload) =>
new Promise((resolve, reject) => {
logger.info('Invoking dokan installer')
const dokanPath = path.resolve(String(env.LOCALAPPDATA), 'Keybase', 'DokanSetup_redist.exe')
const dokanPath = path.resolve(String(process.env.LOCALAPPDATA), 'Keybase', 'DokanSetup_redist.exe')
execFile(dokanPath, [], err => {
if (err) {
reject(err)
return
}
// restart the service, particularly kbfsdokan
// based on desktop/app/start-win-service.js
const binPath = path.resolve(String(env.LOCALAPPDATA), 'Keybase', 'keybase.exe')
const binPath = path.resolve(String(process.env.LOCALAPPDATA), 'Keybase', 'keybase.exe')
if (!binPath) {
reject(new Error('resolve failed'))
return
Expand All @@ -342,8 +339,8 @@ const installCachedDokan = (action: FsGen.DriverEnablePayload) =>
.catch(makeUnretriableErrorHandler(action, null))

const openAndUploadToPromise = (action: FsGen.OpenAndUploadPayload): Promise<Array<string>> =>
Electron.remote.dialog
.showOpenDialog(Electron.remote.getCurrentWindow(), {
SafeElectron.getDialog()
.showOpenDialog(SafeElectron.getCurrentWindowFromRemote(), {
properties: [
'multiSelections' as const,
...(['file', 'both'].includes(action.payload.type) ? (['openFile'] as const) : []),
Expand Down
34 changes: 16 additions & 18 deletions shared/actions/platform-specific/index.desktop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import * as ConfigGen from '../config-gen'
import * as ConfigConstants from '../../constants/config'
import * as EngineGen from '../engine-gen-gen'
import * as RPCTypes from '../../constants/types/rpc-gen'
import * as Electron from 'electron'
import * as SafeElectron from '../../util/safe-electron.desktop'
import * as Saga from '../../util/saga'
import logger from '../../logger'
import path from 'path'
import {NotifyPopup} from '../../native/notifications'
import {execFile} from 'child_process'
import {getEngine} from '../../engine'
Expand All @@ -16,9 +17,6 @@ import InputMonitor from './input-monitor.desktop'
import {skipAppFocusActions} from '../../local-debug.desktop'
import * as Container from '../../util/container'

const {resolve} = KB.path
const {argv, env, pid} = KB.process

export function showShareActionSheet() {
throw new Error('Show Share Action - unsupported on this platform')
}
Expand All @@ -30,7 +28,7 @@ export async function saveAttachmentToCameraRoll() {
}

const showMainWindow = () => {
Electron.ipcRenderer.invoke('KBkeybase', {type: 'showMainWindow'})
SafeElectron.getApp().emit('KBkeybase', '', {type: 'showMainWindow'})
}

export function displayNewMessageNotification() {
Expand Down Expand Up @@ -79,7 +77,7 @@ function* initializeInputMonitor(): Iterable<any> {
const userActive = type === 'active'
yield Saga.put(ConfigGen.createChangedActive({userActive}))
// let node thread save file
Electron.ipcRenderer.invoke('KBkeybase', {
SafeElectron.getApp().emit('KBkeybase', '', {
payload: {changedAtMs: Date.now(), isUserActive: userActive},
type: 'activeChanged',
})
Expand All @@ -89,7 +87,7 @@ function* initializeInputMonitor(): Iterable<any> {

export const dumpLogs = async (_?: Container.TypedState, action?: ConfigGen.DumpLogsPayload) => {
const fromRender = await logger.dump()
const globalLogger: typeof logger = Electron.remote.getGlobal('globalLogger')
const globalLogger: typeof logger = SafeElectron.getRemote().getGlobal('globalLogger')
const fromMain = await globalLogger.dump()
await writeLogLinesToFile([...fromRender, ...fromMain])
// quit as soon as possible
Expand All @@ -106,8 +104,8 @@ function* checkRPCOwnership(_: Container.TypedState, action: ConfigGen.DaemonHan
try {
logger.info('Checking RPC ownership')

const localAppData = String(env.LOCALAPPDATA)
var binPath = localAppData ? resolve(localAppData, 'Keybase', 'keybase.exe') : 'keybase.exe'
const localAppData = String(process.env.LOCALAPPDATA)
var binPath = localAppData ? path.resolve(localAppData, 'Keybase', 'keybase.exe') : 'keybase.exe'
const args = ['pipeowner', socketPath]
yield Saga.callUntyped(
() =>
Expand Down Expand Up @@ -170,7 +168,7 @@ function* setupReachabilityWatcher() {

const onExit = () => {
console.log('App exit requested')
Electron.remote.app.exit(0)
SafeElectron.getApp().exit(0)
}

const onFSActivity = (state: Container.TypedState, action: EngineGen.Keybase1NotifyFSFSActivityPayload) => {
Expand All @@ -187,18 +185,18 @@ const onShutdown = (action: EngineGen.Keybase1NotifyServiceShutdownPayload) => {
if (isWindows && code !== RPCTypes.ExitCode.restart) {
console.log('Quitting due to service shutdown with code: ', code)
// Quit just the app, not the service
Electron.remote.app.quit()
SafeElectron.getApp().quit()
}
}

const onConnected = () => {
// Introduce ourselves to the service
RPCTypes.configHelloIAmRpcPromise({
details: {
argv: argv,
argv: process.argv,
clientType: RPCTypes.ClientType.guiMain,
desc: 'Main Renderer',
pid,
pid: SafeElectron.getRemote().process.pid,
version: __VERSION__, // eslint-disable-line no-undef
},
}).catch(_ => {})
Expand All @@ -223,7 +221,7 @@ const prepareLogSend = async (action: EngineGen.Keybase1LogsendPrepareLogsendPay
}

const copyToClipboard = (action: ConfigGen.CopyToClipboardPayload) => {
Electron.clipboard.writeText(action.payload.text)
SafeElectron.getClipboard().writeText(action.payload.text)
}

const sendWindowsKBServiceCheck = (
Expand All @@ -236,7 +234,7 @@ const sendWindowsKBServiceCheck = (
state.config.daemonHandshakeWaiters.size === 0 &&
state.config.daemonHandshakeFailedReason === ConfigConstants.noKBFSFailReason
) {
Electron.ipcRenderer.invoke('KBkeybase', {type: 'requestWindowsStartService'})
SafeElectron.getApp().emit('keybase' as any, {type: 'requestWindowsStartService'})
}
}

Expand Down Expand Up @@ -279,7 +277,7 @@ const updateNow = async () => {

function* startPowerMonitor() {
const channel = Saga.eventChannel(emitter => {
const pm = Electron.remote.powerMonitor
const pm = SafeElectron.getPowerMonitor()
pm.on('suspend', () => emitter('suspend'))
pm.on('resume', () => emitter('resume'))
pm.on('shutdown', () => emitter('shutdown'))
Expand Down Expand Up @@ -393,9 +391,9 @@ const setOpenAtLogin = async (state: Container.TypedState) => {
(await RPCTypes.ctlGetNixOnLoginStartupRpcPromise()) === RPCTypes.OnLoginStartupStatus.enabled
if (enabled !== openAtLogin) await setNixOnLoginStartup(openAtLogin)
} else {
if (Electron.remote.app.getLoginItemSettings().openAtLogin !== openAtLogin) {
if (SafeElectron.getApp().getLoginItemSettings().openAtLogin !== openAtLogin) {
logger.info(`Login item settings changed! now ${openAtLogin}`)
Electron.remote.app.setLoginItemSettings({openAtLogin})
SafeElectron.getApp().setLoginItemSettings({openAtLogin})
}
}
}
Expand Down
37 changes: 19 additions & 18 deletions shared/constants/platform.desktop.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const {path, process} = KB
const {platform, env} = process
const {join} = path
import path from 'path'

const platform = process.platform
export const isTestDevice = false
export const isMobile = false
export const isAndroid = false
Expand All @@ -20,8 +20,8 @@ export const defaultUseNativeFrame = isDarwin || isLinux
// For storyshots, we only want to test macOS
export const fileUIName = isDarwin || __STORYBOOK__ ? 'Finder' : isWindows ? 'Explorer' : 'File Explorer'

const runMode = env['KEYBASE_RUN_MODE'] || 'prod'
const homeEnv = env['HOME'] || ''
const runMode = process.env['KEYBASE_RUN_MODE'] || 'prod'
const homeEnv = process.env['HOME'] || ''

if (__DEV__ && !__STORYBOOK__) {
console.log(`Run mode: ${runMode}`)
Expand All @@ -30,11 +30,12 @@ if (__DEV__ && !__STORYBOOK__) {
const socketName = 'keybased.sock'

const getLinuxPaths = () => {
const useXDG = (runMode !== 'devel' || env['KEYBASE_DEVEL_USE_XDG']) && !env['KEYBASE_XDG_OVERRIDE']
const useXDG =
(runMode !== 'devel' || process.env['KEYBASE_DEVEL_USE_XDG']) && !process.env['KEYBASE_XDG_OVERRIDE']

// If XDG_RUNTIME_DIR is defined use that, else use $HOME/.config.
const homeConfigDir = (useXDG && env['XDG_CONFIG_HOME']) || join(homeEnv, '.config')
const runtimeDir = (useXDG && env['XDG_RUNTIME_DIR']) || ''
const homeConfigDir = (useXDG && process.env['XDG_CONFIG_HOME']) || path.join(homeEnv, '.config')
const runtimeDir = (useXDG && process.env['XDG_RUNTIME_DIR']) || ''
const socketDir = (useXDG && runtimeDir) || homeConfigDir

const appName = `keybase${runMode === 'prod' ? '' : `.${runMode}`}`
Expand All @@ -45,36 +46,36 @@ const getLinuxPaths = () => {
)
}

const logDir = `${(useXDG && env['XDG_CACHE_HOME']) || `${homeEnv}/.cache`}/${appName}/`
const logDir = `${(useXDG && process.env['XDG_CACHE_HOME']) || `${homeEnv}/.cache`}/${appName}/`

return {
cacheRoot: logDir,
dataRoot: `${(useXDG && env['XDG_DATA_HOME']) || `${homeEnv}/.local/share`}/${appName}/`,
dataRoot: `${(useXDG && process.env['XDG_DATA_HOME']) || `${homeEnv}/.local/share`}/${appName}/`,
guiConfigFilename: `${homeConfigDir}/${appName}/gui_config.json`,
jsonDebugFileName: `${logDir}keybase.app.debug`,
logDir,
serverConfigFileName: `${logDir}keybase.app.serverConfig`,
socketPath: join(socketDir, appName, socketName),
socketPath: path.join(socketDir, appName, socketName),
}
}

const getWindowsPaths = () => {
const appName = `Keybase${runMode === 'prod' ? '' : runMode[0].toUpperCase() + runMode.slice(1)}`
let appdata = env['LOCALAPPDATA'] || ''
let appdata = process.env['LOCALAPPDATA'] || ''
// Remove leading drive letter e.g. C:
if (/^[a-zA-Z]:/.test(appdata)) {
appdata = appdata.slice(2)
}
const dir = `\\\\.\\pipe\\kbservice${appdata}\\${appName}`
const logDir = `${env['LOCALAPPDATA'] || ''}\\${appName}\\`
const logDir = `${process.env['LOCALAPPDATA'] || ''}\\${appName}\\`
return {
cacheRoot: `${env['APPDATA'] || ''}\\${appName}\\`,
dataRoot: `${env['LOCALAPPDATA'] || ''}\\${appName}\\`,
guiConfigFilename: `${env['LOCALAPPDATA'] || ''}\\${appName}\\gui_config.json`,
cacheRoot: `${process.env['APPDATA'] || ''}\\${appName}\\`,
dataRoot: `${process.env['LOCALAPPDATA'] || ''}\\${appName}\\`,
guiConfigFilename: `${process.env['LOCALAPPDATA'] || ''}\\${appName}\\gui_config.json`,
jsonDebugFileName: `${logDir}keybase.app.debug`,
logDir,
serverConfigFileName: `${logDir}keybase.app.serverConfig`,
socketPath: join(dir, socketName),
socketPath: path.join(dir, socketName),
}
}

Expand All @@ -90,7 +91,7 @@ const getDarwinPaths = () => {
jsonDebugFileName: `${logDir}${appName}.app.debug`,
logDir,
serverConfigFileName: `${logDir}${appName}.app.serverConfig`,
socketPath: join(`${libraryDir}Group Containers/keybase/Library/Caches/${appName}/`, socketName),
socketPath: path.join(`${libraryDir}Group Containers/keybase/Library/Caches/${appName}/`, socketName),
}
}

Expand Down
Loading

0 comments on commit 809f784

Please sign in to comment.