electron#shell TypeScript Examples

The following examples show how to use electron#shell. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 6 votes vote down vote up
ipcMain.on("Open-External-Game", async () => {
    const steamProtocol = "steam://run/";
    const steamProtocolMod = "steam://rungameid/";
    const isMod = mod_manager.currentModData.isMod;
    const game = steamProtocol + mod_manager.currentModData.gameId;
    const gameMod = steamProtocolMod + mod_manager.currentModData.gameId;
    const gameDefault = steamProtocol + "440";

    if (mod_manager.currentModData.gameId != "" && mod_manager.currentModState == "INSTALLED") {
        if (isMod == false) {
            log.log("GAME LAUNCHING: User initiated (non-mod) game: " + game);
            shell.openExternal(game);
        } else {
            log.log("GAME LAUNCHING: User initiated (mod) game: " + gameMod);
            shell.openExternal(gameMod);
        }
    } else if (mod_manager.currentModData.gameId == "" && mod_manager.currentModState == "INSTALLED") {
        log.log("GAME LAUNCHING: Current mod doesn't have a gameId, initiating default game: " + gameDefault);
        shell.openExternal(gameDefault);
    } else {
        log.log("GAME LAUNCHING: Can't initiate the current mod's game. It's either uninstalled or with a pending update.");
    }
});
Example #2
Source File: machine-context.ts    From kliveide with MIT License 6 votes vote down vote up
/**
   * Gets hyperlink items from a LinkDescriptor array
   */
  protected getHyperlinkItems(
    links: LinkDescriptor[]
  ): MenuItemConstructorOptions[] {
    return links.map((li) => ({
      type: li.label ? "normal" : "separator",
      label: li?.label,
      click: async () => {
        if (li.uri) {
          await shell.openExternal(li.uri);
        }
      },
    }));
  }
Example #3
Source File: main.dev.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
/*
  Handle IPC requests from the User Interface
 */
ipcMain.on(
  IpcRequest.OpenFileLocation,
  (_, arg: OpenFileLocationRequestBody) => {
    logger.log('received a request to show item in folder', {
      path: arg.path,
    });
    shell.showItemInFolder(arg.path);
  }
);
Example #4
Source File: Settings.tsx    From SpaceEye with MIT License 6 votes vote down vote up
AboutThisApp: React.FC<AboutThisAppProps> = props => {
    return (
        <Dialog open={props.visible} style={{ userSelect: 'none', textAlign: 'center' }}>
            <DialogContent>
                <AppIcon src={infoIcon} alt="SpaceEye icon" />
                <Typography variant="h6">SpaceEye</Typography>
                <Typography variant="body2" style={{ userSelect: 'text' }}>
                    Version {APP_VERSION}
                </Typography>
                <Typography variant="body2">Copyright &copy; 2020 Michael Galliers</Typography>
                <Typography variant="body2">License: {APP_LICENSE}</Typography>
                <Link
                    component="button"
                    variant="body2"
                    onClick={() => shell.openExternal(APP_BUGS_URL)}
                >
                    Report bugs
                </Link>
                <DialogActions>
                    <Button
                        onClick={() =>
                            shell.openPath(path.join(process.resourcesPath, 'legal_notices.txt'))
                        }
                    >
                        Acknowledgements
                    </Button>
                    <Button onClick={props.onClickDone}>Done</Button>
                </DialogActions>
            </DialogContent>
        </Dialog>
    )
}
Example #5
Source File: electron.service.ts    From league-profile-tool with MIT License 6 votes vote down vote up
constructor() {
    if (this.isElectron) {
      this.ipcRenderer = window.require('electron').ipcRenderer;
      this.webFrame = window.require('electron').webFrame;
      this.shell = window.require('electron').shell;
      this.request = window.require('request-promise');
      this.dialog = window.require('electron').remote.dialog;
      this.childProcess = window.require('child_process');
      this.fs = window.require('fs');
      this.LCUConnector = window.require('lcu-connector');
    }
  }
Example #6
Source File: AlphaLink.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
AlphaLink = () => {
  const styles = useStyles();

  const handleClick = useCallback(() => {
    shell.openExternal(outerWildsAlphaUrl);
  }, []);

  return (
    <ListItem className={styles.root}>
      <Button
        variant="outlined"
        color="secondary"
        onClick={handleClick}
        startIcon={<DownloadIcon />}
      >
        {globalText.alphaWebsite}
      </Button>
    </ListItem>
  );
}
Example #7
Source File: app.ts    From SideQuest with MIT License 6 votes vote down vote up
function addWindowDownloadHandler(window) {
    window.webContents.session.on('will-download', (_evt, item, _webContents) => {
        let url = item.getURL();
        let urls = item.getURLChain();
        let name = item.getFilename();
        let etx = path.extname(url.split('?')[0]).toLowerCase();
        let etx2 = urls.length ? path.extname(urls[0].split('?')[0]).toLowerCase() : etx;
        if (~url.indexOf('https://beatsaver.com/cdn')) {
            // beat saber mods /songs
            mainWindow.webContents.send('open-url', 'sidequest://bsaber/#' + url);
        } else if (~url.indexOf('http://songbeater.com/')) {
            // songbeater mods /songs
            mainWindow.webContents.send('open-url', 'sidequest://songbeater/#' + url);
        } else if (~url.indexOf('https://synthriderz.com/')) {
            // synthriderz mods /songs
            mainWindow.webContents.send('open-url', 'sidequest://synthriders/#' + url);
        } else if (etx === '.audica') {
            // audica custom song format
            mainWindow.webContents.send('open-url', 'sidequest://audica/#' + url);
        } else if (etx === '.apk' || etx2 === '.apk') {
            // any file ending with apk.
            mainWindow.webContents.send('pre-open-url', { url, name });
            BrowserWindow.getAllWindows()
                .filter(b => b !== mainWindow)
                .forEach(b => b.close());
        } else if (~url.indexOf('ssl.hwcdn.net/') || ~url.indexOf('patreonusercontent.com/')) {
            //itch.io & patreon
            mainWindow.webContents.send('pre-open-url', { url, name });
            BrowserWindow.getAllWindows()
                .filter(b => b !== mainWindow)
                .forEach(b => b.close());
        } else {
            shell.openExternal(url);
        }
        item.cancel();
    });
}
Example #8
Source File: base.ts    From multi-downloader-nx with MIT License 6 votes vote down vote up
async openFolder(folderType: FolderTypes) {
    const conf = loadCfg();
    switch (folderType) {
    case 'content':
      shell.openPath(conf.dir.content);
      break;
    case 'config':
      shell.openPath(conf.dir.config);
      break;
    }
  }
Example #9
Source File: show-document-adapter.ts    From atom-languageclient with MIT License 6 votes vote down vote up
/**
 * Public: show documents inside Atom text editor or in external programs
 *
 * @param params The {ShowDocumentParams} received from the language server indicating the document to be displayed as
 *   well as other metadata.
 * @returns {Promise<ShowDocumentResult>} With a `success: boolean` property specifying if the operation was sucessful
 *   {@inheritDoc ShowDocumentParams}
 */
export async function showDocument(params: ShowDocumentParams): Promise<ShowDocumentResult> {
  try {
    if (!params.external) {
      // open using atom.workspace
      const view = await atom.workspace.open(Convert.uriToPath(params.uri), {
        activateItem: params.takeFocus,
        activatePane: params.takeFocus,
        pending: true,
        initialLine: params.selection?.start.line ?? 0,
        initialColumn: params.selection?.start.character ?? 0,
      })
      if (!view) {
        return { success: false }
      }
      if (view instanceof TextEditor && params.selection !== undefined) {
        view.selectToBufferPosition(Convert.positionToPoint(params.selection.end))
      }
    } else {
      // open using Electron
      shell.openExternal(params.uri, { activate: params.takeFocus })
    }
    return { success: true }
  } catch (e) {
    const error = e instanceof Error ? e.message : String(e)
    atom.notifications.addError(error)
    return { success: false }
  }
}
Example #10
Source File: shell.ts    From ngx-electronify with MIT License 6 votes vote down vote up
app.on('web-contents-created', (_, contents) => {
  // Angular router is ignored on `will-navigate` event
  contents.on('will-navigate', (event, url) => {
    // allow hot reload to work properly
    if (url !== appUrl) {
      event.preventDefault();
    }
  });

  contents.setWindowOpenHandler(({ url }) => {
    // open all blank href links using the OS default browser
    setImmediate(() => {
      shell.openExternal(url);
    });
    return { action: 'deny' };
  });
});
Example #11
Source File: app-menu.ts    From noteworthy with GNU Affero General Public License v3.0 6 votes vote down vote up
async function makeThemeMenu(themeService:ThemeService): Promise<MenuItemConstructorOptions> {
	// fetch themes
	let themes = await themeService.getThemes();

	let defaultThemeSubmenu: MenuItemConstructorOptions[] = themes.default.map(theme => ({
		label: theme.title,
		click: () => { themeService.setTheme({ type: "default", id: theme.id }); }
	}));

	let customThemeSubmenu: MenuItemConstructorOptions[] = themes.custom.map(theme => ({
		label: theme.title,
		click: () => { themeService.setTheme({ type: "custom", path: theme.path }); }
	}));

	let submenu: MenuItemConstructorOptions[] = [
		{
			label: "Open Themes Folder...",
			click: () => { shell.openPath(themeService.getThemeFolder()); }
		},
		{
			label: "Refresh Custom Themes",
			click: () => { themeService.refreshCustomThemes(); } },
		{ type: "separator" }
	];

	submenu = submenu.concat(
		defaultThemeSubmenu,
		[ { type: "separator" } ],
		customThemeSubmenu,
	);

	return { 
		label: "Theme",
		submenu
	};
}
Example #12
Source File: index.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
createWindow = (): void => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1080,
    height: 900,
    icon: path.join(__dirname, 'assets/icon.png'), // Linux app icon
    webPreferences: {
      nodeIntegration: true,
      // May want to use app.getAppPath() instead
      // preload: path.join(__dirname, 'preload.js'), // use a preload script
      // preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      // allowRunningInsecureContent: true,
      // webSecurity: false,
      // sandbox: false,
    }
  });

  // and load the index.html of the app.
  // mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
  mainWindow.loadURL(`http://localhost:${uiPort}`)

  // Open the DevTools for `npm run start`
  if (!app.isPackaged) mainWindow.webContents.openDevTools()

  mainWindow.on('close', function () {
    console.debug('close')
    clearLocalStorage()
  })
  mainWindow.on('closed', function () {
    console.debug('closed')
    mainWindow = null
  })

  // Open links in browser instead of new electron window
  mainWindow.webContents.on('new-window', function(e: NewWindowWebContentsEvent, url: string) {
    e.preventDefault()
    shell.openExternal(url)
  })
}
Example #13
Source File: main.ts    From EXOS-Core with MIT License 6 votes vote down vote up
ipcMain.on('open-data-folder', (event, arg: string) => {

    let userDataPath = getAppDataPath();

    let dataFolder = null;
    if (os.platform() === 'win32') {
        dataFolder = path.join(userDataPath, 'Blockcore', 'exos', arg);
        writeLog(dataFolder);
    } else {
        dataFolder = path.join(userDataPath, '.blockcore', 'exos', arg);
        writeLog(dataFolder);
    }

    shell.openPath(dataFolder);

    event.returnValue = 'OK';
});
Example #14
Source File: site-launcher.tsx    From desktop with MIT License 6 votes vote down vote up
export function SiteLauncher({ port, siteHash }: IProps): JSX.Element {
  const openUrl = useCallback((): void => {
    trackEvent(`CLICK_TO_OPEN_SITE_IN_BROWSER`, { siteHash })
    shell.openExternal(`http://localhost:${port}`)
  }, [port, siteHash])
  return (
    <GhostButton onClick={openUrl} size="S">
      localhost:{port}
    </GhostButton>
  )
}
Example #15
Source File: contextMenu.ts    From local-addon-image-optimizer with MIT License 6 votes vote down vote up
revealPathMenuItem = (path: string) => {
	return new MenuItem({
		label: isMac ? 'Reveal in Finder' : 'Show folder',
		click() {
			shell.showItemInFolder(path)

			/**
			 * Generally, these calls should live in redux reducers, but given that we do not have
			 * reducers for these, this location makes the most sense
			 */
			reportAnalytics(ANALYTIC_EVENT_TYPES.CONTEXTMENU_REVEAL_IN_FINDER);
		}
	});
}
Example #16
Source File: HelpContentTermsAndConditions.tsx    From mysterium-vpn-desktop with MIT License 6 votes vote down vote up
HelpContentTermsAndConditions: React.FC = observer(function HelpContentTermsAndConditions() {
    return (
        <>
            <Title>Terms & Conditions</Title>
            <TermsMeta>
                Version: {termsPackageJson.version} / Last updated: {termsPackageJson.updatedAt ?? ""}
            </TermsMeta>
            <Terms>
                <Small>
                    <ReactMarkdown
                        components={{
                            // eslint-disable-next-line react/display-name,@typescript-eslint/no-unused-vars
                            a: ({ node, ...props }) => (
                                <Anchor onClick={() => shell.openExternal(props.href as string)}>
                                    {props.href as string}
                                </Anchor>
                            ),
                        }}
                    >
                        {TermsEndUser}
                    </ReactMarkdown>
                </Small>
            </Terms>
        </>
    )
})
Example #17
Source File: tasks.component.ts    From tabby with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    let allLink = document.querySelectorAll('a');
    allLink.forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        shell.openExternal(item.href);
      })
    })
  }
Example #18
Source File: updater.ts    From Aragorn with MIT License 6 votes vote down vote up
protected sendMessage(channelData: UpdaterChannelData, useSystemNotification: boolean) {
    if (useSystemNotification) {
      const notification = new Notification({ title: channelData.message, body: channelData.description || '' });
      if (channelData.url) {
        notification.on('click', () => {
          shell.openExternal(channelData.url as string);
        });
      }
      notification.show();
    } else {
      Ipc.sendMessage('app-updater-message', channelData);
    }
  }
Example #19
Source File: SupportLink.tsx    From CrewLink with GNU General Public License v3.0 6 votes vote down vote up
SupportLink: React.FC = function () {
	return (
		<Typography align="center">
			Need help?{' '}
			<Link
				href="#"
				color="secondary"
				onClick={() => shell.openExternal('https://discord.gg/fFurRtJsZj')}
			>
				Get support
			</Link>
		</Typography>
	);
}
Example #20
Source File: menu.spec.ts    From deskreen with GNU Affero General Public License v3.0 6 votes vote down vote up
jest.mock('electron', () => {
  return {
    app: {
      quit: jest.fn(),
    },
    shell: {
      openExternal: jest.fn(),
    },
    Menu: {
      buildFromTemplate: jest.fn().mockReturnValue({
        popup: jest.fn(),
      }),
      setApplicationMenu: jest.fn(),
    },
  };
});
Example #21
Source File: main.ts    From desktop with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Add navigation handlers.
 */
App.on("web-contents-created", (_, contents) => {
    contents.on("will-navigate", (event, navigationUrl) => {
        const parsedUrl = new URL(navigationUrl);

        if (parsedUrl.origin !== getBuildURL()) {
            event.preventDefault();
        }
    });

    contents.setWindowOpenHandler(({ url }) => {
        if (
            url.startsWith("http:") ||
            url.startsWith("https:") ||
            url.startsWith("mailto:")
        ) {
            setImmediate(() => {
                shell.openExternal(url);
            });
        }

        return { action: "deny" };
    });
});
Example #22
Source File: sapio.ts    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
async trash_compiled_contract(s: string): Promise<void> {
        const file = path.join(
            app.getPath('userData'),
            'workspaces',
            this.name,
            'compiled_contracts',
            s
        );
        return shell.trashItem(file);
    }
Example #23
Source File: electron.service.ts    From StraxUI with MIT License 6 votes vote down vote up
constructor() {
    // Conditional imports
    if (this.isElectron) {
      this.ipcRenderer = window.require('electron').ipcRenderer;
      this.webFrame = window.require('electron').webFrame;
      this.shell = window.require('electron').shell;

      // If you want to use remote object in renderer process, please set enableRemoteModule to true in main.ts
      this.remote = window.require('@electron/remote');

      this.childProcess = window.require('child_process');
      this.fs = window.require('fs');
    }
  }
Example #24
Source File: api-window.ts    From electron-playground with MIT License 6 votes vote down vote up
createApiWindow: CreateWindowHandler = () => {
  const win = new BrowserWindow(OPTIONS)
  win.loadURL(URL)

  win.webContents.on('will-navigate', (event, url) => {
    if (/^http(s)?:/.test(url)) {
      event.preventDefault()
      shell.openExternal(url)
    }
  })

  registerFileManagerService(win)

  return win
}
Example #25
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
private createFailedDialog(message: string, wikiFolderPath: string): void {
    const mainWindow = this.windowService.get(WindowNames.main);
    if (mainWindow !== undefined) {
      void dialog
        .showMessageBox(mainWindow, {
          title: i18n.t('Log.SynchronizationFailed'),
          message,
          buttons: ['OK', 'Github Desktop'],
          cancelId: 0,
          defaultId: 1,
        })
        .then(async ({ response }) => {
          if (response === 1) {
            try {
              const result = await this.nativeService.openInGitGuiApp(wikiFolderPath);
              if (!result) {
                throw new Error('open download site');
              }
            } catch {
              await shell.openExternal(githubDesktopUrl);
            }
          }
        })
        .catch((error) => logger.error('createFailedDialog failed', error));
    }
  }
Example #26
Source File: AutoUpdater.ts    From 3Speak-app with GNU General Public License v3.0 5 votes vote down vote up
async run() {
    try {
      const data = (
        await axios.get('https://api.github.com/repos/3Speaknetwork/3Speak-app/releases/latest')
      ).data
      if (data.id) {
        const tag_name = data['tag_name']
        if (compareVersions.compare(tag_name, version, '>')) {
          //Update available
          for (const asset of data.assets) {
            if (asset.name.includes('Setup') && asset.name.includes('exe') && isWin) {
              const tmpDir = tmp.dirSync()
              const filePath = Path.join(tmpDir.name, asset.name)
              const file = fs.createWriteStream(filePath)
              const response = await axios({
                method: 'get',
                url: asset.browser_download_url,
                responseType: 'stream',
              })
              await new Promise((resolve, reject) => {
                response.data.pipe(file)
                let error = null
                file.on('error', (err) => {
                  error = err
                  // type error: writer not declared?
                  //     writer.close();
                  reject(err)
                })
                file.on('close', () => {
                  if (!error) {
                    resolve(true)
                  }
                })
              })

              let dialogResponse = dialog.showMessageBoxSync({
                type: 'question',
                buttons: ['Remind me later', 'View release log', 'Update'],
                title: 'Update available',
                message: `New update available version ${tag_name.slice(
                  1,
                )}\nWould you like to update your local 3Speak installation?`,
              })

              if (dialogResponse === 2) {
                spawn(filePath, [], { detached: true })
                app.exit(1)
                break
              } else if (dialogResponse === 1) {
                void shell.openExternal(data.html_url)
              } else {
                break
              }

              dialogResponse = dialog.showMessageBoxSync({
                type: 'question',
                buttons: ['Remind me later', 'Update'],
                title: 'Update available',
                message: `New update available version ${tag_name.slice(
                  1,
                )}\nWould you like to update your local 3Speak installation?`,
              })
              if (dialogResponse === 1) {
                spawn(filePath, [], { detached: true })
                app.exit(1)
              }
              break
            }
          }
        }
      }
    } catch (ex) {
      //Shouldn't be important if request fails... But still should be logged.
      console.error(`Error in autoupdater`, ex.message)
    }
  }
Example #27
Source File: main.ts    From bluebubbles-server with Apache License 2.0 5 votes vote down vote up
createWindow = async () => {
    win = new BrowserWindow({
        title: "BlueBubbles Server",
        useContentSize: true,
        width: 1080,
        minWidth: 850,
        height: 750,
        minHeight: 600,
        webPreferences: {
            nodeIntegration: true, // Required in new electron version
            contextIsolation: false // Required or else we get a `global` is not defined error
        }
    });

    if (process.env.NODE_ENV === "development") {
        process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = "1"; // eslint-disable-line require-atomic-updates
        win.loadURL(`http://localhost:3000`);
    } else {
        win.loadURL(`file://${path.join(__dirname, "index.html")}`);
    }

    win.on("closed", () => {
        win = null;
    });

    // Prevent the title from being changed from BlueBubbles
    win.on("page-title-updated", evt => {
        evt.preventDefault();
    });

    // Make links open in the browser
    win.webContents.setWindowOpenHandler((details: HandlerDetails) => {
        shell.openExternal(details.url);
        return { action: 'deny' };
    });

    // Hook onto when we load the UI
    win.webContents.on("dom-ready", async () => {
        win.webContents.send("config-update", Server().repo.config);
    });

    // Set the new window in the Server()
    Server(win);
}
Example #28
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 5 votes vote down vote up
ipcMain.on("Visit-Mod-Social", async (event, arg) => {
    const socialLink = mod_manager.currentModData[arg];
    if (socialLink != null && socialLink != "") {
        shell.openExternal(socialLink);
    }
});
Example #29
Source File: header.component.ts    From dbm with Apache License 2.0 5 votes vote down vote up
handlerDirectGitHub() {
    shell.openExternal('https://github.com/EdurtIO/dbm');
  }