Skip to content

Commit 82ddd01

Browse files
authored
Bring back preload + invoke for electron - again (keybase#22294)
* Revert "Revert "Bring back preload + invoke for electron (keybase#22249)" (keybase#22293)" This reverts commit 2161a3f. * WIP
1 parent fa8da03 commit 82ddd01

44 files changed

Lines changed: 395 additions & 388 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎shared/.eslintrc.js‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@ module.exports = {
2020
},
2121
},
2222
globals: {
23-
requestAnimationFrame: 'readonly',
24-
cancelAnimationFrame: 'readonly',
25-
require: 'readonly',
23+
KB: 'readonly',
2624
__DEV__: false,
2725
__STORYBOOK__: false,
2826
__STORYSHOT__: false,
27+
cancelAnimationFrame: 'readonly',
28+
requestAnimationFrame: 'readonly',
29+
require: 'readonly',
2930
},
3031
reportUnusedDisableDirectives: true,
3132
plugins: ['promise', 'react', 'filenames', 'import', 'react-hooks'],

‎shared/actions/fs/platform-specific.desktop.tsx‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,20 @@ import * as Saga from '../../util/saga'
44
import * as RPCTypes from '../../constants/types/rpc-gen'
55
import * as Types from '../../constants/types/fs'
66
import * as Constants from '../../constants/fs'
7-
import * as SafeElectron from '../../util/safe-electron.desktop'
7+
import * as Electron from 'electron'
88
import * as Tabs from '../../constants/tabs'
99
import fs from 'fs'
1010
import {TypedState, TypedActions} from '../../util/container'
1111
import {fileUIName, isWindows, isLinux} from '../../constants/platform'
1212
import logger from '../../logger'
1313
import {spawn, execFile, exec} from 'child_process'
14-
import path from 'path'
1514
import {makeRetriableErrorHandler, makeUnretriableErrorHandler} from './shared'
1615
import * as RouteTreeGen from '../route-tree-gen'
1716

17+
const {path} = KB
18+
const {sep} = path
19+
const {env} = KB.process
20+
1821
type pathType = 'file' | 'directory'
1922

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

51-
SafeElectron.getShell()
54+
Electron.remote.shell
5255
.openExternal(url, {activate: true})
5356
.then(() => {
5457
logger.info('Opened directory:', openPath)
@@ -87,7 +90,7 @@ const _openPathInSystemFileManagerPromise = (openPath: string, isFolder: boolean
8790
new Promise((resolve, reject) => {
8891
if (isFolder) {
8992
if (isWindows) {
90-
if (SafeElectron.getShell().openItem(openPath)) {
93+
if (Electron.remote.shell.openItem(openPath)) {
9194
resolve()
9295
} else {
9396
reject(new Error('unable to open item'))
@@ -96,7 +99,7 @@ const _openPathInSystemFileManagerPromise = (openPath: string, isFolder: boolean
9699
openInDefaultDirectory(openPath).then(resolve, reject)
97100
}
98101
} else {
99-
SafeElectron.getShell().showItemInFolder(openPath)
102+
Electron.remote.shell.showItemInFolder(openPath)
100103
resolve()
101104
}
102105
})
@@ -115,7 +118,7 @@ const _rebaseKbfsPathToMountLocation = (kbfsPath: Types.Path, mountLocation: str
115118
mountLocation,
116119
Types.getPathElements(kbfsPath)
117120
.slice(1)
118-
.join(path.sep)
121+
.join(sep)
119122
)
120123

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

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

263266
// @ts-ignore
@@ -267,7 +270,7 @@ const uninstallDokanConfirm = async (state: TypedState) => {
267270
}
268271
if (!state.fs.sfmi.driverStatus.dokanUninstallExecPath) {
269272
const action = await new Promise<TypedActions>(resolve =>
270-
SafeElectron.getDialog()
273+
Electron.remote.dialog
271274
.showMessageBox({
272275
buttons: ['Got it'],
273276
detail:
@@ -297,7 +300,7 @@ const uninstallDokan = (state: TypedState) => {
297300
}
298301

299302
const openSecurityPreferences = () => {
300-
SafeElectron.getShell()
303+
Electron.remote.shell
301304
.openExternal('x-apple.systempreferences:com.apple.preference.security?General', {activate: true})
302305
.then(() => {
303306
logger.info('Opened Security Preferences')
@@ -311,15 +314,15 @@ const openSecurityPreferences = () => {
311314
const installCachedDokan = (action: FsGen.DriverEnablePayload) =>
312315
new Promise((resolve, reject) => {
313316
logger.info('Invoking dokan installer')
314-
const dokanPath = path.resolve(String(process.env.LOCALAPPDATA), 'Keybase', 'DokanSetup_redist.exe')
317+
const dokanPath = path.resolve(String(env.LOCALAPPDATA), 'Keybase', 'DokanSetup_redist.exe')
315318
execFile(dokanPath, [], err => {
316319
if (err) {
317320
reject(err)
318321
return
319322
}
320323
// restart the service, particularly kbfsdokan
321324
// based on desktop/app/start-win-service.js
322-
const binPath = path.resolve(String(process.env.LOCALAPPDATA), 'Keybase', 'keybase.exe')
325+
const binPath = path.resolve(String(env.LOCALAPPDATA), 'Keybase', 'keybase.exe')
323326
if (!binPath) {
324327
reject(new Error('resolve failed'))
325328
return
@@ -339,8 +342,8 @@ const installCachedDokan = (action: FsGen.DriverEnablePayload) =>
339342
.catch(makeUnretriableErrorHandler(action, null))
340343

341344
const openAndUploadToPromise = (action: FsGen.OpenAndUploadPayload): Promise<Array<string>> =>
342-
SafeElectron.getDialog()
343-
.showOpenDialog(SafeElectron.getCurrentWindowFromRemote(), {
345+
Electron.remote.dialog
346+
.showOpenDialog(Electron.remote.getCurrentWindow(), {
344347
properties: [
345348
'multiSelections' as const,
346349
...(['file', 'both'].includes(action.payload.type) ? (['openFile'] as const) : []),

‎shared/actions/platform-specific/index.desktop.tsx‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@ import * as ConfigGen from '../config-gen'
22
import * as ConfigConstants from '../../constants/config'
33
import * as EngineGen from '../engine-gen-gen'
44
import * as RPCTypes from '../../constants/types/rpc-gen'
5-
import * as SafeElectron from '../../util/safe-electron.desktop'
5+
import * as Electron from 'electron'
66
import * as Saga from '../../util/saga'
77
import logger from '../../logger'
8-
import path from 'path'
98
import {NotifyPopup} from '../../native/notifications'
109
import {execFile} from 'child_process'
1110
import {getEngine} from '../../engine'
@@ -17,6 +16,9 @@ import InputMonitor from './input-monitor.desktop'
1716
import {skipAppFocusActions} from '../../local-debug.desktop'
1817
import * as Container from '../../util/container'
1918

19+
const {resolve} = KB.path
20+
const {argv, env, pid} = KB.process
21+
2022
export function showShareActionSheet() {
2123
throw new Error('Show Share Action - unsupported on this platform')
2224
}
@@ -28,7 +30,7 @@ export async function saveAttachmentToCameraRoll() {
2830
}
2931

3032
const showMainWindow = () => {
31-
SafeElectron.getApp().emit('KBkeybase', '', {type: 'showMainWindow'})
33+
Electron.ipcRenderer.invoke('KBkeybase', {type: 'showMainWindow'})
3234
}
3335

3436
export function displayNewMessageNotification() {
@@ -77,7 +79,7 @@ function* initializeInputMonitor(): Iterable<any> {
7779
const userActive = type === 'active'
7880
yield Saga.put(ConfigGen.createChangedActive({userActive}))
7981
// let node thread save file
80-
SafeElectron.getApp().emit('KBkeybase', '', {
82+
Electron.ipcRenderer.invoke('KBkeybase', {
8183
payload: {changedAtMs: Date.now(), isUserActive: userActive},
8284
type: 'activeChanged',
8385
})
@@ -87,7 +89,7 @@ function* initializeInputMonitor(): Iterable<any> {
8789

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

107-
const localAppData = String(process.env.LOCALAPPDATA)
108-
var binPath = localAppData ? path.resolve(localAppData, 'Keybase', 'keybase.exe') : 'keybase.exe'
109+
const localAppData = String(env.LOCALAPPDATA)
110+
var binPath = localAppData ? resolve(localAppData, 'Keybase', 'keybase.exe') : 'keybase.exe'
109111
const args = ['pipeowner', socketPath]
110112
yield Saga.callUntyped(
111113
() =>
@@ -168,7 +170,7 @@ function* setupReachabilityWatcher() {
168170

169171
const onExit = () => {
170172
console.log('App exit requested')
171-
SafeElectron.getApp().exit(0)
173+
Electron.remote.app.exit(0)
172174
}
173175

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

192194
const onConnected = () => {
193195
// Introduce ourselves to the service
194196
RPCTypes.configHelloIAmRpcPromise({
195197
details: {
196-
argv: process.argv,
198+
argv: argv,
197199
clientType: RPCTypes.ClientType.guiMain,
198200
desc: 'Main Renderer',
199-
pid: SafeElectron.getRemote().process.pid,
201+
pid,
200202
version: __VERSION__, // eslint-disable-line no-undef
201203
},
202204
}).catch(_ => {})
@@ -221,7 +223,7 @@ const prepareLogSend = async (action: EngineGen.Keybase1LogsendPrepareLogsendPay
221223
}
222224

223225
const copyToClipboard = (action: ConfigGen.CopyToClipboardPayload) => {
224-
SafeElectron.getClipboard().writeText(action.payload.text)
226+
Electron.clipboard.writeText(action.payload.text)
225227
}
226228

227229
const sendWindowsKBServiceCheck = (
@@ -234,7 +236,7 @@ const sendWindowsKBServiceCheck = (
234236
state.config.daemonHandshakeWaiters.size === 0 &&
235237
state.config.daemonHandshakeFailedReason === ConfigConstants.noKBFSFailReason
236238
) {
237-
SafeElectron.getApp().emit('keybase' as any, {type: 'requestWindowsStartService'})
239+
Electron.ipcRenderer.invoke('KBkeybase', {type: 'requestWindowsStartService'})
238240
}
239241
}
240242

@@ -277,7 +279,7 @@ const updateNow = async () => {
277279

278280
function* startPowerMonitor() {
279281
const channel = Saga.eventChannel(emitter => {
280-
const pm = SafeElectron.getPowerMonitor()
282+
const pm = Electron.remote.powerMonitor
281283
pm.on('suspend', () => emitter('suspend'))
282284
pm.on('resume', () => emitter('resume'))
283285
pm.on('shutdown', () => emitter('shutdown'))
@@ -391,9 +393,9 @@ const setOpenAtLogin = async (state: Container.TypedState) => {
391393
(await RPCTypes.ctlGetNixOnLoginStartupRpcPromise()) === RPCTypes.OnLoginStartupStatus.enabled
392394
if (enabled !== openAtLogin) await setNixOnLoginStartup(openAtLogin)
393395
} else {
394-
if (SafeElectron.getApp().getLoginItemSettings().openAtLogin !== openAtLogin) {
396+
if (Electron.remote.app.getLoginItemSettings().openAtLogin !== openAtLogin) {
395397
logger.info(`Login item settings changed! now ${openAtLogin}`)
396-
SafeElectron.getApp().setLoginItemSettings({openAtLogin})
398+
Electron.remote.app.setLoginItemSettings({openAtLogin})
397399
}
398400
}
399401
}

‎shared/app/globals.native.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,5 @@ if (typeof __STORYBOOK__ === 'undefined') {
1616

1717
// We don't storyshot RN
1818
__STORYSHOT__ = false
19+
20+
require('./preload.native')

‎shared/app/preload.native.tsx‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// RN version of preload
2+
const {env} = process
3+
4+
// most of KB is for electron
5+
const invalidPreload = () => {
6+
throw new Error('invalid preload call on RN')
7+
}
8+
9+
global.KB = {
10+
get __dirname() {
11+
return invalidPreload()
12+
},
13+
electron: {
14+
app: {
15+
get appPath() {
16+
return invalidPreload()
17+
},
18+
},
19+
},
20+
path: {
21+
basename: invalidPreload,
22+
extname: invalidPreload,
23+
join: invalidPreload,
24+
resolve: invalidPreload,
25+
sep: '/',
26+
},
27+
process: {
28+
get argv() {
29+
return invalidPreload()
30+
},
31+
env: {},
32+
get pid() {
33+
return invalidPreload()
34+
},
35+
get platform() {
36+
return invalidPreload()
37+
},
38+
get type() {
39+
return invalidPreload()
40+
},
41+
},
42+
// punycode, // used by a dep
43+
}

0 commit comments

Comments
 (0)